code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
package org.rapla.rest; public @interface GwtIncompatible { }
04900db4-rob
src/org/rapla/rest/GwtIncompatible.java
Java
gpl3
64
package org.rapla.rest.client; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.net.HttpURLConnection; import java.net.URL; import java.util.zip.GZIPInputStream; import java.util.zip.Inflater; import java.util.zip.InflaterInputStream; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.JsonParser; public class HTTPJsonConnector { public HTTPJsonConnector() { super(); } private String readResultToString(InputStream input) throws IOException { InputStreamReader in = new InputStreamReader( input,"UTF-8"); char[] buf = new char[4096]; StringBuffer buffer = new StringBuffer(); while ( true ) { int len = in.read(buf); if ( len == -1) { break; } buffer.append( buf, 0,len ); } String result = buffer.toString(); in.close(); return result; } public JsonObject sendPost(URL methodURL, JsonElement jsonObject, String authenticationToken) throws IOException,JsonParseException { return sendCall("POST", methodURL, jsonObject, authenticationToken); } public JsonObject sendGet(URL methodURL, String authenticationToken) throws IOException,JsonParseException { return sendCall("GET", methodURL, null, authenticationToken); } public JsonObject sendPut(URL methodURL, JsonElement jsonObject, String authenticationToken) throws IOException,JsonParseException { return sendCall("PUT", methodURL, jsonObject, authenticationToken); } public JsonObject sendPatch(URL methodURL, JsonElement jsonObject, String authenticationToken) throws IOException,JsonParseException { return sendCall("PATCH", methodURL, jsonObject, authenticationToken); } public JsonObject sendDelete(URL methodURL, String authenticationToken) throws IOException,JsonParseException { return sendCall("DELETE", methodURL, null, authenticationToken); } protected JsonObject sendCall(String requestMethod, URL methodURL, JsonElement jsonObject, String authenticationToken) throws IOException,JsonParseException { HttpURLConnection conn = (HttpURLConnection)methodURL.openConnection(); if ( !requestMethod.equals("POST") && !requestMethod.equals("GET")) { conn.setRequestMethod("POST"); // we tunnel all non POST or GET requests to avoid proxy filtering (e.g. URLConnection does not allow PATCH) conn.setRequestProperty("X-HTTP-Method-Override",requestMethod); } else { conn.setRequestMethod(requestMethod); } conn.setUseCaches( false ); conn.setRequestProperty("Accept-Encoding", "gzip, deflate"); conn.setRequestProperty("Content-Type", "application/json" + ";charset=utf-8"); conn.setRequestProperty("Accept", "application/json"); if ( authenticationToken != null) { conn.setRequestProperty("Authorization", "Bearer " + authenticationToken); } conn.setReadTimeout(20000); //set timeout to 20 seconds conn.setConnectTimeout(15000); //set connect timeout to 15 seconds conn.setDoOutput(true); conn.connect(); if ( requestMethod.equals("PUT") ||requestMethod.equals("POST") ||requestMethod.equals("PATCH")) { OutputStream outputStream = null; Writer wr = null; try { outputStream= conn.getOutputStream(); wr = new OutputStreamWriter(outputStream,"UTF-8"); Gson gson = new GsonBuilder().create(); String body = gson.toJson( jsonObject); wr.write( body); wr.flush(); } finally { if ( wr != null) { wr.close(); } if ( outputStream != null) { outputStream.close(); } } } else { } JsonObject resultMessage = readResult(conn); return resultMessage; } public JsonObject readResult(HttpURLConnection conn) throws IOException,JsonParseException { String resultString; InputStream inputStream = null; try { String encoding = conn.getContentEncoding(); if (encoding != null && encoding.equalsIgnoreCase("gzip")) { inputStream = new GZIPInputStream(conn.getInputStream()); } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) { inputStream = new InflaterInputStream(conn.getInputStream(), new Inflater(true)); } else { inputStream = conn.getInputStream(); } resultString = readResultToString( inputStream); } finally { if ( inputStream != null) { inputStream.close(); } } JsonParser jsonParser = new JsonParser(); JsonElement parsed = jsonParser.parse(resultString); if ( !(parsed instanceof JsonObject)) { throw new JsonParseException("Invalid json result. JsonObject expected."); } JsonObject resultMessage = (JsonObject) parsed; return resultMessage; } }
04900db4-rob
src/org/rapla/rest/client/HTTPJsonConnector.java
Java
gpl3
5,691
package org.rapla.rest.jsonpatch.mergepatch.server; import com.google.gson.JsonElement; final class ArrayMergePatch extends JsonMergePatch { // Always an array private final JsonElement content; ArrayMergePatch(final JsonElement content) { super(content); this.content = clearNulls(content); } @Override public JsonElement apply(final JsonElement input) throws JsonPatchException { return content; } }
04900db4-rob
src/org/rapla/rest/jsonpatch/mergepatch/server/ArrayMergePatch.java
Java
gpl3
435
package org.rapla.rest.jsonpatch.mergepatch.server; public class JsonPatchException extends Exception { private static final long serialVersionUID = 1L; public JsonPatchException(String string) { super(string); } }
04900db4-rob
src/org/rapla/rest/jsonpatch/mergepatch/server/JsonPatchException.java
Java
gpl3
224
package org.rapla.rest.jsonpatch.mergepatch.server; import java.util.Iterator; import java.util.Map; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; public abstract class JsonMergePatch { protected final JsonElement origPatch; /** * Protected constructor * * <p>Only necessary for serialization purposes. The patching process * itself never requires the full node to operate.</p> * * @param node the original patch node */ protected JsonMergePatch(final JsonElement node) { origPatch = node; } public abstract JsonElement apply(final JsonElement input) throws JsonPatchException; public static JsonMergePatch fromJson(final JsonElement input) throws JsonPatchException { if ( input.isJsonPrimitive()) { throw new JsonPatchException("Only json containers are supported"); } return input.isJsonArray() ? new ArrayMergePatch(input) : new ObjectMergePatch(input); } /** * Clear "null values" from a JSON value * * <p>Non container values are unchanged. For arrays, null elements are * removed. From objects, members whose values are null are removed.</p> * * <p>This method is recursive, therefore arrays within objects, or objects * within arrays, or arrays within arrays etc are also affected.</p> * * @param node the original JSON value * @return a JSON value without null values (see description) */ protected static JsonElement clearNulls(final JsonElement node) { if (node.isJsonPrimitive()) return node; return node.isJsonArray() ? clearNullsFromArray((JsonArray)node) : clearNullsFromObject((JsonObject)node); } private static JsonElement clearNullsFromArray(final JsonArray node) { final JsonArray ret = new JsonArray(); /* * Cycle through array elements. If the element is a null node itself, * skip it. Otherwise, add a "cleaned up" element to the result. */ for (final JsonElement element: node) if (!element.isJsonNull()) ret.add(clearNulls(element)); return ret; } private static JsonElement clearNullsFromObject(final JsonObject node) { final JsonObject ret = new JsonObject(); final Iterator<Map.Entry<String, JsonElement>> iterator = node.entrySet().iterator(); Map.Entry<String, JsonElement> entry; JsonElement value; /* * When faces with an object, cycle through this object's entries. * * If the value of the entry is a JSON null, don't include it in the * result. If not, include a "cleaned up" value for this key instead of * the original element. */ while (iterator.hasNext()) { entry = iterator.next(); value = entry.getValue(); if (value != null) { String key = entry.getKey(); JsonElement clearNulls = clearNulls(value); ret.add(key, clearNulls); } } return ret; } public String toString() { return origPatch.toString(); } }
04900db4-rob
src/org/rapla/rest/jsonpatch/mergepatch/server/JsonMergePatch.java
Java
gpl3
2,975
/* * Copyright (c) 2014, Francis Galiegue (fgaliegue@gmail.com) * * This software is dual-licensed under: * * - the Lesser General Public License (LGPL) version 3.0 or, at your option, any * later version; * - the Apache Software License (ASL) version 2.0. * * The text of both licenses is available under the src/resources/ directory of * this project (under the names LGPL-3.0.txt and ASL-2.0.txt respectively). * * Direct link to the sources: * * - LGPL 3.0: https://www.gnu.org/licenses/lgpl-3.0.txt * - ASL 2.0: http://www.apache.org/licenses/LICENSE-2.0.txt */ package org.rapla.rest.jsonpatch.mergepatch.server; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import com.google.gson.JsonElement; import com.google.gson.JsonObject; /** * Merge patch for a JSON Object * * <p>This only takes care of the top level, and delegates to other {@link * JsonMergePatch} instances for deeper levels.</p> */ final class ObjectMergePatch extends JsonMergePatch { private final Map<String, JsonElement> fields; private final Set<String> removals; ObjectMergePatch(final JsonElement content) { super(content); fields = asMap(content); removals = new HashSet<String>(); for (final Map.Entry<String, JsonElement> entry: fields.entrySet()) if (entry.getValue() == null) removals.add(entry.getKey()); fields.keySet().removeAll(removals); } @Override public JsonElement apply(final JsonElement input) throws JsonPatchException { if (!input.isJsonObject()) return mapToNode(fields); final Map<String, JsonElement> map = asMap(input); // Remove all entries which must be removed map.keySet().removeAll(removals); // Now cycle through what is left String memberName; JsonElement patchNode; for (final Map.Entry<String, JsonElement> entry: map.entrySet()) { memberName = entry.getKey(); patchNode = fields.get(memberName); // Leave untouched if no mention in the patch if (patchNode == null) continue; // If the patch node is a primitive type, replace in the result. // Reminder: there cannot be a JSON null anymore if (patchNode.isJsonPrimitive()) { entry.setValue(patchNode); // no need for .deepCopy() continue; } final JsonMergePatch patch = JsonMergePatch.fromJson(patchNode); entry.setValue(patch.apply(entry.getValue())); } // Finally, if there are members in the patch not present in the input, // fill in members for (final String key: difference(fields.keySet(), map.keySet())) map.put(key, clearNulls(fields.get(key))); return mapToNode(map); } private Set<String> difference(Set<String> keySet, Set<String> keySet2) { LinkedHashSet<String> result = new LinkedHashSet<String>(); for ( String key:keySet) { if ( !keySet2.contains(key)) { result.add( key); } } return result; } private Map<String, JsonElement> asMap(JsonElement input) { Map<String,JsonElement> result = new LinkedHashMap<String,JsonElement>(); for ( Entry<String, JsonElement> entry :input.getAsJsonObject().entrySet()) { JsonElement value = entry.getValue(); String key = entry.getKey(); result.put( key,value); } return result; } private static JsonElement mapToNode(final Map<String, JsonElement> map) { final JsonObject ret = new JsonObject(); for ( String key: map.keySet()) { JsonElement value = map.get( key); ret.add(key, value); } return ret; } }
04900db4-rob
src/org/rapla/rest/jsonpatch/mergepatch/server/ObjectMergePatch.java
Java
gpl3
3,911
package org.rapla.rest.server; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Map; import javax.jws.WebParam; import javax.jws.WebService; import org.rapla.entities.User; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.Reservation; import org.rapla.entities.domain.internal.AppointmentImpl; import org.rapla.entities.domain.internal.ReservationImpl; import org.rapla.entities.dynamictype.ClassificationFilter; import org.rapla.entities.dynamictype.DynamicTypeAnnotations; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.servletpages.RaplaPageGenerator; import org.rapla.storage.RaplaSecurityException; @WebService public class RaplaEventsRestPage extends AbstractRestPage implements RaplaPageGenerator { public RaplaEventsRestPage(RaplaContext context) throws RaplaException { super(context); } private Collection<String> CLASSIFICATION_TYPES = Arrays.asList(new String[] {DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION}); public List<ReservationImpl> list(@WebParam(name="user") User user, @WebParam(name="start")Date start, @WebParam(name="end")Date end, @WebParam(name="resources") List<String> resources, @WebParam(name="eventTypes") List<String> eventTypes,@WebParam(name="attributeFilter") Map<String,String> simpleFilter ) throws RaplaException { Collection<Allocatable> allocatables = new ArrayList<Allocatable>(); for (String id :resources) { Allocatable allocatable = operator.resolve(id, Allocatable.class); allocatables.add( allocatable); } ClassificationFilter[] filters = getClassificationFilter(simpleFilter, CLASSIFICATION_TYPES, eventTypes); Map<String, String> annotationQuery = null; boolean canReadReservationsFromOthers = getQuery().canReadReservationsFromOthers(user); User owner = null; Collection<Reservation> reservations = operator.getReservations(owner, allocatables, start, end, filters, annotationQuery); List<ReservationImpl> result = new ArrayList<ReservationImpl>(); for ( Reservation r:reservations) { if ( RaplaComponent.canRead(r, user, canReadReservationsFromOthers)) { result.add((ReservationImpl) r); } } return result; } public ReservationImpl get(@WebParam(name="user") User user, @WebParam(name="id")String id) throws RaplaException { ReservationImpl event = (ReservationImpl) operator.resolve(id, Reservation.class); boolean canReadReservationsFromOthers = getQuery().canReadReservationsFromOthers(user); if (!RaplaComponent.canRead(event, user, canReadReservationsFromOthers)) { throw new RaplaSecurityException("User " + user + " can't read event " + event); } return event; } public ReservationImpl update(@WebParam(name="user") User user, ReservationImpl event) throws RaplaException { if (!RaplaComponent.canModify(event, user)) { throw new RaplaSecurityException("User " + user + " can't modify event " + event); } event.setResolver( operator); getModification().store( event); ReservationImpl result =(ReservationImpl) getModification().getPersistant( event); return result; } public ReservationImpl create(@WebParam(name="user") User user, ReservationImpl event) throws RaplaException { if (!getQuery().canCreateReservations(user)) { throw new RaplaSecurityException("User " + user + " can't modify event " + event); } if (event.getId() != null) { throw new RaplaException("Id has to be null for new events"); } String eventId = operator.createIdentifier(Reservation.TYPE, 1)[0]; event.setId( eventId); event.setResolver( operator); event.setCreateDate( operator.getCurrentTimestamp()); Appointment[] appointments = event.getAppointments(); String[] appointmentIds = operator.createIdentifier(Appointment.TYPE, 1); for ( int i=0;i<appointments.length;i++) { AppointmentImpl app = (AppointmentImpl)appointments[i]; String id = appointmentIds[i]; app.setId(id); } event.setOwner( user ); getModification().store( event); ReservationImpl result =(ReservationImpl) getModification().getPersistant( event); return result; } }
04900db4-rob
src/org/rapla/rest/server/RaplaEventsRestPage.java
Java
gpl3
4,791
package org.rapla.rest.server; import java.io.IOException; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaContextException; import org.rapla.servletpages.RaplaPageGenerator; import org.rapla.storage.dbrm.RemoteServer; public class RaplaAuthRestPage extends RaplaAPIPage implements RaplaPageGenerator { public RaplaAuthRestPage(RaplaContext context) throws RaplaContextException { super(context); } @Override protected String getServiceAndMethodName(HttpServletRequest request) { return RemoteServer.class.getName() +"/auth"; } @Override public void generatePage(ServletContext servletContext, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { super.generatePage(servletContext, request, response); } }
04900db4-rob
src/org/rapla/rest/server/RaplaAuthRestPage.java
Java
gpl3
1,026
package org.rapla.rest.server; import java.io.IOException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.rapla.entities.User; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.ClassificationFilter; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.DynamicTypeAnnotations; import org.rapla.facade.ClientFacade; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.rest.gwtjsonrpc.server.JsonServlet; import org.rapla.server.ServerServiceContainer; import org.rapla.servletpages.RaplaPageGenerator; import org.rapla.storage.RaplaSecurityException; import org.rapla.storage.StorageOperator; public class AbstractRestPage extends RaplaComponent implements RaplaPageGenerator { protected StorageOperator operator; protected JsonServlet servlet; protected final ServerServiceContainer serverContainer; String getMethod = null; String updatetMethod = null; String listMethod = null; String createMethod = null; public AbstractRestPage(RaplaContext context) throws RaplaException { super(context); operator = context.lookup( ClientFacade.class).getOperator(); serverContainer = context.lookup(ServerServiceContainer.class); Class class1 = getServiceObject().getClass(); Collection<String> publicMethodNames = getPublicMethods(class1); servlet = new JsonServlet(getLogger(), class1); if ( publicMethodNames.contains("get")) { getMethod = "get"; } if ( publicMethodNames.contains("update")) { updatetMethod = "update"; } if ( publicMethodNames.contains("create")) { createMethod = "create"; } if ( publicMethodNames.contains("list")) { listMethod = "list"; } } @Override public void generatePage(ServletContext servletContext, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { User user; Object serviceObj = getServiceObject(); try { user = serverContainer.getUser(request); if ( user == null) { throw new RaplaSecurityException("User not authentified. Pass access token"); } request.setAttribute("user", user); String pathInfo = request.getPathInfo(); int appendix = pathInfo.indexOf("/",1); String method = request.getMethod(); if ( appendix > 0) { if ( method.equals("GET") && getMethod != null ) { String id = pathInfo.substring(appendix+1); request.setAttribute("id", id); request.setAttribute("method", getMethod); } else if ( method.equals("PATCH") && getMethod != null && updatetMethod != null) { String id = pathInfo.substring(appendix+1); request.setAttribute("id", id); request.setAttribute("method", getMethod); request.setAttribute("patchMethod", updatetMethod); } else if ( method.equals("PUT") && updatetMethod != null) { String id = pathInfo.substring(appendix+1); request.setAttribute("id", id); request.setAttribute("method", updatetMethod); } else { throw new RaplaException(method + " Method not supported in this context"); } } else { if ( method.equals("GET") && listMethod != null) { request.setAttribute("method", listMethod); } else if ( method.equals("POST") && createMethod != null) { request.setAttribute("method", createMethod); } else { throw new RaplaException(method + " Method not supported in this context"); } } } catch (RaplaException ex) { servlet.serviceError(request, response, servletContext, ex); return; } servlet.service(request, response, servletContext, serviceObj); // super.generatePage(servletContext, request, response); } protected Collection<String> getPublicMethods(Class class1) { HashSet<String> result = new HashSet<String>(); for (Method m:class1.getMethods()) { if ( Modifier.isPublic(m.getModifiers() )) { result.add( m.getName()); } } return result; } public ClassificationFilter[] getClassificationFilter(Map<String, String> simpleFilter, Collection<String> selectedClassificationTypes, Collection<String> typeNames) throws RaplaException { ClassificationFilter[] filters = null; if ( simpleFilter != null || typeNames == null) { DynamicType[] types = getQuery().getDynamicTypes(null); List<ClassificationFilter> filterList = new ArrayList<ClassificationFilter>(); for ( DynamicType type:types) { String classificationType = type.getAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE); if ( classificationType == null || !selectedClassificationTypes.contains(classificationType)) { continue; } ClassificationFilter classificationFilter = type.newClassificationFilter(); if ( typeNames != null) { if ( !typeNames.contains( type.getKey())) { continue; } } if ( simpleFilter != null) { for (String key:simpleFilter.keySet()) { Attribute att = type.getAttribute(key); if ( att != null) { String value = simpleFilter.get(key); // convert from string to attribute type Object object = att.convertValue(value); if ( object != null) { classificationFilter.addEqualsRule(att.getKey(), object); } filterList.add(classificationFilter); } } } else { filterList.add(classificationFilter); } } filters = filterList.toArray( new ClassificationFilter[] {}); } return filters; } private Object getServiceObject() { return this; } }
04900db4-rob
src/org/rapla/rest/server/AbstractRestPage.java
Java
gpl3
7,545
package org.rapla.rest.server; import java.util.ArrayList; import java.util.List; import javax.jws.WebParam; import javax.jws.WebService; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.internal.DynamicTypeImpl; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.servletpages.RaplaPageGenerator; @WebService public class RaplaDynamicTypesRestPage extends AbstractRestPage implements RaplaPageGenerator { public RaplaDynamicTypesRestPage(RaplaContext context) throws RaplaException { super(context); } public List<DynamicTypeImpl> list(@WebParam(name="classificationType") String classificationType ) throws RaplaException { DynamicType[] types = getQuery().getDynamicTypes(classificationType); List<DynamicTypeImpl> result = new ArrayList<DynamicTypeImpl>(); for ( DynamicType r:types) { result.add((DynamicTypeImpl) r); } return result; } }
04900db4-rob
src/org/rapla/rest/server/RaplaDynamicTypesRestPage.java
Java
gpl3
1,040
package org.rapla.rest.server; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import javax.jws.WebParam; import javax.jws.WebService; import org.rapla.entities.User; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.internal.AllocatableImpl; import org.rapla.entities.dynamictype.ClassificationFilter; import org.rapla.entities.dynamictype.DynamicTypeAnnotations; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.servletpages.RaplaPageGenerator; import org.rapla.storage.RaplaSecurityException; @WebService public class RaplaResourcesRestPage extends AbstractRestPage implements RaplaPageGenerator { private Collection<String> CLASSIFICATION_TYPES = Arrays.asList(new String[] {DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE,DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON}); public RaplaResourcesRestPage(RaplaContext context) throws RaplaException { super(context); } public List<AllocatableImpl> list(@WebParam(name="user") User user,@WebParam(name="resourceTypes") List<String> resourceTypes, @WebParam(name="attributeFilter") Map<String,String> simpleFilter ) throws RaplaException { ClassificationFilter[] filters = getClassificationFilter(simpleFilter, CLASSIFICATION_TYPES, resourceTypes); Collection<Allocatable> resources = operator.getAllocatables(filters); List<AllocatableImpl> result = new ArrayList<AllocatableImpl>(); for ( Allocatable r:resources) { if ( RaplaComponent.canRead(r, user)) { result.add((AllocatableImpl) r); } } return result; } public AllocatableImpl get(@WebParam(name="user") User user, @WebParam(name="id")String id) throws RaplaException { AllocatableImpl resource = (AllocatableImpl) operator.resolve(id, Allocatable.class); if (!RaplaComponent.canRead(resource, user)) { throw new RaplaSecurityException("User " + user + " can't read " + resource); } return resource; } public AllocatableImpl update(@WebParam(name="user") User user, AllocatableImpl resource) throws RaplaException { if (!RaplaComponent.canModify(resource, user)) { throw new RaplaSecurityException("User " + user + " can't modify " + resource); } resource.setResolver( operator); getModification().store( resource ); AllocatableImpl result =(AllocatableImpl) getModification().getPersistant( resource); return result; } public AllocatableImpl create(@WebParam(name="user") User user, AllocatableImpl resource) throws RaplaException { if (!getQuery().canCreateReservations(user)) { throw new RaplaSecurityException("User " + user + " can't modify " + resource); } if (resource.getId() != null) { throw new RaplaException("Id has to be null for new events"); } String eventId = operator.createIdentifier(Allocatable.TYPE, 1)[0]; resource.setId( eventId); resource.setResolver( operator); resource.setCreateDate( operator.getCurrentTimestamp()); resource.setOwner( user ); getModification().store( resource); AllocatableImpl result =(AllocatableImpl) getModification().getPersistant( resource); return result; } }
04900db4-rob
src/org/rapla/rest/server/RaplaResourcesRestPage.java
Java
gpl3
3,608
package org.rapla.rest.server; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaContextException; import org.rapla.framework.RaplaException; import org.rapla.rest.gwtjsonrpc.common.JSONParserWrapper; import org.rapla.rest.gwtjsonrpc.server.JsonServlet; import org.rapla.rest.gwtjsonrpc.server.RPCServletUtils; import org.rapla.server.ServerServiceContainer; import org.rapla.servletpages.RaplaPageGenerator; import org.rapla.storage.RaplaSecurityException; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; public class RaplaAPIPage extends RaplaComponent implements RaplaPageGenerator { final ServerServiceContainer serverContainer; public RaplaAPIPage(RaplaContext context) throws RaplaContextException { super(context); serverContainer = context.lookup(ServerServiceContainer.class); } Map<String,JsonServlet> servletMap = new HashMap<String, JsonServlet>(); private JsonServlet getJsonServlet(HttpServletRequest request,String serviceAndMethodName) throws RaplaException { if ( serviceAndMethodName == null || serviceAndMethodName.length() == 0) { throw new RaplaException("Servicename missing in url"); } int indexRole = serviceAndMethodName.indexOf( "/" ); String interfaceName; if ( indexRole > 0 ) { interfaceName= serviceAndMethodName.substring( 0, indexRole ); if ( serviceAndMethodName.length() >= interfaceName.length()) { String methodName = serviceAndMethodName.substring( indexRole + 1 ); request.setAttribute(JsonServlet.JSON_METHOD, methodName); } } else { interfaceName = serviceAndMethodName; } JsonServlet servlet = servletMap.get( interfaceName); if ( servlet == null) { try { if (!serverContainer.hasWebservice(interfaceName)) { throw new RaplaException("Webservice " + interfaceName + " not configured or initialized."); } Class<?> interfaceClass = Class.forName(interfaceName, true,RaplaAPIPage.class.getClassLoader()); // Test if service is found servlet = new JsonServlet(getLogger(), interfaceClass); } catch (Exception ex) { throw new RaplaException( ex.getMessage(), ex); } servletMap.put( interfaceName, servlet); } return servlet; } public void generatePage(ServletContext servletContext, HttpServletRequest request, HttpServletResponse response ) throws IOException, ServletException { String id = request.getParameter("id"); String serviceAndMethodName = getServiceAndMethodName(request); try { JsonServlet servlet; try { servlet = getJsonServlet( request, serviceAndMethodName ); } catch (RaplaException ex) { getLogger().error(ex.getMessage(), ex); String out = serializeException(id, ex); RPCServletUtils.writeResponse(servletContext, response, out, false); return; } Class<?> role = servlet.getInterfaceClass(); Object impl; try { impl = serverContainer.createWebservice(role, request); } catch (RaplaSecurityException ex) { servlet.serviceError(request, response, servletContext, ex); return; } servlet.service(request, response, servletContext, impl); } catch ( RaplaSecurityException ex) { getLogger().error(ex.getMessage()); } catch ( RaplaException ex) { getLogger().error(ex.getMessage(), ex); } } protected String getServiceAndMethodName(HttpServletRequest request) { String requestURI =request.getPathInfo(); String path = "/json/"; int rpcIndex=requestURI.indexOf(path) ; String serviceAndMethodName = requestURI.substring(rpcIndex + path.length()).trim(); return serviceAndMethodName; } protected String serializeException(String id, Exception ex) { final JsonObject r = new JsonObject(); String versionName = "jsonrpc"; int code = -32603; r.add(versionName, new JsonPrimitive("2.0")); if (id != null) { r.add("id", new JsonPrimitive(id)); } GsonBuilder gb = JSONParserWrapper.defaultGsonBuilder(); final JsonObject error = JsonServlet.getError(versionName, code, ex, gb); r.add("error", error); GsonBuilder builder = JSONParserWrapper.defaultGsonBuilder(); String out = builder.create().toJson( r); return out; } }
04900db4-rob
src/org/rapla/rest/server/RaplaAPIPage.java
Java
gpl3
5,352
/* * AbstractTreeTableModel.java * * Copyright (c) 1998 Sun Microsystems, Inc. All Rights Reserved. * * Sun Microsystems grants you ("Licensee") a non-exclusive, royalty * free, license to use, modify and redistribute this software in * source and binary code form, provided that i) this copyright notice * and license appear on all copies of the software; and ii) Licensee * does not utilize the software in a manner which is disparaging to * Sun Microsystems. * * The software media is distributed on an "As Is" basis, without * warranty. Neither the authors, the software developers nor Sun * Microsystems make any representation, or warranty, either express * or implied, with respect to the software programs, their quality, * accuracy, or fitness for a specific purpose. Therefore, neither the * authors, the software developers nor Sun Microsystems shall have * any liability to you or any other person or entity with respect to * any liability, loss, or damage caused or alleged to have been * caused directly or indirectly by programs contained on the * media. This includes, but is not limited to, interruption of * service, loss of data, loss of classroom time, loss of consulting * or anticipatory *profits, or consequential damages from the use of * these programs. */ package org.rapla.components.treetable; import javax.swing.event.EventListenerList; import javax.swing.event.TreeModelEvent; import javax.swing.event.TreeModelListener; import javax.swing.tree.TreePath; /** * @version 1.2 10/27/98 * An abstract implementation of the TreeTableModel interface, handling the list * of listeners. * @author Philip Milne */ public abstract class AbstractTreeTableModel implements TreeTableModel { protected Object root; protected EventListenerList listenerList = new EventListenerList(); public AbstractTreeTableModel(Object root) { this.root = root; } // // Default implementations for methods in the TreeModel interface. // public Object getRoot() { return root; } public boolean isLeaf(Object node) { return getChildCount(node) == 0; } public void valueForPathChanged(TreePath path, Object newValue) {} // This is not called in the JTree's default mode: use a naive implementation. public int getIndexOfChild(Object parent, Object child) { for (int i = 0; i < getChildCount(parent); i++) { if (getChild(parent, i).equals(child)) { return i; } } return -1; } public void addTreeModelListener(TreeModelListener l) { listenerList.add(TreeModelListener.class, l); } public void removeTreeModelListener(TreeModelListener l) { listenerList.remove(TreeModelListener.class, l); } /* * Notify all listeners that have registered interest for * notification on this event type. The event instance * is lazily created using the parameters passed into * the fire method. * @see EventListenerList */ protected void fireTreeNodesChanged(Object source, Object[] path, int[] childIndices, Object[] children) { // Guaranteed to return a non-null array Object[] listeners = listenerList.getListenerList(); TreeModelEvent e = null; // Process the listeners last to first, notifying // those that are interested in this event for (int i = listeners.length-2; i>=0; i-=2) { if (listeners[i]==TreeModelListener.class) { // Lazily create the event: if (e == null) e = new TreeModelEvent(source, path, childIndices, children); ((TreeModelListener)listeners[i+1]).treeNodesChanged(e); } } } /* * Notify all listeners that have registered interest for * notification on this event type. The event instance * is lazily created using the parameters passed into * the fire method. * @see EventListenerList */ protected void fireTreeNodesInserted(Object source, Object[] path, int[] childIndices, Object[] children) { // Guaranteed to return a non-null array Object[] listeners = listenerList.getListenerList(); TreeModelEvent e = null; // Process the listeners last to first, notifying // those that are interested in this event for (int i = listeners.length-2; i>=0; i-=2) { if (listeners[i]==TreeModelListener.class) { // Lazily create the event: if (e == null) e = new TreeModelEvent(source, path, childIndices, children); ((TreeModelListener)listeners[i+1]).treeNodesInserted(e); } } } /* * Notify all listeners that have registered interest for * notification on this event type. The event instance * is lazily created using the parameters passed into * the fire method. * @see EventListenerList */ protected void fireTreeNodesRemoved(Object source, Object[] path, int[] childIndices, Object[] children) { // Guaranteed to return a non-null array Object[] listeners = listenerList.getListenerList(); TreeModelEvent e = null; // Process the listeners last to first, notifying // those that are interested in this event for (int i = listeners.length-2; i>=0; i-=2) { if (listeners[i]==TreeModelListener.class) { // Lazily create the event: if (e == null) e = new TreeModelEvent(source, path, childIndices, children); ((TreeModelListener)listeners[i+1]).treeNodesRemoved(e); } } } /* * Notify all listeners that have registered interest for * notification on this event type. The event instance * is lazily created using the parameters passed into * the fire method. * @see EventListenerList */ protected void fireTreeStructureChanged(Object source, Object[] path, int[] childIndices, Object[] children) { // Guaranteed to return a non-null array Object[] listeners = listenerList.getListenerList(); TreeModelEvent e = null; // Process the listeners last to first, notifying // those that are interested in this event for (int i = listeners.length-2; i>=0; i-=2) { if (listeners[i]==TreeModelListener.class) { // Lazily create the event: if (e == null) e = new TreeModelEvent(source, path, childIndices, children); ((TreeModelListener)listeners[i+1]).treeStructureChanged(e); } } } // // Default impelmentations for methods in the TreeTableModel interface. // public Class<?> getColumnClass(int column) { return Object.class; } /** By default, make the column with the Tree in it the only editable one. * Making this column editable causes the JTable to forward mouse * and keyboard events in the Tree column to the underlying JTree. */ public boolean isCellEditable(Object node, int column) { return getColumnClass(column) == TreeTableModel.class; } public void setValueAt(Object aValue, Object node, int column) {} // Left to be implemented in the subclass: /* * public Object getChild(Object parent, int index) * public int getChildCount(Object parent) * public int getColumnCount() * public String getColumnName(Object node, int column) * public Object getValueAt(Object node, int column) */ }
04900db4-rob
src/org/rapla/components/treetable/AbstractTreeTableModel.java
Java
gpl3
8,174
/* * Sun Microsystems grants you ("Licensee") a non-exclusive, royalty * free, license to use, modify and redistribute this software in * source and binary code form, provided that i) this copyright notice * and license appear on all copies of the software; and ii) Licensee * does not utilize the software in a manner which is disparaging to * Sun Microsystems. * * The software media is distributed on an "As Is" basis, without * warranty. Neither the authors, the software developers nor Sun * Microsystems make any representation, or warranty, either express * or implied, with respect to the software programs, their quality, * accuracy, or fitness for a specific purpose. Therefore, neither the * authors, the software developers nor Sun Microsystems shall have * any liability to you or any other person or entity with respect to * any liability, loss, or damage caused or alleged to have been * caused directly or indirectly by programs contained on the * media. This includes, but is not limited to, interruption of * service, loss of data, loss of classroom time, loss of consulting * or anticipatory *profits, or consequential damages from the use of * these programs. */ package org.rapla.components.treetable; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Insets; import java.awt.Point; import java.awt.Rectangle; import java.awt.Shape; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.ArrayList; import java.util.Enumeration; import java.util.EventObject; import java.util.List; import javax.swing.JComponent; import javax.swing.JTable; import javax.swing.JTree; import javax.swing.KeyStroke; import javax.swing.ListSelectionModel; import javax.swing.LookAndFeel; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.border.Border; import javax.swing.border.CompoundBorder; import javax.swing.event.CellEditorListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.event.TreeExpansionEvent; import javax.swing.event.TreeExpansionListener; import javax.swing.event.TreeModelEvent; import javax.swing.event.TreeModelListener; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeSelectionModel; import javax.swing.tree.TreeCellRenderer; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; /** * Original version Philip Milne and Scott Violet * Modified by Christopher Kohlhaas to support editing and keyboard handling. */ public class JTreeTable extends JTable { private static final long serialVersionUID = 1L; private RendererTree tree = new RendererTree(); private TreeTableEditor treeCellEditor; private TableToolTipRenderer toolTipRenderer = null; private int focusedRow = -1; private String cachedSearchKey = ""; public JTreeTable(TreeTableModel model) { super(); setTreeTableModel( model ); // Force the JTable and JTree to share their row selection models. ListToTreeSelectionModelWrapper selectionWrapper = new ListToTreeSelectionModelWrapper(); setSelectionModel(selectionWrapper.getListSelectionModel()); setShowGrid( false); // No intercell spacing setIntercellSpacing(new Dimension(1, 0)); setShowVerticalLines(true); tree.setEditable(false); tree.setSelectionModel(selectionWrapper); tree.setShowsRootHandles(true); tree.setRootVisible(false); setDefaultRenderer( TreeTableModel.class, tree ); setTreeCellEditor(null); // And update the height of the trees row to match that of // the table. if (tree.getRowHeight() < 1) { // Metal looks better like this. setRowHeight(22); } } public void setToolTipRenderer(TableToolTipRenderer renderer) { toolTipRenderer = renderer; } public TableToolTipRenderer getToolTipRenderer() { return toolTipRenderer; } public String getToolTipText(MouseEvent evt) { if (toolTipRenderer == null) return super.getToolTipText(evt); Point p = new Point(evt.getX(),evt.getY()); int column = columnAtPoint(p); int row = rowAtPoint(p); if (row >=0 && column>=0) return toolTipRenderer.getToolTipText(this,row,column); else return super.getToolTipText(evt); } /** * Overridden to message super and forward the method to the tree. * Since the tree is not actually in the component hierarchy it will * never receive this unless we forward it in this manner. */ public void updateUI() { super.updateUI(); if(tree != null) { tree.updateUI(); } // Use the tree's default foreground and background colors in the // table. LookAndFeel.installColorsAndFont(this, "Tree.background", "Tree.foreground", "Tree.font"); } /** Set a custom TreeCellEditor. The default one is a TextField.*/ public void setTreeCellEditor(TreeTableEditor editor) { treeCellEditor = editor; setDefaultEditor( TreeTableModel.class, new DelegationgTreeCellEditor(treeCellEditor) ); } /** Returns the tree that is being shared between the model. If you set a different TreeCellRenderer for this tree it should inherit from DefaultTreeCellRenderer. Otherwise the selection-color and focus color will not be set correctly. */ public JTree getTree() { return tree; } /** * search for given search term in child nodes of selected nodes * @param search what to search for * @param parentNode where to search fo * @return first childnode where its tostring representation in tree starts with search term, null if no one found */ private TreeNode getNextTreeNodeMatching(String search, TreeNode parentNode) { TreeNode result = null; Enumeration<?> children = parentNode.children(); while (children.hasMoreElements()) { TreeNode treeNode = (TreeNode) children.nextElement(); String compareS = treeNode.toString().toLowerCase(); if (compareS.startsWith(search)) { result = treeNode; break; } } return result; } /** * create treepath from treenode * @param treeNode Treenode * @return treepath object */ public static TreePath getPath(TreeNode treeNode) { List<Object> nodes = new ArrayList<Object>(); if (treeNode != null) { nodes.add(treeNode); treeNode = treeNode.getParent(); while (treeNode != null) { nodes.add(0, treeNode); treeNode = treeNode.getParent(); } } return nodes.isEmpty() ? null : new TreePath(nodes.toArray()); } /** overridden to support keyboard expand/collapse for the tree.*/ protected boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) { if (condition == JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT) { if (tree != null && !isEditing() && getSelectedColumn() == getTreeColumnNumber()) { if (e.getID() == KeyEvent.KEY_PRESSED) { if ( (e.getKeyCode() == KeyEvent.VK_ENTER || e.getKeyChar() =='+')) { int row = getSelectedRow(); if (row >= 0) { if (tree.isExpanded(row)) { tree.collapseRow(row); } else { tree.expandPath(tree.getPathForRow(row)); } } return true; } if (e.getKeyCode() == KeyEvent.VK_LEFT) { int row = getSelectedRow(); if (row >= 0) { TreePath pathForRow = tree.getPathForRow(row); // if selected node is expanded than collapse it // else selected parents node if (tree.isExpanded(pathForRow)) { // only if root is visible we should collapse first level final boolean canCollapse = pathForRow.getPathCount() > (tree.isRootVisible() ? 0 : 1); if (canCollapse) tree.collapsePath(pathForRow); } else { // only if root is visible we should collapse first level or select parent node final boolean canCollapse = pathForRow.getPathCount() > (tree.isRootVisible() ? 1 : 2); if (canCollapse) { pathForRow = pathForRow.getParentPath(); final int parentRow = tree.getRowForPath(pathForRow ); tree.setSelectionInterval(parentRow, parentRow); } } if (pathForRow != null) { Rectangle rect = getCellRect(tree.getRowForPath(pathForRow), 0, false); scrollRectToVisible(rect ); } } return true; } if (e.getKeyCode() == KeyEvent.VK_RIGHT) { int row = getSelectedRow(); if (row >= 0) { final TreePath path = tree.getPathForRow(row); if (tree.isCollapsed(path)) { tree.expandPath(path); } } return true; } // live search in current parent node if ((Character.isLetterOrDigit(e.getKeyChar()))) { char keyChar = e.getKeyChar(); // we are searching in the current parent node // first we assume that we have selected a parent node // so we should have children TreePath selectedPath = tree.getSelectionModel().getLeadSelectionPath(); TreeNode selectedNode = (TreeNode) selectedPath.getLastPathComponent(); // if we don't have children we might have selected a leaf so choose its parent if (selectedNode.getChildCount() == 0) { // set new selectedNode selectedPath = selectedPath.getParentPath(); selectedNode = (TreeNode) selectedPath.getLastPathComponent(); } // search term String search = ("" + keyChar).toLowerCase(); // try to find node with matching searchterm plus the search before TreeNode nextTreeNodeMatching = getNextTreeNodeMatching(cachedSearchKey + search, selectedNode); // if we did not find anything, try to find search term only: restart! if (nextTreeNodeMatching == null) { nextTreeNodeMatching = getNextTreeNodeMatching(search, selectedNode); cachedSearchKey = ""; } // if we found a node, select it, make it visible and return true if (nextTreeNodeMatching != null) { TreePath foundPath = getPath(nextTreeNodeMatching); // select our found path this.tree.getSelectionModel().setSelectionPath(foundPath); //make it visible this.tree.expandPath(foundPath); this.tree.makeVisible(foundPath); // Scroll to the found row int row = tree.getRowForPath( foundPath); int col = 0; Rectangle rect = getCellRect(row, col, false); scrollRectToVisible(rect ); // store found treepath cachedSearchKey = cachedSearchKey + search; return true; } } cachedSearchKey = ""; /* Uncomment this if you don't want to start tree-cell-editing on a non navigation key stroke. if (e.getKeyCode() != e.VK_TAB && e.getKeyCode() != e.VK_F2 && e.getKeyCode() != e.VK_DOWN && e.getKeyCode() != e.VK_UP && e.getKeyCode() != e.VK_LEFT && e.getKeyCode() != e.VK_RIGHT && e.getKeyCode() != e.VK_PAGE_UP && e.getKeyCode() != e.VK_PAGE_DOWN ) return true; */ } } } // reset cachedkey to null if we did not find anything return super.processKeyBinding(ks,e,condition,pressed); } public void setTreeTableModel(TreeTableModel model) { tree.setModel(model); super.setModel(new TreeTableModelAdapter(model)); } /** * Workaround for BasicTableUI anomaly. Make sure the UI never tries to * resize the editor. The UI currently uses different techniques to * paint the renderers and editors; overriding setBounds() below * is not the right thing to do for an editor. Returning -1 for the * editing row in this case, ensures the editor is never painted. */ public int getEditingRow() { int column = getEditingColumn(); if( getColumnClass(column) == TreeTableModel.class ) return -1; return editingRow; } /** * Returns the actual row that is editing as <code>getEditingRow</code> * will always return -1. */ private int realEditingRow() { return editingRow; } /** Overridden to pass the new rowHeight to the tree. */ public void setRowHeight(int rowHeight) { super.setRowHeight(rowHeight); if (tree != null && tree.getRowHeight() != rowHeight) tree.setRowHeight( rowHeight ); } private int getTreeColumnNumber() { for (int counter = getColumnCount() - 1; counter >= 0;counter--) if (getColumnClass(counter) == TreeTableModel.class) return counter; return -1; } /** <code>isCellEditable</code> returns true for the Tree-Column, even if it is not editable. <code>isCellRealEditable</code> returns true only if the underlying TreeTableModel-Cell is editable. */ private boolean isCellRealEditable(int row,int column) { TreePath treePath = tree.getPathForRow(row); if (treePath == null) return false; return (((TreeTableModel)tree.getModel()).isCellEditable(treePath.getLastPathComponent() ,column)); } class RendererTree extends JTree implements TableCellRenderer { private static final long serialVersionUID = 1L; protected int rowToPaint; Color borderColor = Color.gray; /** Border to draw around the tree, if this is non-null, it will * be painted. */ protected Border highlightBorder; public RendererTree() { super(); } public void setRowHeight(int rowHeight) { if (rowHeight > 0) { super.setRowHeight(rowHeight); if ( JTreeTable.this.getRowHeight() != rowHeight) { JTreeTable.this.setRowHeight(getRowHeight()); } } } // Move and resize the tree to the table position public void setBounds( int x, int y, int w, int h ) { super.setBounds( x, 0, w, JTreeTable.this.getHeight() ); } public void paintEditorBackground(Graphics g,int row) { tree.rowToPaint = row; g.translate( 0, -row * getRowHeight()); Rectangle rect = g.getClipBounds(); if (rect.width >0 && rect.height >0) super.paintComponent(g); g.translate( 0, row * getRowHeight()); } // start painting at the rowToPaint public void paint( Graphics g ) { int row = rowToPaint; g.translate( 0, -rowToPaint * getRowHeight() ); super.paint(g); int x = 0; TreePath path = getPathForRow(row); Object value = path.getLastPathComponent(); boolean isSelected = tree.isRowSelected(row); x = tree.getRowBounds(row).x; if (treeCellEditor != null) { x += treeCellEditor.getGap(tree,value,isSelected,row); } else { TreeCellRenderer tcr = getCellRenderer(); if (tcr instanceof DefaultTreeCellRenderer) { DefaultTreeCellRenderer dtcr = ((DefaultTreeCellRenderer)tcr); // super.paint must have been called before x += dtcr.getIconTextGap() + dtcr.getIcon().getIconWidth(); } } // Draw the Table border if we have focus. if (highlightBorder != null) { highlightBorder.paintBorder(this, g, x, rowToPaint * getRowHeight(), getWidth() -x, getRowHeight() ); } // Paint the selection rectangle } public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Color background; Color foreground; if (hasFocus) focusedRow = row; if(isSelected) { background = table.getSelectionBackground(); foreground = table.getSelectionForeground(); } else { background = table.getBackground(); foreground = table.getForeground(); } highlightBorder = null; if (realEditingRow() == row && getEditingColumn() == column) { background = UIManager.getColor("Table.focusCellBackground"); foreground = UIManager.getColor("Table.focusCellForeground"); } else if (hasFocus) { highlightBorder = UIManager.getBorder ("Table.focusCellHighlightBorder"); if (isCellRealEditable(row,convertColumnIndexToModel(column))) { background = UIManager.getColor ("Table.focusCellBackground"); foreground = UIManager.getColor ("Table.focusCellForeground"); } } this.rowToPaint = row; setBackground(background); TreeCellRenderer tcr = getCellRenderer(); if (tcr instanceof DefaultTreeCellRenderer) { DefaultTreeCellRenderer dtcr = ((DefaultTreeCellRenderer)tcr); if (isSelected) { dtcr.setTextSelectionColor(foreground); dtcr.setBackgroundSelectionColor(background); } else { dtcr.setTextNonSelectionColor(foreground); dtcr.setBackgroundNonSelectionColor(background); } } return this; } } class DelegationgTreeCellEditor implements TableCellEditor { TreeTableEditor delegate; JComponent lastComp = null; int textOffset = 0; MouseListener mouseListener = new MouseAdapter() { public void mouseClicked(MouseEvent evt) { if (lastComp == null) return; if (delegate == null) return; if (evt.getY() < 0 || evt.getY()>lastComp.getHeight()) delegate.stopCellEditing(); // User clicked left from the text if (textOffset > 0 && evt.getX()< textOffset ) delegate.stopCellEditing(); } }; public DelegationgTreeCellEditor(TreeTableEditor delegate) { this.delegate = delegate; } public void addCellEditorListener(CellEditorListener listener) { delegate.addCellEditorListener(listener); } public void removeCellEditorListener(CellEditorListener listener) { delegate.removeCellEditorListener(listener); } public void cancelCellEditing() { delegate.cancelCellEditing(); } public Object getCellEditorValue() { return delegate.getCellEditorValue(); } public boolean stopCellEditing() { return delegate.stopCellEditing(); } public boolean shouldSelectCell(EventObject anEvent) { return true; } private int getTextOffset(Object value,boolean isSelected,int row) { int gap = delegate.getGap(tree,value,isSelected,row); TreePath path = tree.getPathForRow(row); return tree.getUI().getPathBounds(tree,path).x + gap; } public boolean inHitRegion(int x,int y) { int row = tree.getRowForLocation(x,y); TreePath path = tree.getPathForRow(row); if (path == null) return false; int gap = (delegate != null) ? delegate.getGap(tree,null,false,row) :16; return (x - gap >= tree.getUI().getPathBounds(tree,path).x || x<0); } public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { JTreeTable.this.tree.rowToPaint = row; JComponent comp = delegate.getEditorComponent(tree,value,isSelected,row); if (lastComp != comp) { if (comp != null) { comp.removeMouseListener(mouseListener); comp.addMouseListener(mouseListener); } } lastComp = comp; textOffset = getTextOffset(value,isSelected,row); Border outerBorder = new TreeBorder(0, textOffset , 0, 0,row); Border editBorder = UIManager.getBorder("Tree.editorBorder"); Border border = new CompoundBorder(outerBorder ,editBorder ); if ( comp != null) { comp.setBorder(border); } return comp; } public boolean isCellEditable( EventObject evt ) { int col = getTreeColumnNumber(); if( evt instanceof MouseEvent ) { MouseEvent me = (MouseEvent)evt; if (col >= 0) { int xPosRelativeToCell = me.getX() - getCellRect(0, col, true).x; if (me.getClickCount() > 1 && inHitRegion(xPosRelativeToCell,me.getY()) && isCellRealEditable(tree.getRowForLocation(me.getX(),me.getY()) ,convertColumnIndexToModel(col))) return true; MouseEvent newME = new MouseEvent(tree, me.getID(), me.getWhen(), me.getModifiers(), xPosRelativeToCell, me.getY(), me.getClickCount(), me.isPopupTrigger()); if (! inHitRegion(xPosRelativeToCell,me.getY()) || me.getClickCount() > 1) tree.dispatchEvent(newME); } return false; } if (delegate != null && isCellRealEditable(focusedRow,convertColumnIndexToModel(col))) return delegate.isCellEditable(evt); else return false; } } class TreeBorder implements Border { int row; Insets insets; public TreeBorder(int top,int left,int bottom,int right,int row) { this.row = row; insets = new Insets(top,left,bottom,right); } public Insets getBorderInsets(Component c) { return insets; } public void paintBorder(Component c,Graphics g,int x,int y,int width,int height) { Shape originalClip = g.getClip(); g.clipRect(0,0,insets.left -1 ,tree.getHeight()); tree.paintEditorBackground(g,row); g.setClip(originalClip); } public boolean isBorderOpaque() { return false; } } /** * ListToTreeSelectionModelWrapper extends DefaultTreeSelectionModel * to listen for changes in the ListSelectionModel it maintains. Once * a change in the ListSelectionModel happens, the paths are updated * in the DefaultTreeSelectionModel. */ class ListToTreeSelectionModelWrapper extends DefaultTreeSelectionModel implements ListSelectionListener{ private static final long serialVersionUID = 1L; /** Set to true when we are updating the ListSelectionModel. */ protected boolean updatingListSelectionModel; public ListToTreeSelectionModelWrapper() { super(); getListSelectionModel().addListSelectionListener (createListSelectionListener()); } /** * Returns the list selection model. ListToTreeSelectionModelWrapper * listens for changes to this model and updates the selected paths * accordingly. */ ListSelectionModel getListSelectionModel() { return listSelectionModel; } /** * This is overridden to set <code>updatingListSelectionModel</code> * and message super. This is the only place DefaultTreeSelectionModel * alters the ListSelectionModel. */ public void resetRowSelection() { if(!updatingListSelectionModel) { updatingListSelectionModel = true; try { super.resetRowSelection(); } finally { updatingListSelectionModel = false; } } // Notice how we don't message super if // updatingListSelectionModel is true. If // updatingListSelectionModel is true, it implies the // ListSelectionModel has already been updated and the // paths are the only thing that needs to be updated. } /** * Creates and returns an instance of ListSelectionHandler. */ protected ListSelectionListener createListSelectionListener() { return this; } /** * If <code>updatingListSelectionModel</code> is false, this will * reset the selected paths from the selected rows in the list * selection model. */ protected void updateSelectedPathsFromSelectedRows() { if(!updatingListSelectionModel) { updatingListSelectionModel = true; try { // This is way expensive, ListSelectionModel needs an // enumerator for iterating. int min = listSelectionModel.getMinSelectionIndex(); int max = listSelectionModel.getMaxSelectionIndex(); clearSelection(); if(min != -1 && max != -1) { for(int counter = min; counter <= max; counter++) { if(listSelectionModel.isSelectedIndex(counter)) { TreePath selPath = tree.getPathForRow (counter); if(selPath != null) { addSelectionPath(selPath); } } } } } finally { updatingListSelectionModel = false; } } } /** Implemention of ListSelectionListener Interface: * Class responsible for calling updateSelectedPathsFromSelectedRows * when the selection of the list changse. */ public void valueChanged(ListSelectionEvent e) { updateSelectedPathsFromSelectedRows(); } } class TreeTableModelAdapter extends AbstractTableModel implements TreeExpansionListener,TreeModelListener { private static final long serialVersionUID = 1L; TreeTableModel treeTableModel; public TreeTableModelAdapter(TreeTableModel treeTableModel) { this.treeTableModel = treeTableModel; tree.addTreeExpansionListener(this); // Install a TreeModelListener that can update the table when // tree changes. We use delayedFireTableDataChanged as we can // not be guaranteed the tree will have finished processing // the event before us. treeTableModel.addTreeModelListener(this); } // Implementation of TreeExpansionListener public void treeExpanded(TreeExpansionEvent event) { int row = tree.getRowForPath(event.getPath()); if (row + 1 < tree.getRowCount()) fireTableRowsInserted(row + 1,row + 1); } public void treeCollapsed(TreeExpansionEvent event) { int row = tree.getRowForPath(event.getPath()); if (row < getRowCount()) fireTableRowsDeleted(row + 1,row + 1); } // Implementation of TreeModelLstener public void treeNodesChanged(TreeModelEvent e) { int firstRow = 0; int lastRow = tree.getRowCount() -1; delayedFireTableRowsUpdated(firstRow,lastRow); } public void treeNodesInserted(TreeModelEvent e) { delayedFireTableDataChanged(); } public void treeNodesRemoved(TreeModelEvent e) { delayedFireTableDataChanged(); } public void treeStructureChanged(TreeModelEvent e) { delayedFireTableDataChanged(); } // Wrappers, implementing TableModel interface. public int getColumnCount() { return treeTableModel.getColumnCount(); } public String getColumnName(int column) { return treeTableModel.getColumnName(column); } public Class<?> getColumnClass(int column) { return treeTableModel.getColumnClass(column); } public int getRowCount() { return tree.getRowCount(); } private Object nodeForRow(int row) { TreePath treePath = tree.getPathForRow(row); if (treePath == null) return null; return treePath.getLastPathComponent(); } public Object getValueAt(int row, int column) { Object node = nodeForRow(row); if (node == null) return null; return treeTableModel.getValueAt(node, column); } public boolean isCellEditable(int row, int column) { if (getColumnClass(column) == TreeTableModel.class) { return true; } else { Object node = nodeForRow(row); if (node == null) return false; return treeTableModel.isCellEditable(node, column); } } public void setValueAt(Object value, int row, int column) { Object node = nodeForRow(row); if (node == null) return; treeTableModel.setValueAt(value, node, column); } /** * Invokes fireTableDataChanged after all the pending events have been * processed. SwingUtilities.invokeLater is used to handle this. */ protected void delayedFireTableRowsUpdated(int firstRow,int lastRow) { SwingUtilities.invokeLater(new UpdateRunnable(firstRow,lastRow)); } class UpdateRunnable implements Runnable { int lastRow; int firstRow; UpdateRunnable(int firstRow,int lastRow) { this.firstRow = firstRow; this.lastRow = lastRow; } public void run() { fireTableRowsUpdated(firstRow,lastRow); } } /** * Invokes fireTableDataChanged after all the pending events have been * processed. SwingUtilities.invokeLater is used to handle this. */ protected void delayedFireTableDataChanged() { SwingUtilities.invokeLater(new Runnable() { public void run() { fireTableDataChanged(); } }); } } /* public void paintComponent(Graphics g) { super.paintComponent( g ); Rectangle r = g.getClipBounds(); g.setColor( Color.white); g.fillRect(0,0, r.width, r.height ); } */ }
04900db4-rob
src/org/rapla/components/treetable/JTreeTable.java
Java
gpl3
35,563
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.treetable; import javax.swing.CellEditor; import javax.swing.JComponent; import javax.swing.JTree; public interface TreeTableEditor extends CellEditor { JComponent getEditorComponent(JTree tree,Object value,boolean isSelected,int row); int getGap(JTree tree, Object value, boolean isSelected, int row); }
04900db4-rob
src/org/rapla/components/treetable/TreeTableEditor.java
Java
gpl3
1,282
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.treetable; import javax.swing.JTable; public interface TableToolTipRenderer { public String getToolTipText(JTable table, int row, int column); }
04900db4-rob
src/org/rapla/components/treetable/TableToolTipRenderer.java
Java
gpl3
1,115
/* * Sun Microsystems grants you ("Licensee") a non-exclusive, royalty * free, license to use, modify and redistribute this software in * source and binary code form, provided that i) this copyright notice * and license appear on all copies of the software; and ii) Licensee * does not utilize the software in a manner which is disparaging to * Sun Microsystems. * * The software media is distributed on an "As Is" basis, without * warranty. Neither the authors, the software developers nor Sun * Microsystems make any representation, or warranty, either express * or implied, with respect to the software programs, their quality, * accuracy, or fitness for a specific purpose. Therefore, neither the * authors, the software developers nor Sun Microsystems shall have * any liability to you or any other person or entity with respect to * any liability, loss, or damage caused or alleged to have been * caused directly or indirectly by programs contained on the * media. This includes, but is not limited to, interruption of * service, loss of data, loss of classroom time, loss of consulting * or anticipatory *profits, or consequential damages from the use of * these programs. */ package org.rapla.components.treetable; import javax.swing.tree.TreeModel; /** * TreeTableModel is the model used by a JTreeTable. It extends TreeModel * to add methods for getting inforamtion about the set of columns each * node in the TreeTableModel may have. Each column, like a column in * a TableModel, has a name and a type associated with it. Each node in * the TreeTableModel can return a value for each of the columns and * set that value if isCellEditable() returns true. * * @author Philip Milne * @author Scott Violet */ public interface TreeTableModel extends TreeModel { /** * Returns the number ofs available columns. */ public int getColumnCount(); /** * Returns the name for column number <code>column</code>. */ public String getColumnName(int column); /** * Returns the type for column number <code>column</code>. * Should return TreeTableModel.class for the tree-column. */ public Class<?> getColumnClass(int column); /** * Returns the value to be displayed for node <code>node</code>, * at column number <code>column</code>. */ public Object getValueAt(Object node, int column); /** * Indicates whether the the value for node <code>node</code>, * at column number <code>column</code> is editable. */ public boolean isCellEditable(Object node, int column); /** * Sets the value for node <code>node</code>, * at column number <code>column</code>. */ public void setValueAt(Object aValue, Object node, int column); }
04900db4-rob
src/org/rapla/components/treetable/TreeTableModel.java
Java
gpl3
2,792
<body> Contains all classes for the treetable widget. </body>
04900db4-rob
src/org/rapla/components/treetable/package.html
HTML
gpl3
65
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.xmlbundle; import java.util.Locale; import java.util.MissingResourceException; import javax.swing.ImageIcon; /** Allows the combination of two resource-bundles. First the inner bundle will be searched. If the requested resource was not found the outer bundle will be searched. */ public class CompoundI18n implements I18nBundle { I18nBundle inner; I18nBundle outer; public CompoundI18n(I18nBundle inner,I18nBundle outer) { this.inner = inner; this.outer = outer; } public String format(String key,Object obj1) { Object[] array1 = new Object[1]; array1[0] = obj1; return format(key,array1); } public String format(String key,Object obj1,Object obj2) { Object[] array2 = new Object[2]; array2[0] = obj1; array2[1] = obj2; return format(key,array2); } @Override public String format(String key,Object[] obj) { try { return inner.format(key, obj); } catch (MissingResourceException ex) { return outer.format( key, obj); } } public ImageIcon getIcon(String key) { try { return inner.getIcon(key); } catch (MissingResourceException ex) { return outer.getIcon(key); } } public String getString(String key) { try { return inner.getString(key); } catch (MissingResourceException ex) { return outer.getString(key); } } public String getLang() { return inner.getLang(); } public Locale getLocale() { return inner.getLocale(); } public String getString(String key, Locale locale) { try { return inner.getString(key,locale); } catch (MissingResourceException ex) { return outer.getString(key, locale); } } }
04900db4-rob
src/org/rapla/components/xmlbundle/CompoundI18n.java
Java
gpl3
2,776
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.xmlbundle; import java.util.EventListener; public interface LocaleChangeListener extends EventListener{ void localeChanged(LocaleChangeEvent evt); }
04900db4-rob
src/org/rapla/components/xmlbundle/LocaleChangeListener.java
Java
gpl3
1,119
package org.rapla.components.xmlbundle.impl; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.util.Enumeration; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Properties; import java.util.ResourceBundle; import java.util.Set; import java.util.Vector; public class PropertyResourceBundleWrapper extends ResourceBundle { private Map<String,Object> lookup; String name; static Charset charset = Charset.forName("UTF-8"); @SuppressWarnings({ "unchecked", "rawtypes" }) public PropertyResourceBundleWrapper(InputStream stream,String name) throws IOException { Properties properties = new Properties(); properties.load(new InputStreamReader(stream, charset)); lookup = new LinkedHashMap(properties); this.name = name; } public String getName() { return name; } // We make the setParent method public, so that we can use it in I18nImpl public void setParent(ResourceBundle parent) { super.setParent(parent); } // Implements java.util.ResourceBundle.handleGetObject; inherits javadoc specification. public Object handleGetObject(String key) { if (key == null) { throw new NullPointerException(); } return lookup.get(key); } /** * Returns an <code>Enumeration</code> of the keys contained in * this <code>ResourceBundle</code> and its parent bundles. * * @return an <code>Enumeration</code> of the keys contained in * this <code>ResourceBundle</code> and its parent bundles. * @see #keySet() */ public Enumeration<String> getKeys() { ResourceBundle parent = this.parent; Set<String> set = new LinkedHashSet<String>(lookup.keySet()); if ( parent != null) { set.addAll( parent.keySet()); } Vector<String> vector = new Vector<String>(set); Enumeration<String> enum1 = vector.elements(); return enum1; } /** * Returns a <code>Set</code> of the keys contained * <em>only</em> in this <code>ResourceBundle</code>. * * @return a <code>Set</code> of the keys contained only in this * <code>ResourceBundle</code> * @since 1.6 * @see #keySet() */ protected Set<String> handleKeySet() { return lookup.keySet(); } // ==================privates==================== }
04900db4-rob
src/org/rapla/components/xmlbundle/impl/PropertyResourceBundleWrapper.java
Java
gpl3
2,578
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.xmlbundle.impl; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.net.URL; import java.text.MessageFormat; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.TreeMap; import javax.swing.Icon; import javax.swing.ImageIcon; import org.rapla.components.util.IOUtil; import org.rapla.components.xmlbundle.I18nBundle; import org.rapla.components.xmlbundle.LocaleChangeEvent; import org.rapla.components.xmlbundle.LocaleChangeListener; import org.rapla.components.xmlbundle.LocaleSelector; import org.rapla.framework.Configuration; import org.rapla.framework.DefaultConfiguration; import org.rapla.framework.Disposable; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.framework.logger.Logger; /** The default implementation of the xmlbundle component allows reading from a compiled ResourceBundle as well as directly from the source-xml-file. <p> Sample Configuration 1: (Resources are loaded from the compiled ResourceBundles) <pre> &lt;resource-bundle id="org.rapla.RaplaResources"/> </pre> </p> <p> Sample Configuration 2: (Resources will be loaded directly from the resource-file) <pre> &lt;resource-bundle id="org.rapla.plugin.periodwizard.WizardResources"> &lt;file>/home/christopher/Rapla/src/org/rapla/periodwizard/WizardResources.xml&lt;/file> &lt;/resource-bundle> </pre> </p> <p> This class looks for a LocaleSelector on the context and registers itself as a LocaleChangeListener and switches to the new Locale on a LocaleChangeEvent. </p> @see TranslationParser @see LocaleSelector */ public class I18nBundleImpl implements I18nBundle, LocaleChangeListener, Disposable { String className; Locale locale; Logger logger = null; LocaleSelectorImpl m_localeSelector; final String dictionaryFile; final RaplaDictionary dict; LinkedHashMap<Locale,LanguagePack> packMap = new LinkedHashMap<Locale,LanguagePack>(); String parentId = null; class LanguagePack { Locale locale; Map<String,Icon> iconCache = Collections.synchronizedMap( new TreeMap<String,Icon>() ); ResourceBundle resourceBundle; public String getString( String key ) throws MissingResourceException { String lang = locale.getLanguage(); if ( dictionaryFile != null ) { String lookup = dict.lookup(key, lang); if ( lookup == null) { throw new MissingResourceException("Entry not found for "+ key, dictionaryFile, key); } return lookup; } DictionaryEntry entry = dict.getEntry(key); String string; if ( entry != null) { string = entry.get( lang ); if ( string == null ) { string = resourceBundle.getString( key ); entry.add(lang, key); } } else { string = resourceBundle.getString( key ); entry = new DictionaryEntry( key); entry.add(lang, string); try { dict.addEntry( entry); } catch (UniqueKeyException e) { // we can ignore it here } } return string; } public ImageIcon getIcon( String key ) throws MissingResourceException { String iconfile; try { iconfile = getString( key ); } catch ( MissingResourceException ex ) { getLogger().debug( ex.getMessage() ); //BJO throw ex; } try { ImageIcon icon = (ImageIcon) iconCache.get( iconfile ); if ( icon == null ) { icon = new ImageIcon( loadResource( iconfile ), key ); iconCache.put( iconfile, icon ); } // end of if () return icon; } catch ( Exception ex ) { String message = "Icon " + iconfile + " can't be created: " + ex.getMessage(); getLogger().error( message ); throw new MissingResourceException( message, className, key ); } } private final byte[] loadResource( String fileName ) throws IOException { return IOUtil.readBytes( getResourceFromFile( fileName ) ); } private URL getResourceFromFile( String fileName ) throws IOException { URL resource = null; String base; if ( dictionaryFile == null ) { if ( resourceBundle == null) { throw new IOException("Resource Bundle for locale " + locale + " is missing while looking up " + fileName); } if ( resourceBundle instanceof PropertyResourceBundleWrapper) { base = ((PropertyResourceBundleWrapper) resourceBundle).getName(); } else { base = resourceBundle.getClass().getName(); } base = base.substring(0,base.lastIndexOf(".")); base = base.replaceAll("\\.", "/"); String file = "/" + base + "/" + fileName; resource = I18nBundleImpl.class.getResource( file ); } else { if ( getLogger().isDebugEnabled() ) getLogger().debug( "Looking for resourcefile " + fileName + " in classpath "); URL resourceBundleURL = getClass().getClassLoader().getResource(dictionaryFile); if (resourceBundleURL != null) { resource = new URL( resourceBundleURL, fileName); base = resource.getPath(); } else { base = ( new File( dictionaryFile ) ).getParent(); if ( base != null) { if ( getLogger().isDebugEnabled() ) getLogger().debug( "Looking for resourcefile " + fileName + " in directory " + base ); File resourceFile = new File( base, fileName ); if ( resourceFile.exists() ) resource = resourceFile.toURI().toURL(); } } } if ( resource == null ) throw new IOException( "File '" + fileName + "' not found. " + " in bundle " + className + " It must be in the same location as '" + base + "'" ); return resource; } } /** * @throws RaplaException when the resource-file is missing or can't be accessed or can't be parsed */ public I18nBundleImpl( RaplaContext context, Configuration config, Logger logger ) throws RaplaException { enableLogging( logger ); Locale locale; m_localeSelector = (LocaleSelectorImpl) context.lookup( LocaleSelector.class ) ; if ( m_localeSelector != null ) { m_localeSelector.addLocaleChangeListenerFirst( this ); locale = m_localeSelector.getLocale(); } else { locale = Locale.getDefault(); } String filePath = config.getChild( "file" ).getValue( null ); try { InputStream resource; if ( filePath == null ) { className = config.getChild( "classname" ).getValue( null ); if ( className == null ) { className = config.getAttribute( "id" ); } else { className = className.trim(); } String resourceFile = "" + className.replaceAll("\\.", "/") + ".xml"; resource = getClass().getClassLoader().getResourceAsStream(resourceFile); dictionaryFile = resource != null ? resourceFile : null; } else { File file = new File( filePath); getLogger().info( "getting lanaguageResources from " + file.getCanonicalPath() ); resource = new FileInputStream( file ); dictionaryFile = filePath; } if ( resource != null) { dict = new TranslationParser().parse( resource ); resource.close(); } else { dict = new RaplaDictionary(locale.getLanguage()); } } catch ( Exception ex ) { throw new RaplaException( ex ); } setLocale( locale ); try { parentId = getPack(locale).getString( TranslationParser.PARENT_BUNDLE_IDENTIFIER ); } catch ( MissingResourceException ex ) { } } public String getParentId() { return parentId; } public static Configuration createConfig( String resourceFile ) { DefaultConfiguration config = new DefaultConfiguration( "component"); config.setAttribute( "id", resourceFile.toString() ); return config; } public void dispose() { if ( m_localeSelector != null ) m_localeSelector.removeLocaleChangeListener( this ); } public void localeChanged( LocaleChangeEvent evt ) { try { setLocale( evt.getLocale() ); } catch ( Exception ex ) { getLogger().error( "Can't set new locale " + evt.getLocale(), ex ); } } public void enableLogging( Logger logger ) { this.logger = logger; } protected Logger getLogger() { return logger; } public String format( String key, Object obj1 ) { Object[] array1 = new Object[1]; array1[0] = obj1; return format( key, array1 ); } public String format( String key, Object obj1, Object obj2 ) { Object[] array2 = new Object[2]; array2[0] = obj1; array2[1] = obj2; return format( key, array2 ); } public String format( String key, Object... obj ) { MessageFormat msg = new MessageFormat( getString( key ) ); return msg.format( obj ); } public ImageIcon getIcon( String key ) throws MissingResourceException { ImageIcon icon = getPack(getLocale()).getIcon( key); return icon; } public Locale getLocale() { if ( locale == null ) throw new IllegalStateException( "Call setLocale first!" ); return locale; } public String getLang() { if ( locale == null ) throw new IllegalStateException( "Call setLocale first!" ); return locale.getLanguage(); } public String getString( String key ) throws MissingResourceException { if ( locale == null ) throw new IllegalStateException( "Call setLocale first!" ); return getString(key, locale); } public String getString( String key, Locale locale) throws MissingResourceException { LanguagePack pack = getPack(locale); return pack.getString(key); } // /* replaces XHTML with HTML because swing can't display proper XHTML*/ // String filterXHTML( String text ) // { // if ( text.indexOf( "<br/>" ) >= 0 ) // { // return applyXHTMLFilter( text ); // } // else // { // return text; // } // end of else // } // public static String replaceAll( String text, String token, String with ) // { // StringBuffer buf = new StringBuffer(); // int i = 0; // int lastpos = 0; // while ( ( i = text.indexOf( token, lastpos ) ) >= 0 ) // { // if ( i > 0 ) // buf.append( text.substring( lastpos, i ) ); // buf.append( with ); // i = ( lastpos = i + token.length() ); // } // end of if () // buf.append( text.substring( lastpos, text.length() ) ); // return buf.toString(); // } // // private String applyXHTMLFilter( String text ) // { // return replaceAll( text, "<br/>", "<br></br>" ); // } public void setLocale( Locale locale ) { this.locale = locale; getLogger().debug( "Locale changed to " + locale ); try { getPack(locale); } catch (MissingResourceException ex) { getLogger().error(ex.getMessage(), ex); } } private LanguagePack getPack(Locale locale) throws MissingResourceException { LanguagePack pack = packMap.get(locale); if (pack != null) { return pack; } synchronized ( packMap ) { // again, now with synchronization pack = packMap.get(locale); if (pack != null) { return pack; } pack = new LanguagePack(); pack.locale = locale; if ( dictionaryFile == null ) { pack.resourceBundle = new ResourceBundleLoader().loadResourceBundle( className, locale ); } packMap.put( locale, pack); return pack; } } } class ResourceBundleLoader { /** this method imitates the orginal * <code>ResourceBundle.getBundle(String className,Locale * locale)</code> which causes problems when the locale is changed * to the base locale (english). For a full description see * ResourceBundle.getBundle(String className) in the java-api.*/ public ResourceBundle loadResourceBundle( String className, Locale locale ) throws MissingResourceException { String tries[] = new String[7]; StringBuffer buf = new StringBuffer(); tries[6] = className; buf.append( className ); if ( locale.getLanguage().length() > 0 ) { buf.append( '_' ); buf.append( locale.getLanguage() ); tries[2] = buf.toString(); } if ( locale.getCountry().length() > 0 ) { buf.append( '_' ); buf.append( locale.getCountry() ); tries[1] = buf.toString(); } if ( locale.getVariant().length() > 0 ) { buf.append( '_' ); buf.append( locale.getVariant() ); tries[0] = buf.toString(); } buf.delete( className.length(), buf.length() - 1 ); Locale defaultLocale = Locale.getDefault(); if ( defaultLocale.getLanguage().length() > 0 ) { buf.append( defaultLocale.getLanguage() ); tries[5] = buf.toString(); } if ( defaultLocale.getCountry().length() > 0 ) { buf.append( '_' ); buf.append( defaultLocale.getCountry() ); tries[4] = buf.toString(); } if ( defaultLocale.getVariant().length() > 0 ) { buf.append( '_' ); buf.append( defaultLocale.getVariant() ); tries[3] = buf.toString(); } ResourceBundle bundle = null; for ( int i = 0; i < tries.length; i++ ) { if ( tries[i] == null ) continue; bundle = loadBundle( tries[i] ); if ( bundle != null ) { loadParent( tries, i, bundle ); return bundle; } } throw new MissingResourceException( "'" + className + "' not found. The resource-file is missing.", className, "" ); } private ResourceBundle loadBundle( String name ) { InputStream io = null; try { String pathName = getPropertyFileNameFromClassName( name ); io = this.getClass().getResourceAsStream( pathName ); if ( io != null ) { return new PropertyResourceBundleWrapper(io , name); } ResourceBundle bundle = (ResourceBundle) this.getClass().getClassLoader().loadClass( name ).newInstance(); return bundle; } catch ( Exception ex ) { return null; } catch ( ClassFormatError ex ) { return null; } finally { if ( io != null) { try { io.close(); } catch (IOException e) { return null; } } } } private void loadParent( String[] tries, int i, ResourceBundle bundle ) { ResourceBundle parent = null; if ( i == 0 || i == 3 ) { parent = loadBundle( tries[i++] ); if ( parent != null ) setParent( bundle, parent ); bundle = parent; } if ( i == 1 || i == 4 ) { parent = loadBundle( tries[i++] ); if ( parent != null ) setParent( bundle, parent ); bundle = parent; } if ( i == 2 || i == 5 ) { parent = loadBundle( tries[6] ); if ( parent != null ) setParent( bundle, parent ); } } private void setParent( ResourceBundle bundle, ResourceBundle parent ) { try { Method method = bundle.getClass().getMethod( "setParent", new Class[] { ResourceBundle.class } ); method.invoke( bundle, new Object[] { parent } ); } catch ( Exception ex ) { } } private String getPropertyFileNameFromClassName( String classname ) { StringBuffer result = new StringBuffer( classname ); for ( int i = 0; i < result.length(); i++ ) { if ( result.charAt( i ) == '.' ) result.setCharAt( i, '/' ); } result.insert( 0, '/' ); result.append( ".properties" ); return result.toString(); } }
04900db4-rob
src/org/rapla/components/xmlbundle/impl/I18nBundleImpl.java
Java
gpl3
19,002
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.xmlbundle.impl; import java.util.Collections; import java.util.Iterator; import java.util.Map; import java.util.TreeMap; class DictionaryEntry { String key; Map<String,String> translations = Collections.synchronizedMap(new TreeMap<String,String>()); public DictionaryEntry(String key) { this.key = key; } public void add(String lang,String value) { translations.put(lang,value); } public String getKey() { return key; } public String get(String lang) { return translations.get(lang); } public String get(String lang,String defaultLang) { String content = translations.get(lang); if ( content == null) { content = translations.get(defaultLang); } // end of if () if ( content == null) { Iterator<String> it = translations.values().iterator(); content = it.next(); } return content; } public String[] availableLanguages() { String[] result = new String[translations.keySet().size()]; Iterator<String> it = translations.keySet().iterator(); int i = 0; while ( it.hasNext()) { result[i++] = it.next(); } return result; } }
04900db4-rob
src/org/rapla/components/xmlbundle/impl/DictionaryEntry.java
Java
gpl3
2,234
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.xmlbundle.impl; /** thrown by the RaplaDictionary when a duplicated entry is found */ class UniqueKeyException extends Exception { private static final long serialVersionUID = 1L; public UniqueKeyException(String text) { super(text); } }
04900db4-rob
src/org/rapla/components/xmlbundle/impl/UniqueKeyException.java
Java
gpl3
1,233
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.xmlbundle.impl; import java.util.ArrayList; import java.util.Collection; import java.util.Map; import java.util.TreeMap; class RaplaDictionary { Map<String,DictionaryEntry> entries = new TreeMap<String,DictionaryEntry>(); Collection<String> availableLang = new ArrayList<String>(); String defaultLang; public RaplaDictionary(String defaultLang) { this.defaultLang = defaultLang; } public void addEntry(DictionaryEntry entry) throws UniqueKeyException { if ( entries.get(entry.getKey()) != null) { throw new UniqueKeyException("Key '" + entry.getKey() + "' already in map."); } // end of if () String[] lang = entry.availableLanguages(); for ( int i = 0; i<lang.length;i++) if (!availableLang.contains(lang[i])) availableLang.add(lang[i]); entries.put(entry.getKey(),entry); } public Collection<DictionaryEntry> getEntries() { return entries.values(); } public String getDefaultLang() { return defaultLang; } public String[] getAvailableLanguages() { return availableLang.toArray(new String[0]); } public String lookup(String key,String lang) { DictionaryEntry entry = getEntry(key); if ( entry != null) { return entry.get(lang,defaultLang); } else { return null; } // end of else } public DictionaryEntry getEntry(String key) { return entries.get(key); } }
04900db4-rob
src/org/rapla/components/xmlbundle/impl/RaplaDictionary.java
Java
gpl3
2,486
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.xmlbundle.impl; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Collections; import java.util.Enumeration; import java.util.HashSet; import java.util.Iterator; import java.util.Properties; import java.util.Set; import java.util.Stack; import java.util.Vector; import org.rapla.framework.ConfigurationException; import org.rapla.framework.logger.ConsoleLogger; import org.rapla.framework.logger.Logger; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; class ResourceFileGenerator { public static final String encoding = "UTF-8"; static Logger log = new ConsoleLogger( ConsoleLogger.LEVEL_INFO ); boolean writeProperties = true; public void transform(RaplaDictionary dict ,String packageName ,String classPrefix ,File destDir ) throws IOException { String[] languages = dict.getAvailableLanguages(); for (String lang:languages) { String className = classPrefix; if (!lang.equals(dict.getDefaultLang())) { className += "_" + lang; } String ending = writeProperties ? ".properties" : ".java"; File file = new File(destDir, className + ending); PrintWriter w = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),encoding))); if ( writeProperties) { Properties properties = new Properties(); Iterator<DictionaryEntry> it = dict.getEntries().iterator(); while ( it.hasNext()) { DictionaryEntry entry = it.next(); String key = entry.getKey(); String value = entry.get(lang); if ( value != null) { properties.put(key, value); } } @SuppressWarnings("serial") Properties temp = new Properties() { @SuppressWarnings({ "rawtypes", "unchecked" }) public synchronized Enumeration keys() { Enumeration<Object> keysEnum = super.keys(); Vector keyList = new Vector<Object>(); while(keysEnum.hasMoreElements()){ keyList.add(keysEnum.nextElement()); } Collections.sort(keyList); return keyList.elements(); } }; temp.putAll( properties); String comment = packageName + "." + className + "_" + lang; temp.store(w, comment); } else { generateJavaHeader(w,packageName); generateJavaContent(w,dict, className, lang); } w.flush(); w.close(); } } // public void transformSingleLanguage(RaplaDictionary dict // ,String packageName // ,String classPrefix // ,String lang // ) { // String className = classPrefix + "_" + lang; // w = new PrintWriter(System.out); // generateHeader(packageName); // generateContent(dict,className, lang); // w.flush(); // } public static String toPackageName(String pathName) { StringBuffer buf = new StringBuffer(); char[] c =pathName.toCharArray(); for (int i=0;i<c.length;i++) { if (c[i] == File.separatorChar ) { if (i>0 && i<c.length-1) buf.append('.'); } else { buf.append(c[i]); } } return buf.toString(); } private void generateJavaHeader(PrintWriter w, String packageName) { w.println("/*******************************************"); w.println(" * Autogenerated file. Please do not edit. *"); w.println(" * Edit the *Resources.xml file. *"); w.println(" *******************************************/"); w.println(); w.println("package " + packageName + ";"); } private void generateJavaContent(PrintWriter w, RaplaDictionary dict ,String className ,String lang ) { w.println("import java.util.ListResourceBundle;"); w.println("import java.util.ResourceBundle;"); w.println(); w.println("public class " + className + " extends ListResourceBundle {"); w.println(" public Object[][] getContents() { return contents; }"); // We make the setParent method public, so that we can use it in I18nImpl w.println(" public void setParent(ResourceBundle parent) { super.setParent(parent); }"); w.println(" static final Object[][] contents = { {\"\",\"\"} "); Iterator<DictionaryEntry> it = dict.getEntries().iterator(); while ( it.hasNext()) { DictionaryEntry entry = it.next(); String value = entry.get(lang); if (value != null) { String content = convertToJava(value); w.println(" , { \"" + entry.getKey() + "\",\"" + content + "\"}"); } } w.println(" };"); w.println("}"); } static public String byteToHex(byte b) { // Returns hex String representation of byte b char hexDigit[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; char[] array = { hexDigit[(b >> 4) & 0x0f], hexDigit[b & 0x0f] }; return new String(array); } static public String charToHex(char c) { // Returns hex String representation of char c byte hi = (byte) (c >>> 8); byte lo = (byte) (c & 0xff); return byteToHex(hi) + byteToHex(lo); } private String convertToJava(String text) { StringBuffer result = new StringBuffer(); for ( int i = 0;i< text.length();i++) { char c = text.charAt(i); switch ( c) { case '\n': // LineBreaks result.append("\" \n + \""); break; case '\\': // \ result.append("\\\\"); break; case '\"': // " result.append("\\\""); break; default: if ( c > 127) { result.append("\\u" + charToHex(c)); } else { result.append(c); } // end of else break; } // end of switch () } // end of for () return result.toString(); } public static final String USAGE = new String( "Usage : \n" + "PATH_TO_SOURCES [DESTINATION_PATH]\n" + "Example usage under windows:\n" + "java -classpath build\\classes " + "org.rapla.components.xmlbundle.ResourceFileGenerator " + "src \n" ); public static void processDir( String srcDir, String destDir ) throws IOException, SAXException, ConfigurationException { TranslationParser parser = new TranslationParser(); ResourceFileGenerator generator = new ResourceFileGenerator(); Set<String> languages = new HashSet<String>(); Stack<File> stack = new Stack<File>(); File topDir = new File( srcDir ); stack.push( topDir ); while ( !stack.empty() ) { File file = stack.pop(); if ( file.isDirectory() ) { // System.out.println("Checking Dir: " + file.getName()); File[] files = file.listFiles(); for ( int i = 0; i < files.length; i++ ) stack.push( files[i] ); } else { // System.out.println("Checking File: " + file.getName()); if ( file.getName().endsWith( "Resources.xml" ) ) { String absolut = file.getAbsolutePath(); System.out.println( "Transforming source:" + file ); String relativePath = absolut.substring( topDir.getAbsolutePath().length() ); String prefix = file.getName().substring( 0, file.getName().length() - "Resources.xml".length() ); String pathName = relativePath.substring( 0, relativePath.indexOf( file.getName() ) ); RaplaDictionary dict = parser.parse( file.toURI().toURL().toExternalForm() ); File dir = new File( destDir, pathName ); System.out.println( "destination:" + dir ); dir.mkdirs(); String packageName = ResourceFileGenerator.toPackageName( pathName ); generator.transform( dict, packageName, prefix + "Resources", dir ); String[] langs = dict.getAvailableLanguages(); for ( int i = 0; i < langs.length; i++ ) languages.add( langs[i] ); } } } } public static void main( String[] args ) { try { if ( args.length < 1 ) { System.out.println( USAGE ); return; } // end of if () String sourceDir = args[0]; String destDir = ( args.length > 1 ) ? args[1] : sourceDir; processDir( sourceDir, destDir ); } catch ( SAXParseException ex ) { log.error( "Line:" + ex.getLineNumber() + " Column:" + ex.getColumnNumber() + " " + ex.getMessage(), ex ); System.exit( 1 ); } catch ( Throwable e ) { log.error( e.getMessage(), e ); System.exit( 1 ); } } // end of main () }
04900db4-rob
src/org/rapla/components/xmlbundle/impl/ResourceFileGenerator.java
Java
gpl3
11,079
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.xmlbundle.impl; import java.io.IOException; import java.io.InputStream; import java.net.URL; import org.rapla.components.util.Assert; import org.rapla.components.util.IOUtil; import org.rapla.components.util.xml.XMLReaderAdapter; import org.rapla.framework.ConfigurationException; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; /** This class reads *Resources.xml files and generates the appropriate ResourceBundle java-files. <pre> Usage : org.rapla.components.xmlbundle.TranslationParser PATH_TO_SOURCES [DESTINATION_PATH] Note: a xml-parser must be on your classpath. Example usage under windows: java -classpath lib\saxon.jar;lib\fortress.jar;build\classes org.rapla.components.xmlbundle.TranslationParser src </pre> */ public class TranslationParser extends DefaultHandler { RaplaDictionary dict; DictionaryEntry currentEntry = null; String currentLang = null; String defaultLang = null; String currentIconSrc = null; int level = 0; // used to store the nested content in the translation element StringBuffer charBuffer; XMLReader xmlReader; /** The translation parser will add an extra identifer {$i18nbundle_parent$} to the translation table if a parentbundle is specified. */ public final static String PARENT_BUNDLE_IDENTIFIER = "{$i18nbundle_parent$}"; DefaultHandler handler = new DefaultHandler() { public InputSource resolveEntity( String publicId, String systemId ) throws SAXException { if ( systemId.endsWith( "resources.dtd" ) ) { try { URL resource = getClass().getResource( "/org/rapla/components/xmlbundle/resources.dtd" ); Assert.notNull( resource, "resources.dtd not found on classpath" ); return new InputSource( IOUtil.getInputStream( resource ) ); } catch ( IOException ex ) { throw new SAXException( ex ); } } else { // use the default behaviour try { return super.resolveEntity( publicId, systemId ); } catch ( SAXException ex ) { throw ex; } catch ( Exception ex ) { throw new SAXException( ex ); } } } public void startElement( String uri, String name, String qName, Attributes atts ) throws SAXException { // if ( log.isDebugEnabled() ) // log.debug( indent() + "Start element: " + qName + "(" + name + ")" ); level: { if ( name.equals( "resources" ) ) { String defaultLang = atts.getValue( "", "default" ); String parentDict = atts.getValue( "", "parent" ); dict = new RaplaDictionary( defaultLang ); if ( parentDict != null && parentDict.trim().length() > 0 ) { DictionaryEntry entry = new DictionaryEntry( PARENT_BUNDLE_IDENTIFIER ); entry.add( "en", parentDict.trim() ); try { dict.addEntry( entry ); } catch ( UniqueKeyException ex ) { //first entry must be unique } } break level; } if ( name.equals( "entry" ) ) { String key = atts.getValue( "", "key" ); currentEntry = new DictionaryEntry( key ); break level; } if ( name.equals( "text" ) ) { currentLang = atts.getValue( "", "lang" ); if ( currentLang == null ) currentLang = dict.getDefaultLang(); charBuffer = new StringBuffer(); break level; } if ( name.equals( "icon" ) ) { currentLang = atts.getValue( "", "lang" ); if ( currentLang == null ) currentLang = dict.getDefaultLang(); currentIconSrc = atts.getValue( "", "src" ); charBuffer = new StringBuffer(); break level; } // copy startag if ( charBuffer != null ) { copyStartTag( name, atts ); } } level++; } public void endElement( String uri, String name, String qName ) throws SAXException { level--; // if ( log.isDebugEnabled() ) // log.debug( indent() + "End element: " + qName + "(" + name + ")" ); level: { if ( name.equals( "icon" ) ) { if ( currentIconSrc != null ) currentEntry.add( currentLang, currentIconSrc ); break level; } if ( name.equals( "text" ) ) { removeWhiteSpaces( charBuffer ); currentEntry.add( currentLang, charBuffer.toString() ); break level; } if ( name.equals( "entry" ) ) { try { dict.addEntry( currentEntry ); } catch ( UniqueKeyException e ) { throw new SAXException( e.getMessage() ); } // end of try-catch currentEntry = null; break level; } // copy endtag if ( charBuffer != null ) { copyEndTag( name ); } // end of if () } } public void characters( char ch[], int start, int length ) { // copy nested content if ( charBuffer != null ) { charBuffer.append( ch, start, length ); } // end of if () } }; TranslationParser() throws ConfigurationException { super(); try { xmlReader = XMLReaderAdapter.createXMLReader( false ); xmlReader.setContentHandler( handler ); xmlReader.setErrorHandler( handler ); xmlReader.setDTDHandler( handler ); xmlReader.setEntityResolver( handler ); } catch ( SAXException ex ) { if ( ex.getException() != null ) { throw new ConfigurationException( "", ex.getException() ); } else { throw new ConfigurationException( "", ex ); } // end of else } } RaplaDictionary parse( InputStream in ) throws IOException, SAXException { dict = null; xmlReader.parse( new InputSource( in ) ); checkDict(); return dict; } RaplaDictionary parse( String systemID ) throws IOException, SAXException { dict = null; xmlReader.parse( systemID ); checkDict(); return dict; } private void checkDict() throws IOException { if ( dict == null ) { throw new IOException( "Dictionary file empty " ); } } private void copyStartTag( String name, Attributes atts ) { charBuffer.append( '<' ); charBuffer.append( name ); for ( int i = 0; i < atts.getLength(); i++ ) { charBuffer.append( ' ' ); charBuffer.append( atts.getLocalName( i ) ); charBuffer.append( '=' ); charBuffer.append( '\"' ); charBuffer.append( atts.getValue( i ) ); charBuffer.append( '\"' ); } charBuffer.append( '>' ); } private void copyEndTag( String name ) { if ( ( charBuffer != null ) && ( charBuffer.length() > 0 ) && ( charBuffer.charAt( charBuffer.length() - 1 ) == '>' ) ) { // <some-tag></some-tag> --> <some-tag/> charBuffer.insert( charBuffer.length() - 1, "/" ); } else { // </some-tag> charBuffer.append( "</" + name + ">" ); } // end of else } private void removeWhiteSpaces( StringBuffer buf ) { for ( int i = 1; i < buf.length(); i++ ) { if ( ( buf.charAt( i ) == ' ' ) && ( buf.charAt( i - 1 ) == ' ' ) ) buf.deleteCharAt( --i ); } // end of for () } /** @deprecated moved to {@link ResourceFileGenerator}*/ @Deprecated public static void main( String[] args ) { ResourceFileGenerator.main(args); } }
04900db4-rob
src/org/rapla/components/xmlbundle/impl/TranslationParser.java
Java
gpl3
10,387
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.xmlbundle.impl; import java.util.Locale; import java.util.Vector; import org.rapla.components.xmlbundle.LocaleChangeEvent; import org.rapla.components.xmlbundle.LocaleChangeListener; import org.rapla.components.xmlbundle.LocaleSelector; /** If you want to change the locales during runtime put a LocaleSelector in the base-context. Instances of {@link I18nBundleImpl} will then register them-self as {@link LocaleChangeListener LocaleChangeListeners}. Change the locale with {@link #setLocale} and all bundles will try to load the appropriate resources. */ public class LocaleSelectorImpl implements LocaleSelector { Locale locale; Vector<LocaleChangeListener> localeChangeListeners = new Vector<LocaleChangeListener>(); public LocaleSelectorImpl() { locale = Locale.getDefault(); } public void addLocaleChangeListener(LocaleChangeListener listener) { localeChangeListeners.add(listener); } public void removeLocaleChangeListener(LocaleChangeListener listener) { localeChangeListeners.remove(listener); } public void setLocale(Locale locale) { this.locale = locale; fireLocaleChanged(); } public Locale getLocale() { return this.locale; } public LocaleChangeListener[] getLocaleChangeListeners() { return localeChangeListeners.toArray(new LocaleChangeListener[]{}); } public void setLanguage(String language) { setLocale(new Locale(language,locale.getCountry())); } public void setCountry(String country) { setLocale(new Locale(locale.getLanguage(),country)); } public String getLanguage() { return locale.getLanguage(); } protected void fireLocaleChanged() { if (localeChangeListeners.size() == 0) return; LocaleChangeListener[] listeners = getLocaleChangeListeners(); LocaleChangeEvent evt = new LocaleChangeEvent(this,getLocale()); for (int i=0;i<listeners.length;i++) listeners[i].localeChanged(evt); } /** This Listeners is for the bundles only, it will ensure the bundles are always notified first. */ void addLocaleChangeListenerFirst(LocaleChangeListener listener) { localeChangeListeners.add(0,listener); } }
04900db4-rob
src/org/rapla/components/xmlbundle/impl/LocaleSelectorImpl.java
Java
gpl3
3,269
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.xmlbundle; import java.util.Locale; /** If you want to change the locales during runtime put a LocaleSelector in the base-context. Instances of I18nBundle will then register them-self as {@link LocaleChangeListener LocaleChangeListeners}. Change the locale with {@link #setLocale} and all bundles will try to load the appropriate resources. */ public interface LocaleSelector { void addLocaleChangeListener(LocaleChangeListener listener); void removeLocaleChangeListener(LocaleChangeListener listener); void setLocale(Locale locale); Locale getLocale(); void setLanguage(String language); void setCountry(String country); String getLanguage(); }
04900db4-rob
src/org/rapla/components/xmlbundle/LocaleSelector.java
Java
gpl3
1,664
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.xmlbundle; import java.util.Locale; import java.util.MissingResourceException; import javax.swing.ImageIcon; /**The interface provides access to a resourcebundle that can be defined in XML or as an java-object. Example Usage: <pre> I18nBundle i18n = serviceManager.lookup(I18nBundle.class); i18n.getString("yes"); // will get the translation for yes. </pre> */ public interface I18nBundle { /** same as </code>format(key,new Object[] {obj1});</code> @see #format(String,Object[]) */ String format(String key,Object obj1) throws MissingResourceException; /** same as </code>format(key,new Object[] {obj1, obj2});</code> @see #format(String,Object[]) */ String format(String key,Object obj1,Object obj2) throws MissingResourceException; /** same as <code> (new MessageFormat(getString(key))).format(obj); </code> @see java.text.MessageFormat */ String format(String key,Object... obj) throws MissingResourceException; /** returns the specified icon from the image-resource-file. @throws MissingResourceException if not found or can't be loaded. */ ImageIcon getIcon(String key) throws MissingResourceException; /** returns the specified string from the selected resource-file. * Same as getString(key,getLocale()) * @throws MissingResourceException if not found or can't be loaded. */ String getString(String key) throws MissingResourceException; /** returns the specified string from the selected resource-file for the specified locale @throws MissingResourceException if not found or can't be loaded. */ String getString( String key, Locale locale); /** @return the selected language. */ String getLang(); /** @return the selected Locale. */ Locale getLocale(); }
04900db4-rob
src/org/rapla/components/xmlbundle/I18nBundle.java
Java
gpl3
2,815
<body> <p>Components for storing locale-specific resources in xml-files. Java Resource-Bundles can be created automatically. </p> <p> For adding a new language to Rapla take a look at resources.xml. </p> @see <A HREF="http://rapla.sourceforge.net/">rapla.sourceforge.net</A> </body>
04900db4-rob
src/org/rapla/components/xmlbundle/package.html
HTML
gpl3
284
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.xmlbundle; import java.util.EventObject; import java.util.Locale; public class LocaleChangeEvent extends EventObject{ private static final long serialVersionUID = 1L; Locale locale; public LocaleChangeEvent(Object source,Locale locale) { super(source); this.locale = locale; } public Locale getLocale() { return locale; } }
04900db4-rob
src/org/rapla/components/xmlbundle/LocaleChangeEvent.java
Java
gpl3
1,343
/* * Sun Microsystems grants you ("Licensee") a non-exclusive, royalty * free, license to use, modify and redistribute this software in * source and binary code form, provided that i) this copyright notice * and license appear on all copies of the software; and ii) Licensee * does not utilize the software in a manner which is disparaging to * Sun Microsystems. * * The software media is distributed on an "As Is" basis, without * warranty. Neither the authors, the software developers nor Sun * Microsystems make any representation, or warranty, either express * or implied, with respect to the software programs, their quality, * accuracy, or fitness for a specific purpose. Therefore, neither the * authors, the software developers nor Sun Microsystems shall have * any liability to you or any other person or entity with respect to * any liability, loss, or damage caused or alleged to have been * caused directly or indirectly by programs contained on the * media. This includes, but is not limited to, interruption of * service, loss of data, loss of classroom time, loss of consulting * or anticipatory *profits, or consequential damages from the use of * these programs. */ package org.rapla.components.tablesorter; import java.awt.Color; import java.awt.Component; import java.awt.Graphics; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.swing.Icon; import javax.swing.JLabel; import javax.swing.JTable; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import javax.swing.table.AbstractTableModel; import javax.swing.table.JTableHeader; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumnModel; import javax.swing.table.TableModel; /** * TableSorter is a decorator for TableModels; adding sorting * functionality to a supplied TableModel. TableSorter does * not store or copy the data in its TableModel; instead it maintains * a map from the row indexes of the view to the row indexes of the * model. As requests are made of the sorter (like getValueAt(row, col)) * they are passed to the underlying model after the row numbers * have been translated via the internal mapping array. This way, * the TableSorter appears to hold another copy of the table * with the rows in a different order. * <p/> * TableSorter registers itself as a listener to the underlying model, * just as the JTable itself would. Events recieved from the model * are examined, sometimes manipulated (typically widened), and then * passed on to the TableSorter's listeners (typically the JTable). * If a change to the model has invalidated the order of TableSorter's * rows, a note of this is made and the sorter will resort the * rows the next time a value is requested. * <p/> * When the tableHeader property is set, either by using the * setTableHeader() method or the two argument constructor, the * table header may be used as a complete UI for TableSorter. * The default renderer of the tableHeader is decorated with a renderer * that indicates the sorting status of each column. In addition, * a mouse listener is installed with the following behavior: * <ul> * <li> * Mouse-click: Clears the sorting status of all other columns * and advances the sorting status of that column through three * values: {NOT_SORTED, ASCENDING, DESCENDING} (then back to * NOT_SORTED again). * <li> * SHIFT-mouse-click: Clears the sorting status of all other columns * and cycles the sorting status of the column through the same * three values, in the opposite order: {NOT_SORTED, DESCENDING, ASCENDING}. * <li> * CONTROL-mouse-click and CONTROL-SHIFT-mouse-click: as above except * that the changes to the column do not cancel the statuses of columns * that are already sorting - giving a way to initiate a compound * sort. * </ul> * <p/> * This is a long overdue rewrite of a class of the same name that * first appeared in the swing table demos in 1997. * * @author Philip Milne * @author Brendon McLean * @author Dan van Enckevort * @author Parwinder Sekhon * @version 2.0 02/27/04 */ public class TableSorter extends AbstractTableModel { private static final long serialVersionUID = 1L; protected TableModel tableModel; public static final int DESCENDING = -1; public static final int NOT_SORTED = 0; public static final int ASCENDING = 1; private Map<Integer,Boolean> enabled= new HashMap<Integer,Boolean>(); private static Directive EMPTY_DIRECTIVE = new Directive(-1, NOT_SORTED); @SuppressWarnings("rawtypes") public static final Comparator<Comparable> COMPARABLE_COMAPRATOR = new Comparator<Comparable>() { @SuppressWarnings("unchecked") public int compare(Comparable o1, Comparable o2) { return o1.compareTo(o2); } }; private Row[] viewToModel; private int[] modelToView; private JTableHeader tableHeader; private MouseListener mouseListener; private TableModelListener tableModelListener; private Map<Integer,Comparator<?>> columnComparators = new HashMap<Integer,Comparator<?>>(); private List<Directive> sortingColumns = new ArrayList<Directive>(); public TableSorter() { this.mouseListener = new MouseHandler(); this.tableModelListener = new TableModelHandler(); } public TableSorter(TableModel tableModel) { this(); setTableModel(tableModel); } public TableSorter(TableModel tableModel, JTableHeader tableHeader) { this(); setTableHeader(tableHeader); setTableModel(tableModel); } private void clearSortingState() { viewToModel = null; modelToView = null; } public TableModel getTableModel() { return tableModel; } public void setTableModel(TableModel tableModel) { if (this.tableModel != null) { this.tableModel.removeTableModelListener(tableModelListener); } this.tableModel = tableModel; if (this.tableModel != null) { this.tableModel.addTableModelListener(tableModelListener); } clearSortingState(); fireTableStructureChanged(); } public JTableHeader getTableHeader() { return tableHeader; } public void setTableHeader(JTableHeader tableHeader) { if (this.tableHeader != null) { this.tableHeader.removeMouseListener(mouseListener); TableCellRenderer defaultRenderer = this.tableHeader.getDefaultRenderer(); if (defaultRenderer instanceof SortableHeaderRenderer) { this.tableHeader.setDefaultRenderer(((SortableHeaderRenderer) defaultRenderer).tableCellRenderer); } } this.tableHeader = tableHeader; if (this.tableHeader != null) { this.tableHeader.addMouseListener(mouseListener); this.tableHeader.setDefaultRenderer( new SortableHeaderRenderer(this.tableHeader.getDefaultRenderer())); } } public boolean isSorting() { return sortingColumns.size() != 0; } private Directive getDirective(int column) { for (int i = 0; i < sortingColumns.size(); i++) { Directive directive = sortingColumns.get(i); if (directive.column == column) { return directive; } } return EMPTY_DIRECTIVE; } public int getSortingStatus(int column) { return getDirective(column).direction; } private void sortingStatusChanged() { clearSortingState(); fireTableDataChanged(); if (tableHeader != null) { tableHeader.repaint(); } } public void setSortingStatus(int column, int status) { Directive directive = getDirective(column); if (directive != EMPTY_DIRECTIVE) { sortingColumns.remove(directive); } if (status != NOT_SORTED) { sortingColumns.add(new Directive(column, status)); } sortingStatusChanged(); } protected Icon getHeaderRendererIcon(int column, int size) { Directive directive = getDirective(column); if (directive == EMPTY_DIRECTIVE) { return null; } return new Arrow(directive.direction == DESCENDING, size, sortingColumns.indexOf(directive)); } private void cancelSorting() { sortingColumns.clear(); sortingStatusChanged(); } public void setColumnComparator(int column, Comparator<?> comparator) { if (comparator == null) { columnComparators.remove(column); } else { columnComparators.put(column, comparator); } setSortingStatus(column, ASCENDING); } @SuppressWarnings("rawtypes") protected Comparator getComparator(int column) { Comparator<?> comparator = columnComparators.get(column); if (comparator != null) { return comparator; } Class<?> columnType = tableModel.getColumnClass(column); if ( columnType.isAssignableFrom( String.class)) { return String.CASE_INSENSITIVE_ORDER; } if (Comparable.class.isAssignableFrom(columnType)) { return COMPARABLE_COMAPRATOR; } return String.CASE_INSENSITIVE_ORDER; } private Row[] getViewToModel() { if (viewToModel == null) { int tableModelRowCount = tableModel.getRowCount(); viewToModel = new Row[tableModelRowCount]; for (int row = 0; row < tableModelRowCount; row++) { viewToModel[row] = new Row(row); } if (isSorting()) { Arrays.sort(viewToModel); } } return viewToModel; } public int modelIndex(int viewIndex) { return getViewToModel()[viewIndex].modelIndex; } private int[] getModelToView() { if (modelToView == null) { int n = getViewToModel().length; modelToView = new int[n]; for (int i = 0; i < n; i++) { modelToView[modelIndex(i)] = i; } } return modelToView; } // TableModel interface methods public int getRowCount() { return (tableModel == null) ? 0 : tableModel.getRowCount(); } public int getColumnCount() { return (tableModel == null) ? 0 : tableModel.getColumnCount(); } public String getColumnName(int column) { return tableModel.getColumnName(column); } public Class<?> getColumnClass(int column) { return tableModel.getColumnClass(column); } public boolean isCellEditable(int row, int column) { return tableModel.isCellEditable(modelIndex(row), column); } public Object getValueAt(int row, int column) { return tableModel.getValueAt(modelIndex(row), column); } public void setValueAt(Object aValue, int row, int column) { tableModel.setValueAt(aValue, modelIndex(row), column); } // Helper classes private class Row implements Comparable<Object> { private int modelIndex; public Row(int index) { this.modelIndex = index; } @SuppressWarnings("unchecked") public int compareTo(Object o) { int row1 = modelIndex; int row2 = ((Row) o).modelIndex; for (Iterator<Directive> it = sortingColumns.iterator(); it.hasNext();) { Directive directive = it.next(); int column = directive.column; Object o1 = tableModel.getValueAt(row1, column); Object o2 = tableModel.getValueAt(row2, column); int comparison = 0; // Define null less than everything, except null. if (o1 == null && o2 == null) { comparison = 0; } else if (o1 == null) { comparison = -1; } else if (o2 == null) { comparison = 1; } else { if ( isSortabe(column) ) { comparison = getComparator(column).compare(o1, o2); } } if (comparison != 0) { return directive.direction == DESCENDING ? -comparison : comparison; } } return 0; } } private class TableModelHandler implements TableModelListener { public void tableChanged(TableModelEvent e) { // If we're not sorting by anything, just pass the event along. if (!isSorting()) { clearSortingState(); fireTableChanged(e); return; } // If the table structure has changed, cancel the sorting; the // sorting columns may have been either moved or deleted from // the model. if (e.getFirstRow() == TableModelEvent.HEADER_ROW) { cancelSorting(); fireTableChanged(e); return; } // We can map a cell event through to the view without widening // when the following conditions apply: // // a) all the changes are on one row (e.getFirstRow() == e.getLastRow()) and, // b) all the changes are in one column (column != TableModelEvent.ALL_COLUMNS) and, // c) we are not sorting on that column (getSortingStatus(column) == NOT_SORTED) and, // d) a reverse lookup will not trigger a sort (modelToView != null) // // Note: INSERT and DELETE events fail this test as they have column == ALL_COLUMNS. // // The last check, for (modelToView != null) is to see if modelToView // is already allocated. If we don't do this check; sorting can become // a performance bottleneck for applications where cells // change rapidly in different parts of the table. If cells // change alternately in the sorting column and then outside of // it this class can end up re-sorting on alternate cell updates - // which can be a performance problem for large tables. The last // clause avoids this problem. int column = e.getColumn(); if (e.getFirstRow() == e.getLastRow() && column != TableModelEvent.ALL_COLUMNS && getSortingStatus(column) == NOT_SORTED && modelToView != null) { int viewIndex = getModelToView()[e.getFirstRow()]; fireTableChanged(new TableModelEvent(TableSorter.this, viewIndex, viewIndex, column, e.getType())); return; } // Something has happened to the data that may have invalidated the row order. clearSortingState(); fireTableDataChanged(); return; } } private class MouseHandler extends MouseAdapter { public void mouseClicked(MouseEvent e) { JTableHeader h = (JTableHeader) e.getSource(); TableColumnModel columnModel = h.getColumnModel(); int viewColumn = columnModel.getColumnIndexAtX(e.getX()); if ( viewColumn != -1) { int column = columnModel.getColumn(viewColumn).getModelIndex(); if (column != -1) { if ( !isSortabe( column)) { return; } int status = getSortingStatus(column); if (!e.isControlDown()) { cancelSorting(); } // Cycle the sorting states through {NOT_SORTED, ASCENDING, DESCENDING} or // {NOT_SORTED, DESCENDING, ASCENDING} depending on whether shift is pressed. status = status + (e.isShiftDown() ? -1 : 1); status = (status + 4) % 3 - 1; // signed mod, returning {-1, 0, 1} setSortingStatus(column, status); } } } } private static class Arrow implements Icon { private boolean descending; private int size; private int priority; public Arrow(boolean descending, int size, int priority) { this.descending = descending; this.size = size; this.priority = priority; } public void paintIcon(Component c, Graphics g, int x, int y) { Color color = c == null ? Color.gray : c.getBackground(); // In a compound sort, make each succesive triangle 20% // smaller than the previous one. int dx = (int)(size/2*Math.pow(0.8, priority)); int dy = descending ? dx : -dx; // Align icon (roughly) with font baseline. y = y + 5*size/6 + (descending ? -dy : 0); int shift = descending ? 1 : -1; g.translate(x, y); // Right diagonal. g.setColor(color.darker()); g.drawLine(dx / 2, dy, 0, 0); g.drawLine(dx / 2, dy + shift, 0, shift); // Left diagonal. g.setColor(color.brighter()); g.drawLine(dx / 2, dy, dx, 0); g.drawLine(dx / 2, dy + shift, dx, shift); // Horizontal line. if (descending) { g.setColor(color.darker().darker()); } else { g.setColor(color.brighter().brighter()); } g.drawLine(dx, 0, 0, 0); g.setColor(color); g.translate(-x, -y); } public int getIconWidth() { return size; } public int getIconHeight() { return size; } } private class SortableHeaderRenderer implements TableCellRenderer { private TableCellRenderer tableCellRenderer; public SortableHeaderRenderer(TableCellRenderer tableCellRenderer) { this.tableCellRenderer = tableCellRenderer; } public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Component c = tableCellRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); if (c instanceof JLabel) { JLabel l = (JLabel) c; l.setHorizontalTextPosition(JLabel.LEFT); int modelColumn = table.convertColumnIndexToModel(column); l.setIcon(getHeaderRendererIcon(modelColumn, l.getFont().getSize())); } return c; } } private static class Directive { private int column; private int direction; public Directive(int column, int direction) { this.column = column; this.direction = direction; } } public void setSortable(int column, boolean b) { enabled.put( column,b); } public boolean isSortabe( int column) { final Boolean sortable = enabled.get(column); if ( sortable == null) { return true; } return sortable; } }
04900db4-rob
src/org/rapla/components/tablesorter/TableSorter.java
Java
gpl3
19,976
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendar; import java.awt.Color; /** Implement this interface if you want to highlight special times or show tooltip for some times. */ public interface TimeRenderer { /** Specifies a special background color for the passed time. Return null if you want to use the default color.*/ public Color getBackgroundColor(int hourOfDay,int minute); /** Specifies a tooltip text for the passed time. Return null if you don't want to use a tooltip for this time.*/ public String getToolTipText(int hourOfDay,int minute); /** returns a formated text of the duration can return null if the duration should not be appended, e.g. if its < 0*/ public String getDurationString(int durationInMinutes); }
04900db4-rob
src/org/rapla/components/calendar/TimeRenderer.java
Java
gpl3
1,708
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendar; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Image; import java.awt.MediaTracker; import java.awt.Point; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.image.BufferedImage; import java.net.URL; import java.text.DateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import javax.swing.BorderFactory; import javax.swing.DefaultListCellRenderer; import javax.swing.DefaultListModel; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollBar; import javax.swing.JScrollPane; import javax.swing.ListSelectionModel; import javax.swing.MenuElement; import javax.swing.MenuSelectionManager; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; /** A ComboBox like time chooser. * It is localizable and it uses swing-components. * <p>The combobox editor is a {@link TimeField}. If the ComboBox-Button * is pressed a TimeSelectionList will drop down.</p> * @author Christopher Kohlhaas */ public final class RaplaTime extends RaplaComboBox { private static final long serialVersionUID = 1L; protected TimeField m_timeField; protected TimeList m_timeList; protected TimeModel m_timeModel; protected Collection<DateChangeListener> m_listenerList = new ArrayList<DateChangeListener>(); private Date m_lastTime; private int m_visibleRowCount = -1; private int m_rowsPerHour = 4; private TimeRenderer m_renderer; private static Image clock; boolean m_showClock; /** Create a new TimeBox with the default locale. */ public RaplaTime() { this(Locale.getDefault(),TimeZone.getDefault(),true, true); } /** Create a new TimeBox with the specified locale and timeZone. */ public RaplaTime(Locale locale,TimeZone timeZone) { this(locale,timeZone,true, true); } /** Create a new TimeBox with the specified locale and timeZone. The isDropDown flag specifies if times could be selected via a drop-down-box. */ public RaplaTime(Locale locale,TimeZone timeZone,boolean isDropDown, boolean showClock) { super(isDropDown,new TimeField(locale,timeZone)); m_showClock = showClock; m_timeModel = new TimeModel(locale, timeZone); m_timeField = (TimeField) m_editorComponent; Listener listener = new Listener(); m_timeField.addChangeListener(listener); m_timeModel.addDateChangeListener(listener); m_lastTime = m_timeModel.getTime(); if ( showClock ) { if ( clock == null ) { URL url = RaplaTime.class.getResource("clock.png"); if ( url != null ) { clock =Toolkit.getDefaultToolkit().createImage(url ); MediaTracker m = new MediaTracker(this); m.addImage(clock, 0); try { m.waitForID(0); } catch (InterruptedException ex) {} } } getLabel().setIcon( new ImageIcon( createClockImage())); getLabel().setBorder( BorderFactory.createEmptyBorder(0,0,0,1)); } } public TimeField getTimeField() { return m_timeField; } static Color HOUR_POINTER = new Color( 40,40,100); static Color MINUTE_POINTER = new Color( 100,100,180); protected Image createClockImage() { BufferedImage image = new BufferedImage( 17, 17, BufferedImage.TYPE_INT_ARGB); Calendar calendar = Calendar.getInstance(getTimeZone(),m_timeModel.getLocale()); calendar.setTime( m_timeModel.getTime()); int hourOfDay = calendar.get( Calendar.HOUR_OF_DAY) % 12; int minute = calendar.get( Calendar.MINUTE); Graphics g = image.getGraphics(); double hourPos = (hourOfDay * 60 + minute - 180) / (60.0 * 12) * 2 * Math.PI ; double minutePos = (minute -15) / 60.0 * 2 * Math.PI; int xhour = (int) (Math.cos( hourPos) * 4.5); int yhour = (int) (Math.sin( hourPos ) * 4.5 ); int xminute = (int) (Math.cos( minutePos ) * 6.5 ); int yminute = (int) (Math.sin( minutePos) * 6.5); g.drawImage( clock,0,0,17,17, null); g.setColor( HOUR_POINTER); int centerx = 8; int centery = 8; g.drawLine( centerx, centery, centerx + xhour,centery + yhour); g.setColor( MINUTE_POINTER); g.drawLine( centerx, centery, centerx + xminute,centery +yminute); return image; } /** The granularity of the selection rows: * <ul> * <li>1: 1 rows per hour = 1 Hour</li> * <li>2: 2 rows per hour = 1/2 Hour</li> * <li>2: 3 rows per hour = 20 Minutes</li> * <li>4: 4 rows per hour = 15 Minutes</li> * <li>6: 6 rows per hour = 10 Minutes</li> * <li>12: 12 rows per hour = 5 Minutes</li> * </ul> */ public void setRowsPerHour(int rowsPerHour) { m_rowsPerHour = rowsPerHour; if (m_timeList != null) { throw new IllegalStateException("Property can only be set during initialization."); } } /** @see #setRowsPerHour */ public int getRowsPerHour() { return m_rowsPerHour; } class Listener implements ChangeListener,DateChangeListener { // Implementation of ChangeListener public void stateChanged(ChangeEvent evt) { validateEditor(); } public void dateChanged(DateChangeEvent evt) { closePopup(); if (needSync()) m_timeField.setTime(evt.getDate()); if (m_lastTime == null || !m_lastTime.equals(evt.getDate())) fireTimeChanged(evt.getDate()); m_lastTime = evt.getDate(); if ( clock != null && m_showClock) { getLabel().setIcon( new ImageIcon( createClockImage())); } } } /** test if we need to synchronize the dateModel and the m_timeField*/ private boolean needSync() { return (m_timeField.getTime() != null && !m_timeModel.sameTime(m_timeField.getTime())); } protected void validateEditor() { if (needSync()) m_timeModel.setTime(m_timeField.getTime()); } /** the number of visble rows in the drop-down menu.*/ public void setVisibleRowCount(int count) { m_visibleRowCount = count; if (m_timeList != null) m_timeList.getList().setVisibleRowCount(count); } public void setFont(Font font) { super.setFont(font); // Method called during constructor? if (m_timeList == null || font == null) return; m_timeList.setFont(font); } public TimeZone getTimeZone() { return m_timeField.getTimeZone(); } /** Set the time relative to the given timezone. * The date,month and year values will be ignored. */ public void setTime(Date time) { m_timeModel.setTime(time); } public Date getDurationStart() { return m_timeModel.getDurationStart(); } public void setDurationStart(Date durationStart) { m_timeModel.setDurationStart(durationStart); if ( m_timeList != null) { m_timeList.setModel(m_timeModel,m_timeField.getOutputFormat()); } } /** Set the time relative to the given timezone. */ public void setTime(int hour, int minute) { m_timeModel.setTime(hour,minute); } /** Parse this date with a calendar-object set to the correct time-zone to get the hour,minute and second. The date,month and year values should be ignored. */ public Date getTime() { return m_timeModel.getTime(); } protected void showPopup() { validateEditor(); super.showPopup(); m_timeList.selectTime(m_timeField.getTime()); } /** registers new DateChangedListener for this component. * An DateChangedEvent will be fired to every registered DateChangedListener * when the a different time is selected. * @see DateChangeListener * @see DateChangeEvent */ public void addDateChangeListener(DateChangeListener listener) { m_listenerList.add(listener); } /** removes a listener from this component.*/ public void removeDateChangeListener(DateChangeListener listener) { m_listenerList.remove(listener); } public DateChangeListener[] getDateChangeListeners() { return m_listenerList.toArray(new DateChangeListener[]{}); } protected void fireTimeChanged(Date date) { DateChangeListener[] listeners = getDateChangeListeners(); if (listeners.length == 0) return; DateChangeEvent evt = new DateChangeEvent(this,date); for (int i = 0; i<listeners.length; i++) { listeners[i].dateChanged(evt); } } /** The popup-component will be created lazily.*/ public JComponent getPopupComponent() { if (m_timeList == null) { m_timeList = new TimeList( m_rowsPerHour); m_timeList.setFont( getFont() ); if (m_visibleRowCount>=0) m_timeList.getList().setVisibleRowCount(m_visibleRowCount); } m_timeList.setTimeRenderer( m_renderer ); m_timeList.setModel(m_timeModel,m_timeField.getOutputFormat()); return m_timeList; } public void setTimeRenderer(TimeRenderer renderer) { m_renderer = renderer; } } class TimeList extends JPanel implements MenuElement,MouseListener,MouseMotionListener { private static final long serialVersionUID = 1L; JScrollPane scrollPane = new JScrollPane(); NavButton upButton = new NavButton('^',10); NavButton downButton = new NavButton('v',10); JList m_list; DateFormat m_format; TimeModel m_timeModel; int m_rowsPerHour = 4; int m_minutesPerRow = 60 / m_rowsPerHour; TimeRenderer m_renderer; private double getRowHeight() { return m_list.getVisibleRect().getHeight()/m_list.getVisibleRowCount(); } public TimeList(int rowsPerHour) { super(); this.setLayout( new BorderLayout()); JPanel upPane = new JPanel(); upPane.setLayout( new BorderLayout()); upPane.add( upButton, BorderLayout.CENTER ); JPanel downPane = new JPanel(); downPane.setLayout( new BorderLayout()); downPane.add( downButton, BorderLayout.CENTER ); upButton.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { int direction = (int)- getRowHeight() * (m_list.getVisibleRowCount() -1); JScrollBar bar = scrollPane.getVerticalScrollBar(); int value = Math.min( Math.max( 0, bar.getValue() + direction ), bar.getMaximum()); scrollPane.getVerticalScrollBar().setValue( value ); } }); downButton.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { int direction = (int) getRowHeight() * (m_list.getVisibleRowCount() -1) ; JScrollBar bar = scrollPane.getVerticalScrollBar(); int value = Math.min( Math.max( 0, bar.getValue() + direction ), bar.getMaximum()); scrollPane.getVerticalScrollBar().setValue( value ); } }); /* upPane.addMouseListener( new Mover( -1)); upButton.addMouseListener( new Mover( -1)); downPane.addMouseListener( new Mover( 1)); downButton.addMouseListener( new Mover( 1)); */ //upPane.setPreferredSize( new Dimension(0,0)); //downPane.setPreferredSize( new Dimension(0,0)); this.add(upPane, BorderLayout.NORTH); this.add( scrollPane, BorderLayout.CENTER); this.add( downPane, BorderLayout.SOUTH); scrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER ); scrollPane.getVerticalScrollBar().setEnabled( false ); scrollPane.getVerticalScrollBar().setSize( new Dimension(0,0)); scrollPane.getVerticalScrollBar().setPreferredSize( new Dimension(0,0)); scrollPane.getVerticalScrollBar().setMaximumSize( new Dimension(0,0)); scrollPane.getVerticalScrollBar().setMinimumSize( new Dimension(0,0)); m_rowsPerHour = rowsPerHour; m_minutesPerRow = 60 / m_rowsPerHour; //this.setLayout(new BorderLayout()); m_list = new JList(); scrollPane.setViewportView( m_list); m_list.setBackground(this.getBackground()); //JScrollPane scrollPane = new JScrollPane(m_list, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); m_list.setVisibleRowCount(8); m_list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); m_list.addMouseListener(this); m_list.addMouseMotionListener(this); DefaultListCellRenderer cellRenderer = new DefaultListCellRenderer() { private static final long serialVersionUID = 1L; public Component getListCellRendererComponent( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus ) { int hour = getHourForIndex( index ); int minute = getMinuteForIndex( index ); String string = (String) value; Component component = super.getListCellRendererComponent( list, string, index, isSelected,cellHasFocus ); if ( m_renderer!= null && !isSelected && !cellHasFocus ) { Color color = m_renderer.getBackgroundColor( hour, minute ); if ( color != null ) { component.setBackground( color ); } } return component; } }; setRenderer(cellRenderer); } @SuppressWarnings("unchecked") private void setRenderer(DefaultListCellRenderer cellRenderer) { m_list.setCellRenderer( cellRenderer); } @SuppressWarnings("unchecked") public void setModel(TimeModel model,DateFormat format) { m_timeModel = model; m_format = (DateFormat) format.clone(); Calendar calendar = Calendar.getInstance(m_format.getTimeZone(),model.getLocale()); DefaultListModel listModel = new DefaultListModel(); for (int i=0;i<24 * m_rowsPerHour;i++) { int hour = i/m_rowsPerHour; int minute = (i%m_rowsPerHour) * m_minutesPerRow; calendar.setTimeInMillis(0); calendar.set(Calendar.HOUR_OF_DAY,hour ); calendar.set(Calendar.MINUTE,minute); Date durationStart = m_timeModel.getDurationStart(); String duration = ""; if ( m_renderer != null && durationStart != null) { Date time = calendar.getTime(); long millis = time.getTime() - durationStart.getTime(); int durationInMinutes = (int) (millis / (1000 * 60)); duration = m_renderer.getDurationString(durationInMinutes); } String timeWithoutDuration = m_format.format(calendar.getTime()); String time = timeWithoutDuration; if ( duration != null) { time += " " + duration; } listModel.addElement(" " + time + " "); } m_list.setModel(listModel); int pos = (int)getPreferredSize().getWidth()/2 - 5; upButton.setLeftPosition( pos); downButton.setLeftPosition( pos ); } public void setTimeRenderer(TimeRenderer renderer) { m_renderer = renderer; } public JList getList() { return m_list; } public void setFont(Font font) { super.setFont(font); if (m_list == null || font == null) return; m_list.setFont(font); int pos = (int)getPreferredSize().getWidth()/2 - 5; upButton.setLeftPosition( pos); downButton.setLeftPosition( pos ); } /** Implementation-specific. Should be private.*/ public void mousePressed(MouseEvent e) { ok(); } /** Implementation-specific. Should be private.*/ public void mouseClicked(MouseEvent e) { } /** Implementation-specific. Should be private.*/ public void mouseReleased(MouseEvent e) { } /** Implementation-specific. Should be private.*/ public void mouseEntered(MouseEvent me) { } /** Implementation-specific. Should be private.*/ public void mouseExited(MouseEvent me) { } private int lastIndex = -1; private int lastY= -1; public void mouseDragged(MouseEvent e) { } public void mouseMoved(MouseEvent e) { if (e.getY() == lastY) return; lastY = e.getY(); Point p = new Point(e.getX(),e.getY()); int index = m_list.locationToIndex(p); if (index == lastIndex) return; lastIndex = index; m_list.setSelectedIndex(index); } public void selectTime(Date time) { Calendar calendar = Calendar.getInstance(m_timeModel.getTimeZone(),m_timeModel.getLocale()); calendar.setTime(time); int index = (calendar.get(Calendar.HOUR_OF_DAY)) * m_rowsPerHour + (calendar.get(Calendar.MINUTE) / m_minutesPerRow); select(index); } private void select(int index) { m_list.setSelectedIndex(index); m_list.ensureIndexIsVisible(Math.max(index -3,0)); m_list.ensureIndexIsVisible(Math.min(index + 3,m_list.getModel().getSize() -1)); } // Start of MenuElement implementation public Component getComponent() { return this; } public MenuElement[] getSubElements() { return new MenuElement[0]; } public void menuSelectionChanged(boolean isIncluded) { } public void processKeyEvent(KeyEvent event, MenuElement[] path, MenuSelectionManager manager) { int index; if (event.getID() == KeyEvent.KEY_PRESSED) { switch (event.getKeyCode()) { case (KeyEvent.VK_KP_UP): case (KeyEvent.VK_UP): index = m_list.getSelectedIndex(); if (index > 0) select(index - 1); break; case (KeyEvent.VK_KP_DOWN): case (KeyEvent.VK_DOWN): index = m_list.getSelectedIndex(); if (index <m_list.getModel().getSize()-1) select(index + 1); break; case (KeyEvent.VK_SPACE): case (KeyEvent.VK_ENTER): ok(); break; case (KeyEvent.VK_ESCAPE): manager.clearSelectedPath(); break; } // System.out.println(event.getKeyCode()); event.consume(); } } private int getHourForIndex( int index ) { return index / m_rowsPerHour; } private int getMinuteForIndex( int index ) { return (index % m_rowsPerHour) * m_minutesPerRow; } private void ok() { int index = m_list.getSelectedIndex(); int hour = getHourForIndex( index ); int minute = getMinuteForIndex( index ); Calendar calendar = Calendar.getInstance(m_timeModel.getTimeZone(),m_timeModel.getLocale()); if (hour >= 0) { calendar.set(Calendar.HOUR_OF_DAY,hour ); calendar.set(Calendar.MINUTE,minute); calendar.set(Calendar.SECOND,0); calendar.set(Calendar.MILLISECOND,0); m_timeModel.setTime(calendar.getTime()); } } public void processMouseEvent(MouseEvent event, MenuElement[] path, MenuSelectionManager manager) { } // End of MenuElement implementation }
04900db4-rob
src/org/rapla/components/calendar/RaplaTime.java
Java
gpl3
21,438
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendar; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.SwingUtilities; public class RaplaArrowButton extends JButton { private static final long serialVersionUID = 1L; ButtonStateChecker m_checker = new ButtonStateChecker(); int m_delay = 0; boolean m_buttonDown = false; ArrowPolygon poly; char c; public RaplaArrowButton(char c) { this(c,18); } public RaplaArrowButton(char c,int size) { super(); this.c = c; setMargin(new Insets(0,0,0,0)); setSize(size,size); addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) { if (!isEnabled()) return; m_buttonDown = true; // repaint(); m_checker.start(); } /** Implementation-specific. Should be private.*/ public void mouseReleased(MouseEvent me) { m_buttonDown = false; // repaint(); } /** Implementation-specific. Should be private.*/ public void mouseClicked(MouseEvent me) { m_buttonDown = false; //repaint(); } }); } /** Here you can set if the button should fire repeated clicks. If set to 0 the button will fire only once when pressed. */ public void setClickRepeatDelay(int millis) { m_delay = millis; } public int getClickRepeatDelay() { return m_delay; } public boolean isOpen() { return c == '^'; } public void setChar( char c) { this.c = c; final Dimension size = getSize(); final int width2 = (int)size.getWidth(); final int height2 = (int)size.getHeight(); setSize( width2,height2); } /** Set the size of the drop-down button. The minimum of width and height will be used as new size of the arrow. */ public void setSize(int width,int height) { int size = Math.min(width,height); int imageSize = size - 8; if (imageSize > 0) { poly = new ArrowPolygon(c,imageSize); BufferedImage image = new BufferedImage(imageSize,imageSize,BufferedImage.TYPE_INT_ARGB); Graphics g = image.createGraphics(); g.setColor(new Color(0, 0, 0, 0)); g.fillRect( 0, 0, imageSize, imageSize ); g.setColor( Color.darkGray ); g.fillPolygon( poly ); g.setColor( Color.black ); g.drawPolygon( poly ); setIcon(new ImageIcon(image)); } else { setIcon(null); } super.setSize(width ,height); Dimension dim = new Dimension(width ,height); setPreferredSize(dim); setMaximumSize(dim); setMinimumSize(dim); } class ButtonStateChecker implements Runnable{ long startMillis; long startDelay; public void start() { startDelay = m_delay * 10; startMillis = System.currentTimeMillis(); if (m_delay > 0) SwingUtilities.invokeLater(this); } private void fireAndReset() { fireActionPerformed(new ActionEvent(this ,ActionEvent.ACTION_PERFORMED ,"")); startMillis = System.currentTimeMillis(); } public void run() { if (!m_buttonDown) return; if ((Math.abs(System.currentTimeMillis() - startMillis) > startDelay)) { if (startDelay > m_delay) startDelay = startDelay/2; fireAndReset(); } try { Thread.sleep(10); } catch (Exception ex) { return; } SwingUtilities.invokeLater(this); } } }
04900db4-rob
src/org/rapla/components/calendar/RaplaArrowButton.java
Java
gpl3
5,166
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendar; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.TimeZone; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.MenuElement; import javax.swing.MenuSelectionManager; import javax.swing.border.Border; import javax.swing.border.EmptyBorder; import javax.swing.border.LineBorder; /** The graphical date-selection field with month and year incerement/decrement buttons. * @author Christopher Kohlhaas */ public class CalendarMenu extends JPanel implements MenuElement { private static final long serialVersionUID = 1L; static Color BACKGROUND_COLOR = Color.white; static Border FOCUSBORDER = new LineBorder(DaySelection.FOCUSCOLOR,1); static Border EMPTYBORDER = new EmptyBorder(1,1,1,1); BorderLayout borderLayout1 = new BorderLayout(); JPanel topSelection = new JPanel(); Border border1 = BorderFactory.createEtchedBorder(); BorderLayout borderLayout2 = new BorderLayout(); JPanel monthSelection = new JPanel(); NavButton jPrevMonth = new NavButton('<'); JLabel labelMonth = new JLabel(); NavButton jNextMonth = new NavButton('>'); JPanel yearSelection = new JPanel(); NavButton jPrevYear = new NavButton('<'); JLabel labelYear = new JLabel(); NavButton jNextYear = new NavButton('>'); protected DaySelection daySelection; JLabel labelCurrentDay = new JLabel(); JButton focusButton = new JButton() { private static final long serialVersionUID = 1L; public void paint(Graphics g) { Dimension size = getSize(); g.setColor(getBackground()); g.fillRect(0,0,size.width,size.height); } }; DateModel m_model; DateModel m_focusModel; String[] m_monthNames; boolean m_focusable = true; public CalendarMenu(DateModel newModel) { m_model = newModel; m_monthNames = createMonthNames(); m_focusModel = new DateModel(newModel.getLocale(),newModel.getTimeZone()); daySelection = new DaySelection(newModel,m_focusModel); initGUI(); Listener listener = new Listener(); jPrevMonth.addActionListener(listener); jPrevMonth.setBorder( null ); jNextMonth.addActionListener(listener); jNextMonth.setBorder( null ); jPrevYear.addActionListener(listener); jPrevYear.setBorder( null ); jNextYear.addActionListener(listener); jNextYear.setBorder( null ); jPrevMonth.setFocusable( false ); jNextMonth.setFocusable( false ); jPrevYear.setFocusable( false ); jNextYear.setFocusable( false ); this.addMouseListener(listener); jPrevMonth.addMouseListener(listener); jNextMonth.addMouseListener(listener); jPrevYear.addMouseListener(listener); jNextYear.addMouseListener(listener); labelCurrentDay.addMouseListener(listener); daySelection.addMouseListener(listener); labelCurrentDay.addMouseListener(listener); m_model.addDateChangeListener(listener); m_focusModel.addDateChangeListener(listener); focusButton.addKeyListener(listener); focusButton.addFocusListener(listener); calculateSizes(); m_focusModel.setDate(m_model.getDate()); } class Listener implements ActionListener,MouseListener,FocusListener,DateChangeListener,KeyListener { public void actionPerformed(ActionEvent evt) { if ( evt.getSource() == jNextMonth) { m_focusModel.addMonth(1); } // end of if () if ( evt.getSource() == jPrevMonth) { m_focusModel.addMonth(-1); } // end of if () if ( evt.getSource() == jNextYear) { m_focusModel.addYear(1); } // end of if () if ( evt.getSource() == jPrevYear) { m_focusModel.addYear(-1); } // end of if () } // Implementation of DateChangeListener public void dateChanged(DateChangeEvent evt) { if (evt.getSource() == m_model) { m_focusModel.setDate(evt.getDate()); } else { updateFields(); } } // Implementation of MouseListener public void mousePressed(MouseEvent me) { if (me.getSource() == labelCurrentDay) { // Set the current day as sellected day m_model.setDate(new Date()); } else { if (m_focusable && !focusButton.hasFocus()) focusButton.requestFocus(); } } public void mouseClicked(MouseEvent me) { } public void mouseReleased(MouseEvent me) { } public void mouseEntered(MouseEvent me) { } public void mouseExited(MouseEvent me) { } // Implementation of KeyListener public void keyPressed(KeyEvent e) { processCalendarKey(e); } public void keyReleased(KeyEvent e) { } public void keyTyped(KeyEvent e) { } // Implementation of FocusListener public void focusGained(FocusEvent e) { if (e.getSource() == focusButton) setBorder(FOCUSBORDER); else transferFocus(); } public void focusLost(FocusEvent e) { if (e.getSource() == focusButton) setBorder(EMPTYBORDER); } } private void updateFields() { labelCurrentDay.setText(m_focusModel.getCurrentDateString()); labelMonth.setText(m_monthNames[m_focusModel.getMonth() -1]); labelYear.setText(m_focusModel.getYearString()); } public DateModel getModel() { return m_model; } public boolean hasFocus() { return focusButton.hasFocus(); } public boolean isFocusable() { return m_focusable; } public void setFocusable(boolean m_focusable) { this.m_focusable = m_focusable; } // #TODO Property change listener for TimeZone public void setTimeZone(TimeZone timeZone) { m_focusModel.setTimeZone(timeZone); } public void setFont(Font font) { super.setFont(font); // Method called during constructor? if (labelMonth == null || font == null) return; labelMonth.setFont(font); labelYear.setFont(font); daySelection.setFont(font); labelCurrentDay.setFont(font); calculateSizes(); invalidate(); } public void requestFocus() { if (m_focusable) focusButton.requestFocus(); } public DaySelection getDaySelection() { return daySelection; } private void calculateSizes() { // calculate max size of month names int maxWidth =0; FontMetrics fm = getFontMetrics(labelMonth.getFont()); for (int i=0;i< m_monthNames.length;i++) { int len = fm.stringWidth(m_monthNames[i]); if (len>maxWidth) maxWidth = len; } labelMonth.setPreferredSize(new Dimension(maxWidth,fm.getHeight())); int h = fm.getHeight(); jPrevMonth.setSize(h,h); jNextMonth.setSize(h,h); jPrevYear.setSize(h,h); jNextYear.setSize(h,h); // Workaraund for focus-bug in JDK 1.3.1 Border dummyBorder = new EmptyBorder(fm.getHeight(),0,0,0); focusButton.setBorder(dummyBorder); } private void initGUI() { setBorder(EMPTYBORDER); topSelection.setLayout(borderLayout2); topSelection.setBorder(border1); daySelection.setBackground(BACKGROUND_COLOR); FlowLayout flowLayout = new FlowLayout(FlowLayout.LEFT,0,0); monthSelection.setLayout(flowLayout); monthSelection.add(focusButton); monthSelection.add(jPrevMonth); monthSelection.add(labelMonth); monthSelection.add(jNextMonth); yearSelection.setLayout(flowLayout); yearSelection.add(jPrevYear); yearSelection.add(labelYear); yearSelection.add(jNextYear); topSelection.add(monthSelection,BorderLayout.WEST); topSelection.add(yearSelection,BorderLayout.EAST); setLayout(borderLayout1); add(topSelection,BorderLayout.NORTH); add(daySelection,BorderLayout.CENTER); add(labelCurrentDay,BorderLayout.SOUTH); } private String[] createMonthNames( ) { Calendar calendar = Calendar.getInstance(m_model.getLocale()); calendar.setLenient(true); Collection<String> monthNames = new ArrayList<String>(); SimpleDateFormat format = new SimpleDateFormat("MMM",m_model.getLocale()); int firstMonth = 0; int month = 0; while (true) { calendar.set(Calendar.DATE,1); calendar.set(Calendar.MONTH,month); if (month == 0) firstMonth = calendar.get(Calendar.MONTH); else if (calendar.get(Calendar.MONTH) == firstMonth) break; monthNames.add(format.format(calendar.getTime())); month ++; } return monthNames.toArray(new String[0]); } private void processCalendarKey(KeyEvent e) { switch (e.getKeyCode()) { case (KeyEvent.VK_KP_UP): case (KeyEvent.VK_UP): m_focusModel.addDay(-7); break; case (KeyEvent.VK_KP_DOWN): case (KeyEvent.VK_DOWN): m_focusModel.addDay(7); break; case (KeyEvent.VK_KP_LEFT): case (KeyEvent.VK_LEFT): m_focusModel.addDay(-1); break; case (KeyEvent.VK_KP_RIGHT): case (KeyEvent.VK_RIGHT): m_focusModel.addDay(1); break; case (KeyEvent.VK_PAGE_DOWN): m_focusModel.addMonth(1); break; case (KeyEvent.VK_PAGE_UP): m_focusModel.addMonth(-1); break; case (KeyEvent.VK_ENTER): m_model.setDate(m_focusModel.getDate()); break; case (KeyEvent.VK_SPACE): m_model.setDate(m_focusModel.getDate()); break; } } // Start of MenuElement implementation public Component getComponent() { return this; } public MenuElement[] getSubElements() { return new MenuElement[0]; } public void menuSelectionChanged(boolean isIncluded) { } public void processKeyEvent(KeyEvent event, MenuElement[] path, MenuSelectionManager manager) { if (event.getID() == KeyEvent.KEY_PRESSED) processCalendarKey(event); switch (event.getKeyCode()) { case (KeyEvent.VK_ENTER): case (KeyEvent.VK_ESCAPE): manager.clearSelectedPath(); } event.consume(); } public void processMouseEvent(MouseEvent event, MenuElement[] path, MenuSelectionManager manager) { } // End of MenuElement implementation }
04900db4-rob
src/org/rapla/components/calendar/CalendarMenu.java
Java
gpl3
12,794
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendar; import java.text.DateFormat; import java.text.FieldPosition; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; /** The TimeField only accepts characters that are part of DateFormat.getTimeInstance(DateFormat.SHORT,locale). * The input blocks are [hour,minute,am_pm] or [hour_of_day,minute] * depending on the selected locale. You can use the keyboard to * navigate between the blocks or to increment/decrement the blocks. * @see AbstractBlockField */ final public class TimeField extends AbstractBlockField { private static final long serialVersionUID = 1L; private DateFormat m_outputFormat; private DateFormat m_parsingFormat; private Calendar m_calendar; private int m_rank[] = null; private char[] m_separators; private boolean m_useAM_PM = false; private boolean americanAM_PM_character = false; public TimeField() { this(Locale.getDefault()); } public TimeField(Locale locale) { this(locale, TimeZone.getDefault()); } public TimeField(Locale locale,TimeZone timeZone) { super(); m_calendar = Calendar.getInstance(timeZone, locale); super.setLocale(locale); setFormat(); setTime(new Date()); } public void setLocale(Locale locale) { super.setLocale(locale); if (locale != null && getTimeZone() != null) setFormat(); } private void setFormat() { m_parsingFormat = DateFormat.getTimeInstance(DateFormat.SHORT, getLocale()); m_parsingFormat.setTimeZone(getTimeZone()); Date oldDate = m_calendar.getTime(); m_calendar.set(Calendar.HOUR_OF_DAY,0); m_calendar.set(Calendar.MINUTE,0); String formatStr = m_parsingFormat.format(m_calendar.getTime()); FieldPosition minutePos = new FieldPosition(DateFormat.MINUTE_FIELD); m_parsingFormat.format(m_calendar.getTime(), new StringBuffer(),minutePos); FieldPosition hourPos = new FieldPosition(DateFormat.HOUR0_FIELD); StringBuffer hourBuf = new StringBuffer(); m_parsingFormat.format(m_calendar.getTime(), hourBuf,hourPos); FieldPosition hourPos1 = new FieldPosition(DateFormat.HOUR1_FIELD); StringBuffer hourBuf1 = new StringBuffer(); m_parsingFormat.format(m_calendar.getTime(), hourBuf1,hourPos1); FieldPosition amPmPos = new FieldPosition(DateFormat.AM_PM_FIELD); m_parsingFormat.format(m_calendar.getTime(), new StringBuffer(),amPmPos); String zeroDigit = m_parsingFormat.getNumberFormat().format(0); int zeroPos = hourBuf.toString().indexOf(zeroDigit,hourPos.getBeginIndex()); // 0:30 or 12:30 boolean zeroBased = (zeroPos == 0); String testFormat = m_parsingFormat.format( m_calendar.getTime() ).toLowerCase(); int mp = minutePos.getBeginIndex(); int ap = amPmPos.getBeginIndex(); int hp = Math.max( hourPos.getBeginIndex(), hourPos1.getBeginIndex() ); int pos[] = null; // Use am/pm if (amPmPos.getEndIndex()>0) { m_useAM_PM = true; americanAM_PM_character = m_useAM_PM && (testFormat.indexOf( "am" )>=0 || testFormat.indexOf( "pm" )>=0); // System.out.println(formatStr + " hour:"+hp+" minute:"+mp+" ampm:"+ap); if (hp<0 || mp<0 || ap<0 || formatStr == null) { throw new IllegalArgumentException("Can't parse the time-format for this locale: " + formatStr); } // quick and diry sorting if (mp<hp && hp<ap) { pos = new int[] {mp,hp,ap}; m_rank = new int[] {Calendar.MINUTE, Calendar.HOUR, Calendar.AM_PM}; } else if (mp<ap && ap<hp) { pos = new int[] {mp,ap,hp}; m_rank = new int[] {Calendar.MINUTE, Calendar.AM_PM, Calendar.HOUR}; } else if (hp<mp && mp<ap) { pos = new int[] {hp,mp,ap}; m_rank = new int[] {Calendar.HOUR, Calendar.MINUTE, Calendar.AM_PM}; } else if (hp<ap && ap<mp) { pos = new int[] {hp,ap,mp}; m_rank = new int[] {Calendar.HOUR, Calendar.AM_PM, Calendar.MINUTE}; } else if (ap<mp && mp<hp) { pos = new int[] {ap,mp,hp}; m_rank = new int[] {Calendar.AM_PM, Calendar.MINUTE, Calendar.HOUR}; } else if (ap<hp && hp<mp) { pos = new int[] {ap,hp,mp}; m_rank = new int[] {Calendar.AM_PM, Calendar.HOUR, Calendar.MINUTE}; } else { throw new IllegalStateException("Ordering am=" +ap + " h=" +hp + " m="+mp +" not supported"); } char firstSeparator = formatStr.charAt(pos[1]-1); char secondSeparator = formatStr.charAt(pos[2]-1); if (Character.isDigit(firstSeparator) || Character.isDigit(secondSeparator)) throw new IllegalArgumentException("Can't parse the time-format for this locale: " + formatStr); m_separators = new char[] {firstSeparator,secondSeparator}; StringBuffer buf = new StringBuffer(); for (int i=0;i<m_rank.length;i++) { if (m_rank[i] == Calendar.HOUR) { if (zeroBased) buf.append("KK"); else buf.append("hh"); } else if (m_rank[i] == Calendar.MINUTE) { buf.append("mm"); } else if (m_rank[i] == Calendar.AM_PM) { buf.append("a"); } if (i==0 && americanAM_PM_character) { buf.append(firstSeparator); } else if (i==1) { buf.append(secondSeparator); } } m_outputFormat= new SimpleDateFormat(buf.toString(), getLocale()); m_outputFormat.setTimeZone(getTimeZone()); setColumns(7); // Don't use am/pm } else { m_useAM_PM = false; // System.out.println(formatStr + " hour:"+hp+" minute:" + mp); if (hp<0 || mp<0) { throw new IllegalArgumentException("Can't parse the time-format for this locale"); } // quick and diry sorting if (mp<hp) { pos = new int[] {mp,hp}; m_rank = new int[] {Calendar.MINUTE, Calendar.HOUR_OF_DAY}; } else { pos = new int[] {hp,mp}; m_rank = new int[] {Calendar.HOUR_OF_DAY, Calendar.MINUTE}; } char firstSeparator = formatStr.charAt(pos[1]-1); if (Character.isDigit(firstSeparator)) throw new IllegalArgumentException("Can't parse the time-format for this locale"); m_separators = new char[] {firstSeparator}; StringBuffer buf = new StringBuffer(); for (int i=0;i<m_rank.length;i++) { if (m_rank[i] == Calendar.HOUR_OF_DAY) { if (zeroBased) buf.append("HH"); else buf.append("kk"); } else if (m_rank[i] == Calendar.MINUTE) { buf.append("mm"); } else if (m_rank[i] == Calendar.AM_PM) { buf.append("a"); } if (i==0) { buf.append(firstSeparator); } } m_outputFormat= new SimpleDateFormat(buf.toString(), getLocale()); m_outputFormat.setTimeZone(getTimeZone()); setColumns(5); } m_calendar.setTime(oldDate); } public TimeZone getTimeZone() { if (m_calendar != null) return m_calendar.getTimeZone(); return null; } /** returns the parsingFormat of the selected locale. This is same as the default time-format of the selected locale.*/ public DateFormat getParsingFormat() { return m_parsingFormat; } /** returns the output format of the date-field. The outputFormat always uses the full block size: 01:02 instead of 1:02 */ public DateFormat getOutputFormat() { return m_outputFormat; } private void update(TimeZone timeZone, Locale locale) { Date date = getTime(); m_calendar = Calendar.getInstance(timeZone, locale); setFormat(); setText(m_outputFormat.format(date)); } public void setTimeZone(TimeZone timeZone) { update(timeZone, getLocale()); } public Date getTime() { return m_calendar.getTime(); } public void setTime(Date value) { m_calendar.setTime(value); setText(m_outputFormat.format(value)); } protected char[] getSeparators() { return m_separators; } protected boolean isSeparator(char c) { for (int i=0;i<m_separators.length;i++) if (m_separators[i] == c) return true; return false; } protected void changeSelectedBlock(int[] blocks,int block,String selected,int count) { int type = m_rank[block]; if (m_rank.length<block) return; if (type == Calendar.AM_PM) { m_calendar.roll(Calendar.HOUR_OF_DAY,12); } else if (type == Calendar.MINUTE) { m_calendar.add(type,count); } else { if (Math.abs(count) == 10) m_calendar.add(type,count/Math.abs(count) * 12); else m_calendar.add(type,count/Math.abs(count)); } setTime(m_calendar.getTime()); calcBlocks(blocks); markBlock(blocks,block); } public boolean blocksValid() { try { m_calendar.setTime(m_parsingFormat.parse(getText())); return true; } catch (ParseException e) { return false; } } static int[] BLOCKLENGTH1 = new int[] {2,2,2}; static int[] BLOCKLENGTH2 = new int[] {2,2}; protected int blockCount() { return m_useAM_PM ? BLOCKLENGTH1.length : BLOCKLENGTH2.length; } protected int maxBlockLength(int block) { return m_useAM_PM ? BLOCKLENGTH1[block] : BLOCKLENGTH2[block]; } protected boolean isValidChar(char c) { return (Character.isDigit(c) || isSeparator(c) || ((m_useAM_PM) && ((americanAM_PM_character && (c == 'a' || c=='A' || c=='p' || c=='P' || c=='m' || c=='M')) || (!americanAM_PM_character && Character.isLetter( c )) ) )); } }
04900db4-rob
src/org/rapla/components/calendar/TimeField.java
Java
gpl3
11,907
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendar; import java.awt.Polygon; /* The following classes are only responsible to paint the Arrows for the NavButton. */ class ArrowPolygon extends Polygon { private static final long serialVersionUID = 1L; public ArrowPolygon(char type,int width) { this(type,width,true); } public ArrowPolygon(char type,int width,boolean border) { int polyWidth = ((width - 7) / 8); polyWidth = (polyWidth + 1) * 8; int dif = border ? (width - polyWidth) /2 : 0; int half = polyWidth / 2 + dif; int insets = (polyWidth == 8) ? 0 : polyWidth / 4; int start = insets + dif; int full = polyWidth - insets + dif; int size = (polyWidth == 8) ? polyWidth / 4 : polyWidth / 8; if ( type == '>') { addPoint(half - size,start); addPoint(half + size,half); addPoint(half - size,full); } // end of if () if ( type == '<') { addPoint(half + size,start); addPoint(half - size,half); addPoint(half + size,full); } // end of if () if ( type == '^') { addPoint(start,half + size); addPoint(half,half - size); addPoint(full,half + size); } // end of if () if ( type == 'v') { addPoint(start,half - size); addPoint(half,half + size); addPoint(full,half - size); } // end of if () if ( type == '-') { addPoint(start + 1,half - 1); addPoint(full - 3,half - 1); } // end of if () if ( type == '+') { addPoint(start + 1,half - 1); addPoint(full - 3,half - 1); addPoint(half -1,half - 1); addPoint(half- 1, half - (size + 1)); addPoint(half -1,half + ( size -1)); addPoint(half -1,half - 1); } // end of if () } }
04900db4-rob
src/org/rapla/components/calendar/ArrowPolygon.java
Java
gpl3
2,888
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendar; import java.awt.Color; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Insets; import java.awt.event.MouseEvent; import java.text.DateFormat; import java.text.FieldPosition; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import org.rapla.components.calendar.DateRenderer.RenderingInfo; /** The DateField only accepts characters that are part of * DateFormat.getDateInstance(DateFormat.SHORT,locale). The * inputblocks are [date,month,year]. The order of the input-blocks is * determined by the locale. You can use the keyboard to navigate * between the blocks or to increment/decrement the blocks. * @see AbstractBlockField */ final public class DateField extends AbstractBlockField { private static final long serialVersionUID = 1L; private DateFormat m_outputFormat; private DateFormat m_parsingFormat; private Calendar m_calendar; private int m_rank[] = null; private char[] m_separators; private SimpleDateFormat m_weekdayFormat; private boolean m_weekdaysVisible = true; private DateRenderer m_dateRenderer; /** stores the y-coordinate of the weekdays display field*/ private int m_weekdaysX; private boolean nullValuePossible; private boolean nullValue; RenderingInfo renderingInfo; public boolean isNullValue() { return nullValue; } public void setNullValue(boolean nullValue) { this.nullValue = nullValue; } public boolean isNullValuePossible() { return nullValuePossible; } public void setNullValuePossible(boolean nullValuePossible) { this.nullValuePossible = nullValuePossible; } public DateField() { this(Locale.getDefault(),TimeZone.getDefault()); } public DateField(Locale locale,TimeZone timeZone) { super(); m_calendar = Calendar.getInstance(timeZone, locale); super.setLocale(locale); setFormat(); setDate(new Date()); } /** you can choose, if weekdays should be displayed in the right corner of the DateField. Default is true. */ public void setWeekdaysVisible(boolean m_weekdaysVisible) { this.m_weekdaysVisible = m_weekdaysVisible; } /** sets the DateRenderer for the calendar */ public void setDateRenderer(DateRenderer dateRenderer) { m_dateRenderer = dateRenderer; } private void setFormat() { m_parsingFormat = DateFormat.getDateInstance(DateFormat.SHORT, getLocale()); m_weekdayFormat = new SimpleDateFormat("EE", getLocale()); TimeZone timeZone = getTimeZone(); m_parsingFormat.setTimeZone(timeZone); m_weekdayFormat.setTimeZone(timeZone); String formatStr = m_parsingFormat.format(m_calendar.getTime()); FieldPosition datePos = new FieldPosition(DateFormat.DATE_FIELD); FieldPosition monthPos = new FieldPosition(DateFormat.MONTH_FIELD); FieldPosition yearPos = new FieldPosition(DateFormat.YEAR_FIELD); m_parsingFormat.format(m_calendar.getTime(), new StringBuffer(),datePos); m_parsingFormat.format(m_calendar.getTime(), new StringBuffer(),monthPos); m_parsingFormat.format(m_calendar.getTime(), new StringBuffer(),yearPos); int mp = monthPos.getBeginIndex(); int dp = datePos.getBeginIndex(); int yp = yearPos.getBeginIndex(); int pos[] = null; // System.out.println(formatStr + " day:"+dp+" month:"+mp+" year:"+yp); if (mp<0 || dp<0 || yp<0) { throw new IllegalArgumentException("Can't parse the date-format for this locale"); } // quick and diry sorting if (dp<mp && mp<yp) { pos = new int[] {dp,mp,yp}; m_rank = new int[] {Calendar.DATE, Calendar.MONTH, Calendar.YEAR}; } else if (dp<yp && yp<mp) { pos = new int[] {dp,yp,mp}; m_rank = new int[] {Calendar.DATE, Calendar.YEAR, Calendar.MONTH}; } else if (mp<dp && dp<yp) { pos = new int[] {mp,dp,yp}; m_rank = new int[] {Calendar.MONTH, Calendar.DATE, Calendar.YEAR}; } else if (mp<yp && yp<dp) { pos = new int[] {mp,yp,dp}; m_rank = new int[] {Calendar.MONTH, Calendar.YEAR, Calendar.DATE}; } else if (yp<dp && dp<mp) { pos = new int[] {yp,dp,mp}; m_rank = new int[] {Calendar.YEAR, Calendar.DATE, Calendar.MONTH}; } else if (yp<mp && mp<dp) { pos = new int[] {yp,mp,dp}; m_rank = new int[] {Calendar.YEAR, Calendar.MONTH, Calendar.DATE}; } else { throw new IllegalStateException("Ordering y=" +yp + " d=" +dp + " m="+mp +" not supported"); } char firstSeparator = formatStr.charAt(pos[1]-1); char secondSeparator = formatStr.charAt(pos[2]-1); // System.out.println("first-sep:"+firstSeparator+" sec-sep:"+secondSeparator); if (Character.isDigit(firstSeparator) || Character.isDigit(secondSeparator)) throw new IllegalArgumentException("Can't parse the date-format for this locale"); m_separators = new char[] {firstSeparator,secondSeparator}; StringBuffer buf = new StringBuffer(); for (int i=0;i<m_rank.length;i++) { if (m_rank[i] == Calendar.YEAR) { buf.append("yyyy"); } else if (m_rank[i] == Calendar.MONTH) { buf.append("MM"); } else if (m_rank[i] == Calendar.DATE) { buf.append("dd"); } if (i==0) { buf.append(firstSeparator); } else if (i==1) { buf.append(secondSeparator); } } setColumns(buf.length() -1 + (m_weekdaysVisible ? 1:0 )); m_outputFormat= new SimpleDateFormat(buf.toString(),getLocale()); m_outputFormat.setTimeZone(timeZone); } public TimeZone getTimeZone() { if (m_calendar != null) return m_calendar.getTimeZone(); return null; } public Date getDate() { if ( nullValue && nullValuePossible) { return null; } Date date = m_calendar.getTime(); return date; } public void setDate(Date value) { if ( value == null) { if ( !nullValuePossible) { return; } } nullValue = value == null; if ( !nullValue) { m_calendar.setTime(value); if (m_dateRenderer != null) { renderingInfo = m_dateRenderer.getRenderingInfo( m_calendar.get(Calendar.DAY_OF_WEEK) ,m_calendar.get(Calendar.DATE) ,m_calendar.get(Calendar.MONTH) + 1 ,m_calendar.get(Calendar.YEAR) ); String text = renderingInfo.getTooltipText(); setToolTipText(text); } String formatedDate = m_outputFormat.format(value); setText(formatedDate); } else { setText(""); } } protected char[] getSeparators() { return m_separators; } protected boolean isSeparator(char c) { for (int i=0;i<m_separators.length;i++) if (m_separators[i] == c) return true; return false; } /** returns the parsingFormat of the selected locale. This is same as the default date-format of the selected locale.*/ public DateFormat getParsingFormat() { return m_parsingFormat; } /** returns the output format of the date-field. The OutputFormat always uses the full block size: 01.01.2000 instead of 1.1.2000 */ public DateFormat getOutputFormat() { return m_outputFormat; } protected void changeSelectedBlock(int[] blocks,int block,String selected,int count) { int type = m_rank[block]; if (m_rank.length<block) return; if (type == Calendar.MONTH) if (Math.abs(count) == 10) m_calendar.add(type,count/Math.abs(count) * 3); else m_calendar.add(type,count/Math.abs(count)); else if (type == Calendar.DATE) if (Math.abs(count) == 10) m_calendar.add(type,count/Math.abs(count) * 7); else m_calendar.add(type,count/Math.abs(count)); else m_calendar.add(type,count); setDate(m_calendar.getTime()); calcBlocks(blocks); markBlock(blocks,block); } public String getToolTipText(MouseEvent event) { if (m_weekdaysVisible && event.getX() >= m_weekdaysX) return super.getToolTipText(event); return null; } public boolean blocksValid() { String dateTxt = null; try { dateTxt = getText(); if ( isNullValuePossible() && dateTxt.length() == 0) { nullValue = true; return true; } m_calendar.setTime(m_parsingFormat.parse(dateTxt)); nullValue = false; return true; } catch (ParseException e) { return false; } } static int[] BLOCKLENGTH = new int[] {2,2,5}; protected int blockCount() { return BLOCKLENGTH.length; } protected void mark(int dot,int mark) { super.mark(dot,mark); if (!m_weekdaysVisible) repaint(); } protected int maxBlockLength(int block) { return BLOCKLENGTH[block]; } protected boolean isValidChar(char c) { return (Character.isDigit(c) || isSeparator(c) ); } /** This method is necessary to shorten the names down to 2 characters. Some date-formats ignore the setting. */ private String small(String string) { return string.substring(0,Math.min(string.length(),2)); } public void paint(Graphics g) { super.paint(g); if (!m_weekdaysVisible) return; Insets insets = getInsets(); final String format = nullValue ? "" :m_weekdayFormat.format(m_calendar.getTime()); String s = small(format); FontMetrics fm = g.getFontMetrics(); int width = fm.stringWidth(s); int x = getWidth()-width-insets.right-3; m_weekdaysX = x; int y = insets.top + (getHeight() - (insets.bottom + insets.top))/2 + fm.getAscent()/3; g.setColor(Color.gray); if (renderingInfo != null) { Color color = renderingInfo.getBackgroundColor(); if (color != null) { g.setColor(color); g.fillRect(x-1, insets.top, width + 3 , getHeight() - insets.bottom - insets.top - 1); } color = renderingInfo.getForegroundColor(); if (color != null) { g.setColor(color); } else { g.setColor(Color.GRAY); } } g.drawString(s,x,y); } }
04900db4-rob
src/org/rapla/components/calendar/DateField.java
Java
gpl3
12,381
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendar; import java.awt.Component; import java.awt.MouseInfo; import java.awt.Point; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import java.util.ArrayList; import javax.swing.InputVerifier; import javax.swing.JComponent; import javax.swing.JTextField; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import javax.swing.text.PlainDocument; /** The base class for TextFields that supports entering values in blocks. Most notifiably the DateField and the TimeField. <br> You can use the left/right arrow keys to switch the blocks. Use of the top/down arrow keys will increase/decrease the values in the selected block (page_up/page_down for major changes). You can specify maximum length for each block. If a block reaches this maximum value the focus will switch to the next block. @see DateField @see TimeField */ public abstract class AbstractBlockField extends JTextField { private static final long serialVersionUID = 1L; int m_markedBlock = 0; char m_lastChar = 0; boolean m_keyPressed = false; protected String m_oldText; ArrayList<ChangeListener> m_listenerList = new ArrayList<ChangeListener>(); public AbstractBlockField() { Listener listener = new Listener(); addMouseListener(listener); addActionListener(listener); addFocusListener(listener); addKeyListener(listener); addMouseWheelListener( listener ); setInputVerifier(new InputVerifier() { public boolean verify(JComponent comp) { boolean valid = blocksValid(); if ( valid ) { fireValueChanged(); } return valid; } }); } class Listener implements MouseListener,KeyListener,FocusListener,ActionListener, MouseWheelListener { public void mouseReleased(MouseEvent evt) { } public void mousePressed(MouseEvent evt) { if ( !isMouseOverComponent()) { blocksValid(); fireValueChanged(); } if ( evt.getButton() != MouseEvent.BUTTON1) { return; } // We have to mark the block on mouse pressed and mouse clicked. // Windows needs mouse clicked while Linux needs mouse pressed. markCurrentBlock(); } public void mouseEntered(MouseEvent me) { } public void mouseExited(MouseEvent me) { blocksValid(); fireValueChanged(); } public void mouseClicked(MouseEvent evt) { if ( evt.getButton() != MouseEvent.BUTTON1) { return; } // We have to mark the block on mouse pressed and mouse clicked. markCurrentBlock(); if (evt.getClickCount()>1) { selectAll(); return; } if (blocksValid()) { fireValueChanged(); } } // Implementation of ActionListener public void actionPerformed(ActionEvent e) { blocksValid(); fireValueChanged(); } public void focusGained(FocusEvent evt) { if (blocksValid()) { //setBlock(0); } } public void focusLost(FocusEvent evt) { //select(-1,-1); blocksValid(); fireValueChanged(); } public void keyPressed(KeyEvent evt) { m_keyPressed = true; m_lastChar=evt.getKeyChar(); if (!blocksValid()) return; if (isSeparator(evt.getKeyChar())) { evt.consume(); return; } switch (evt.getKeyCode()) { case KeyEvent.VK_LEFT: case KeyEvent.VK_KP_LEFT: if (blockCount() >1) { setBlock(-1); evt.consume(); } return; case KeyEvent.VK_KP_RIGHT: case KeyEvent.VK_RIGHT: if (blockCount() >1) { setBlock(1); evt.consume(); } return; case KeyEvent.VK_HOME: setBlock(-1000); evt.consume(); return; case KeyEvent.VK_END: setBlock(1000); evt.consume(); return; case KeyEvent.VK_KP_UP: case KeyEvent.VK_UP: changeSelectedBlock(1); evt.consume(); return; case KeyEvent.VK_KP_DOWN: case KeyEvent.VK_DOWN: changeSelectedBlock(-1); evt.consume(); return; case KeyEvent.VK_PAGE_UP: changeSelectedBlock(10); evt.consume(); return; case KeyEvent.VK_PAGE_DOWN: changeSelectedBlock(-10); evt.consume(); return; } } public void keyReleased(KeyEvent evt) { m_lastChar=evt.getKeyChar(); // Only change the block if the keyReleased // event follows a keyPressed. // If you type very quickly you could // get two strunged keyReleased events if (m_keyPressed == true) m_keyPressed = false; else return; if (!blocksValid()) return; if (isSeparator(m_lastChar) ) { if ( isSeparator( getText().charAt(getCaretPosition()))) nextBlock(); evt.consume(); } else if (isValidChar(m_lastChar)) { advance(); evt.consume(); if (blocksValid() && !isMouseOverComponent()) { // fireValueChanged(); } } } private boolean isMouseOverComponent() { Component comp = AbstractBlockField.this; Point compLoc = comp.getLocationOnScreen(); Point mouseLoc = MouseInfo.getPointerInfo().getLocation(); boolean result = (mouseLoc.x >= compLoc.x && mouseLoc.x <= compLoc.x + comp.getWidth() && mouseLoc.y >= compLoc.y && mouseLoc.y <= compLoc.y + comp.getHeight()); return result; } public void keyTyped(KeyEvent evt) { } public void mouseWheelMoved(MouseWheelEvent e) { if (!hasFocus()) { return; } if (!blocksValid() || e == null) return; int count = e.getWheelRotation(); changeSelectedBlock(-1 * count/(Math.abs(count))); } } private void markCurrentBlock() { if (!blocksValid()) { return; } int blockstart[] = new int[blockCount()]; int block = calcBlocks(blockstart); markBlock(blockstart,block); } public void addChangeListener(ChangeListener listener) { m_listenerList.add(listener); } /** removes a listener from this component.*/ public void removeChangeListener(ChangeListener listener) { m_listenerList.remove(listener); } public ChangeListener[] getChangeListeners() { return m_listenerList.toArray(new ChangeListener[]{}); } /** A ChangeEvent will be fired to every registered ActionListener * when the value has changed. */ protected void fireValueChanged() { if (m_listenerList.size() == 0) return; // Only fire, when text has changed. if (m_oldText != null && m_oldText.equals(getText())) return; m_oldText = getText(); ChangeEvent evt = new ChangeEvent(this); ChangeListener[] listeners = getChangeListeners(); for (int i = 0; i<listeners.length; i ++) { listeners[i].stateChanged(evt); } } // switch to next block private void nextBlock() { int[] blockstart = new int[blockCount()]; int block = calcBlocks(blockstart); markBlock(blockstart,Math.min(block + 1,blockCount() -1)); } // switch to next block if blockend is reached and private void advance() { if (blockCount()<2) return; int blockstart[] = new int[blockCount()]; int block = calcBlocks(blockstart); if (block >= blockCount() -1) return; int selectedLen = (block ==0) ? blockstart[1] : (blockstart[block + 1] - blockstart[block] - 1); if (selectedLen == maxBlockLength(block)) { markBlock(blockstart,Math.min(block + 1,blockCount() -1)); } } /** changes the value of the selected Block. Adds the count value. */ private void changeSelectedBlock(int count) { int blockstart[] = new int[blockCount()]; int block = calcBlocks(blockstart); int start = (block == 0) ? 0 : blockstart[block] + 1; int end = (block == blockCount() -1) ? getText().length() : blockstart[block+1]; String selected = getText().substring(start,end); markBlock(blockstart,block); changeSelectedBlock(blockstart,block,selected,count); } private void setBlock(int count) { if (blockCount()<1) return; int blockstart[] = new int[blockCount()]; int block = calcBlocks(blockstart); if (count !=0) markBlock(blockstart,Math.min(Math.max(0,block + count),blockCount()-1)); else markBlock(blockstart,m_markedBlock); } /** Select the specified block. */ final protected void markBlock(int[] blockstart,int block) { m_markedBlock = block; if (m_markedBlock == 0) mark(blockstart[0], (blockCount()>1) ? blockstart[1] : getText().length()); else if (m_markedBlock==blockCount()-1) mark(blockstart[m_markedBlock] + 1,getText().length()); else mark(blockstart[m_markedBlock] + 1,blockstart[m_markedBlock+1]); } private boolean isPrevSeparator(int i,char[] source,String currentText,int offs) { return (i>0 && isSeparator(source[i-1]) || (offs > 0 && isSeparator(currentText.charAt(offs-1)))); } private boolean isNextSeparator(String currentText,int offs) { return (offs < currentText.length()-1 && isSeparator(currentText.charAt(offs))); } class DateDocument extends PlainDocument { private static final long serialVersionUID = 1L; public void insertString(int offs, String str, AttributeSet a) throws BadLocationException { String currentText = getText(0, getLength()); char[] source = str.toCharArray(); char[] result = new char[source.length]; int j = 0; boolean bShouldBeep = false; for (int i = 0; i < source.length; i++) { boolean bValid = true; if (!isValidChar(source[i])) { bValid = false; } else { //if (offs < currentText.length()-1) //System.out.println("offset-char: " + currentText.charAt(offs)); // if (isSeparator(source[i])) if (isNextSeparator(currentText,offs) || isPrevSeparator(i,source,currentText,offs) || (i==0 && offs==0) || (i==source.length && offs==currentText.length()) ) { // beep(); continue; } } if (bValid) result[j++] = source[i]; else bShouldBeep = true; } if (bShouldBeep) beep(); super.insertString(offs, new String(result, 0, j), a); } public void remove(int offs, int len) throws BadLocationException { if (m_lastChar == 0 || (!isSeparator(m_lastChar) && (isValidChar(m_lastChar) || !Character.isLetter(m_lastChar)) ) ) super.remove(offs, len); } } final protected Document createDefaultModel() { return new DateDocument(); } /** Calculate the blocks. The new blockstarts will be stored in the int array. @return the block that contains the caret. */ protected int calcBlocks(int[] blockstart) { String text = getText(); int dot = getCaretPosition(); int block = 0; blockstart[0] = 0; char[] separators = getSeparators(); for (int i=1;i<blockstart.length;i++) { int min = text.length(); for (int j=0;j<separators.length;j++) { int pos = text.indexOf(separators[j], blockstart[i-1] + 1); if (pos>=0 && pos < min) min = pos; } blockstart[i] = min; if (dot>blockstart[i]) block = i; } return block; } /** Select the text from dot to mark. */ protected void mark(int dot,int mark) { setCaretPosition(mark); moveCaretPosition(dot); } /** this method will be called when an non-valid character is entered. */ protected void beep() { Toolkit.getDefaultToolkit().beep(); } /** returns true if the text can be split into blocks. */ abstract public boolean blocksValid(); /** The number of blocks for this Component. */ abstract protected int blockCount(); /** This method will be called, when the user has pressed the up/down * arrows on a selected block. * @param count Posible values are 1,-1,10,-10. */ abstract protected void changeSelectedBlock(int[] blocks,int block,String selected,int count); /** returns the maximum length of the specified block. */ abstract protected int maxBlockLength(int block); /** returns true if the character should be accepted by the component. */ abstract protected boolean isValidChar(char c); /** returns true if the character is a block-separator. All block-separators must be valid characters. @see #isValidChar */ abstract protected boolean isSeparator(char c); /** @return all seperators.*/ abstract protected char[] getSeparators(); }
04900db4-rob
src/org/rapla/components/calendar/AbstractBlockField.java
Java
gpl3
16,251
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendar; import java.awt.Color; import java.util.Calendar; /** Renders the weekdays (or any other day of week, if selected) in a special color. */ public class WeekendHighlightRenderer implements DateRenderer { Color m_weekendBackgroundColor = new Color(0xe2, 0xf3, 0xff); boolean[] m_highlightedDays = new boolean[10]; public WeekendHighlightRenderer() { setHighlight(Calendar.SATURDAY,true); setHighlight(Calendar.SUNDAY,true); } /** Default color is #e2f3ff */ public void setWeekendBackgroundColor(Color color) { m_weekendBackgroundColor = color; } /** enable/disable the highlighting for the selected day. Default highlighted days are saturday and sunday. */ public void setHighlight(int day,boolean highlight) { m_highlightedDays[day] = highlight; } public boolean isHighlighted(int day) { return m_highlightedDays[day]; } public RenderingInfo getRenderingInfo(int dayOfWeek, int day, int month, int year) { Color backgroundColor = isHighlighted(dayOfWeek) ? m_weekendBackgroundColor : null; Color foregroundColor = null; String tooltipText = null; RenderingInfo info = new RenderingInfo(backgroundColor, foregroundColor, tooltipText); return info; } }
04900db4-rob
src/org/rapla/components/calendar/WeekendHighlightRenderer.java
Java
gpl3
2,295
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendar; import java.util.Date; import java.util.EventObject; public class DateChangeEvent extends EventObject { private static final long serialVersionUID = 1L; Date m_date; public DateChangeEvent(Object source,Date date) { super(source); m_date = date; } public Date getDate() { return m_date; } }
04900db4-rob
src/org/rapla/components/calendar/DateChangeEvent.java
Java
gpl3
1,317
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendar; /* The components that implement DateChangeListener * get notified by the DateModel if the date has been changed */ public interface DateChangeListener extends java.util.EventListener { public void dateChanged(DateChangeEvent evt); }
04900db4-rob
src/org/rapla/components/calendar/DateChangeListener.java
Java
gpl3
1,222
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendar; import java.awt.ComponentOrientation; /** * The NumberField only accepts integer values. * <strong>Warning!<strong> Currently only Longs are supported. */ public class NumberField extends AbstractBlockField { private static final long serialVersionUID = 1L; static char[] m_separators = new char[0]; Number m_number; Number m_minimum; Number m_maximum; /** * @return Returns the m_blockStepSize. */ public int getBlockStepSize() { return m_blockStepSize; } /** * @param stepSize The m_blockStepSize to set. */ public void setBlockStepSize(int stepSize) { m_blockStepSize = stepSize; } /** * @return Returns the m_stepSize. */ public int getStepSize() { return m_stepSize; } /** * @param size The m_stepSize to set. */ public void setStepSize(int size) { m_stepSize = size; } int m_stepSize; int m_blockStepSize; int m_maxLength; boolean m_isNullPermitted = true; public NumberField() { setComponentOrientation( ComponentOrientation.RIGHT_TO_LEFT); updateColumns(); } public NumberField(Number minimum,Number maximum,int stepSize,int blockStepSize) { this(); setStepSize(stepSize); setBlockStepSize(blockStepSize); setMinimum( minimum ); setMaximum( maximum ); } public void setMinimum(Number minimum){ m_minimum = minimum; updateColumns(); } public void setMaximum(Number maximum){ m_maximum = maximum; updateColumns(); } public Number getMinimum() { return m_minimum; } public Number getMaximum() { return m_maximum; } private void updateColumns() { if (m_maximum!= null && m_minimum != null) { if ((Math.abs(m_maximum.longValue())) > (Math.abs(m_minimum.longValue())) * 10) m_maxLength = m_maximum.toString().length(); else m_maxLength = m_minimum.toString().length(); setColumns(m_maxLength); } else { m_maxLength = 100; setColumns(4); } } public boolean isNullPermitted() { return m_isNullPermitted; } public void setNullPermitted(boolean isNullPermitted) { m_isNullPermitted = isNullPermitted; if (m_number == null && !isNullPermitted) m_number = new Double(defaultValue()); } private long defaultValue() { if (m_minimum != null && m_minimum.longValue()>0) return m_minimum.longValue(); else if (m_maximum != null && m_maximum.longValue()<0) return m_maximum.longValue(); return 0; } public void setNumber(Number number) { updateNumber( number ); m_oldText = getText(); fireValueChanged(); } private void updateNumber(Number number) { m_number = number; String text; if (number != null) { text = String.valueOf(number.longValue()); } else { text = ""; } String previous = getText(); if ( previous != null && text.equals( previous)) { return; } setText( text ); } public void increase() { changeSelectedBlock(new int[1],0,"",1); } public void decrease() { changeSelectedBlock(new int[1],0,"",-1); } public Number getNumber() { return m_number; } public boolean allowsNegative() { return (m_minimum == null || m_minimum.longValue()<0); } protected char[] getSeparators() { return m_separators; } protected boolean isSeparator(char c) { return false; } protected void changeSelectedBlock(int[] blocks,int block,String selected,int count) { long longValue = ((m_number != null) ? m_number.longValue() : defaultValue()); if (count == 1) longValue = longValue + m_stepSize; if (count == -1) longValue = longValue - m_stepSize; if (count == 10) longValue = longValue + m_blockStepSize; if (count == -10) longValue = longValue - m_blockStepSize; if (m_minimum != null && longValue<m_minimum.longValue()) longValue = m_minimum.longValue(); if (m_maximum != null && longValue>m_maximum.longValue()) longValue = m_maximum.longValue(); updateNumber(new Long(longValue)); calcBlocks(blocks); markBlock(blocks,block); } public boolean blocksValid() { try { String text = getText(); if (text.length() ==0) { if (isNullPermitted()) m_number = null; return true; } long newLong = Long.parseLong(text); if ((m_minimum == null || newLong>=m_minimum.longValue()) && (m_maximum == null || newLong<=m_maximum.longValue())) { m_number = new Long(newLong); return true; } } catch (NumberFormatException e) { if (isNullPermitted()) m_number = null; } return false; } protected int blockCount() { return 1; } protected int maxBlockLength(int block) { return m_maxLength; } protected boolean isValidChar(char c) { return (Character.isDigit(c) || (allowsNegative() && c=='-')); } }
04900db4-rob
src/org/rapla/components/calendar/NumberField.java
Java
gpl3
6,523
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendar; import java.awt.Color; /** Implement this interface if you want to highlight special days or show tooltip for some days. Use {@link DateRendererAdapter} if you want to work with Date objects. */ public interface DateRenderer { /** Specifies a rendering info ( colors and tooltip text) for the passed day. Return null if you don't want to use rendering info for this day. month ranges from 1-12*/ public RenderingInfo getRenderingInfo(int dayOfWeek,int day,int month, int year); class RenderingInfo { Color backgroundColor; Color foregroundColor; String tooltipText; public RenderingInfo(Color backgroundColor, Color foregroundColor, String tooltipText) { this.backgroundColor = backgroundColor; this.foregroundColor = foregroundColor; this.tooltipText = tooltipText; } public Color getBackgroundColor() { return backgroundColor; } public Color getForegroundColor() { return foregroundColor; } public String getTooltipText() { return tooltipText; } } }
04900db4-rob
src/org/rapla/components/calendar/DateRenderer.java
Java
gpl3
2,156
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendar; import java.awt.Font; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import javax.swing.JComponent; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; /** This is another ComboBox-like calendar component. * It is localizable and it uses swing-components. * <p>The combobox editor is a {@link DateField}. If the ComboBox-Button * is pressed, a CalendarMenu will drop down.</p> * @see CalendarMenu * @see DateField * @author Christopher Kohlhaas */ public final class RaplaCalendar extends RaplaComboBox { private static final long serialVersionUID = 1L; protected DateField m_dateField; protected CalendarMenu m_calendarMenu; Collection<DateChangeListener> m_listenerList = new ArrayList<DateChangeListener>(); protected DateModel m_model; private Date m_lastDate; DateRenderer m_dateRenderer; /** Create a new Calendar with the default locale. The calendarmenu will be accessible via a drop-down-box */ public RaplaCalendar() { this(Locale.getDefault(),TimeZone.getDefault(),true); } public DateField getDateField() { return m_dateField; } /** Create a new Calendar with the specified locale and timezone. The calendarmenu will be accessible via a drop-down-box */ public RaplaCalendar(Locale locale,TimeZone timeZone) { this(locale,timeZone,true); } /** Create a new Calendar with the specified locale and timezone. The isDropDown flag specifies if the calendarmenu should be accessible via a drop-down-box. Alternatively you can get the calendarmenu with getPopupComponent(). */ public RaplaCalendar(Locale locale,TimeZone timeZone,boolean isDropDown) { super(isDropDown,new DateField(locale,timeZone)); m_model = new DateModel(locale,timeZone); m_dateField = (DateField) m_editorComponent; Listener listener = new Listener(); m_dateField.addChangeListener(listener); m_model.addDateChangeListener(listener); m_lastDate = m_model.getDate(); setDateRenderer(new WeekendHighlightRenderer()); } class Listener implements ChangeListener,DateChangeListener { // Implementation of ChangeListener public void stateChanged(ChangeEvent evt) { validateEditor(); } // Implementation of DateChangeListener public void dateChanged(DateChangeEvent evt) { closePopup(); if (needSync()) m_dateField.setDate(evt.getDate()); if (m_lastDate == null || !m_lastDate.equals(evt.getDate())) fireDateChange(evt.getDate()); m_lastDate = evt.getDate(); } } public TimeZone getTimeZone() { return m_model.getTimeZone(); } /* Use this to get the CalendarMenu Component. The calendar menu will be created lazily.*/ public JComponent getPopupComponent() { if (m_calendarMenu == null) { m_calendarMenu = new CalendarMenu(m_model); m_calendarMenu.setFont( getFont() ); // #TODO Property change listener for TimeZone m_calendarMenu.getDaySelection().setDateRenderer(m_dateRenderer); javax.swing.ToolTipManager.sharedInstance().registerComponent(m_calendarMenu.getDaySelection()); } return m_calendarMenu; } public void setFont(Font font) { super.setFont(font); // Method called during super-constructor? if (m_calendarMenu == null || font == null) return; m_calendarMenu.setFont(font); } /** Selects the date relative to the given timezone. * The hour,minute,second and millisecond values will be ignored. */ public void setDate(Date date) { if ( date != null) { m_model.setDate(date); } else { boolean changed = m_dateField.getDate() != null; m_dateField.setDate( null); m_lastDate =null; if ( changed ) { fireDateChange(null); } } } /** Parse the returned date with a calendar-object set to the * correct time-zone to get the date,month and year. The * hour,minute,second and millisecond values should be ignored. * @return the selected date * @see #getYear * @see #getMonth * @see #getDay */ public Date getDate() { if ( m_dateField.isNullValue()) { return null; } return m_model.getDate(); } /** selects the specified day, month and year. @see #setDate(Date date)*/ public void select(int day,int month,int year) { m_model.setDate(day,month,year); } /** sets the DateRenderer for the calendar */ public void setDateRenderer(DateRenderer dateRenderer) { m_dateRenderer = dateRenderer; if (m_calendarMenu != null) { m_calendarMenu.getDaySelection().setDateRenderer(m_dateRenderer); } m_dateField.setDateRenderer(m_dateRenderer); } /** you can choose, if weekdays should be displayed in the right corner of the DateField. Default is true. This method simply calls setWeekdaysVisble on the DateField Component. If a DateRender is installed the weekday will be rendered with the DateRenderer. This includes a tooltip that shows up on the DateRenderer. @see DateField */ public void setWeekdaysVisibleInDateField(boolean bVisible) { m_dateField.setWeekdaysVisible(bVisible); } /** @return the selected year (relative to the given TimeZone) @see #getDate @see #getMonth @see #getDay */ public int getYear() {return m_model.getYear(); } /** @return the selected month (relative to the given TimeZone) @see #getDate @see #getYear @see #getDay */ public int getMonth() {return m_model.getMonth(); } /** @return the selected day (relative to the given TimeZone) @see #getDate @see #getYear @see #getMonth */ public int getDay() {return m_model.getDay(); } /** registers new DateChangeListener for this component. * A DateChangeEvent will be fired to every registered DateChangeListener * when the a different date is selected. * @see DateChangeListener * @see DateChangeEvent */ public void addDateChangeListener( DateChangeListener listener ) { m_listenerList.add(listener); } /** removes a listener from this component.*/ public void removeDateChangeListener( DateChangeListener listener ) { m_listenerList.remove(listener); } public DateChangeListener[] getDateChangeListeners() { return m_listenerList.toArray(new DateChangeListener[]{}); } /** A DateChangeEvent will be fired to every registered DateChangeListener * when the a different date is selected. */ protected void fireDateChange( Date date ) { if (m_listenerList.size() == 0) return; DateChangeListener[] listeners = getDateChangeListeners(); DateChangeEvent evt = new DateChangeEvent(this,date); for (int i = 0;i<listeners.length;i++) { listeners[i].dateChanged(evt); } } protected void showPopup() { validateEditor(); super.showPopup(); } /** test if we need to synchronize the dateModel and the dateField*/ private boolean needSync() { return (isNullValuePossible() && m_dateField.getDate() == null ) || (m_dateField.getDate() != null && !m_model.sameDate(m_dateField.getDate())) ; } protected void validateEditor() { if (needSync() ) if (m_dateField.isNullValue()) { if ( m_lastDate != null) { m_lastDate = null; fireDateChange(null); } } else { m_model.setDate(m_dateField.getDate()); } } public boolean isNullValuePossible() { return m_dateField.isNullValuePossible(); } public void setNullValuePossible(boolean nullValuePossible) { m_dateField.setNullValuePossible(nullValuePossible); } }
04900db4-rob
src/org/rapla/components/calendar/RaplaCalendar.java
Java
gpl3
9,393
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendar; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Polygon; import java.awt.event.ActionEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.AbstractButton; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.plaf.ButtonUI; public class NavButton extends AbstractButton implements MouseListener { private static final long serialVersionUID = 1L; Polygon m_poly; char m_type; boolean m_buttonDown = false; Color m_disabledColor; boolean m_enabled=true; boolean m_border=true; int m_delay = 0; int leftPosition; ButtonStateChecker m_checker = new ButtonStateChecker(); /** You can set the alignment of the arrow with one of these four characters: '<', '^', '>', 'v' */ public NavButton(char type) { this(type,18); } public NavButton(char type,int size) { this(type,size,true); } public NavButton(char type,int size,boolean border) { super(); m_border = border; m_type = type; setSize(size,size); addMouseListener(this); m_disabledColor = UIManager.getColor("Button.disabledText"); } /** Here you can set if the button should fire repeated clicks. If set to 0 the button will fire only once when pressed. */ public void setClickRepeatDelay(int millis) { m_delay = millis; } public int getClickRepeatDelay() { return m_delay; } public void setUI(ButtonUI ui) { super.setUI(ui); m_disabledColor = UIManager.getColor("Button.disabledText"); } void setLeftPosition(int position) { leftPosition = position; } /** Implementation-specific. Should be private.*/ public void mouseEntered(MouseEvent me) { } /** Implementation-specific. Should be private.*/ public void mouseExited(MouseEvent me) { } /** Implementation-specific. Should be private.*/ public void mousePressed(MouseEvent me) { if (!isEnabled()) return; m_buttonDown = true; repaint(); m_checker.start(); } /** Implementation-specific. Should be private.*/ public void mouseReleased(MouseEvent me) { m_buttonDown = false; repaint(); } /** Implementation-specific. Should be private.*/ public void mouseClicked(MouseEvent me) { m_buttonDown = false; repaint(); } /** Set the size of the nav-button. A nav button is square. The maximum of width and height will be used as new size. */ public void setSize(int width,int height) { int size = Math.max(width,height); m_poly = new ArrowPolygon(m_type,size,m_border); super.setSize(size,size); Dimension dim = new Dimension(size,size); setPreferredSize(dim); setMaximumSize(dim); setMinimumSize(dim); } public void setEnabled(boolean enabled) { m_enabled = enabled; repaint(); } public boolean isEnabled() { return m_enabled; } public void paint(Graphics g) { g.translate( leftPosition, 0); if (m_buttonDown) { //g.setColor( UIManager.getColor("Button.pressed")); g.setColor( UIManager.getColor("Button.focus")); g.fillPolygon(m_poly); g.drawPolygon(m_poly); } else { if (isEnabled()) { g.setColor( UIManager.getColor("Button.font") ); g.fillPolygon(m_poly); } else { g.setColor(m_disabledColor); } g.drawPolygon(m_poly); } } class ButtonStateChecker implements Runnable{ long startMillis; long startDelay; public void start() { startDelay = m_delay * 8; fireAndReset(); if (m_delay > 0) SwingUtilities.invokeLater(this); } private void fireAndReset() { fireActionPerformed(new ActionEvent(this ,ActionEvent.ACTION_PERFORMED ,"")); startMillis = System.currentTimeMillis(); } public void run() { if (!m_buttonDown) return; if ((Math.abs(System.currentTimeMillis() - startMillis) > startDelay)) { if (startDelay > m_delay) startDelay = startDelay/2; fireAndReset(); } try { Thread.sleep(10); } catch (Exception ex) { return; } SwingUtilities.invokeLater(this); } } }
04900db4-rob
src/org/rapla/components/calendar/NavButton.java
Java
gpl3
5,798
<body> Contains widgets for date- and time- selection. This package is independant from the rest of rapla. </body>
04900db4-rob
src/org/rapla/components/calendar/package.html
HTML
gpl3
119
/*--------------------------------------------------------------------------* | Copyright (C) 2003 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendar; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Font; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.JPanel; import javax.swing.SwingUtilities; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.EventListenerList; /** The RaplaNumber is an adapter for NumberField. * <strong>Warning!<strong> Currently only Longs are supported. * @see NumberField */ public final class RaplaNumber extends JPanel{ private static final long serialVersionUID = 1L; NumberField m_numberField = null; public static Number ZERO = new Long(0); public static Number ONE = new Long(1); public static Number DEFAULT_STEP_SIZE = new Long(1); EventListenerList m_listenerList; Listener m_listener = new Listener(); Number m_emptyValue = ZERO; JPanel m_buttonPanel = new JPanel(); RaplaArrowButton m_upButton = new RaplaArrowButton('+', 15);//'^',10,false); RaplaArrowButton m_downButton = new RaplaArrowButton('-', 15);//new NavButton('v',10,false); /** currently only Longs are supported */ public RaplaNumber() { this( null, null, null, false); } public RaplaNumber(Number value,Number minimum,Number maximum,boolean isNullPermitted) { m_numberField = new NumberField(minimum,maximum,DEFAULT_STEP_SIZE.intValue(),10); m_numberField.setNumber(value); m_numberField.setNullPermitted(isNullPermitted); if (minimum != null && minimum.longValue()>0) m_emptyValue = minimum; else if (maximum != null && maximum.longValue()<0) m_emptyValue = maximum; m_buttonPanel.setLayout(new GridLayout(2,1)); m_buttonPanel.add(m_upButton); m_upButton.setBorder( null); m_buttonPanel.add(m_downButton); m_downButton.setBorder(null); m_buttonPanel.setMinimumSize(new Dimension(18,20)); m_buttonPanel.setPreferredSize(new Dimension(18,20)); m_buttonPanel.setBorder(BorderFactory.createEtchedBorder()); m_upButton.setClickRepeatDelay(50); m_downButton.setClickRepeatDelay(50); m_upButton.addActionListener(m_listener); m_downButton.addActionListener(m_listener); setLayout(new BorderLayout()); add(m_numberField,BorderLayout.CENTER); add(m_buttonPanel,BorderLayout.EAST); m_upButton.setFocusable( false); m_downButton.setFocusable( false); } public void setFont(Font font) { super.setFont(font); // Method called during constructor? if (m_numberField == null || font == null) return; m_numberField.setFont(font); } public void setColumns(int columns) { m_numberField.setColumns(columns); } public NumberField getNumberField() { return m_numberField; } public void setEnabled( boolean enabled ) { super.setEnabled( enabled ); if ( m_numberField != null ) { m_numberField.setEnabled( enabled ); } if ( m_upButton != null ) { m_upButton.setEnabled ( enabled ); m_downButton.setEnabled ( enabled ); } } /** currently only Longs are supported */ public void setNumber(Number newValue) { m_numberField.setNumber(newValue); } public Number getNumber() { return m_numberField.getNumber(); } public void addChangeListener(ChangeListener changeListener) { if (m_listenerList == null) { m_listenerList = new EventListenerList(); m_numberField.addChangeListener(m_listener); } m_listenerList.add(ChangeListener.class,changeListener); } public void removeChangeListener(ChangeListener changeListener) { if (m_listenerList == null) { return; } m_listenerList.remove(ChangeListener.class,changeListener); } class Listener implements ChangeListener,ActionListener { public void actionPerformed(ActionEvent evt) { m_numberField.requestFocus(); if (evt.getSource() == m_upButton) { m_numberField.increase(); } if (evt.getSource() == m_downButton) { m_numberField.decrease(); } SwingUtilities.invokeLater( new Runnable() { public void run() { stateChanged(null); m_numberField.selectAll(); } } ); } public void stateChanged(ChangeEvent originalEvent) { if (m_listenerList == null) return; ChangeEvent evt = new ChangeEvent(RaplaNumber.this); Object[] listeners = m_listenerList.getListenerList(); for (int i = listeners.length-2; i>=0; i-=2) { if (listeners[i]==ChangeListener.class) { ((ChangeListener)listeners[i+1]).stateChanged(evt); } } } } }
04900db4-rob
src/org/rapla/components/calendar/RaplaNumber.java
Java
gpl3
6,153
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendar; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; /** Maps the DateRenderer methods to the appropriate date method. @see DateRenderer */ public class DateRendererAdapter implements DateRenderer { Calendar m_calendar; DateRenderer m_renderer = null; /** use this constructor if you want to implement a custom getBackgroundColor(Date) or getToolTipText(Date) method. */ public DateRendererAdapter(TimeZone timeZone,Locale locale) { m_calendar = Calendar.getInstance(timeZone,locale); } /** use this constructor if you want to make an existing {@link DateRenderer} listen to the methods getBackgroundColor(Date) and getToolTipText(Date). */ public DateRendererAdapter(DateRenderer renderer,TimeZone timeZone,Locale locale) { m_calendar = Calendar.getInstance(timeZone,locale); m_renderer = renderer; } /** override this method for a custom renderiungInfo @return null.*/ public RenderingInfo getRenderingInfo(Date date) { if (m_renderer == null) return null; m_calendar.setTime(date); return m_renderer.getRenderingInfo( m_calendar.get(Calendar.DAY_OF_WEEK) ,m_calendar.get(Calendar.DATE) ,m_calendar.get(Calendar.MONTH) + 1 ,m_calendar.get(Calendar.YEAR) ); } /* calls {@link #getBackgroundColor(Date)} */ public RenderingInfo getRenderingInfo(int dayOfWeek,int day,int month, int year) { m_calendar.set(Calendar.DATE,day); m_calendar.set(Calendar.MONTH,month -1 ); m_calendar.set(Calendar.YEAR,year); m_calendar.set(Calendar.HOUR_OF_DAY,0); m_calendar.set(Calendar.MINUTE,0); m_calendar.set(Calendar.SECOND,0); m_calendar.set(Calendar.MILLISECOND,0); return getRenderingInfo(m_calendar.getTime()); } }
04900db4-rob
src/org/rapla/components/calendar/DateRendererAdapter.java
Java
gpl3
3,069
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendar; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Locale; import javax.swing.JComponent; import javax.swing.UIManager; import org.rapla.components.calendar.DateRenderer.RenderingInfo; /** The graphical date-selection field * @author Christopher Kohlhaas */ final class DaySelection extends JComponent implements DateChangeListener,MouseListener { private static final long serialVersionUID = 1L; // 7 rows and 7 columns static final int ROWS = 7; //including the header row static final int COLUMNS = 7; // 6 * 7 Fields for the Month + 7 Fields for the Header static final int FIELDS = (ROWS - 1) * COLUMNS; static final int HBORDER = 0; // horizontal BORDER of the component static final int VBORDER = 0; // vertical BORDER of the component static final int VGAP = 2; // vertical gap between the cells static final int HGAP = 2; // horizontal gap between the cells static final Color DARKBLUE = new Color(0x00, 0x00, 0x88); static final Color LIGHTGRAY = new Color(0xdf, 0xdf, 0xdf); static final Color FOCUSCOLOR = UIManager.getColor("Button.focus"); static final Color DEFAULT_CELL_BACKGROUND = Color.white; static final Color HEADER = Color.white; static final Color HEADER_BACKGROUND = DARKBLUE; static final Color SELECTION = Color.white; static final Color SELECTION_BACKGROUND = DARKBLUE; static final Color SELECTION_BORDER = Color.red; static final Color SELECTABLE = Color.black; static final Color UNSELECTABLE = LIGHTGRAY; /** stores the weekdays order e.g so,mo,tu,.. or mo,tu. * Requirement: The week has seven days */ private int[] weekday2slot = new int[8]; /** stores the weekdayNames mon - sun. * Requirement: The week has seven days. */ private String[] weekdayNames = new String[7]; /** stores the days 1 - 31 days[1] = 1 * <br>maximum days per month 40 */ private String[] days = new String[40]; private int selectedField = 10; private int focusedField = 10; private DateModel model; private DateModel focusModel; private int lastFocusedMonth; // performance improvement private int lastFocusedYear; // performance improvement private PaintEnvironment e; private DateRenderer dateRenderer = null; public DaySelection(DateModel model,DateModel focusModel) { this.model = model; this.focusModel = focusModel; focusModel.addDateChangeListener(this); addMouseListener(this); createWeekdays(model.getLocale()); createDays(model.getLocale()); // setFont(DEFAULT_FONT); } /** Implementation-specific. Should be private.*/ public void mousePressed(MouseEvent me) { me.consume(); selectField(me.getX(),me.getY()); } /** Implementation-specific. Should be private.*/ public void mouseReleased(MouseEvent me) { me.consume(); } /** Implementation-specific. Should be private.*/ public void mouseClicked(MouseEvent me) { me.consume(); } /** Implementation-specific. Should be private.*/ public void mouseEntered(MouseEvent me) { } /** You must call javax.swing.ToolTipManager.sharedInstance().registerComponent(thisComponent) to enable ToolTip text. */ public String getToolTipText(MouseEvent me) { int day = calcDay(me.getX(),me.getY()); if (day >=0 && dateRenderer != null) return dateRenderer.getRenderingInfo(focusModel.getWeekday(day), day, focusModel.getMonth(), focusModel.getYear()).getTooltipText(); else return ""; } /** Implementation-specific. Should be private.*/ public void mouseExited(MouseEvent me) { } public void setDateRenderer(DateRenderer dateRenderer) { this.dateRenderer = dateRenderer; } // Recalculate the Components minimum and maximum sizes private void calculateSizes() { if (e == null) e = new PaintEnvironment(); int maxWidth =0; FontMetrics fm = getFontMetrics(getFont()); e.fontHeight = fm.getHeight(); e.cellHeight = fm.getHeight() + VGAP *2; for (int i=0;i<weekdayNames.length;i++) { int len = fm.stringWidth(weekdayNames[i]); if (len>maxWidth) maxWidth = len; } if (fm.stringWidth("33")> maxWidth) maxWidth = fm.stringWidth("33"); e.fontWidth = maxWidth; e.cellWidth = maxWidth + HGAP * 2 ; int width = COLUMNS * e.cellWidth + HBORDER *2; setPreferredSize(new Dimension( width,(ROWS) * e.cellHeight + 2*HBORDER)); setMinimumSize(new Dimension( width,(ROWS) * e.cellHeight + 2*VBORDER)); invalidate(); } public void setFont(Font font) { super.setFont(font); if (font == null) return; else // We need the font-size to calculate the component size calculateSizes(); } public Dimension getPreferredSize() { if (getFont() != null && e==null) // We need the font-size to calculate the component size calculateSizes(); return super.getPreferredSize(); } public void dateChanged(DateChangeEvent evt) { if (e==null) // We need the font-size to calculate the component size if (getFont() != null ) calculateSizes(); else return; int lastSelectedField = selectedField; if (model.getMonth() == focusModel.getMonth() && model.getYear() == focusModel.getYear()) // #BUGFIX consider index shift. // weekdays 1..7 and days 1..31 but field 0..40 selectedField = weekday2slot[model.firstWeekday()]+ (model.getDay() - 1) ; else selectedField = -1; int lastFocusedField = focusedField; // #BUGFIX consider index shift. // weekdays 1..7 and days 1..31 but field 0..40 int newFocusedField = weekday2slot[focusModel.firstWeekday()] + (focusModel.getDay() - 1) ; if (lastSelectedField == selectedField && lastFocusedMonth == focusModel.getMonth() && lastFocusedYear == focusModel.getYear() ) { // Only repaint the focusedField (Performance improvement) focusedField = -1; calculateRectangle(lastFocusedField); repaint(e.r); focusedField = newFocusedField; calculateRectangle(focusedField); repaint(e.r); } else { // repaint everything focusedField = newFocusedField; repaint(); } lastFocusedMonth = focusModel.getMonth(); lastFocusedYear = focusModel.getYear(); } /** calculate the day of month from the specified field. 1..31 */ private int calcDay(int field) { return (field + 1) - weekday2slot[focusModel.firstWeekday()] ; } /** calculate the day of month from the x and y coordinates. @return -1 if coordinates don't point to a day in the selected month */ private int calcDay(int x,int y) { int col = (x - HBORDER) / e.cellWidth; int row = (y - VBORDER) / e.cellHeight; int field = 0; // System.out.println(row + ":" + col); if ( row > 0 && col < COLUMNS && row < ROWS) { field =(row-1) * COLUMNS + col; } if (belongsToMonth(field)) { return calcDay(field); } else { return -1; } } private void createDays(Locale locale) { NumberFormat format = NumberFormat.getInstance(locale); // Try to simluate a right align of the numbers with a space for ( int i=0; i <10; i++) days[i] = " " + format.format(i); for ( int i=10; i < 40; i++) days[i] = format.format(i); } /** This method is necessary to shorten the names down to 2 characters. Some date-formats ignore the setting. */ private String small(String string) { return string.substring(0,Math.min(string.length(),2)); } private void createWeekdays(Locale locale ) { Calendar calendar = Calendar.getInstance(locale); SimpleDateFormat format = new SimpleDateFormat("EE",locale); calendar.set(Calendar.DAY_OF_WEEK,calendar.getFirstDayOfWeek()); for (int i=0;i<7;i++) { weekday2slot[calendar.get(Calendar.DAY_OF_WEEK)] = i; weekdayNames[i] = small(format.format(calendar.getTime())); calendar.add(Calendar.DAY_OF_WEEK,1); } } // calculates the rectangle for a given field private void calculateRectangle(int field) { int row = (field / COLUMNS) + 1; int col = (field % COLUMNS); calculateRectangle(row,col); } // calculates the rectangle for a given row and col private void calculateRectangle(int row,int col) { Rectangle r = e.r; r.x = e.cellWidth * col + HBORDER; r.y = e.cellHeight * row + VBORDER; r.width = e.cellWidth; r.height = e.cellHeight; } private void calculateTextPos(int field) { int row = (field / COLUMNS) + 1; int col = (field % COLUMNS); calculateTextPos(row,col); } // calculates the text-anchor for a giver field private void calculateTextPos(int row,int col) { Point p = e.p; p.x = e.cellWidth * col + HBORDER + (e.cellWidth - e.fontWidth)/2; p.y = e.cellHeight * row + VBORDER + e.fontHeight - 1; } private boolean belongsToMonth(int field) { return (calcDay(field) > 0 && calcDay(field) <= focusModel.daysMonth()); } private void selectField(int x,int y) { int day = calcDay(x,y); if ( day >=0 ) { model.setDate(day, focusModel.getMonth(), focusModel.getYear()); } // end of if () } private Color getBackgroundColor(RenderingInfo renderingInfo) { Color color = null; if ( renderingInfo != null) { color = renderingInfo.getBackgroundColor(); } if (color != null) return color; return DEFAULT_CELL_BACKGROUND; } protected RenderingInfo getRenderingInfo(int field) { RenderingInfo renderingInfo = null; int day = calcDay(field); if (belongsToMonth(field) && dateRenderer != null) { renderingInfo = dateRenderer.getRenderingInfo(focusModel.getWeekday(day), day, focusModel.getMonth(), focusModel.getYear()); } return renderingInfo; } // return the Daytext, that should be displayed in the specified field private String getText(int field) { int index = 0; if ( calcDay(field) < 1) index = focusModel.daysLastMonth() + calcDay(field) ; if (belongsToMonth(field)) index = calcDay(field); if ( calcDay(field) > focusModel.daysMonth() ) index = calcDay(field) - focusModel.daysMonth(); return days[index]; } static char[] test = {'1'}; private void drawField(int field,boolean highlight) { if (field <0) return; Graphics g = e.g; Rectangle r = e.r; Point p = e.p; calculateRectangle(field); RenderingInfo renderingInfo = getRenderingInfo( field); if ( field == selectedField ) { g.setColor(SELECTION_BACKGROUND); g.fillRect(r.x +2 ,r.y +2 ,r.width-4,r.height-4); g.setColor(SELECTION_BORDER); //g.drawRect(r.x,r.y,r.width-1,r.height-1); g.drawRect(r.x+1,r.y+1,r.width-3,r.height-3); if ( field == focusedField ) { g.setColor(FOCUSCOLOR); } else { g.setColor(getBackgroundColor(renderingInfo)); } g.drawRect(r.x,r.y,r.width-1,r.height-1); g.setColor(SELECTION); } else if ( field == focusedField ) { g.setColor(getBackgroundColor(renderingInfo)); g.fillRect(r.x,r.y,r.width -1,r.height -1); g.setColor(FOCUSCOLOR); g.drawRect(r.x,r.y,r.width-1,r.height-1); if ( highlight) { g.setColor(SELECTABLE); } else { g.setColor(UNSELECTABLE); } // end of else } else { g.setColor(getBackgroundColor(renderingInfo)); g.fillRect(r.x ,r.y ,r.width ,r.height); if ( highlight) { g.setColor(SELECTABLE); } else { g.setColor(UNSELECTABLE); } // end of else } calculateTextPos(field); if ( field!= selectedField) { if ( renderingInfo != null) { Color foregroundColor = renderingInfo.getForegroundColor(); if ( foregroundColor != null) { g.setColor( foregroundColor); } } } g.drawString(getText(field) , p.x , p.y); } private void drawHeader() { Graphics g = e.g; Point p = e.p; g.setColor(HEADER_BACKGROUND); g.fillRect(HBORDER,VBORDER, getSize().width - 2 * HBORDER, e.cellHeight); g.setColor(HEADER); for ( int i=0; i < COLUMNS; i++) { calculateTextPos(0,i); g.drawString(weekdayNames[i], p.x,p.y); } } private void paintComplete() { drawHeader(); int field = 0; int start = weekday2slot[focusModel.firstWeekday()]; int end= start + focusModel.daysMonth() -1 ; for ( int i=0; i< start; i++) { drawField(field ++,false); } for ( int i= start; i <= end ; i++) { drawField(field ++,true); } for ( int i= end + 1; i< FIELDS ; i++) { drawField(field ++,false); } } private void updateEnvironment(Graphics g) { e.cellWidth = (getSize().width - HBORDER * 2) / COLUMNS; e.g = g; } public void paint(Graphics g) { super.paint(g); if (e==null) if (getFont() != null ) // We need the font-size to calculate the component size calculateSizes(); else return; updateEnvironment(g); paintComplete(); drawField(selectedField,true); drawField(focusedField,true); } } // Environment stores the values that would normaly be stored on the stack. // This is to speedup performance, e.g. new Point and new Rectangle are only called once. class PaintEnvironment { Graphics g; int cellWidth; int cellHeight; int fontWidth; int fontHeight; Point p = new Point(); Rectangle r = new Rectangle(); }
04900db4-rob
src/org/rapla/components/calendar/DaySelection.java
Java
gpl3
16,229
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendar; import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Dimension; import java.awt.Font; import java.awt.Point; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.Timer; import java.util.TimerTask; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.event.PopupMenuEvent; import javax.swing.event.PopupMenuListener; /** This is an alternative ComboBox implementation. The main differences are: <ul> <li>No pluggable look and feel</li> <li>drop-down button and editor in a separate component (each can get focus)</li> <li>the popup-component can be an arbitrary JComponent.</li> </ul> */ public abstract class RaplaComboBox extends JPanel { private static final long serialVersionUID = 1L; private JPopupMenu m_popup; private boolean m_popupVisible = false; private boolean m_isDropDown = true; protected RaplaArrowButton m_popupButton; protected JLabel jLabel; protected JComponent m_editorComponent; // If you click on the popupButton while the PopupWindow is shown, // the Window will be closed, because you clicked outside the Popup // (not because you clicked that special button). // The flag popupVisible is unset. // After that the same click will trigger the actionPerfomed method // on our button. And the window would popup again. // Solution: We track down that one mouseclick that closes the popup // with the following flags: private boolean m_closing = false; private boolean m_pressed = false; private Listener m_listener = new Listener(); public RaplaComboBox(JComponent editorComponent) { this(true,editorComponent); } RaplaComboBox(boolean isDropDown,JComponent editorComponent) { m_editorComponent = editorComponent; m_isDropDown = isDropDown; jLabel = new JLabel(); setLayout(new BorderLayout()); add(jLabel,BorderLayout.WEST); add(m_editorComponent,BorderLayout.CENTER); if (m_isDropDown) { installPopupButton(); add(m_popupButton,BorderLayout.EAST); m_popupButton.addActionListener(m_listener); m_popupButton.addMouseListener(m_listener); m_popupVisible = false; } } public JLabel getLabel() { return jLabel; } class Listener implements ActionListener,MouseListener,PopupMenuListener { // Implementation of ActionListener public void actionPerformed(ActionEvent e) { // Ignore action, when Popup is closing log("Action Performed"); if (m_pressed && m_closing) { m_closing = false; return; } if ( !m_popupVisible && !m_closing) { log("Open"); showPopup(); } else { m_popupVisible = false; closePopup(); } // end of else } private void log(@SuppressWarnings("unused") String string) { // System.out.println(System.currentTimeMillis() / 1000 + "m_visible:" + m_popupVisible + " closing: " + m_closing + " [" + string + "]"); } // Implementation of MouseListener public void mousePressed(MouseEvent evt) { m_pressed = true; m_closing = false; log("Pressed"); } public void mouseClicked(MouseEvent evt) { m_closing = false; } public void mouseReleased(MouseEvent evt) { m_pressed = false; m_closing = false; log("Released"); } public void mouseEntered(MouseEvent me) { } public void mouseExited(MouseEvent me) { } // Implementation of PopupListener public void popupMenuWillBecomeVisible(PopupMenuEvent e) { m_popupVisible = true; } public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { m_popupVisible = false; m_closing = true; m_popupButton.requestFocus(); m_popupButton.setChar('v'); log("Invisible"); final boolean oldState = m_popupButton.isEnabled(); m_popupButton.setEnabled( false); final Timer timer = new Timer(true); TimerTask task = new TimerTask() { public void run() { m_popupButton.setEnabled( oldState); } }; timer.schedule(task, 100); } public void popupMenuCanceled(PopupMenuEvent e) { m_popupVisible = false; m_closing = true; m_popupButton.requestFocus(); log("Cancel"); } } private void installPopupButton() { // Maybe we could use the combobox drop-down button here. m_popupButton = new RaplaArrowButton('v'); } public void setFont(Font font) { super.setFont(font); // Method called during constructor? if (font == null) return; if (m_editorComponent != null) m_editorComponent.setFont(font); if (m_popupButton != null && m_isDropDown) { int size = (int) getPreferredSize().getHeight(); m_popupButton.setSize(size,size); } } public void setEnabled( boolean enabled ) { super.setEnabled( enabled ); if ( m_editorComponent != null ) { m_editorComponent.setEnabled( enabled ); } if ( m_popupButton != null ) { m_popupButton.setEnabled ( enabled ); } } protected void showPopup() { if (m_popup == null) createPopup(); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Dimension menuSize = m_popup.getPreferredSize(); Dimension buttonSize = m_popupButton.getSize(); Point location = m_popupButton.getLocationOnScreen(); int diffx= buttonSize.width - menuSize.width; if (location.x + diffx<0) diffx = - location.x; int diffy= buttonSize.height; if (location.y + diffy + menuSize.height > screenSize.height) diffy = screenSize.height - menuSize.height - location.y; m_popup.show(m_popupButton,diffx,diffy); m_popup.requestFocus(); m_popupButton.setChar('^'); } protected void closePopup() { if (m_popup != null && m_popup.isVisible()) { // #Workaround for JMenuPopup-Bug in JDK 1.4 // intended behaviour: m_popup.setVisible(false); javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { // Show JMenuItem and fire a mouse-click cardLayout.last(m_popup); menuItem.menuSelectionChanged(true); menuItem.dispatchEvent(new MouseEvent(m_popup ,MouseEvent.MOUSE_RELEASED ,System.currentTimeMillis() ,0 ,0 ,0 ,1 ,false)); // show original popup again cardLayout.first(m_popup); m_popupButton.requestFocus(); } }); } m_popupVisible = false; } private JMenuItem menuItem; private CardLayout cardLayout; class MyPopup extends JPopupMenu { private static final long serialVersionUID = 1L; MyPopup() { super(); } public void menuSelectionChanged(boolean isIncluded) { closePopup(); } } private void createPopup() { m_popup = new JPopupMenu(); /* try { PopupMenu.class.getMethod("isPopupTrigger",new Object[]{}); } catch (Exception ex) { m_popup.setLightWeightPopupEnabled(true); }*/ m_popup.setBorder(null); cardLayout = new CardLayout(); m_popup.setLayout(cardLayout); m_popup.setInvoker(this); m_popup.add(getPopupComponent(),"0"); menuItem = new JMenuItem(""); m_popup.add(menuItem,"1"); m_popup.setBorderPainted(true); m_popup.addPopupMenuListener(m_listener); } /** the component that should apear in the popup menu */ protected abstract JComponent getPopupComponent(); }
04900db4-rob
src/org/rapla/components/calendar/RaplaComboBox.java
Java
gpl3
9,662
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendar; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import java.util.TimeZone; /** * The model of the obligatory MVC approach is a wrapper arround an * Calendar object. */ final class DateModel { private Calendar m_calendar; private int m_daysMonth; private int m_daysLastMonth; private int m_firstWeekday; private Locale m_locale; private DateFormat m_yearFormat; private DateFormat m_currentDayFormat; ArrayList<DateChangeListener> listenerList = new ArrayList<DateChangeListener>(); public DateModel(Locale locale,TimeZone timeZone) { m_locale = locale; m_calendar = Calendar.getInstance(timeZone,m_locale); trim(m_calendar); m_yearFormat = new SimpleDateFormat("yyyy", m_locale); m_yearFormat.setTimeZone(timeZone); m_currentDayFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, m_locale); m_currentDayFormat.setTimeZone(timeZone); m_calendar.setLenient(true); recalculate(); } public boolean sameDate(Date date) { Calendar calendar2 = Calendar.getInstance(m_locale); TimeZone timeZone = getTimeZone(); calendar2.setTimeZone(timeZone); calendar2.setTime(date); trim(calendar2); Date trimedDate = getDate(); Date date2 = calendar2.getTime(); return date2.equals(trimedDate); } public void addDateChangeListener(DateChangeListener listener) { listenerList.add(listener); } public void removeDateChangeListener(DateChangeListener listener) { listenerList.remove(listener); } public Locale getLocale() {return m_locale; } public int getDay() { return m_calendar.get(Calendar.DATE); } public int getMonth() { return m_calendar.get(Calendar.MONTH) + 1; } public int getYear() { return m_calendar.get(Calendar.YEAR); } /** return the number of days of the selected month */ public int daysMonth() { return m_daysMonth; } /** return the number of days of the month before the selected month. */ public int daysLastMonth() { return m_daysLastMonth; } /** return the first weekday of the selected month (1 - 7). */ public int firstWeekday() { return m_firstWeekday; } /** calculates the weekday from the passed day. */ public int getWeekday(int day) { // calculate the weekday, consider the index shift return (((firstWeekday() - 1) + (day - 1)) % 7 ) + 1; } public Date getDate() { return m_calendar.getTime(); } // #TODO Property change listener for TimeZone public void setTimeZone(TimeZone timeZone) { m_calendar.setTimeZone(timeZone); m_yearFormat.setTimeZone(timeZone); m_currentDayFormat.setTimeZone(timeZone); recalculate(); } public TimeZone getTimeZone() { return m_calendar.getTimeZone(); } public String getDateString() { return m_currentDayFormat.format(getDate()); } public String getCurrentDateString() { return m_currentDayFormat.format(new Date()); } public void addMonth(int count) { m_calendar.add(Calendar.MONTH,count); recalculate(); } public void addYear(int count) { m_calendar.add(Calendar.YEAR,count); recalculate(); } public void addDay(int count) { m_calendar.add(Calendar.DATE,count); recalculate(); } public void setDay(int day) { m_calendar.set(Calendar.DATE,day); recalculate(); } public void setMonth(int month) { m_calendar.set(Calendar.MONTH,month); recalculate(); } public String getYearString() { DateFormat format; if (m_calendar.get(Calendar.ERA)!=GregorianCalendar.AD) format = new SimpleDateFormat("yyyy GG", getLocale()); else format = m_yearFormat; return format.format(getDate()); } public void setYear(int year) { m_calendar.set(Calendar.YEAR,year); recalculate(); } public void setDate(int day,int month,int year) { m_calendar.set(Calendar.DATE,day); m_calendar.set(Calendar.MONTH,month -1); m_calendar.set(Calendar.YEAR,year); trim(m_calendar); recalculate(); } public void setDate(Date date) { m_calendar.setTime(date); trim(m_calendar); recalculate(); } private void trim(Calendar calendar) { calendar.set(Calendar.HOUR_OF_DAY,0); calendar.set(Calendar.MINUTE,0); calendar.set(Calendar.SECOND,0); calendar.set(Calendar.MILLISECOND,0); } // 18.02.2004 CK: Workaround for bug in JDK 1.5.0 .Replace add with roll private void recalculate() { Calendar calendar = Calendar.getInstance(getTimeZone(), getLocale()); Date date = getDate(); calendar.setTime(date); // calculate the number of days of the selected month calendar.add(Calendar.MONTH,1); calendar.set(Calendar.DATE,1); calendar.add(Calendar.DAY_OF_YEAR,-1); calendar.getTime(); m_daysMonth = calendar.get(Calendar.DAY_OF_MONTH); // calculate the number of days of the month before the selected month calendar.set(Calendar.DATE,1); m_firstWeekday = calendar.get(Calendar.DAY_OF_WEEK); calendar.add(Calendar.DAY_OF_YEAR,-1); m_daysLastMonth = calendar.get(Calendar.DAY_OF_MONTH); // System.out.println("Calendar Recalculate: " + getDay() + "." + getMonth() + "." + getYear()); fireDateChanged(); } public DateChangeListener[] getDateChangeListeners() { return listenerList.toArray(new DateChangeListener[]{}); } protected void fireDateChanged() { DateChangeListener[] listeners = getDateChangeListeners(); Date date = getDate(); DateChangeEvent evt = new DateChangeEvent(this,date); for (int i = 0;i<listeners.length; i++) { listeners[i].dateChanged(evt); } } }
04900db4-rob
src/org/rapla/components/calendar/DateModel.java
Java
gpl3
7,156
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendar; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; /** The model is a wrapper arround an Calendar object. */ final class TimeModel { Calendar m_calendar; Locale m_locale; private Date durationStart; ArrayList<DateChangeListener> m_listenerList = new ArrayList<DateChangeListener>(); public TimeModel(Locale locale,TimeZone timeZone) { m_locale = locale; m_calendar = Calendar.getInstance(timeZone, m_locale); trim(m_calendar); m_calendar.setLenient(true); } public void addDateChangeListener(DateChangeListener listener) { m_listenerList.add(listener); } public void removeDateChangeListener(DateChangeListener listener) { m_listenerList.remove(listener); } public Locale getLocale() {return m_locale; } public Date getTime() { return m_calendar.getTime(); } public Date getDurationStart() { return durationStart; } public void setDurationStart(Date durationStart) { if ( durationStart == null) { this.durationStart = durationStart; return; } Calendar clone = Calendar.getInstance(m_calendar.getTimeZone(), m_locale); clone.setTime( durationStart); trim(clone); this.durationStart = clone.getTime(); } // #TODO Property change listener for TimeZone public void setTimeZone(TimeZone timeZone) { m_calendar.setTimeZone(timeZone); } public TimeZone getTimeZone() { return m_calendar.getTimeZone(); } public void setTime(int hours,int minutes) { m_calendar.set(Calendar.HOUR_OF_DAY,hours); m_calendar.set(Calendar.MINUTE,minutes); trim(m_calendar); fireDateChanged(); } public void setTime(Date date) { m_calendar.setTime(date); trim(m_calendar); fireDateChanged(); } public boolean sameTime(Date date) { Calendar calendar = Calendar.getInstance(getTimeZone(), getLocale()); calendar.setTime(date); trim(calendar); return calendar.getTime().equals(getTime()); } private void trim(Calendar calendar) { int hours = calendar.get(Calendar.HOUR_OF_DAY); int minutes = calendar.get(Calendar.MINUTE); calendar.setTimeInMillis(0); calendar.set(Calendar.HOUR_OF_DAY, hours); calendar.set(Calendar.MINUTE, minutes); } public DateChangeListener[] getDateChangeListeners() { return m_listenerList.toArray(new DateChangeListener[]{}); } protected void fireDateChanged() { DateChangeListener[] listeners = getDateChangeListeners(); DateChangeEvent evt = new DateChangeEvent(this,getTime()); for (int i = 0;i<listeners.length; i++) { listeners[i].dateChanged(evt); } } }
04900db4-rob
src/org/rapla/components/calendar/TimeModel.java
Java
gpl3
3,813
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.iolayer; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.print.PageFormat; import java.awt.print.Printable; import java.awt.print.PrinterException; import javax.swing.RepaintManager; /** Use this to print an awt-Component on one page. */ public class ComponentPrinter implements Printable { private Component component; protected Dimension scaleToFit; public ComponentPrinter(Component c, Dimension scaleToFit) { component= c; this.scaleToFit = scaleToFit; } protected boolean setPage( int pageNumber) { // default is one page return pageNumber == 0; } public int print(Graphics g, PageFormat format, int pagenumber) throws PrinterException { if (!setPage( pagenumber)) { return Printable.NO_SUCH_PAGE; } Graphics2D g2 = (Graphics2D) g; if ( scaleToFit != null) { scaleToFit(g2, format, scaleToFit); } RepaintManager rm = RepaintManager.currentManager(component); boolean db= rm.isDoubleBufferingEnabled(); try { rm.setDoubleBufferingEnabled(false); component.printAll(g2); } finally { rm.setDoubleBufferingEnabled(db); } return Printable.PAGE_EXISTS; } private static void scaleToFit(Graphics2D g, PageFormat format, Dimension dim) { scaleToFit(g, format, dim.getWidth(),dim.getHeight()); } public static void scaleToFit(Graphics2D g, PageFormat format, double width, double height) { g.translate(format.getImageableX(), format.getImageableY()); double sx = format.getImageableWidth() / width; double sy = format.getImageableHeight() / height; if (sx < sy) { sy = sx; } else { sx = sy; } g.scale(sx, sy); } }
04900db4-rob
src/org/rapla/components/iolayer/ComponentPrinter.java
Java
gpl3
2,726
package org.rapla.components.iolayer; import java.awt.Graphics2D; import java.awt.print.PageFormat; import java.awt.print.Printable; import com.itextpdf.text.Document; import com.itextpdf.text.Rectangle; import com.itextpdf.text.pdf.PdfContentByte; import com.itextpdf.text.pdf.PdfTemplate; import com.itextpdf.text.pdf.PdfWriter; public class ITextPrinter { static public void createPdf( Printable printable, java.io.OutputStream fileOutputStream, PageFormat format) { float width = (float)format.getWidth(); float height = (float)format.getHeight(); Rectangle pageSize = new Rectangle(width, height); Document document = new Document(pageSize); try { PdfWriter writer = PdfWriter.getInstance(document, fileOutputStream); document.open(); PdfContentByte cb = writer.getDirectContent(); for (int page = 0;page<5000;page++) { Graphics2D g2; PdfTemplate tp = cb.createTemplate(width, height); g2 = tp.createGraphics(width, height); int status = printable.print(g2, format, page); g2.dispose(); if ( status == Printable.NO_SUCH_PAGE) { break; } if ( status != Printable.PAGE_EXISTS) { break; } cb.addTemplate(tp, 0, 0); document.newPage(); } } catch (Exception e) { System.err.println(e.getMessage()); } document.close(); } }
04900db4-rob
src/org/rapla/components/iolayer/ITextPrinter.java
Java
gpl3
1,507
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.iolayer; import java.awt.Component; import java.awt.Frame; import java.awt.datatransfer.ClipboardOwner; import java.awt.datatransfer.Transferable; import java.awt.print.PageFormat; import java.awt.print.Printable; import java.awt.print.PrinterException; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import org.rapla.framework.logger.Logger; final public class WebstartIO extends DefaultIO { Method lookup; Method getDefaultPage; Method showPageFormatDialog; Method print; Method saveFileDialog; Method openFileDialog; Method getName; Method getInputStream; Method setContents; Method getContents; Method showDocument; Class<?> unavailableServiceException; String basicService = "javax.jnlp.BasicService"; String printService = "javax.jnlp.PrintService"; String fileSaveService = "javax.jnlp.FileSaveService"; String fileOpenService = "javax.jnlp.FileOpenService"; String clipboardService = "javax.jnlp.ClipboardService"; public WebstartIO(Logger logger) throws UnsupportedOperationException { super( logger); try { Class<?> serviceManagerC = Class.forName("javax.jnlp.ServiceManager"); Class<?> printServiceC = Class.forName(printService); Class<?> fileSaveServiceC = Class.forName(fileSaveService); Class<?> fileOpenServiceC = Class.forName(fileOpenService); Class<?> clipboardServiceC = Class.forName(clipboardService); Class<?> basicServiceC = Class.forName(basicService); Class<?> fileContents = Class.forName("javax.jnlp.FileContents"); unavailableServiceException = Class.forName("javax.jnlp.UnavailableServiceException"); getName = fileContents.getMethod("getName", new Class[] {} ); getInputStream = fileContents.getMethod("getInputStream", new Class[] {} ); lookup = serviceManagerC.getMethod("lookup", new Class[] {String.class}); getDefaultPage = printServiceC.getMethod("getDefaultPage",new Class[] {}); showPageFormatDialog = printServiceC.getMethod("showPageFormatDialog",new Class[] {PageFormat.class}); print = printServiceC.getMethod("print",new Class[] {Printable.class}); saveFileDialog = fileSaveServiceC.getMethod("saveFileDialog",new Class[] {String.class,String[].class,InputStream.class,String.class}); openFileDialog = fileOpenServiceC.getMethod("openFileDialog",new Class[] {String.class,String[].class}); setContents = clipboardServiceC.getMethod("setContents", new Class[] {Transferable.class}); getContents = clipboardServiceC.getMethod("getContents", new Class[] {}); showDocument = basicServiceC.getMethod("showDocument", new Class[] {URL.class}); } catch (ClassNotFoundException ex) { getLogger().error(ex.getMessage()); throw new UnsupportedOperationException("Java Webstart not available due to " + ex.getMessage()); } catch (Exception ex) { getLogger().error(ex.getMessage()); throw new UnsupportedOperationException(ex.getMessage()); } } private Object invoke(String serviceName, Method method, Object[] args) throws Exception { Object service; try { service = lookup.invoke( null, new Object[] { serviceName }); return method.invoke( service, args); } catch (InvocationTargetException e) { throw (Exception) e.getTargetException(); } catch (Exception e) { if ( unavailableServiceException.isInstance( e ) ) { throw new UnsupportedOperationException("The java-webstart service " + serviceName + " is not available!"); } throw new UnsupportedOperationException(e.getMessage()); } } public PageFormat defaultPage() throws UnsupportedOperationException { if ( isJDK1_5orHigher() ) return super.defaultPage(); PageFormat format = null; try { format = (PageFormat) invoke ( printService, getDefaultPage, new Object[] {} ) ; } catch (Exception ex) { getLogger().error("Can't get print service using default PageFormat." + ex.getMessage()); } if (format == null) format = new PageFormat(); logPaperSize (format.getPaper()); return format; } public void setContents(Transferable transferable, ClipboardOwner owner) { try { invoke( clipboardService, setContents, new Object[] {transferable}); } catch (Exception ex) { throw new UnsupportedOperationException(ex.getMessage()); } } public Transferable getContents( ClipboardOwner owner) { try { return (Transferable)invoke( clipboardService, getContents, new Object[] {}); } catch (Exception ex) { throw new UnsupportedOperationException(ex.getMessage()); } } public PageFormat showFormatDialog(PageFormat format) throws UnsupportedOperationException { if ( isJDK1_5orHigher() ) return super.showFormatDialog( format ); logPaperSize (format.getPaper()); try { // format = getPrintService().showPageFormatDialog(format); format = (PageFormat) invoke( printService, showPageFormatDialog, new Object[] {format}); } catch (Exception ex) { throw new UnsupportedOperationException(ex.getMessage()); } return format; } /** in the new JDK we don't need the webstart print service */ private boolean isJDK1_5orHigher() { try { String version = System.getProperty("java.version"); boolean oldVersion = version.startsWith("1.4") || version.startsWith("1.3"); //System.out.println( version + " new=" + !oldVersion); return !oldVersion; //return false; } catch (SecurityException ex) { return false; } } /** Prints an printable object. The format parameter is ignored, if askFormat is not set. Call showFormatDialog to set the PageFormat. @param askFormat If true a dialog will show up to allow the user to edit printformat. */ public boolean print(Printable printable, PageFormat format, boolean askFormat) throws PrinterException,UnsupportedOperationException { if ( isJDK1_5orHigher() ) { return super.print( printable , format, askFormat ); } logPaperSize (format.getPaper()); if ( askFormat ) { format= showFormatDialog(format); } try { Boolean result = (Boolean) invoke( printService , print, new Object[] { printable }); return result.booleanValue(); } catch (PrinterException ex) { throw ex; } catch (Exception ex) { throw new UnsupportedOperationException(ex.getMessage()); } } public String saveAsFileShowDialog(String dir,Printable printable,PageFormat format,boolean askFormat,Component owner, boolean pdf) throws IOException,UnsupportedOperationException { if (askFormat) { format= showFormatDialog(format); } ByteArrayOutputStream out = new ByteArrayOutputStream(); callExport(printable,format,out, pdf); if (dir == null) dir = ""; if ( pdf){ return saveFile( null, dir, new String[] {"pdf"},"RaplaOutput.pdf", out.toByteArray()); } else { return saveFile( null, dir, new String[] {"ps"},"RaplaOutput.ps", out.toByteArray()); } } public String saveFile(Frame frame,String dir, String[] fileExtensions, String filename, byte[] content) throws IOException { try { InputStream in = new ByteArrayInputStream( content); Object result = invoke( fileSaveService, saveFileDialog, new Object[] { dir ,fileExtensions ,in ,filename }); if (result != null) return (String) getName.invoke( result, new Object[] {}); else return null; } catch (IOException ex) { throw ex; } catch (Exception ex) { throw new UnsupportedOperationException("Can't invoke save Method " + ex.getMessage() ); } } public FileContent openFile(Frame frame,String dir, String[] fileExtensions) throws IOException { try { Object result = invoke( fileOpenService, openFileDialog, new Object[] { dir ,fileExtensions }); if (result != null) { String name = (String) getName.invoke( result, new Object[] {}); InputStream in = (InputStream) getInputStream.invoke( result, new Object[] {}); FileContent content = new FileContent(); content.setName( name ); content.setInputStream( in ); return content; } return null; } catch (IOException ex) { throw ex; } catch (Exception ex) { throw new UnsupportedOperationException("Can't invoke open Method " + ex.getMessage() ); } } public boolean openUrl(URL url) throws IOException { try { // Lookup the javax.jnlp.BasicService object invoke(basicService,showDocument, new Object[] {url}); // Invoke the showDocument method return true; } catch(Exception ex) { return false; } } }
04900db4-rob
src/org/rapla/components/iolayer/WebstartIO.java
Java
gpl3
10,975
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.iolayer; import java.awt.Component; import java.awt.FileDialog; import java.awt.Frame; import java.awt.Toolkit; import java.awt.datatransfer.ClipboardOwner; import java.awt.datatransfer.Transferable; import java.awt.print.PageFormat; import java.awt.print.Paper; import java.awt.print.Printable; import java.awt.print.PrinterException; import java.awt.print.PrinterJob; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.OutputStream; import java.net.URL; import javax.print.Doc; import javax.print.DocFlavor; import javax.print.PrintException; import javax.print.SimpleDoc; import javax.print.StreamPrintService; import javax.print.StreamPrintServiceFactory; import javax.print.attribute.HashPrintRequestAttributeSet; import javax.print.attribute.PrintRequestAttributeSet; import javax.print.attribute.Size2DSyntax; import javax.print.attribute.standard.MediaName; import javax.print.attribute.standard.MediaPrintableArea; import javax.print.attribute.standard.OrientationRequested; import javax.swing.JFileChooser; import javax.swing.filechooser.FileFilter; import org.rapla.framework.logger.Logger; public class DefaultIO implements IOInterface{ static DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE; /** * Name of all Rapla printjobs (used in dialogs, printerqueue, etc). */ public final static String RAPLA_JOB= "Rapla Printjob"; public PrinterJob job; Logger logger; public DefaultIO(Logger logger) { this.logger = logger; } public Logger getLogger() { return logger; } private PrinterJob getJob() { if (job == null) job = PrinterJob.getPrinterJob(); return job; } public PageFormat defaultPage() throws UnsupportedOperationException { try { PageFormat format = getJob().defaultPage(); return format; } catch (SecurityException ex) { return new PageFormat(); } } public PageFormat showFormatDialog(PageFormat format) throws UnsupportedOperationException { logPaperSize (format.getPaper()); format = getJob().pageDialog(format); logPaperSize (format.getPaper()); return format; } public void setContents(Transferable transferable, ClipboardOwner owner) { Toolkit.getDefaultToolkit().getSystemClipboard().setContents( transferable, owner ); } public Transferable getContents( ClipboardOwner owner) { return Toolkit.getDefaultToolkit().getSystemClipboard().getContents( owner); } public boolean supportsPostscriptExport() { if (!supportsPrintService()) return false; return getPSExportServiceFactory() != null; } private boolean supportsPrintService() { try { getClass().getClassLoader().loadClass("javax.print.StreamPrintServiceFactory"); return true; } catch (ClassNotFoundException ex) { getLogger().warn("No support for javax.print.StreamPrintServiceFactory"); return false; } } protected void callExport(Printable printable, PageFormat format,OutputStream out, boolean pdf) throws UnsupportedOperationException,IOException { if ( pdf) { ITextPrinter.createPdf(printable, out, format); } save(printable,format,out); } private static StreamPrintServiceFactory getPSExportServiceFactory() { StreamPrintServiceFactory []factories = StreamPrintServiceFactory.lookupStreamPrintServiceFactories(flavor,"application/postscript"); if (factories.length == 0) { return null; } /* for (int i=0;i<factories.length;i++) { System.out.println("Stream Factory " + factories[i]); System.out.println(" Output " + factories[i].getOutputFormat()); DocFlavor[] docFlavors = factories[i].getSupportedDocFlavors(); for (int j=0;j<docFlavors.length;j++) { System.out.println(" Flavor " + docFlavors[j].getMimeType()); } }*/ return factories[0]; } public void save(Printable print,PageFormat format,OutputStream out) throws IOException { StreamPrintService sps = null; try { StreamPrintServiceFactory spsf = getPSExportServiceFactory(); if (spsf == null) { throw new UnsupportedOperationException("No suitable factories for postscript-export."); } sps = spsf.getPrintService(out); Doc doc = new SimpleDoc(print, flavor, null); PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet(); if (format.getOrientation() == PageFormat.LANDSCAPE) { aset.add(OrientationRequested.LANDSCAPE); } if (format.getOrientation() == PageFormat.PORTRAIT) { aset.add(OrientationRequested.PORTRAIT); } if (format.getOrientation() == PageFormat.REVERSE_LANDSCAPE) { aset.add(OrientationRequested.REVERSE_LANDSCAPE); } aset.add(MediaName.ISO_A4_WHITE); Paper paper = format.getPaper(); if (sps.getSupportedAttributeValues(MediaPrintableArea.class,null,null) != null) { MediaPrintableArea printableArea = new MediaPrintableArea ( (float)(paper.getImageableX()/72) ,(float)(paper.getImageableY()/72) ,(float)(paper.getImageableWidth()/72) ,(float)(paper.getImageableHeight()/72) ,Size2DSyntax.INCH ); aset.add(printableArea); // System.out.println("new Area: " + printableArea); } sps.createPrintJob().print(doc,aset); } catch (PrintException ex) { throw new IOException(ex.getMessage()); } finally { if (sps != null) sps.dispose(); } } public String saveAsFileShowDialog(String dir,Printable printable,PageFormat format,boolean askFormat,Component owner, boolean pdf) throws UnsupportedOperationException,IOException { if (askFormat) { format= showFormatDialog(format); } JFileChooser chooser = new JFileChooser(); chooser.setAcceptAllFileFilterUsed(false); chooser.setApproveButtonText("Save"); if (dir != null) chooser.setCurrentDirectory(new File(dir)); // Note: source for ExampleFileFilter can be found in FileChooserDemo, // under the demo/jfc directory in the Java 2 SDK, Standard Edition. chooser.setFileFilter( pdf ? new PDFFileFilter() :new PSFileFilter()); int returnVal = chooser.showOpenDialog(owner); if(returnVal != JFileChooser.APPROVE_OPTION) return null; File selectedFile = chooser.getSelectedFile(); String suffix = pdf ? ".pdf" : ".ps"; String name = selectedFile.getName(); if (!name.endsWith(suffix)) { String parent = selectedFile.getParent(); selectedFile = new File( parent, name + suffix); } OutputStream out = new FileOutputStream(selectedFile); callExport(printable,format,out, pdf); out.close(); return selectedFile.getPath(); } private class PSFileFilter extends FileFilter { public boolean accept(File file) { return (file.isDirectory() || file.getName().toLowerCase().endsWith(".ps")); } public String getDescription() { return "Postscript"; } } private class PDFFileFilter extends FileFilter { public boolean accept(File file) { return (file.isDirectory() || file.getName().toLowerCase().endsWith(".pdf")); } public String getDescription() { return "PDF"; } } public void saveAsFile(Printable printable,PageFormat format,OutputStream out, boolean pdf) throws UnsupportedOperationException,IOException { callExport(printable,format,out, pdf); } /** Prints an awt or swing component. @param askFormat If true a dialog will show up to allow the user to edit printformat. */ public boolean print(Printable printable, PageFormat format, boolean askFormat) throws PrinterException { getJob().setPrintable(printable, format); getJob().setJobName(RAPLA_JOB); if (askFormat) { if (getJob().printDialog()) { logPaperSize (format.getPaper()); getJob().print(); return true; } } else { getJob().print(); return true; } getJob().cancel(); return false; } void logPaperSize(Paper paper) { if (getLogger().isDebugEnabled()) getLogger().debug( (paper.getImageableX()/72) * INCH_TO_MM +", " +(paper.getImageableY()/72) * INCH_TO_MM +", " +(paper.getImageableWidth() /72) * INCH_TO_MM +", " +(paper.getImageableHeight() /72) * INCH_TO_MM ); } public String saveFile(Frame frame,String dir,final String[] fileExtensions, String filename, byte[] content) throws IOException { final FileDialog fd = new FileDialog(frame, "Save File", FileDialog.SAVE); if ( dir == null) { try { dir = getDirectory(); } catch (Exception ex) { } } if ( dir != null) { fd.setDirectory(dir); } fd.setFile(filename); if ( fileExtensions.length > 0) { fd.setFilenameFilter( new FilenameFilter() { public boolean accept(File dir, String name) { final String[] split = name.split("."); if ( split.length > 1) { String extension = split[split.length -1].toLowerCase(); for ( String ext: fileExtensions) { if ( ext.toLowerCase().equals(extension )) { return true; } } } return false; } }); } fd.setLocation(50, 50); fd.setVisible( true); final String savedFileName = fd.getFile(); if (savedFileName == null) { return null; } String path = createFullPath(fd); final File savedFile = new File( path); writeFile(savedFile, content); return path; } public FileContent openFile(Frame frame,String dir, String[] fileExtensions) throws IOException { final FileDialog fd = new FileDialog(frame, "Open File", FileDialog.LOAD); if ( dir == null) { dir = getDirectory(); } fd.setDirectory(dir); fd.setLocation(50, 50); fd.setVisible( true); final String openFileName = fd.getFile(); if (openFileName == null) { return null; } String path = createFullPath(fd); final FileInputStream openFile = new FileInputStream( path); FileContent content = new FileContent(); content.setName( openFileName); content.setInputStream( openFile ); return content; } private String getDirectory() { final String userHome = System.getProperty("user.home"); if (userHome == null) { final File execDir = new File(""); return execDir.getAbsolutePath(); } return userHome; } private String createFullPath(final FileDialog fd) { return fd.getDirectory() + System.getProperty("file.separator").charAt(0) + fd.getFile(); } private void writeFile(final File savedFile, byte[] content) throws IOException { final FileOutputStream out; out = new FileOutputStream(savedFile); out.write( content); out.flush(); out.close(); } public boolean openUrl(URL url) throws IOException { try { java.awt.Desktop.getDesktop().browse(url.toURI()); return true; } catch (Throwable ex) { getLogger().error(ex.getMessage(), ex); return false; } } }
04900db4-rob
src/org/rapla/components/iolayer/DefaultIO.java
Java
gpl3
13,759
package org.rapla.components.iolayer; import java.io.InputStream; public class FileContent { String name; InputStream inputStream; public InputStream getInputStream() { return inputStream; } void setInputStream(InputStream inputStream) { this.inputStream = inputStream; } public String getName() { return name; } void setName(String name) { this.name = name; } }
04900db4-rob
src/org/rapla/components/iolayer/FileContent.java
Java
gpl3
452
<body> The IO layer is an abstraction from the io differences in webstart or desktop mode. With JDK 1.4 or higher PS export is supported. </body>
04900db4-rob
src/org/rapla/components/iolayer/package.html
HTML
gpl3
149
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.iolayer; import java.awt.Frame; import java.awt.datatransfer.ClipboardOwner; import java.awt.datatransfer.Transferable; import java.awt.print.PageFormat; import java.awt.print.Printable; import java.awt.print.PrinterException; import java.io.IOException; import java.io.OutputStream; import java.net.URL; /** The IO layer is an abstraction from the io differences in webstart or desktop mode */ public interface IOInterface { String saveAsFileShowDialog( String toDir ,Printable printable ,PageFormat format ,boolean askFormat ,java.awt.Component owner ,boolean pdf ) throws IOException,UnsupportedOperationException; void saveAsFile( Printable printable ,PageFormat format ,OutputStream out ,boolean pdf ) throws IOException,UnsupportedOperationException; boolean print( Printable printable ,PageFormat format ,boolean askFormat ) throws PrinterException,UnsupportedOperationException; PageFormat defaultPage() throws UnsupportedOperationException; PageFormat showFormatDialog(PageFormat format) throws UnsupportedOperationException; void setContents(Transferable transferable, ClipboardOwner owner); Transferable getContents( ClipboardOwner owner); public String saveFile(Frame frame,String dir, String[] fileExtensions,String path, byte[] content) throws IOException; public FileContent openFile(Frame frame,String dir, String[] fileExtensions) throws IOException; public boolean openUrl(final URL url) throws IOException; boolean supportsPostscriptExport(); public double INCH_TO_MM = 25.40006; public double MM_TO_INCH = 1.0 / INCH_TO_MM; }
04900db4-rob
src/org/rapla/components/iolayer/IOInterface.java
Java
gpl3
3,045
<body> Contains all components and classes that are independant from the rest of rapla, and can easily be reused in other projects. Dependencies with other components or packages are explicitly stated in a file called DEPENDENCIES. </body>
04900db4-rob
src/org/rapla/components/package.html
HTML
gpl3
244
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview; import java.util.Date; public interface Builder { /** Calculate the blocks that should be displayed in the weekview. * This method should not be called manually. * It is called by the CalendarView during the build process. * @see #build * @param start * @param end */ void prepareBuild(Date start, Date end); /** The maximal ending-time of all blocks that should be displayed. Call prepareBuild first to calculate the blocks.*/ int getMaxMinutes(); /** The minimal starting-time of all blocks that should be displayed. Call prepareBuild first to calculate the blocks.*/ int getMinMinutes(); /** Build the calculated blocks into the weekview. This method should not be called manually. * It is called by the CalendarView during the build process. * @see #prepareBuild */ void build(CalendarView cv); void setEnabled(boolean enable); boolean isEnabled(); }
04900db4-rob
src/org/rapla/components/calendarview/Builder.java
Java
gpl3
1,941
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview; import java.util.Date; /** implementierung von block koennen in ein slot eingefuegt werden. Sie dienen als modell fuer beliebige grafische komponenten. mit getStart() und getEnd() wird anfangs- und endzeit des blocks definiert (nur uhrzeit ist fuer positionierung in slots relevant). */ public interface Block { Date getStart(); Date getEnd(); String getName(); }
04900db4-rob
src/org/rapla/components/calendarview/Block.java
Java
gpl3
1,365
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview; import java.util.Collection; import java.util.Date; import java.util.TimeZone; public interface CalendarView { public TimeZone getTimeZone(); /** returns the first Date that will be displayed in the calendar */ public Date getStartDate(); /** returns the last Date that will be displayed in the calendar */ public Date getEndDate(); /** sets the calendarview to the selected date*/ public void setToDate(Date weekDate); /** This method removes all existing blocks first. * Then it calls the build method of all added builders, so that they can add blocks into the CalendarView again. * After all blocks are added the Calendarthat repaints the screen. */ public void rebuild(); /** Adds a block. You can optionaly specify a slot, if the day-view supports multiple slots (like in the weekview). * If the selected slot does not exist it will be created. This method is usually called by the builders. */ public void addBlock(Block bl, int column,int slot); /** returns a collection of all the added blocks * @see #addBlock*/ Collection<Block> getBlocks(); }
04900db4-rob
src/org/rapla/components/calendarview/CalendarView.java
Java
gpl3
2,143
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview.swing; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Rectangle; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Locale; import javax.swing.JComponent; import org.rapla.components.calendarview.AbstractCalendar; /** A vertical scale displaying the hours of day. Uses am/pm notation * in the appropriate locale. */ public class TimeScale extends JComponent { private static final long serialVersionUID = 1L; private int pixelPerHour = 60; private int mintime; private int maxtime; private boolean useAM_PM = false; private Font fontLarge= new Font("SansSerif", Font.PLAIN, 14); private Font fontSmall= new Font("SansSerif", Font.PLAIN, 9); private FontMetrics fm1 = getFontMetrics(fontLarge); private FontMetrics fm2 = getFontMetrics(fontSmall); String[] hours; private int SCALE_WIDTH = 35; private boolean smallSize = false; private int repeat = 1; private String days[] ; public TimeScale() { useAM_PM = AbstractCalendar.isAmPmFormat(Locale.getDefault()); createHours(Locale.getDefault()); } public void setLocale(Locale locale) { if (locale == null) return; useAM_PM = AbstractCalendar.isAmPmFormat(locale); createHours(locale); } /** mintime und maxtime definieren das zeitintevall in vollen stunden. die skalen-einteilung wird um vgap pixel nach unten verschoben (um ggf. zu justieren). */ public void setTimeIntervall(int minHour, int maxHour, int pixelPerHour) { removeAll(); this.mintime = minHour; this.maxtime = maxHour; this.pixelPerHour = pixelPerHour; //setBackground(Color.yellow); //super(JSeparator.VERTICAL); setLayout(null); setPreferredSize(new Dimension( SCALE_WIDTH, (maxHour-minHour + 1) * pixelPerHour * repeat)); } private void createHours(Locale locale) { hours = new String[24]; Calendar cal = Calendar.getInstance(locale); SimpleDateFormat format = new SimpleDateFormat(useAM_PM ? "h" : "H",locale); for (int i=0;i<24;i++) { cal.set(Calendar.HOUR_OF_DAY,i); hours[i] = format.format(cal.getTime()); } } public void setSmallSize(boolean smallSize) { this.smallSize = smallSize; } public void setRepeat(int repeat, String[] days) { this.repeat = repeat; this.days = days; } public void paint(Graphics g) { super.paint(g); int indent[]; int heightHour = (int) fm1.getLineMetrics("12",g).getHeight() ; int heightEnding = (int) fm2.getLineMetrics("12",g).getHeight() ; int current_y ; // Compute indentations FontMetrics fm; String[] indent_string = new String[3] ; if ( days != null ) { indent_string[0] = "M"; indent_string[1] = "M2"; indent_string[2] = "M22"; } else { indent_string[0] = ""; indent_string[1] = "2"; indent_string[2] = "22"; } if ( smallSize ) { fm = fm2; } else { fm = fm1; } indent = new int[3]; for(int i=0; i<3; i++) { indent[i] = fm.stringWidth(indent_string[i]) ; } Rectangle rect = g.getClipBounds(); //System.out.println(mintime + " - " + maxtime); int height = (maxtime - mintime) * pixelPerHour + 1 ; if ( days != null ) { g.drawLine(indent[0]+1,0,indent[0]+1,repeat*height); } for (int r=0; r<repeat; r++) { current_y = height * r; g.drawLine(0,current_y-1,SCALE_WIDTH ,current_y-1); int pad = 0; if ( days != null ) { pad = (maxtime - mintime - days[r].length())/2 ; if ( pad < 0 ) { pad = 0; } } for (int i=mintime; i<maxtime; i++) { int y = current_y + (i - mintime) * pixelPerHour; int hour; String ending; String prefix; if (useAM_PM) { hour = (i == 0) ? 12 : ((i-1)%12 + 1); ending = (i<=11) ? "AM" : "PM"; } else { hour = i; ending = "00"; } if ( days != null && i - mintime < days[r].length() + pad && i - mintime >= pad ) { prefix = days[r].substring(i-mintime-pad,i-mintime+1-pad); } else { prefix = null; } if (y >= rect.y && y <= (rect.y + rect.height)) { g.drawLine(i == mintime ? 0:indent[0]+1,y,SCALE_WIDTH ,y); } // Uncommenting this draws the last line // if (y >= rect.y && y <= (rect.y + rect.height) && i == maxtime-1) { // g.drawLine(0,y+pixelPerHour,SCALE_WIDTH ,y+pixelPerHour); // } if (y >= rect.y -heightHour && y <= (rect.y + rect.height) + heightHour ) { if ( smallSize ) { g.setFont(fontSmall); } else { g.setFont(fontLarge); } if ( prefix != null ) { g.drawString(prefix, (indent[0]-fm.stringWidth(prefix)+1)/2,y + heightEnding); } g.drawString(hours[i],(hour < 10) ? indent[1]+2:indent[0]+2,y + ( smallSize ? heightEnding : heightHour)); if ( !smallSize ) { g.setFont(fontSmall); } g.drawString(ending, indent[2]+2,y + heightEnding); } } } } }
04900db4-rob
src/org/rapla/components/calendarview/swing/TimeScale.java
Java
gpl3
7,023
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview.swing; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.util.ArrayList; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import javax.swing.BoxLayout; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.JScrollBar; import javax.swing.JScrollPane; import javax.swing.JViewport; import javax.swing.ScrollPaneConstants; import javax.swing.SwingUtilities; import javax.swing.border.Border; import javax.swing.border.EtchedBorder; import org.rapla.components.calendarview.AbstractCalendar; import org.rapla.components.calendarview.Block; import org.rapla.components.calendarview.CalendarView; import org.rapla.components.layout.TableLayout; import org.rapla.components.util.TimeInterval; public abstract class AbstractSwingCalendar extends AbstractCalendar implements CalendarView { static Border SLOTHEADER_BORDER = new EtchedBorder(); int slotSize = 100; boolean bEditable = true; protected int minBlockWidth = 3; ArrayList<ViewListener> listenerList = new ArrayList<ViewListener>(); JScrollPane scrollPane = new JScrollPane(); JPanel jHeader = new JPanel(); BoxLayout boxLayout1 = new BoxLayout(jHeader, BoxLayout.X_AXIS); JPanel jCenter = new JPanel(); protected JPanel jTitlePanel = new JPanel(); protected JPanel component = new JPanel(); AbstractSwingCalendar(boolean showScrollPane) { jHeader.setLayout(boxLayout1); jHeader.setOpaque( false ); jCenter.setOpaque( false ); jTitlePanel.setOpaque( false); jTitlePanel.setLayout( new BorderLayout()); jTitlePanel.add(jHeader,BorderLayout.CENTER); if (showScrollPane) { component.setLayout(new BorderLayout()); component.add(scrollPane,BorderLayout.CENTER); scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED); scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); scrollPane.setViewportView(jCenter); scrollPane.setColumnHeaderView(jTitlePanel); scrollPane.getVerticalScrollBar().setUnitIncrement(10); scrollPane.getHorizontalScrollBar().setUnitIncrement(10); scrollPane.setBorder(null); } else { component.setLayout(new TableLayout(new double[][] { {TableLayout.PREFERRED,TableLayout.FILL} ,{TableLayout.PREFERRED,TableLayout.FILL} })); component.add(jTitlePanel,"1,0"); component.add(jCenter,"1,1"); } this.timeZone = TimeZone.getDefault(); setLocale( Locale.getDefault() ); if ( showScrollPane) { component.addComponentListener( new ComponentListener() { private boolean resizing = false; public void componentShown(ComponentEvent e) { } public void componentResized(ComponentEvent e) { if ( resizing) { return; } resizing = true; if ( isEditable() ) { int width = component.getSize().width; updateSize(width); } SwingUtilities.invokeLater(new Runnable() { public void run() { resizing = false; } }); } public void componentMoved(ComponentEvent e) { } public void componentHidden(ComponentEvent e) { } }); } } abstract public void updateSize(int width); public JComponent getComponent() { return component; } void checkBlock( Block bl ) { if ( !bl.getStart().before(this.getEndDate())) { throw new IllegalStateException("Start-date " +bl.getStart() + " must be before calendar end at " +this.getEndDate()); } } public boolean isEditable() { return bEditable; } public void setEditable( boolean editable ) { bEditable = editable; } /** Width of a single slot in pixel. */ public void setSlotSize(int slotSize) { this.slotSize = slotSize; } public int getSlotSize() { return slotSize; } /** the minimum width of a block in pixel */ public int getMinBlockWidth() { return minBlockWidth; } /** the minimum width of a block in pixel */ public void setMinBlockWidth(int minBlockWidth) { this.minBlockWidth = Math.max(3,minBlockWidth); } public void setBackground(Color color) { component.setBackground(color); if (scrollPane != null) scrollPane.setBackground(color); if (jCenter != null) jCenter.setBackground(color); if (jHeader != null) jHeader.setBackground(color); } public void addCalendarViewListener(ViewListener listener) { listenerList.add(listener); } public void removeCalendarViewListener(ViewListener listener) { listenerList.remove(listener); } JScrollPane getScrollPane() { return scrollPane; } void scrollTo(int x, int y) { JViewport viewport = scrollPane.getViewport(); Rectangle rect = viewport.getViewRect(); int leftBound = rect.x; int upperBound = rect.y; int lowerBound = rect.y + rect.height; int rightBound = rect.x + rect.width; int maxX = viewport.getView().getWidth(); int maxY = viewport.getView().getHeight(); JScrollBar scrollBar = scrollPane.getVerticalScrollBar(); if ( y > lowerBound && lowerBound < maxY) { scrollBar.setValue(scrollBar.getValue() + 20); } if ( y < upperBound && upperBound >0) { scrollBar.setValue(scrollBar.getValue() - 20); } scrollBar = scrollPane.getHorizontalScrollBar(); if ( x > rightBound && rightBound < maxX) { scrollBar.setValue(scrollBar.getValue() + 20); } if ( x < leftBound && leftBound >0) { scrollBar.setValue(scrollBar.getValue() - 20); } } public ViewListener[] getWeekViewListeners() { return listenerList.toArray(new ViewListener[]{}); } final void fireSelectionChanged(Date start, Date end) { // Fire the popup event ViewListener[] listeners = getWeekViewListeners(); for (int i=0;i<listeners.length;i++) { listeners[i].selectionChanged(start,end); } } final void fireSelectionPopup(Component slot, Point p, Date start, Date end, int slotNr) { // Fire the popup event ViewListener[] listeners = getWeekViewListeners(); for (int i=0;i<listeners.length;i++) { listeners[i].selectionPopup(slot,p,start,end, slotNr); } } final void fireMoved(SwingBlock block, Point p, Date newTime, int slotNr) { // Fire the popup event ViewListener[] listeners = getWeekViewListeners(); for (int i=0;i<listeners.length;i++) { listeners[i].moved(block,p,newTime, slotNr); } } final void fireResized(SwingBlock block, Point p, Date newStart, Date newEnd, int slotNr) { // Fire the popup event ViewListener[] listeners = getWeekViewListeners(); for (int i=0;i<listeners.length;i++) { listeners[i].resized(block,p,newStart,newEnd, slotNr); } } void fireResized(SwingBlock block, Point p, Date newTime, int slotNr) { // Fire the popup event ViewListener[] listeners = getWeekViewListeners(); for (int i=0;i<listeners.length;i++) { listeners[i].moved(block,p,newTime, slotNr); } } void fireBlockPopup(SwingBlock block, Point p) { // Fire the popup event ViewListener[] listeners = getWeekViewListeners(); for (int i=0;i<listeners.length;i++) { listeners[i].blockPopup(block,p); } } void fireBlockEdit(SwingBlock block, Point p) { // Fire the popup event ViewListener[] listeners = getWeekViewListeners(); for (int i=0;i<listeners.length;i++) { listeners[i].blockEdit(block,p); } } abstract int getDayCount(); abstract DaySlot getSlot(int num); abstract public boolean isSelected(int nr); abstract int calcSlotNr( int x, int y); abstract int getSlotNr( DaySlot slot); abstract int getRowsPerDay(); abstract Date createDate( DaySlot slot, int row, boolean startOfRow); public TimeInterval normalizeBlockIntervall(SwingBlock block) { return new TimeInterval(block.getStart(), block.getEnd()); } }
04900db4-rob
src/org/rapla/components/calendarview/swing/AbstractSwingCalendar.java
Java
gpl3
9,801
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview.swing; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.Point; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.SwingConstants; import org.rapla.components.calendarview.AbstractCalendar; import org.rapla.components.calendarview.Block; import org.rapla.components.calendarview.Builder; import org.rapla.components.calendarview.swing.SelectionHandler.SelectionStrategy; import org.rapla.components.layout.TableLayout; import org.rapla.components.util.DateTools; /** Graphical component for displaying a calendar like weekview. * This view doesn't show the times and arranges the different slots * Vertically. */ public class SwingCompactWeekView extends AbstractSwingCalendar { private SmallDaySlot[] slots = new SmallDaySlot[0]; private List<List<Block>> rows = new ArrayList<List<Block>>(); DraggingHandler draggingHandler = new DraggingHandler(this, false); SelectionHandler selectionHandler = new SelectionHandler(this); String[] rowNames = new String[] {}; int leftColumnSize = 100; Map<Block, Integer> columnMap = new HashMap<Block, Integer>(); public SwingCompactWeekView() { this(true); } public SwingCompactWeekView(boolean showScrollPane) { super( showScrollPane ); selectionHandler.setSelectionStrategy(SelectionStrategy.BLOCK); } public Collection<Block> getBlocks() { ArrayList<Block> list = new ArrayList<Block>(); for (int i=0;i<slots.length;i++) { list.addAll(slots[i].getBlocks()); } return Collections.unmodifiableCollection( list ); } public void setEditable(boolean b) { super.setEditable( b); if ( slots == null ) return; // Hide the rest for (int i= 0;i<slots.length;i++) { SmallDaySlot slot = slots[i]; if (slot == null) continue; slot.setEditable(b); } } public void setSlots(String[] slotNames) { this.rowNames = slotNames; } TableLayout tableLayout; public void rebuild() { rows.clear(); columnMap.clear(); for ( int i=0; i<rowNames.length; i++ ) { addRow(); } // calculate the blocks Iterator<Builder> it= builders.iterator(); while (it.hasNext()) { Builder b= it.next(); b.prepareBuild(getStartDate(), getEndDate()); } // clear everything jHeader.removeAll(); jCenter.removeAll(); // build Blocks it= builders.iterator(); while (it.hasNext()) { Builder b= it.next(); if (b.isEnabled()) { b.build(this); } } tableLayout= new TableLayout(); jCenter.setLayout(tableLayout); Calendar calendar = createCalendar(); calendar.setTime(getStartDate()); int firstDayOfWeek = getFirstWeekday(); calendar.set( Calendar.DAY_OF_WEEK, firstDayOfWeek); if ( rowNames.length > 0) { tableLayout.insertColumn(0, leftColumnSize); jHeader.add( createColumnHeader( null ), "0,0,l,t" ); } else { tableLayout.insertColumn(0, 0); } int columns = getColumnCount(); // add headers for (int column=0;column<columns;column++) { if ( !isExcluded(column) ) { tableLayout.insertColumn(column + 1, slotSize ); jHeader.add( createColumnHeader( column ) ); } else { tableLayout.insertColumn(column + 1, 0.); } } int rowsize = rows.size(); slots = new SmallDaySlot[rowsize * columns]; for (int row=0;row<rowsize;row++) { tableLayout.insertRow(row, TableLayout.PREFERRED ); jCenter.add(createRowLabel( row ), "" + 0 + "," + row + ",f,t"); for (int column=0;column < columns; column++) { int fieldNumber = row * columns + column; SmallDaySlot field = createField( ); for (Block block:getBlocksForColumn(rows.get( row ), column)) { field.putBlock( (SwingBlock ) block); } slots[fieldNumber] = field; if ( !isExcluded( column ) ) { jCenter.add(slots[fieldNumber], "" + (column + 1) + "," + row); } } } selectionHandler.clearSelection(); jCenter.validate(); jHeader.validate(); if ( isEditable()) { updateSize(component.getSize().width); } component.revalidate(); component.repaint(); } protected int getColumnCount() { return getDaysInView(); } public int getLeftColumnSize() { return leftColumnSize; } public void setLeftColumnSize(int leftColumnSize) { this.leftColumnSize = leftColumnSize; } protected JComponent createRowLabel(int row) { JLabel label = new JLabel(); if ( row < rowNames.length ) { label.setText( rowNames[ row ] ); label.setToolTipText(rowNames[ row ]); } return label; } public boolean isSelected(int nr) { SmallDaySlot slot = getSlot(nr); if ( slot == null) { return false; } return slot.isSelected(); } /** override this method, if you want to create your own slot header. */ protected JComponent createColumnHeader(Integer column) { JLabel jLabel = new JLabel(); jLabel.setFont(new Font("SansSerif", Font.PLAIN, 13)); jLabel.setHorizontalAlignment(JLabel.CENTER); jLabel.setOpaque(false); jLabel.setForeground(Color.black); Dimension dim; if (column != null ) { Date date = getDateFromColumn(column); jLabel.setText(AbstractCalendar.formatDayOfWeekDateMonth(date,locale,getTimeZone())); jLabel.setBorder(isEditable() ? SLOTHEADER_BORDER : null); dim = new Dimension(this.slotSize,20); } else { dim = new Dimension(this.leftColumnSize,20); jLabel.setFont(jLabel.getFont().deriveFont((float)11.)); jLabel.setHorizontalAlignment(SwingConstants.LEFT); } jLabel.setPreferredSize( dim); jLabel.setMinimumSize( dim ); jLabel.setMaximumSize( dim ); return jLabel; } private SmallDaySlot createField( ) { SmallDaySlot c= new SmallDaySlot("",slotSize, Color.BLACK, null); c.setEditable(isEditable()); c.setDraggingHandler(draggingHandler); c.addMouseListener(selectionHandler); c.addMouseMotionListener(selectionHandler); return c; } protected List<Block> getBlocksForColumn(List<Block> blocks,int column) { List<Block> result = new ArrayList<Block>(); //Date startDate = getDateFromColumn(column); if ( blocks != null) { Iterator<Block> it = blocks.iterator(); while (it.hasNext()){ Block block = it.next(); if (columnMap.get( block) == column) { // if ( DateTools.cutDate( block.getStart()).equals( startDate)) { result.add( block); } } } return result; } protected Date getDateFromColumn(int column) { Date startDate = getStartDate(); return DateTools.addDays( startDate, column); } public void addBlock(Block block, int column,int slot) { if ( rows.size() <= slot) { return; } checkBlock( block ); List<Block> blocks = rows.get( slot ); blocks.add( block ); columnMap.put(block, column); } private void addRow() { rows.add( rows.size(), new ArrayList<Block>()); } public int getSlotNr( DaySlot slot) { for (int i=0;i<slots.length;i++) if (slots[i] == slot) return i; throw new IllegalStateException("Slot not found in List"); } int getRowsPerDay() { return 1; } SmallDaySlot getSlot(int nr) { if ( nr >=0 && nr< slots.length) return slots[nr]; else return null; } int getDayCount() { return slots.length; } int calcSlotNr(int x, int y) { for (int i=0;i<slots.length;i++) { if (slots[i] == null) continue; Point p = slots[i].getLocation(); if ((p.x <= x) && (x <= p.x + slots[i].getWidth()) && (p.y <= y) && (y <= p.y + slots[i].getHeight()) ) { return i; } } return -1; } SmallDaySlot calcSlot(int x,int y) { int nr = calcSlotNr(x, y); if (nr == -1) { return null; } else { return slots[nr]; } } Date createDate(DaySlot slot, int row, boolean startOfRow) { Calendar calendar = createCalendar(); Date startDate = getStartDate(); calendar.setTime( startDate ); calendar.set( Calendar.DAY_OF_WEEK, getFirstWeekday() ); calendar.add( Calendar.DATE , getSlotNr( slot ) % getDaysInView() ); //calendar.set( Calendar.DAY_OF_WEEK, getDayOfWeek(slot) ); if ( !startOfRow ) { calendar.add( Calendar.DATE , 1 ); } calendar.set( Calendar.HOUR_OF_DAY, 0 ); calendar.set( Calendar.MINUTE, 0 ); calendar.set( Calendar.SECOND, 0 ); calendar.set( Calendar.MILLISECOND, 0 ); return calendar.getTime(); } /** must be called after the slots are filled*/ protected boolean isEmpty(int column) { for (Integer value: columnMap.values()) { if ( value.equals( column)) { return false; } } return true; } @Override public void updateSize(int width) { int columnSize = tableLayout.getNumColumn(); int realColumns= columnSize; for ( int i=1;i< columnSize;i++) { if( isExcluded(i)) { realColumns--; } } int newWidth = Math.max( minBlockWidth ,(width - leftColumnSize -20 - realColumns) / (Math.max(1,realColumns-1))); for (SmallDaySlot slot: this.slots) { if ( slot != null) { slot.updateSize(newWidth); } } setSlotSize(newWidth); for ( int i=1;i< columnSize;i++) { if( !isExcluded(i-1)) { tableLayout.setColumn(i, newWidth); } } boolean first = true; for (Component comp:jHeader.getComponents()) { if ( first) { first = false; continue; } double height = comp.getPreferredSize().getHeight(); Dimension dim = new Dimension( newWidth,(int) height); comp.setPreferredSize(dim); comp.setMaximumSize(dim); comp.setMinimumSize( dim); comp.invalidate(); } jCenter.invalidate(); jCenter.repaint(); } }
04900db4-rob
src/org/rapla/components/calendarview/swing/SwingCompactWeekView.java
Java
gpl3
12,157
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview.swing; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Graphics; import java.awt.Point; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.HashMap; import java.util.Map; import javax.swing.JPanel; import javax.swing.UIManager; abstract class AbstractDaySlot extends JPanel implements DaySlot { private static final long serialVersionUID = 1L; private boolean bEditable = true; boolean paintDraggingGrid; int draggingSlot; int draggingY; SwingBlock draggingView; int draggingHeight; protected Map<Object,SwingBlock> blockViewMapper = new HashMap<Object,SwingBlock>(); // BJO 00000076 // protected Method getButtonMethod = null; // BJO 00000076 AbstractDaySlot() { /* // BJO 00000076 try { //is only available sind 1.4 getButtonMethod = MouseEvent.class.getMethod("getButton", new Class[] {}); } catch (Exception ex) { } // BJO 00000076 */ } public void setEditable(boolean b) { bEditable = b; } public boolean isEditable() { return bEditable; } SwingBlock getBlockFor(Object component) { return blockViewMapper.get(component); } protected void showPopup(MouseEvent evt) { Point p = new Point(evt.getX(),evt.getY()); SwingBlock block = getBlockFor(evt.getSource()); if (block != null) draggingHandler.blockPopup(block,p); } protected Color getSelectionColor() { return UIManager.getColor("Table.selectionBackground"); } public void paintDraggingGrid(int slot,int y, int height,SwingBlock draggingView,int oldY,int oldHeight,boolean bPaint) { this.paintDraggingGrid = bPaint; this.draggingSlot = slot; this.draggingY = y; this.draggingHeight = height; this.draggingView = draggingView; this.invalidateDragging(); } public int getX(Component component) { return component.getParent().getLocation().x; } void invalidateDragging() { repaint(); } void setDraggingHandler(DraggingHandler draggingHandler) { this.draggingHandler = draggingHandler; } private DraggingHandler draggingHandler; /** BlockListener handles the dragging events and the Block * Context Menu (right click). */ class BlockListener extends MouseAdapter { boolean preventDragging = false; public void mouseClicked(MouseEvent evt) { if (evt.isPopupTrigger()) { showPopup(evt); } else { if (evt.getClickCount()>1) blockEdit(evt); } //draggingPointOffset = evt.getY(); } private int calcResizeDirection( MouseEvent evt ) { if ( !draggingHandler.supportsResizing()) return 0; int height = ((Component)evt.getSource()).getHeight(); int diff = height- evt.getY() ; if ( diff <= 5 && diff >=0 ) return 1; if (evt.getY() >=0 && evt.getY() < 5) return -1; return 0; } public void mousePressed(MouseEvent evt) { if (evt.isPopupTrigger()) { showPopup(evt); } preventDragging = false; /* // BJO 00000076 //System.out.println ("Button:" +evt.getButton() ); if ( getButtonMethod != null) { try { Integer button = (Integer) getButtonMethod.invoke( evt, new Object [] {}); preventDragging = button.intValue() != 1; } catch (Exception ex) { } } */ preventDragging = evt.getButton() != 1; // BJO 00000076 if ( preventDragging ) return; SwingBlock block = getBlockFor(evt.getSource()); int resizeDirection = calcResizeDirection( evt ); if ( resizeDirection != 0) { draggingHandler.blockBorderPressed( AbstractDaySlot.this,block, evt, resizeDirection ); } } public void mouseReleased(MouseEvent evt) { if (evt.isPopupTrigger()) { showPopup(evt); } preventDragging = false; SwingBlock block = getBlockFor(evt.getSource()); draggingHandler.mouseReleased( AbstractDaySlot.this, block, evt); } public void mouseEntered(MouseEvent evt) { } public void mouseExited(MouseEvent evt) { if ( draggingHandler.isDragging()) return; setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } public void mouseMoved(MouseEvent evt) { if ( draggingHandler.isDragging()) { return; } SwingBlock block = getBlockFor(evt.getSource()); // BJO 00000137 if(!block.isMovable()) return; // BJO 00000137 if ( calcResizeDirection( evt ) == 1 && block.isEndResizable()) { setCursor(Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR)); } else if (calcResizeDirection( evt ) == -1 && block.isStartResizable()){ setCursor(Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR)); } else { setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } } public void mouseDragged(MouseEvent evt) { if ( preventDragging || !isEditable()) return; SwingBlock block = getBlockFor(evt.getSource()); draggingHandler.mouseDragged( AbstractDaySlot.this, block, evt); } private void blockEdit(MouseEvent evt) { SwingBlock block = getBlockFor(evt.getSource()); draggingHandler.blockEdit(block,new Point(evt.getX(),evt.getY())); } } protected void paintDraggingGrid(Graphics g, int x, int y, int width, int height) { /* Rectangle rect = g.getClipBounds(); int startx = draggingView.getView().getX(); int starty = draggingView.getView().getY(); g.setColor(Color.gray); for (int y1=10;y1<height-5; y1+=11) for (int x1=10;x1<width-5; x1+=11) { int x2 = startx + x1; int y2 = starty + y1; if ( x2 >= rect.x && x2 <= rect.x + rect.width && y2 >= rect.y && y2 <= rect.y + rect.height ) g.drawRect(x2,y2,2,2); } */ g.translate( x-1, y-1); if ( draggingView != null) { draggingView.paintDragging( g, width , height +1 ); } g.translate( -(x-1), -(y-1)); } static int count = 0; }
04900db4-rob
src/org/rapla/components/calendarview/swing/AbstractDaySlot.java
Java
gpl3
8,275
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview.swing; import java.awt.Color; import java.awt.Font; import java.awt.Point; import java.awt.Rectangle; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Iterator; import java.util.Locale; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JScrollPane; import org.rapla.components.calendarview.AbstractCalendar; import org.rapla.components.calendarview.Block; import org.rapla.components.calendarview.Builder; import org.rapla.components.calendarview.swing.scaling.IRowScale; import org.rapla.components.calendarview.swing.scaling.LinearRowScale; import org.rapla.components.calendarview.swing.scaling.VariableRowScale; import org.rapla.components.util.DateTools; /** Graphical component for displaying a calendar like weekview. */ public class SwingWeekView extends AbstractSwingCalendar { public final static int SLOT_GAP= 5; LargeDaySlot[] daySlots = new LargeDaySlot[] {}; private int startMinutes= 0; private int endMinutes= 24 * 60; BoxLayout boxLayout2= new BoxLayout(jCenter, BoxLayout.X_AXIS); TimeScale timeScale = new TimeScale(); IRowScale rowScale = new LinearRowScale(); protected JLabel weekTitle; protected SelectionHandler selectionHandler ; public SwingWeekView() { this(true); } public SwingWeekView(boolean showScrollPane) { super(showScrollPane); weekTitle = new JLabel(); weekTitle.setHorizontalAlignment( JLabel.CENTER); weekTitle.setFont(weekTitle.getFont().deriveFont((float)11.)); jCenter.setLayout(boxLayout2); jCenter.setAlignmentY(JComponent.TOP_ALIGNMENT); jCenter.setAlignmentX(JComponent.LEFT_ALIGNMENT); if ( showScrollPane ) { scrollPane.setRowHeaderView(timeScale); scrollPane.setCorner( JScrollPane.UPPER_LEFT_CORNER, weekTitle); } else { component.add(weekTitle, "0,0"); component.add(timeScale,"0,1"); } selectionHandler = new SelectionHandler(this); } public void updateSize(int width) { int slotCount = 0; int columnCount = 0; for (int i=0; i<daySlots.length; i++) { LargeDaySlot largeDaySlot = daySlots[i]; if ( isExcluded(i) ) { continue; } if ( largeDaySlot != null) { slotCount += largeDaySlot.getSlotCount(); columnCount++; } } int newWidth = Math.round(((width - timeScale.getWidth() - 10- columnCount* (16 + SLOT_GAP)) / (Math.max(1,slotCount)))-2); newWidth = Math.max( newWidth , minBlockWidth); for (LargeDaySlot slot: daySlots) { if ( slot != null) { slot.updateSize(newWidth); } } setSlotSize(newWidth); } public void setWorktime(int startHour, int endHour) { this.startMinutes = startHour * 60; this.endMinutes = endHour * 60; } public void setWorktimeMinutes(int startMinutes, int endMinutes) { this.startMinutes = startMinutes; this.endMinutes = endMinutes; if (getStartDate() != null) calcMinMaxDates( getStartDate() ); } public void setLocale(Locale locale) { super.setLocale( locale ); if ( timeScale != null ) timeScale.setLocale( locale ); } public void scrollDateVisible(Date date) { LargeDaySlot slot = getSlot(date); if ( slot == null) { return; } if (!jCenter.isAncestorOf( slot) ) { return; } LargeDaySlot scrollSlot = slot; Rectangle viewRect = scrollPane.getViewport().getViewRect(); Rectangle slotRect = scrollSlot.getBounds(); // test if already visible if (slotRect.x>=viewRect.x && (slotRect.x + slotRect.width)< (viewRect.x + viewRect.width ) ) { return; } scrollSlot.scrollRectToVisible(new Rectangle(0 ,viewRect.y ,scrollSlot.getWidth() ,10)); } public void scrollToStart() { int y = rowScale.getStartWorktimePixel(); int x = 0; scrollPane.getViewport().setViewPosition(new Point(x,y)); } public Collection<Block> getBlocks() { ArrayList<Block> list = new ArrayList<Block>(); for (int i=0;i<getDaysInView();i++) { list.addAll(daySlots[i].getBlocks()); } return Collections.unmodifiableCollection( list ); } /** The granularity of the selection rows. * <ul> * <li>1: 1 rows per hour = 1 Hour</li> * <li>2: 2 rows per hour = 1/2 Hour</li> * <li>3: 3 rows per hour = 20 Minutes</li> * <li>4: 4 rows per hour = 15 Minutes</li> * <li>6: 6 rows per hour = 10 Minutes</li> * <li>12: 12 rows per hour = 5 Minutes</li> * </ul> * Default is 4. */ public void setRowsPerHour(int rowsPerHour) { if ( rowScale instanceof LinearRowScale) ((LinearRowScale)rowScale).setRowsPerHour(rowsPerHour); } /** @see #setRowsPerHour */ public int getRowsPerHour() { if ( rowScale instanceof LinearRowScale) return ((LinearRowScale)rowScale).getRowsPerHour(); return 0; } /** The size of each row (in pixel). Default is 15.*/ public void setRowSize(int rowSize) { if ( rowScale instanceof LinearRowScale) ((LinearRowScale)rowScale).setRowSize(rowSize); } public int getRowSize() { if ( rowScale instanceof LinearRowScale) return ((LinearRowScale)rowScale).getRowSize(); return 0; } public void setBackground(Color color) { super.setBackground(color); if (timeScale != null) timeScale.setBackground(color); } public void setEditable(boolean b) { super.setEditable( b ); // Hide the rest for (int i= 0;i<daySlots.length;i++) { LargeDaySlot slot = daySlots[i]; if (slot == null) continue; slot.setEditable(b); slot.getHeader().setBorder(b ? SLOTHEADER_BORDER : null); } } /** must be called after the slots are filled*/ protected boolean isEmpty(int column) { return daySlots[column].isEmpty(); } public void rebuild() { daySlots= new LargeDaySlot[getColumnCount()]; selectionHandler.clearSelection(); // clear everything jHeader.removeAll(); jCenter.removeAll(); int start = startMinutes ; int end = endMinutes ; // calculate the blocks Iterator<Builder> it= builders.iterator(); while (it.hasNext()) { Builder b= it.next(); b.prepareBuild(getStartDate(),getEndDate()); if (! bEditable) { start = Math.min(b.getMinMinutes(),start); end = Math.max(b.getMaxMinutes(),end); if (start<0) throw new IllegalStateException("builder.getMin() is smaller than 0"); if (end>24*60) throw new IllegalStateException("builder.getMax() is greater than 24"); } } //rowScale = new VariableRowScale(); if ( rowScale instanceof LinearRowScale) { LinearRowScale linearScale = (LinearRowScale) rowScale; int pixelPerHour = linearScale.getRowsPerHour() * linearScale.getRowSize(); timeScale.setBackground(component.getBackground()); linearScale.setTimeZone( timeZone ); if ( isEditable()) { timeScale.setTimeIntervall(0, 24, pixelPerHour); linearScale.setTimeIntervall( 0, 24 * 60); } else { timeScale.setTimeIntervall(start / 60, end / 60, pixelPerHour); linearScale.setTimeIntervall( (start /60) * 60, Math.min( 24 * 60, ((end / 60) + ((end%60 != 0) ? 1 : 0)) * 60 )); } linearScale.setWorktimeMinutes( this.startMinutes, this.endMinutes); } else { timeScale.setBackground(component.getBackground()); timeScale.setTimeIntervall(0, 24, 60); VariableRowScale periodScale = (VariableRowScale) rowScale; periodScale.setTimeZone( timeZone ); } // create Slots DraggingHandler draggingHandler = new DraggingHandler(this, rowScale,true); for (int i=0; i<getColumnCount(); i++) { createMultiSlot(i, i, draggingHandler, selectionHandler); } // build Blocks it= builders.iterator(); while (it.hasNext()) { Builder b= it.next(); if (b.isEnabled()) { b.build(this); } } // add Slots for (int i=0; i<daySlots.length; i++) { if ( isExcluded(i) ) { continue; } addToWeekView(daySlots[i]); } jHeader.add(Box.createGlue()); jHeader.validate(); jCenter.validate(); if ( isEditable()) { updateSize(component.getSize().width); } component.revalidate(); component.repaint(); } private void createMultiSlot(int pos, int column, DraggingHandler draggingHandler, SelectionHandler selectionHandler) { JComponent header = createSlotHeader(column); LargeDaySlot c= new LargeDaySlot(slotSize,rowScale, header); c.setEditable(isEditable()); c.setTimeIntervall(); c.setDraggingHandler(draggingHandler); c.addMouseListener(selectionHandler); c.addMouseMotionListener(selectionHandler); daySlots[pos]= c; } protected Date getDateFromColumn(int column) { return DateTools.addDays( getStartDate(), column); } /** override this method, if you want to create your own slot header. */ protected JComponent createSlotHeader(Integer column) { JLabel jLabel = new JLabel(); jLabel.setBorder(isEditable() ? SLOTHEADER_BORDER : null); Date date = getDateFromColumn(column); jLabel.setText(AbstractCalendar.formatDayOfWeekDateMonth(date,locale,getTimeZone())); jLabel.setFont(new Font("SansSerif", Font.PLAIN, 13)); jLabel.setHorizontalAlignment(JLabel.CENTER); jLabel.setOpaque(false); jLabel.setForeground(Color.black); return jLabel; } protected int getColumnCount() { return getDaysInView(); } public void addBlock(Block bl, int col,int slot) { checkBlock( bl ); LargeDaySlot dslot = daySlots[col]; dslot.putBlock((SwingBlock)bl, slot); } private LargeDaySlot getSlot(Date start) { long countDays = DateTools.countDays(DateTools.cutDate(getStartDate()), start); int slotNr = (int) countDays; if ( daySlots.length ==0) { return null; } int min = Math.min(daySlots.length-1,slotNr); return daySlots[min]; } private void addToWeekView(LargeDaySlot slot) { jHeader.add(slot.getHeader()); jHeader.add(Box.createHorizontalStrut(SLOT_GAP)); jCenter.add(slot); jCenter.add(Box.createHorizontalStrut(SLOT_GAP)); } public int getSlotNr(DaySlot slot) { for (int i=0;i<daySlots.length;i++) { if (daySlots[i] == slot) { return i; } } throw new IllegalStateException("Slot not found in List"); } int getRowsPerDay() { return rowScale.getRowsPerDay(); } LargeDaySlot getSlot( int nr ) { if ( nr >=0 && nr< daySlots.length) return daySlots[nr]; else return null; } public boolean isSelected(int slotNr) { LargeDaySlot slot = getSlot(slotNr); if ( slot == null) { return false; } return slot.isSelected(); } int getDayCount() { return daySlots.length; } int calcSlotNr(int x, int y) { for (int i=0;i<daySlots.length;i++) { if (getSlot(i) == null) continue; Point p = getSlot(i).getLocation(); if (p.x <= x && x <= p.x + daySlots[i].getWidth() && p.y <= y && y <= p.y + daySlots[i].getHeight() ) return i; } return -1; } public LargeDaySlot calcSlot(int x, int y) { int nr = calcSlotNr(x, y); if (nr == -1) return null; else return daySlots[nr]; } protected Date createDate(DaySlot slot,int index, boolean startOfRow) { Calendar calendar = createCalendar(); calendar.setTime( getStartDate() ); calendar.set( Calendar.DAY_OF_WEEK, getFirstWeekday() ); calendar.add( Calendar.DATE , getSlotNr( slot ) %getDaysInView()); if (!startOfRow) index++; calendar.set(Calendar.HOUR_OF_DAY,rowScale.calcHour(index)); calendar.set(Calendar.MINUTE,rowScale.calcMinute(index)); calendar.set(Calendar.SECOND,0); calendar.set(Calendar.MILLISECOND,0); return calendar.getTime(); } }
04900db4-rob
src/org/rapla/components/calendarview/swing/SwingWeekView.java
Java
gpl3
14,650
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview.swing; import java.awt.Component; import java.awt.Graphics; import org.rapla.components.calendarview.Block; public interface SwingBlock extends Block { Component getView(); public void paintDragging(Graphics g, int width, int height); boolean isMovable(); boolean isStartResizable(); boolean isEndResizable(); }
04900db4-rob
src/org/rapla/components/calendarview/swing/SwingBlock.java
Java
gpl3
1,305
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview.swing; import java.awt.Component; import java.awt.Cursor; import java.awt.Point; public interface DaySlot { void paintDraggingGrid(int x,int y, int height,SwingBlock block, int oldY,int oldHeight,boolean bPaint); Point getLocation(); void unselectAll(); int calcRow(int y); int calcSlot(int x); int getX(Component component); void select(int startRow,int endRow); void setCursor(Cursor cursor); }
04900db4-rob
src/org/rapla/components/calendarview/swing/DaySlot.java
Java
gpl3
1,409
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview.swing; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.Point; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Iterator; import javax.swing.JComponent; import javax.swing.JLabel; import org.rapla.components.calendarview.Block; import org.rapla.components.calendarview.Builder; import org.rapla.components.layout.TableLayout; import org.rapla.components.util.DateTools; /** Graphical component for displaying a calendar like monthview. * */ public class SwingMonthView extends AbstractSwingCalendar { public final static int ROWS = 6; //without the header row public final static int COLUMNS = 7; private SmallDaySlot[] slots; DraggingHandler draggingHandler = new DraggingHandler(this, false); SelectionHandler selectionHandler = new SelectionHandler(this); JLabel monthTitle = new JLabel(); public SwingMonthView() { this(true); } public SwingMonthView(boolean showScrollPane) { super( showScrollPane ); monthTitle.setOpaque( false); jTitlePanel.add(monthTitle, BorderLayout.NORTH); monthTitle.setHorizontalAlignment( JLabel.CENTER); monthTitle.setFont(monthTitle.getFont().deriveFont(Font.BOLD)); } protected boolean isEmpty(int column) { for ( int i=column;i < slots.length;i+=7 ) { if (!slots[i].isEmpty() ) { return false; } } return true; } public Collection<Block> getBlocks(int dayOfMonth) { int index = dayOfMonth-1; return Collections.unmodifiableCollection(slots[ index ].getBlocks()); } public Collection<Block> getBlocks() { ArrayList<Block> list = new ArrayList<Block>(); for (int i=0;i<slots.length;i++) { list.addAll(slots[i].getBlocks()); } return Collections.unmodifiableCollection( list ); } public void setEditable(boolean b) { super.setEditable( b); if ( slots == null ) return; // Hide the rest for (int i= 0;i<slots.length;i++) { SmallDaySlot slot = slots[i]; if (slot == null) continue; slot.setEditable(b); } } TableLayout tableLayout; public void rebuild() { // we need to clone the calendar, because we modify the calendar object in the getExclude() method Calendar counter = createCalendar(); Iterator<Builder> it= builders.iterator(); Date startDate = getStartDate(); while (it.hasNext()) { Builder b= it.next(); b.prepareBuild(startDate,getEndDate() ); } // create fields slots = new SmallDaySlot[daysInMonth]; counter.setTime(startDate); int year = counter.get(Calendar.YEAR); SimpleDateFormat format = new SimpleDateFormat("MMMMMM",locale); String monthname = format.format(counter.getTime()); // calculate the blocks for (int i=0; i<daysInMonth; i++) { createField(i, counter.getTime()); counter.add(Calendar.DATE,1); } // clear everything jHeader.removeAll(); jCenter.removeAll(); monthTitle.setText( monthname + " " + year); // build Blocks it= builders.iterator(); while (it.hasNext()) { Builder b= it.next(); if (b.isEnabled()) { b.build(this); } } tableLayout= new TableLayout(); jCenter.setLayout(tableLayout); counter.setTime(startDate); int firstDayOfWeek = getFirstWeekday(); if ( counter.get(Calendar.DAY_OF_WEEK) != firstDayOfWeek) { counter.set(Calendar.DAY_OF_WEEK, firstDayOfWeek); if ( counter.getTime().after( startDate)) { counter.add(Calendar.DATE, -7); } } // add headers int offset = (int) DateTools.countDays(counter.getTime(),startDate); for (int i=0;i<COLUMNS;i++) { int weekday = counter.get(Calendar.DAY_OF_WEEK); if ( !isExcluded(i) ) { tableLayout.insertColumn(i, slotSize ); jHeader.add( createSlotHeader( weekday ) ); } else { tableLayout.insertColumn(i, 0); } counter.add(Calendar.DATE,1); } for (int i=0;i<ROWS;i++) { tableLayout.insertRow(i, TableLayout.PREFERRED ); } // add Fields counter.setTime(startDate); for (int i=0; i<daysInMonth; i++) { int column = (offset + i) % 7; int row = (counter.get(Calendar.DATE) + 6 - column ) / 7; if ( !isExcluded( column ) ) { jCenter.add( slots[i] , "" + column + "," + row); } counter.add(Calendar.DATE,1); } selectionHandler.clearSelection(); jHeader.validate(); jCenter.validate(); if ( isEditable()) { updateSize(component.getSize().width); } component.revalidate(); component.repaint(); } private void createField(int pos, Date date) { slots[pos]= createSmallslot(pos, date); } protected SmallDaySlot createSmallslot(int pos, Date date) { String headerText = "" + (pos + 1); Color headerColor = getNumberColor( date); Color headerBackground = null; return createSmallslot(headerText, headerColor,headerBackground); } protected SmallDaySlot createSmallslot(String headerText, Color headerColor, Color headerBackground) { return createSmallslot(headerText, slotSize,headerColor,headerBackground); } protected SmallDaySlot createSmallslot(String headerText, int width, Color headerColor, Color headerBackground ) { SmallDaySlot c= new SmallDaySlot(headerText, width, headerColor, headerBackground); c.setEditable(isEditable()); c.setDraggingHandler(draggingHandler); c.addMouseListener(selectionHandler); c.addMouseMotionListener(selectionHandler); return c; } public static Color DATE_NUMBER_COLOR = Color.gray; /** * @param date */ protected Color getNumberColor( Date date) { return DATE_NUMBER_COLOR; } /** override this method, if you want to create your own header. */ protected JComponent createSlotHeader(int weekday) { JLabel jLabel = new JLabel(); jLabel.setBorder(isEditable() ? SLOTHEADER_BORDER : null); jLabel.setText( getWeekdayName(weekday) ); jLabel.setFont(new Font("SansSerif", Font.PLAIN, 13)); jLabel.setHorizontalAlignment(JLabel.CENTER); jLabel.setOpaque(false); jLabel.setForeground(Color.black); Dimension dim = new Dimension(this.slotSize,20); jLabel.setPreferredSize( dim); jLabel.setMinimumSize( dim ); jLabel.setMaximumSize( dim ); return jLabel; } public void addBlock(Block bl, int col,int slot) { checkBlock( bl ); // System.out.println("Put " + bl.getStart() + " into field " + (date -1)); slots[col].putBlock((SwingBlock)bl); } public int getSlotNr( DaySlot slot) { for (int i=0;i<slots.length;i++) if (slots[i] == slot) return i; throw new IllegalStateException("Slot not found in List"); } public boolean isSelected(int nr) { SmallDaySlot slot = getSlot(nr); if ( slot == null) { return false; } return slot.isSelected(); } int getRowsPerDay() { return 1; } SmallDaySlot getSlot(int nr) { if ( nr >=0 && nr< slots.length) return slots[nr]; else return null; } int getDayCount() { return slots.length; } int calcSlotNr(int x, int y) { for (int i=0;i<slots.length;i++) { if (slots[i] == null) continue; Point p = slots[i].getLocation(); if ((p.x <= x) && (x <= p.x + slots[i].getWidth()) && (p.y <= y) && (y <= p.y + slots[i].getHeight()) ) { return i; } } return -1; } SmallDaySlot calcSlot(int x,int y) { int nr = calcSlotNr(x, y); if (nr == -1) { return null; } else { return slots[nr]; } } Date createDate(DaySlot slot, int row, boolean startOfRow) { Calendar calendar = createCalendar(); calendar.setTime( getStartDate() ); int dayOfMonth = getSlotNr( slot ) +1; calendar.set( Calendar.DAY_OF_MONTH, dayOfMonth); if ( !startOfRow ) { calendar.add( Calendar.DATE , 1 ); } calendar.set( Calendar.HOUR_OF_DAY, 0 ); calendar.set( Calendar.MINUTE, 0 ); calendar.set( Calendar.SECOND, 0 ); calendar.set( Calendar.MILLISECOND, 0 ); return calendar.getTime(); } @Override public void updateSize(int width) { int columnSize = tableLayout.getNumColumn(); int newWidth = Math.max( minBlockWidth , (width - 10 ) / (Math.max(1,columnSize))); for (SmallDaySlot slot: this.slots) { if ( slot != null) { slot.updateSize(newWidth); } } setSlotSize(newWidth); for ( int i=0;i< columnSize;i++) { tableLayout.setColumn(i, newWidth); } for (Component comp:jHeader.getComponents()) { double height = comp.getPreferredSize().getHeight(); Dimension dim = new Dimension( newWidth,(int) height); comp.setPreferredSize(dim); comp.setMaximumSize(dim); comp.setMinimumSize( dim); comp.invalidate(); } jCenter.invalidate(); jCenter.repaint(); } }
04900db4-rob
src/org/rapla/components/calendarview/swing/SwingMonthView.java
Java
gpl3
10,974
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview.swing; import java.awt.Cursor; import java.awt.Point; import java.awt.event.MouseEvent; import java.util.Date; import org.rapla.components.calendarview.swing.scaling.IRowScaleSmall; import org.rapla.components.calendarview.swing.scaling.OneRowScale; import org.rapla.components.util.TimeInterval; /** DraggingHandler coordinates the drag events from the Block-Components * between the different MultiSlots of a weekview. */ class DraggingHandler { int draggingPointOffset = 0; DaySlot oldSlot; int oldY = 0; int oldHeight = 0; AbstractSwingCalendar m_cv; Date start = null; Date newStart = null; Date end = null; Date newEnd = null; int resizeDirection; boolean bMoving; boolean bResizing; boolean supportsResizing; IRowScaleSmall rowScale; public DraggingHandler(AbstractSwingCalendar wv,IRowScaleSmall rowScale, boolean supportsResizing) { this.supportsResizing = supportsResizing; this.rowScale = rowScale; m_cv = wv; } public DraggingHandler(AbstractSwingCalendar wv, boolean supportsResizing) { this ( wv, new OneRowScale(), supportsResizing ); } public boolean supportsResizing() { return supportsResizing; } public void blockPopup(SwingBlock block,Point p) { m_cv.fireBlockPopup(block,p); } public void blockEdit(SwingBlock block,Point p) { m_cv.fireBlockEdit(block,p); } public void mouseReleased(DaySlot slot, SwingBlock block, MouseEvent evt) { if ( isDragging() ) stopDragging(slot, block, evt); } public void blockBorderPressed(DaySlot slot,SwingBlock block,MouseEvent evt, int direction) { if (!bResizing && supportsResizing ) { this.resizeDirection = direction; startResize( slot, block, evt); } } public boolean isDragging() { return bResizing || bMoving; } public void mouseDragged(DaySlot slot,SwingBlock block,MouseEvent evt) { if ( bResizing ) startResize( slot, block, evt ); else startMoving( slot, block, evt ); } private void dragging(DaySlot slot,SwingBlock block,int _x,int _y,boolean bDragging) { // 1. Calculate slot DaySlot newSlot = null; if ( bResizing ) { newSlot = slot; } else { int slotNr = m_cv.calcSlotNr( slot.getLocation().x + _x , slot.getLocation().y + _y); newSlot = m_cv.getSlot( slotNr ); if (newSlot == null) return; } // 2. Calculate new x relative to slot int y = _y; int xslot = 0; int height = block.getView().getHeight(); xslot = newSlot.calcSlot( slot.getLocation().x + _x - newSlot.getLocation().x ); if ( bResizing ) { if ( resizeDirection == 1) { y = block.getView().getLocation().y; // we must trim the endRow int endrow = newSlot.calcRow(_y ) + 1; endrow = Math.max( newSlot.calcRow(y) + 2, endrow); height = rowScale.getYCoordForRow(endrow) - y; if ( bDragging ) { start = block.getStart(); end = m_cv.createDate( newSlot, endrow, true); //System.out.println ( "Resizeing@end: start=" + start + ", end=" + end) ; } } else if (resizeDirection == -1){ // we must trim y y = rowScale.trim( y ); int row = newSlot.calcRow( y ) ; int rowSize = rowScale.getRowSizeForRow( row ); y = Math.min ( block.getView().getLocation().y + block.getView().getHeight() - rowSize, y ); height = block.getView().getLocation().y + block.getView().getHeight() - y; if ( bDragging ) { row = newSlot.calcRow( y ); if(y==0) start = m_cv.createDate( newSlot, row, true); else start = m_cv.createDate( newSlot, row, false); end = block.getEnd(); //System.out.println ( "Resizeing@start: start=" + start + ", end=" + end) ; } } } else if (bMoving){ // we must trim y //y = rowScale.trim( y); if ( bDragging ) { int newRow = newSlot.calcRow( y ); start = m_cv.createDate( newSlot, newRow, true); y = rowScale.trim( y ); //System.out.println ( "Moving: start=" + start + ", end=" + end +" row: " + row) ; } } if (oldSlot != null && oldSlot != newSlot) oldSlot.paintDraggingGrid(xslot, y, height, block, oldY, oldHeight, false); newSlot.paintDraggingGrid(xslot, y, height, block, oldY, oldHeight, bDragging); oldSlot = newSlot; oldY = y; oldHeight = height; } private void startMoving(DaySlot slot,SwingBlock block,MouseEvent evt) { if (!bMoving) { draggingPointOffset = evt.getY(); if (block.isMovable()) { bMoving = true; slot.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)); } else { bMoving = false; slot.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); return; } } if ( block == null) return; int x = evt.getX() + slot.getX(block.getView()); int y = evt.getY() + block.getView().getLocation().y; scrollTo( slot, x, y); // Correct y with the draggingPointOffset y = evt.getY() - draggingPointOffset + block.getView().getLocation().y ; y += rowScale.getDraggingCorrection(y ) ; dragging( slot, block, x, y, bMoving); } private void startResize(DaySlot slot,SwingBlock block, MouseEvent evt) { if ( block == null) return; int x = evt.getX() + slot.getX(block.getView()); int y = evt.getY() + block.getView().getLocation().y; if (!bResizing) { if (block.isMovable() && ( ( resizeDirection == -1 && block.isStartResizable() ) || ( resizeDirection == 1 && block.isEndResizable()))) { bResizing = true; } else { bResizing = false; return; } } scrollTo( slot, x, y); dragging( slot, block, x, y, bResizing); } private void stopDragging(DaySlot slot, SwingBlock block,MouseEvent evt) { slot.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); if ( block == null) { return ; } if (!m_cv.isEditable()) return; try { int x = evt.getX() + slot.getX( block.getView() ); int y = evt.getY() - draggingPointOffset + block.getView().getLocation().y ; y += rowScale.getDraggingCorrection(y ); dragging(slot,block,x,y,false); Point upperLeft = m_cv.getScrollPane().getViewport().getViewPosition(); Point newPoint = new Point(slot.getLocation().x + x -upperLeft.x ,y-upperLeft.y); int slotNr = m_cv.getSlotNr(oldSlot); TimeInterval normalizedInterval = m_cv.normalizeBlockIntervall(block); Date blockStart = normalizedInterval.getStart(); Date blockEnd = normalizedInterval.getEnd(); if ( bMoving ) { // Has the block moved //System.out.println("Moved to " + newStart + " - " + newEnd); if ( !start.equals( blockStart ) || oldSlot!= slot) { m_cv.fireMoved(block, newPoint, start, slotNr); } } if ( bResizing ) { // System.out.println("Resized to " + start + " - " + end); if ( !( start.equals( blockStart ) && end.equals( blockEnd) )) { m_cv.fireResized(block, newPoint, start, end, slotNr); } } } finally { bResizing = false; bMoving = false; start = null; end = null; } } // Begin scrolling when hitting the upper or lower border while // dragging or selecting. private void scrollTo(DaySlot slot,int x,int y) { // 1. Transfer p.x relative to jCenter m_cv.scrollTo(slot.getLocation().x + x, slot.getLocation().y + y); } }
04900db4-rob
src/org/rapla/components/calendarview/swing/DraggingHandler.java
Java
gpl3
9,735
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview.swing; import java.awt.Component; import java.awt.Point; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.Date; import javax.swing.SwingUtilities; /** SelectionHandler handles the selection events and the Slot * Context Menu (right click). * This is internally used by the weekview to communicate with its slots. */ public class SelectionHandler extends MouseAdapter { Date start; Date end; boolean bPopupClicked = false; boolean bSelecting = false; public int selectionStart = -1; public int selectionEnd = -1; private int oldIndex = -1; private int oldSlotNr = -1; private int startSlot = -1; private int endSlot = -1; private int draggingSlot = -1; private int draggingIndex = -1; AbstractSwingCalendar m_wv; public enum SelectionStrategy { FLOW,BLOCK; } SelectionStrategy selectionStrategy = SelectionStrategy.FLOW; public SelectionHandler(AbstractSwingCalendar wv) { m_wv = wv; } public void mouseClicked(MouseEvent evt) { if (evt.isPopupTrigger()) { bPopupClicked = true; slotPopup(evt); } else { /* We don't check click here if (SwingUtilities.isLeftMouseButton(evt)) move(evt); */ } } public void mousePressed(MouseEvent evt) { if (evt.isPopupTrigger()) { bPopupClicked = true; move(evt, true); slotPopup(evt); } else { if (SwingUtilities.isLeftMouseButton(evt)) move(evt,false); } } public void mouseReleased(MouseEvent evt) { if (evt.isPopupTrigger()) { bPopupClicked = true; move(evt, true); slotPopup(evt); } if (SwingUtilities.isLeftMouseButton(evt) && !bPopupClicked) move(evt, false); bPopupClicked = false; bSelecting = false; } public void mouseDragged(MouseEvent evt) { if (SwingUtilities.isLeftMouseButton(evt) && !bPopupClicked) move(evt, false); } public void mouseMoved(MouseEvent evt) { } public void setSelectionStrategy(SelectionStrategy strategy) { selectionStrategy = strategy; } public void clearSelection() { for (int i=0;i<m_wv.getDayCount();i++) { if (m_wv.getSlot(i) != null) { m_wv.getSlot(i).unselectAll(); } } selectionStart = -1; selectionEnd = -1; oldIndex = -1; oldSlotNr = -1; startSlot = -1; endSlot = -1; draggingSlot = -1; draggingIndex = -1; } public void slotPopup(MouseEvent evt) { Point p = new Point(evt.getX(),evt.getY()); DaySlot slot= (DaySlot)evt.getSource(); if (start == null || end == null) { int index = slot.calcRow( evt.getY() ); start = m_wv.createDate(slot, index, true); end = m_wv.createDate(slot, index, false); clearSelection(); slot.select(index,index); } m_wv.fireSelectionPopup((Component)slot,p,start,end,m_wv.getSlotNr( slot )); } public void move(MouseEvent evt, boolean contextPopup) { if (!m_wv.isEditable()) return; DaySlot source = (DaySlot) evt.getSource(); int slotNr; { Point location = source.getLocation(); slotNr = m_wv.calcSlotNr( location.x + evt.getX() ,location.y + evt.getY() ); } if (slotNr == -1) return; int selectedIndex = source.calcRow(evt.getY()); if ( contextPopup && inCurrentSelection(slotNr,selectedIndex)) { return; } if (!bSelecting) { clearSelection(); bSelecting = true; selectionStart = selectedIndex; selectionEnd = selectedIndex; draggingSlot =slotNr; draggingIndex = selectedIndex; startSlot = slotNr; endSlot = slotNr; } else { if (slotNr == draggingSlot) { startSlot = endSlot = slotNr; if ( selectedIndex > draggingIndex ) { selectionStart = draggingIndex; selectionEnd = selectedIndex; } else if (selectedIndex < draggingIndex ){ selectionStart = selectedIndex; selectionEnd = draggingIndex; } } else if (slotNr > draggingSlot) { startSlot = draggingSlot; selectionStart = draggingIndex; endSlot = slotNr; selectionEnd = selectedIndex; } else if (slotNr < draggingSlot) { startSlot = slotNr; selectionStart = selectedIndex; endSlot = draggingSlot; selectionEnd = draggingIndex; } if (selectedIndex == oldIndex && slotNr == oldSlotNr) { return; } int rowsPerDay = m_wv.getRowsPerDay(); if (selectedIndex >= rowsPerDay-1) { selectedIndex = rowsPerDay-1; } } oldSlotNr = slotNr; oldIndex = selectedIndex; switch ( selectionStrategy) { case BLOCK: setSelectionBlock();break; case FLOW: setSelectionFlow();break; } { Point location = m_wv.getSlot(slotNr).getLocation(); m_wv.scrollTo( location.x + evt.getX() ,location.y + evt.getY() ); } } private boolean inCurrentSelection(int slotNr, int selectedIndex) { if ( slotNr < startSlot || slotNr > endSlot) { return false; } if (slotNr == startSlot && selectedIndex < selectionStart) { return false; } if (slotNr == endSlot && selectedIndex > selectionEnd) { return false; } return true; } protected void setSelectionFlow() { int startRow = selectionStart; int endRow = m_wv.getRowsPerDay() -1; for (int i=0;i<startSlot;i++) { DaySlot daySlot = m_wv.getSlot(i); if (daySlot != null) { daySlot.unselectAll(); } } int dayCount = m_wv.getDayCount(); for (int i=startSlot;i<=endSlot;i++) { if (i > startSlot) { startRow = 0; } if (i == endSlot) { endRow = selectionEnd; } DaySlot slot = m_wv.getSlot(i); if (slot != null) { slot.select(startRow,endRow); } } startRow = selectionStart ; endRow = selectionEnd ; for (int i=endSlot+1;i<dayCount;i++) { DaySlot slot = m_wv.getSlot(i); if (slot != null) { slot.unselectAll(); } } start = m_wv.createDate(m_wv.getSlot(startSlot),startRow, true); end = m_wv.createDate(m_wv.getSlot(endSlot),endRow, false); m_wv.fireSelectionChanged(start,end); } protected void setSelectionBlock() { int startRow = selectionStart; int endRow = selectionEnd; Point endSlotLocation = m_wv.getSlot(endSlot).getLocation(); Point startSlotLocation = m_wv.getSlot(startSlot).getLocation(); int min_y = Math.min(startSlotLocation.y, endSlotLocation.y); int min_x = Math.min(startSlotLocation.x, endSlotLocation.x); int max_y = Math.max(startSlotLocation.y, endSlotLocation.y); int max_x = Math.max(startSlotLocation.x, endSlotLocation.x); int dayCount = m_wv.getDayCount(); for (int i=0;i<dayCount;i++) { DaySlot slot = m_wv.getSlot(i); if (slot != null) { Point location = slot.getLocation(); if ( location.x >= min_x && location.x <= max_x && location.y >= min_y && location.y <= max_y) { slot.select(startRow,endRow); } else { slot.unselectAll(); } } } start = m_wv.createDate(m_wv.getSlot(startSlot),startRow, true); end = m_wv.createDate(m_wv.getSlot(endSlot),endRow, false); m_wv.fireSelectionChanged(start,end); } }
04900db4-rob
src/org/rapla/components/calendarview/swing/SelectionHandler.java
Java
gpl3
9,569
package org.rapla.components.calendarview.swing.scaling; import java.util.Date; public interface IRowScale extends IRowScaleSmall { int calcHour( int index ); int calcMinute( int index ); int getSizeInPixel(); int getMaxRows(); int getRowsPerDay(); int getYCoord( Date time ); int getStartWorktimePixel(); int getEndWorktimePixel(); int getSizeInPixelBetween( int startRow, int endRow ); boolean isPaintRowThick( int row ); }
04900db4-rob
src/org/rapla/components/calendarview/swing/scaling/IRowScale.java
Java
gpl3
485
package org.rapla.components.calendarview.swing.scaling; public interface IRowScaleSmall { int getYCoordForRow( int row ); int getRowSizeForRow( int row ); int calcRow( int y ); int trim( int y ); int getDraggingCorrection(int y); }
04900db4-rob
src/org/rapla/components/calendarview/swing/scaling/IRowScaleSmall.java
Java
gpl3
254
package org.rapla.components.calendarview.swing.scaling; public class OneRowScale implements IRowScaleSmall { public int getYCoordForRow( int row ) { return 0; } public int getRowSizeForRow( int row ) { return 15; } public int calcRow( int y ) { return 0; } public int trim( int y ) { return 0; } public int getDraggingCorrection( int y) { return 15 / 2; } }
04900db4-rob
src/org/rapla/components/calendarview/swing/scaling/OneRowScale.java
Java
gpl3
470
package org.rapla.components.calendarview.swing.scaling; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; public class LinearRowScale implements IRowScale { private int rowSize = 15; private int rowsPerHour = 4; final private static int MINUTES_PER_HOUR= 60; private TimeZone timeZone = TimeZone.getDefault(); private int mintime; private int maxtime; private int workstartMinutes; private int workendMinutes; public LinearRowScale() { } public void setTimeZone( TimeZone timeZone) { this.timeZone = timeZone; } public int getRowsPerDay() { return rowsPerHour * 24; } public void setRowSize( int rowSize ) { this.rowSize = rowSize; } public int getRowSize() { return rowSize; } public int getRowsPerHour() { return rowsPerHour; } public void setRowsPerHour( int rowsPerHour ) { this.rowsPerHour = rowsPerHour; } public int calcHour(int index) { return index / rowsPerHour; } public int calcMinute(int index) { double minutesPerRow = 60. / rowsPerHour; long minute = Math.round((index % rowsPerHour) * (minutesPerRow)); return (int)minute; } public int getSizeInPixel() { return rowSize * getMaxRows(); } public int getMaxRows() { int max; max = (rowsPerHour * (maxtime - mintime)) / 60 ; return max; } private int getMinuteOfDay(Date time) { Calendar cal = getCalendar(); cal.setTime(time); return (cal.get(Calendar.HOUR_OF_DAY )) * MINUTES_PER_HOUR + cal.get(Calendar.MINUTE); } public int getYCoord(Date time) { int diff = getMinuteOfDay(time) - mintime ; int pixelPerHour= rowSize * rowsPerHour; return (diff * pixelPerHour) / MINUTES_PER_HOUR; } public int getStartWorktimePixel() { int pixelPerHour= rowSize * rowsPerHour; int starty = (int) (pixelPerHour * workstartMinutes / 60.); return starty; } public int getEndWorktimePixel() { int pixelPerHour= rowSize * rowsPerHour; int endy = (int) (pixelPerHour * workendMinutes / 60.); return endy; } private Calendar calendar = null; private Calendar getCalendar() { // Lazy creation of the calendar if (calendar == null) calendar = Calendar.getInstance(timeZone); return calendar; } public boolean isPaintRowThick( int row ) { return row % rowsPerHour == 0; } public void setTimeIntervall( int startMinutes, int endMinutes ) { mintime = startMinutes; maxtime = endMinutes; } public void setWorktimeMinutes( int workstartMinutes, int workendMinutes ) { this.workstartMinutes = workstartMinutes; this.workendMinutes = workendMinutes; } public int getYCoordForRow( int row ) { return row * rowSize; } public int getSizeInPixelBetween( int startRow, int endRow ) { return (endRow - startRow) * rowSize; } public int getRowSizeForRow( int row ) { return rowSize; } public int calcRow(int y) { int rowsPerDay = getRowsPerDay(); int row = (y-3) / rowSize; return Math.min(Math.max(0, row), rowsPerDay -1); } public int trim(int y ) { return (y / rowSize) * rowSize; } public int getDraggingCorrection( int y) { return rowSize / 2; } }
04900db4-rob
src/org/rapla/components/calendarview/swing/scaling/LinearRowScale.java
Java
gpl3
3,610
package org.rapla.components.calendarview.swing.scaling; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; public class VariableRowScale implements IRowScale { PeriodRow[] periodRows; private int hourSize = 60; final private static int MINUTES_PER_HOUR= 60; private TimeZone timeZone = TimeZone.getDefault(); private int mintime =0 ; /* private int maxtime = 24; private int workstart = 0; private int workend = 24; */ class PeriodRow { int minutes; int ypos; int startMinute; PeriodRow( int minutes ) { this.minutes = minutes; } public int getRowSize() { return (minutes * hourSize) / 60; } } public VariableRowScale() { periodRows = new PeriodRow[] { new PeriodRow( 60 * 8 ), new PeriodRow( 45 ), new PeriodRow( 60 ), new PeriodRow( 10 ), new PeriodRow( 110 ), new PeriodRow( 60 + 15), new PeriodRow( 60 * 3 ), new PeriodRow( 60 * 8 ) }; for ( int i=0;i< periodRows.length-1;i++) { periodRows[i+1].ypos = periodRows[i].ypos + periodRows[i].getRowSize(); periodRows[i+1].startMinute = periodRows[i].startMinute + periodRows[i].minutes; } } public void setTimeZone( TimeZone timeZone) { this.timeZone = timeZone; } public int getRowsPerDay() { return periodRows.length; } public int getSizeInPixel() { PeriodRow lastRow = getLastRow(); return lastRow.ypos + lastRow.getRowSize(); } public int getMaxRows() { return periodRows.length; } private int getMinuteOfDay(Date time) { Calendar cal = getCalendar(); cal.setTime(time); return (cal.get(Calendar.HOUR_OF_DAY )) * MINUTES_PER_HOUR + cal.get(Calendar.MINUTE); } public int calcHour(int index) { return periodRows[index].startMinute / MINUTES_PER_HOUR; } public int calcMinute(int index) { return periodRows[index].startMinute % MINUTES_PER_HOUR; } public int getYCoord(Date time) { int diff = getMinuteOfDay(time) - mintime * MINUTES_PER_HOUR ; return (diff * hourSize) / MINUTES_PER_HOUR; } public int getStartWorktimePixel() { return periodRows[0].getRowSize(); } public int getEndWorktimePixel() { PeriodRow lastRow = getLastRow(); return lastRow.ypos; } private PeriodRow getLastRow() { PeriodRow lastRow = periodRows[periodRows.length-1]; return lastRow; } private Calendar calendar = null; private Calendar getCalendar() { // Lazy creation of the calendar if (calendar == null) calendar = Calendar.getInstance(timeZone); return calendar; } public boolean isPaintRowThick( int row ) { return true; } /* public void setTimeIntervall( int startHour, int endHour ) { mintime = startHour; maxtime = endHour; } public void setWorktime( int startHour, int endHour ) { workstart = startHour; workend = endHour; } */ public int getYCoordForRow( int row ) { if ( row < 0 || row >= periodRows.length) { return row* 400; } return periodRows[row].ypos; } public int getSizeInPixelBetween( int startRow, int endRow ) { if ( startRow < 0 || endRow < 0 || startRow >= periodRows.length || endRow >=periodRows.length) { return (endRow - startRow) * 400; } return periodRows[endRow].ypos - periodRows[startRow].ypos; } public int getRowSizeForRow( int row ) { /* if ( row < 0 || row >= periodRows.length) { return 60; } */ return periodRows[row].getRowSize(); } public int calcRow(int y) { for ( int i=0;i< periodRows.length;i++) { PeriodRow row =periodRows[i]; if (row.ypos + row.getRowSize() >=y) return i; } return 0; } public int trim(int y ) { int row = calcRow( y ); int rowSize = getRowSizeForRow( row); return (y / rowSize) * rowSize; } public int getDraggingCorrection(int y) { return 0; } }
04900db4-rob
src/org/rapla/components/calendarview/swing/scaling/VariableRowScale.java
Java
gpl3
4,570
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview.swing; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Insets; import java.awt.Point; import java.awt.Rectangle; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JComponent; import javax.swing.JPanel; import org.rapla.components.calendarview.Block; import org.rapla.components.calendarview.swing.scaling.IRowScale; /** Komponente, welche eine beliebige anzahl von Slot-komponenten zusammenfasst. * die slots koennen zur laufzeit hinzugefuegt oder auch dynamisch bei bedarf *erzeugt werden. sie werden horizontal nebeneinander angeordnet. */ class LargeDaySlot extends AbstractDaySlot { private static final long serialVersionUID = 1L; public static Color THICK_LINE_COLOR = Color.black; public static Color LINE_COLOR = new Color(0xaa, 0xaa, 0xaa); public static Color WORKTIME_BACKGROUND = Color.white; public static Color NON_WORKTIME_BACKGROUND = new Color(0xcc, 0xcc, 0xcc); private List<Slot> slots= new ArrayList<Slot>(); private int slotxsize; private int selectionStart = -1; private int selectionEnd = -1; private int oldSelectionStart = -1; private int oldSelectionEnd = -1; BoxLayout boxLayout1 = new BoxLayout(this, BoxLayout.X_AXIS); int right_gap = 8; int left_gap = 5; int slot_space = 3; JComponent header; IRowScale rowScale; private BlockListener blockListener = new BlockListener(); /** es muss auch noch setTimeIntervall() aufgerufen werden, um die initialisierung fertig zu stellen (wie beim konstruktor von Slot). slotxsize ist die breite der einzelnen slots. "date" legt das Datum fest, fuer welches das Slot anzeigt (Uhrzeit bleibt unberuecksichtigt) */ public LargeDaySlot( int slotxsize ,IRowScale rowScale ,JComponent header) { this.slotxsize= slotxsize; this.rowScale = rowScale; this.header = header; setLayout(boxLayout1); this.add(Box.createHorizontalStrut(left_gap)); addSlot(); setBackground(getBackground()); setAlignmentX(0); setAlignmentY(TOP_ALIGNMENT); this.setBackground(Color.white); } public boolean isBorderVisible() { return true; // return getBackground() != Color.white; } public int getSlotCount() { return slots.size(); } public boolean isSelected() { return selectionStart >=0 ; } public void setVisible(boolean b) { super.setVisible(b); header.setVisible(b); } public JComponent getHeader() { return header; } public int calcSlot(int x) { int slot = ((x - left_gap) / (slotxsize + slot_space)); //System.out.println ( x + " slot " + slot); if (slot<0) slot = 0; if (slot >= slots.size()) slot = slots.size() -1; return slot; } public Collection<Block> getBlocks() { ArrayList<Block> list = new ArrayList<Block>(); for (int i=0;i<slots.size();i++) list.addAll(slots.get(i).getBlocks()); return list; } public void select(int start,int end) { if (start == selectionStart && end == selectionEnd) return; selectionStart = start; selectionEnd = end; invalidateSelection(); } public void unselectAll() { if (selectionStart == -1 || selectionEnd == -1) return; selectionStart = -1; selectionEnd = -1; invalidateSelection(); } public void setTimeIntervall() { Iterator<Slot> it= slots.iterator(); while (it.hasNext()) { Slot slot = it.next(); slot.setTimeIntervall(); } } private int addSlot() { Slot slot= new Slot(); slot.setTimeIntervall(); slots.add(slot); this.add(slot); this.add(Box.createHorizontalStrut(slot_space)); updateHeaderSize(); return slots.size()-1; } public void updateHeaderSize() { Dimension size = header.getPreferredSize(); Dimension newSize = new Dimension(slotxsize * slots.size() //Slotwidth and border + slot_space * slots.size() //Space between Slots + left_gap + right_gap // left and right gap , (int)size.getHeight()); header.setPreferredSize(newSize); header.setMaximumSize(newSize); header.invalidate(); } /** fuegt einen block im gewuenschten slot ein (konflikte werden ignoriert). */ public void putBlock(SwingBlock bl, int slotnr) { while (slotnr >= slots.size()) { addSlot(); } slots.get(slotnr).putBlock(bl); // The blockListener can be shared among all blocks, // as long es we can only click on one block simultanously bl.getView().addMouseListener(blockListener); bl.getView().addMouseMotionListener(blockListener); blockViewMapper.put(bl.getView(),bl); } public Dimension getMinimumSize() { return getPreferredSize(); } public Dimension getMaximumSize() { return getPreferredSize(); } Insets insets = new Insets(0,0,0, right_gap); Insets slotInsets = new Insets(0,0,0,0); public Insets getInsets() { return insets; } SwingBlock getBlockFor(Object component) { return blockViewMapper.get(component); } int getBlockCount() { int count = 0; Iterator<Slot> it = slots.iterator(); while (it.hasNext()) count += it.next().getBlockCount(); return count; } boolean isEmpty() { return getBlockCount() == 0; } protected void invalidateDragging(Point oldPoint) { int width = getSize().width; int startRow = Math.min(calcRow(draggingY),calcRow(oldPoint.y )); int endRow = Math.max(calcRow(draggingY),calcRow(oldPoint.y )) + 1; repaint(0 , rowScale.getYCoordForRow(startRow) -10 , width , rowScale.getSizeInPixelBetween(startRow, endRow) + draggingHeight + 20 ); } private void invalidateSelection() { int width = getSize().width; int startRow = Math.min(selectionStart,oldSelectionStart); int endRow = Math.max(selectionEnd,oldSelectionEnd) + 1; repaint(0,rowScale.getYCoordForRow(startRow ), width, rowScale.getSizeInPixelBetween(startRow, endRow )); // Update the values after calling repaint, because paint needs the old values. oldSelectionStart = selectionStart; oldSelectionEnd = selectionEnd; } public void paint(Graphics g) { Dimension dim = getSize(); Rectangle rect = g.getClipBounds(); if (!isEditable()) { g.setColor(Color.white); g.fillRect(rect.x ,rect.y ,rect.width ,rect.height); } else { int starty = rowScale.getStartWorktimePixel(); int endy = rowScale.getEndWorktimePixel(); int height = rowScale.getSizeInPixel(); Color firstColor = NON_WORKTIME_BACKGROUND; Color secondColor = WORKTIME_BACKGROUND; if ( starty >= endy) { int c = starty; starty = endy; endy = c; secondColor = NON_WORKTIME_BACKGROUND; firstColor = WORKTIME_BACKGROUND; } if (rect.y - rect.height <= starty) { g.setColor( firstColor ); g.fillRect(rect.x ,Math.max(rect.y,0) ,rect.width ,Math.min(rect.height,starty)); } if (rect.y + rect.height >= starty && rect.y <= endy ) { g.setColor( secondColor ); g.fillRect(rect.x ,Math.max(rect.y,starty) ,rect.width ,Math.min(rect.height,endy - starty)); } if (rect.y + rect.height >= endy) { g.setColor( firstColor ); g.fillRect(rect.x ,Math.max(rect.y,endy) ,rect.width ,Math.min(rect.height, height - endy)); } } if (isBorderVisible()) { g.setColor(LINE_COLOR); g.drawLine(0,rect.y,0,rect.y + rect.height); g.drawLine(dim.width - 1,rect.y,dim.width - 1 ,rect.y + rect.height); } int max = rowScale.getMaxRows() ; // Paint selection for (int i=0; i < max ; i++) { int rowSize = rowScale.getRowSizeForRow( i); int y = rowScale.getYCoordForRow( i); if ((y + rowSize) >= rect.y && y < (rect.y + rect.height)) { if (i>= selectionStart && i<=selectionEnd) { g.setColor(getSelectionColor()); g.fillRect(Math.max (rect.x,1) , y , Math.min (rect.width,dim.width - Math.max (rect.x,1) - 1) , rowSize); } boolean bPaintRowThick = (rowScale.isPaintRowThick(i)); g.setColor((bPaintRowThick) ? THICK_LINE_COLOR : LINE_COLOR); if (isEditable() || (bPaintRowThick && (i<max || isBorderVisible()))) g.drawLine(rect.x,y ,rect.x + rect.width , y); if ( i == max -1 ) { g.setColor( THICK_LINE_COLOR ); g.drawLine(rect.x,y+rowSize ,rect.x + rect.width , y+rowSize); } } } super.paintChildren(g); if ( paintDraggingGrid ) { int x = draggingSlot * (slotxsize + slot_space) + left_gap; paintDraggingGrid(g, x , draggingY, slotxsize -1, draggingHeight); } } /** grafische komponente, in die implementierungen von Block (genauer deren zugehoerige BlockViews) eingefuegt werden koennen. * entsprechend start- und end-zeit des blocks wird der view * im slot dargestellt. die views werden dabei vertikal angeordnet. */ class Slot extends JPanel { private static final long serialVersionUID = 1L; private Collection<Block> blocks= new ArrayList<Block>(); public Slot() { setLayout(null); setBackground(Color.white); setOpaque(false); } /** legt fest, fuer welches zeitintervall das slot gelten soll. (Beispiel 8:00 - 13:00) min und max sind uhrzeiten in vollen stunden. zur initialisierung der komponente muss diese methode mindestens einmal aufgerufen werden. */ public void setTimeIntervall() { int ysize= rowScale.getSizeInPixel() + 1; setSize(slotxsize, ysize); Dimension preferredSize = new Dimension(slotxsize, ysize ); setPreferredSize(preferredSize ); setMinimumSize(preferredSize ); } /** fuegt b in den Slot ein. */ public void putBlock(SwingBlock b) { blocks.add(b); add(b.getView()); updateBounds(b); } public void updateBounds(SwingBlock b) { //update bounds int y1= rowScale.getYCoord(b.getStart()); final int minimumSize = 15; int y2= Math.max( y1+minimumSize,rowScale.getYCoord(b.getEnd())); if ( y1 < 0) y1 = 0; if ( y2 > getMaximumSize().height) y2 = getMaximumSize().height; b.getView().setBounds(0, y1, slotxsize, y2 - y1 + 1); } public int getBlockCount() { return blocks.size(); } public Dimension getMinimumSize() { return getPreferredSize(); } public Dimension getMaximumSize() { return getPreferredSize(); } public Insets getInsets() { return slotInsets; } public Collection<Block> getBlocks() { return blocks; } } void updateSize(int slotsize) { this.slotxsize = slotsize; for ( Slot slot:slots) { slot.setTimeIntervall(); for (Block block:slot.getBlocks()) { slot.updateBounds((SwingBlock)block); } } updateHeaderSize(); } public int calcRow( int y ) { return rowScale.calcRow( y); } }
04900db4-rob
src/org/rapla/components/calendarview/swing/LargeDaySlot.java
Java
gpl3
13,917
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview.swing; import java.awt.Component; import java.awt.Point; import java.util.Date; import org.rapla.components.calendarview.Block; /** Listeners for user-changes in the weekview.*/ public interface ViewListener { /** Invoked when the user invokes the slot-contex (right-clicks on slot). The selected area and suggested coordinates at which the popup menu can be shown are passed.*/ void selectionPopup(Component slotComponent,Point p,Date start,Date end, int slotNr); /** Invoked when the selection has changed.*/ void selectionChanged(Date start,Date end); /** Invoked when the user invokes a block-context (right-clicks on a block). The suggested coordinates at which the popup menu can be shown are passed.*/ void blockPopup(Block block,Point p); /** Invoked when the user invokes a block-edit (double-clicks on a block). The suggested coordinates at which the popup menu can be shown are passed.*/ void blockEdit(Block block,Point p); /** Invoked when the user has dragged/moved a block */ void moved(Block block,Point p,Date newStart, int slotNr); /** Invoked when the user has resized a block */ void resized(Block block,Point p,Date newStart, Date newEnd, int slotNr); }
04900db4-rob
src/org/rapla/components/calendarview/swing/ViewListener.java
Java
gpl3
2,244
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview.swing; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Insets; import java.awt.Rectangle; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.rapla.components.calendarview.Block; public class SmallDaySlot extends AbstractDaySlot { private static final long serialVersionUID = 1L; public static int BLOCK_HEIGHT = 32 +20; public static int START_GAP = 10; public static Color THICK_LINE_COLOR = Color.black; public static Color LINE_COLOR = new Color(0xaa, 0xaa, 0xaa); public static Color WORKTIME_BACKGROUND = Color.white; private List<Block> blocks = new LinkedList<Block>(); private int slotxsize; private Color headerColor; private Color headerBackground; private int rowSize = 15; private boolean selected; int slot_space = 3; private BlockListener blockListener = new BlockListener(); private String headerText; public SmallDaySlot(String headerText,int slotxsize,Color headerColor, Color headerBackground ) { this.headerColor = headerColor; this.headerBackground = headerBackground; this.slotxsize= slotxsize; this.headerText = headerText; setLayout( null ); setAlignmentX(0); setAlignmentY(TOP_ALIGNMENT); Dimension newSize = new Dimension(slotxsize, 10); setPreferredSize(newSize); this.setBackground(Color.white); } public boolean isBorderVisible() { return true; } public Collection<Block> getBlocks() { return blocks; } public void select(int startRow, int endRow) { boolean selected = (startRow >=0 || endRow>=0); if (this.selected == selected) return; this.selected = selected; invalidateSelection(); } public void unselectAll() { if (!selected ) return; selected = false; invalidateSelection(); } private void invalidateSelection() { repaint(); // Update the values after calling repaint, because paint needs the old values. } /** fuegt einen block im gewuenschten slot ein (konflikte werden ignoriert). */ public void putBlock(SwingBlock bl) { add( bl.getView() ); blocks.add( bl ); // The blockListener can be shared among all blocks, // as long as we can only click on one block simultaneously bl.getView().addMouseListener( blockListener ); bl.getView().addMouseMotionListener( blockListener ); blockViewMapper.put( bl.getView(), bl ); updateSize(); } public void updateSize() { int blockHeight = 0; for ( Block b:blocks) { blockHeight += getHeight( b); } int height = Math.max( 25, blockHeight + START_GAP ); Dimension newSize = new Dimension( slotxsize, height ); setPreferredSize( newSize ); updateBounds(); } private void updateBounds() { int y= START_GAP; for (int i=0;i< blocks.size();i++) { SwingBlock bl = (SwingBlock) blocks.get(i); int blockHeight = getHeight(bl); bl.getView().setBounds( 1 ,y, slotxsize -1, blockHeight-1); y+= blockHeight; } } /** * @param bl */ private int getHeight(Block bl) { int blockHeight = BLOCK_HEIGHT; // Special Solution for doubling the block height // if (DateTools.countMinutes(bl.getStart(), bl.getEnd()) >= 60) // { // blockHeight*= 2; // } return blockHeight; } public Dimension getMinimumSize() { return getPreferredSize(); } public Dimension getMaximumSize() { return getPreferredSize(); } Insets insets = new Insets(0,0,0, 0); public Insets getInsets() { return insets; } int getBlockCount() { return blocks.size(); } public boolean isEmpty() { return getBlockCount() == 0; } public int calcRow(int y) { return 0; } public int calcSlot(int x) { return 0; } public int getX(Component component) { return component.getLocation().x; } int max; public void paint(Graphics g) { Dimension dim = getSize(); Rectangle rect = g.getClipBounds(); g.setColor(getForeground()); if (selected) { g.setColor(getSelectionColor()); } else { g.setColor(getBackground()); } g.fillRect(rect.x , rect.y , rect.x + rect.width , rect.y + rect.height); if (isBorderVisible()) { g.setColor(LINE_COLOR); g.drawLine(0, rect.y, 0, rect.y + rect.height); g.drawLine(dim.width - 1, rect.y, dim.width - 1, rect.y + rect.height); g.drawLine(rect.x, 0, rect.x + rect.width, 0); g.drawLine(rect.x, dim.height - 1, rect.x + rect.width, dim.height - 1); } if ( headerText != null) { FontMetrics fontMetrics = g.getFontMetrics(); int headerWidth = fontMetrics.stringWidth(headerText); int headerHeight = 10;//fontMetrics.stringWidth(headerText); int x = Math.max(10, dim.width - headerWidth - 3); int y = Math.max(START_GAP, headerHeight); if ( headerBackground != null) { g.setColor(headerBackground); g.fillRect(1, y-headerHeight+1, dim.width -2, headerHeight); } g.setColor(headerColor); g.drawString(headerText, x, y); g.setColor(getForeground()); } super.paintChildren(g); if (paintDraggingGrid) { int height = draggingView.getView().getHeight() - 1; int x = 0; int y = draggingView.getView().getBounds().y; if (y + height + 2 > getHeight()) { y = getHeight() - height - 2; } paintDraggingGrid(g, x, y, slotxsize - 1, height); } } public int getRowSize() { return rowSize; } public boolean isSelected() { return selected ; } public void updateSize(int newWidth) { this.slotxsize = newWidth; updateSize(); } }
04900db4-rob
src/org/rapla/components/calendarview/swing/SmallDaySlot.java
Java
gpl3
7,301
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas, Bettina Lademann | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; /** maps weekday names to Calendar.DAY_OF_WEEK. Example: <pre> WeekdayMapper mapper = new WeekdayMapper(); // print name of Sunday System.out.println(mapper.getName(Calendar.SUNDAY)); // Create a weekday ComboBox JComboBox comboBox = new JComboBox(); comboBox.setModel(new DefaultComboBoxModel(mapper.getNames())); // select sunday comboBox.setSelectedIndex(mapper.getIndexForDay(Calendar.SUNDAY)); // weekday == Calendar.SUNDAY int weekday = mapper.getDayForIndex(comboBox.getSelectedIndex()); </pre> */ public class WeekdayMapper { String[] weekdayNames; int[] weekday2index; int[] index2weekday; Map<Integer,String> map = new LinkedHashMap<Integer,String>(); public WeekdayMapper() { this(Locale.getDefault()); } public WeekdayMapper(Locale locale) { int days = 7; weekdayNames = new String[days]; weekday2index = new int[days+1]; index2weekday = new int[days+1]; SimpleDateFormat format = new SimpleDateFormat("EEEEEE",locale); Calendar calendar = Calendar.getInstance(locale); calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek()); for (int i=0;i<days;i++) { int weekday = calendar.get(Calendar.DAY_OF_WEEK); weekday2index[weekday] = i; index2weekday[i] = weekday; String weekdayName = format.format(calendar.getTime()); weekdayNames[i] = weekdayName; calendar.add(Calendar.DATE,1); map.put(weekday, weekdayName); } } public String[] getNames() { return weekdayNames; } public String getName(int weekday) { return map.get( weekday); } public int dayForIndex(int index) { return index2weekday[index]; } public int indexForDay(int weekday) { return weekday2index[weekday]; } }
04900db4-rob
src/org/rapla/components/calendarview/WeekdayMapper.java
Java
gpl3
3,054
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.rapla.components.util.DateTools; import org.rapla.entities.domain.Allocatable; import org.rapla.plugin.abstractcalendar.AbstractRaplaBlock; /** Tries to put reservations that allocate the same Ressources in the same column.*/ public class GroupStartTimesStrategy extends AbstractGroupStrategy { List<Allocatable> allocatables; List<Integer> startTimes = new ArrayList<Integer>(); { for ( int i=0;i<=23;i++) { startTimes.add(i*60); } } @Override protected Map<Block, Integer> getBlockMap(CalendarView wv, List<Block> blocks) { if (allocatables != null) { Map<Block,Integer> map = new LinkedHashMap<Block, Integer>(); for (Block block:blocks) { AbstractRaplaBlock b = (AbstractRaplaBlock)block; for (Allocatable a:b.getReservation().getAllocatablesFor(b.getAppointment())) { int index = allocatables.indexOf( a ); if ( index >= 0 ) { map.put( block, index ); } } } return map; } else { return super.getBlockMap(wv, blocks); } } @Override protected List<List<Block>> getSortedSlots(List<Block> list) { TreeMap<Integer,List<Block>> groups = new TreeMap<Integer,List<Block>>(); for (Iterator<Block> it = list.iterator();it.hasNext();) { Block block = it.next(); long startTime = block.getStart().getTime(); int minuteOfDay = DateTools.getMinuteOfDay(startTime); int rowNumber = -1 ; for ( Integer start: startTimes) { if ( start <= minuteOfDay) { rowNumber++; } else { break; } } if ( rowNumber <0) { rowNumber = 0; } List<Block> col = groups.get( rowNumber ); if (col == null) { col = new ArrayList<Block>(); groups.put( rowNumber, col ); } col.add(block); } List<List<Block>> slots = new ArrayList<List<Block>>(); for (int row =0 ;row<startTimes.size();row++) { List<Block> oneRow = groups.get( row ); if ( oneRow == null) { oneRow = new ArrayList<Block>(); } else { Collections.sort( oneRow, blockComparator); } slots.add(oneRow); } return slots; } @Override protected Collection<List<Block>> group(List<Block> blockList) { List<List<Block>> singleGroup = new ArrayList<List<Block>>(); singleGroup.add(blockList); return singleGroup; } public List<Allocatable> getAllocatables() { return allocatables; } public void setAllocatables(List<Allocatable> allocatables) { this.allocatables = allocatables; } public List<Integer> getStartTimes() { return startTimes; } public void setStartTimes(List<Integer> startTimes) { this.startTimes = startTimes; } }
04900db4-rob
src/org/rapla/components/calendarview/GroupStartTimesStrategy.java
Java
gpl3
4,298
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview; import java.util.Comparator; /** Compares to blocks by the starting time. block1<block2 if * it block1.getStart()< block2.getStart(). */ public class BlockComparator implements Comparator<Block> { public static BlockComparator COMPARATOR = new BlockComparator(); public int compare(Block b1,Block b2) { int result = b1.getStart().compareTo(b2.getStart()); if (result != 0) return result; else return b1.getName().compareTo(b2.getName()); } }
04900db4-rob
src/org/rapla/components/calendarview/BlockComparator.java
Java
gpl3
1,496
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview; import java.util.List; public interface BuildStrategy { public void build(CalendarView wv,List<Block> blocks); }
04900db4-rob
src/org/rapla/components/calendarview/BuildStrategy.java
Java
gpl3
1,102
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas, Bettina Lademann | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Locale; /** maps weekday names to Calendar.DAY_OF_WEEK. Example: <pre> WeekdayMapper mapper = new WeekdayMapper(); // print name of Sunday System.out.println(mapper.getName(Calendar.SUNDAY)); // Create a weekday ComboBox JComboBox comboBox = new JComboBox(); comboBox.setModel(new DefaultComboBoxModel(mapper.getNames())); // select sunday comboBox.setSelectedIndex(mapper.getIndexForDay(Calendar.SUNDAY)); // weekday == Calendar.SUNDAY int weekday = mapper.getDayForIndex(comboBox.getSelectedIndex()); </pre> */ public class MonthMapper { String[] monthNames; public MonthMapper() { this(Locale.getDefault()); } public MonthMapper(Locale locale) { monthNames = new String[12]; SimpleDateFormat format = new SimpleDateFormat("MMMMMM",locale); Calendar calendar = Calendar.getInstance(locale); for (int i=0;i<12;i++) { calendar.set(Calendar.MONTH,i); monthNames[i] = format.format(calendar.getTime()); } } public String[] getNames() { return monthNames; } /** month are 0 based */ public String getName(int month) { return getNames()[month]; } }
04900db4-rob
src/org/rapla/components/calendarview/MonthMapper.java
Java
gpl3
2,331
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** This strategy groups all blocks in a single group */ public class BestFitStrategy extends AbstractGroupStrategy { protected Collection<List<Block>> group(List<Block> blockList) { List<List<Block>> singleGroup = new ArrayList<List<Block>>(); singleGroup.add(blockList); return singleGroup; } }
04900db4-rob
src/org/rapla/components/calendarview/BestFitStrategy.java
Java
gpl3
1,393
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.rapla.components.util.DateTools; /** Arranges blocks into groups, and tries to place one group into one slot. The subclass must overide the group method to perform the grouping on a given list of blocks. */ public abstract class AbstractGroupStrategy implements BuildStrategy { boolean m_sortSlotsBySize; public static long MILLISECONDS_PER_DAY = 24 * 3600 * 1000; private boolean m_fixedSlots; private boolean m_conflictResolving; protected Comparator<Block> blockComparator = new BlockComparator(); protected Comparator<List<Block>> slotComparator = new Comparator<List<Block>>() { public int compare(List<Block> s1,List<Block> s2) { if (s1.size() == 0 || s2.size() ==0) { if (s1.size() == s2.size()) return 0; else return s1.size() < s2.size() ? -1 : 1; } Block b1 = s1.get(0); Block b2 = s2.get(0); return b1.getStart().compareTo(b2.getStart()); } }; public void build(CalendarView wv, List<Block> blocks) { LinkedHashMap<Integer,List<Block>> days = new LinkedHashMap<Integer,List<Block>>(); Map<Block, Integer> blockMap = getBlockMap(wv, blocks); for (Block b:blockMap.keySet()) { Integer index = blockMap.get(b); List<Block> list = days.get(index); if (list == null) { list = new ArrayList<Block>(); days.put(index, list); } list.add(b); } for (Integer day: days.keySet()) { List<Block> list = days.get(day); Collections.sort(list, blockComparator); if (list == null) continue; insertDay( wv, day,list ); } } protected Map<Block,Integer> getBlockMap(CalendarView wv, List<Block> blocks) { Map<Block,Integer> map = new LinkedHashMap<Block, Integer>(); Date startDate = wv.getStartDate(); for (Block block:blocks) { int days = (int)DateTools.countDays(startDate, block.getStart()); map.put(block, days); } return map; } protected void insertDay(CalendarView wv, int column,List<Block> blockList) { Iterator<List<Block>> it = getSortedSlots(blockList).iterator(); int slotCount= 0; while (it.hasNext()) { List<Block> slot = it.next(); if (slot == null) { continue; } for (int i=0;i<slot.size();i++) { wv.addBlock(slot.get(i),column,slotCount); } slotCount ++; } } /** You can split the blockList into different groups. * This method returns a collection of lists. * Each list represents a group * of blocks. * @return a collection of List-objects * @see List * @see Collection */ abstract protected Collection<List<Block>> group(List<Block> blockList); public boolean isSortSlotsBySize() { return m_sortSlotsBySize; } public void setSortSlotsBySize(boolean enable) { m_sortSlotsBySize = enable; } /** takes a block list and returns a sorted slotList */ protected List<List<Block>> getSortedSlots(List<Block> blockList) { Collection<List<Block>> group = group(blockList); List<List<Block>> slots = new ArrayList<List<Block>>(group); if ( isResolveConflictsEnabled()) { resolveConflicts(slots); } if ( !isFixedSlotsEnabled() ) { mergeSlots(slots); } if (isSortSlotsBySize()) Collections.sort(slots, slotComparator); return slots; } protected boolean isCollision(Block b1, Block b2) { final long start1 = b1.getStart().getTime(); long minimumLength = DateTools.MILLISECONDS_PER_MINUTE * 5; final long end1 = Math.max(start1+ minimumLength,b1.getEnd().getTime()); final long start2 = b2.getStart().getTime(); final long end2 = Math.max(start2 + minimumLength,b2.getEnd().getTime()); boolean result = start1 < end2 && start2 <end1 ; return result; } private void resolveConflicts(List<List<Block>> groups) { int pos = 0; while (pos < groups.size()) { List<Block> group = groups.get(pos++ ); List<Block> newSlot = null; int i = 0; while (i< group.size()) { Block element1 = group.get( i++ ); int j = i; while (j< group.size()) { Block element2 = group.get( j ++); if ( isCollision( element1, element2 ) ) { group.remove( element2 ); j --; if (newSlot == null) { newSlot = new ArrayList<Block>(); groups.add(pos, newSlot); } newSlot.add( element2); } } } } } /** the lists must be sorted */ private boolean canMerge(List<Block> slot1,List<Block> slot2) { int size1 = slot1.size(); int size2 = slot2.size(); int i = 0; int j = 0; while (i<size1 && j < size2) { Block b1 = slot1.get(i); Block b2 = slot2.get(j); if (isCollision( b1, b2)) return false; if ( b1.getStart().before( b2.getStart() )) i ++; else j ++; } return true; } /** merge two slots */ private void mergeSlots(List<List<Block>> slots) { // We use a (sub-optimal) greedy algorithm for merging slots int pos = 0; while (pos < slots.size()) { List<Block> slot1 = slots.get(pos ++); for (int i= pos; i<slots.size(); i++) { List<Block> slot2 = slots.get(i); if (canMerge(slot1, slot2)) { slot1.addAll(slot2); Collections.sort(slot1, blockComparator); slots.remove(slot2); pos --; break; } } } } public void setFixedSlotsEnabled( boolean enable) { m_fixedSlots = enable; } public boolean isFixedSlotsEnabled() { return m_fixedSlots; } /** enables or disables conflict resolving. If turned on and 2 blocks ocupy the same slot, * a new slot will be inserted dynamicly * @param enable */ public void setResolveConflictsEnabled( boolean enable) { m_conflictResolving = enable; } public boolean isResolveConflictsEnabled() { return m_conflictResolving; } public Comparator<Block> getBlockComparator() { return blockComparator; } public void setBlockComparator(Comparator<Block> blockComparator) { this.blockComparator = blockComparator; } }
04900db4-rob
src/org/rapla/components/calendarview/AbstractGroupStrategy.java
Java
gpl3
8,387
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview.html; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import org.rapla.components.calendarview.AbstractCalendar; import org.rapla.components.calendarview.Block; import org.rapla.components.calendarview.BlockComparator; import org.rapla.components.calendarview.CalendarView; public abstract class AbstractHTMLView extends AbstractCalendar implements CalendarView { public static String COLOR_NO_RESOURCE = "#BBEEBB"; String m_html; abstract public Collection<Block> getBlocks(); void checkBlock( Block bl ) { Date endDate = getEndDate(); if ( !bl.getStart().before(endDate)) { throw new IllegalStateException("Start-date " +bl.getStart() + " must be before calendar end at " +endDate); } } public String getHtml() { return m_html; } protected class HTMLSmallDaySlot extends ArrayList<Block> { private static final long serialVersionUID = 1L; private String date; private Date startTime; public HTMLSmallDaySlot(String date) { super(2); this.date = date; } public void putBlock(Block block) { add( block ); } public void sort() { Collections.sort( this, BlockComparator.COMPARATOR); } public void paint(StringBuffer out) { out.append("<div valign=\"top\" align=\"right\">"); out.append( date ); out.append("</div>\n"); for ( int i=0;i<size();i++) { Block block = get(i); out.append("<div valign=\"top\" class=\"month_block\""); if ( block instanceof HTMLBlock ) { out.append(" style=\"background-color:" + ((HTMLBlock)block).getBackgroundColor() + ";\""); } out.append(">"); out.append(block.toString()); out.append("</div>\n"); } } public void setStart(Date date) { startTime = date; } public Date getStart() { return startTime; } } }
04900db4-rob
src/org/rapla/components/calendarview/html/AbstractHTMLView.java
Java
gpl3
3,212
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview.html; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.rapla.components.calendarview.AbstractCalendar; import org.rapla.components.calendarview.Block; import org.rapla.components.calendarview.Builder; import org.rapla.components.util.DateTools; public class HTMLCompactWeekView extends AbstractHTMLView { public final static int ROWS = 6; //without the header row /** shared calendar instance. Only used for temporary stored values. */ HTMLSmallDaySlot[] slots = {}; String[] slotNames = {}; private ArrayList<List<Block>> rows = new ArrayList<List<Block>>(); Map<Block, Integer> columnMap = new HashMap<Block, Integer>(); private double leftColumnSize = 0.1; String weeknumber = ""; public String getWeeknumber() { return weeknumber; } public void setWeeknumber(String weeknumber) { this.weeknumber = weeknumber; } public void setLeftColumnSize(double leftColumnSize) { this.leftColumnSize = leftColumnSize; } public void setSlots( String[] slotNames ) { this.slotNames = slotNames; } public Collection<Block> getBlocks() { ArrayList<Block> list = new ArrayList<Block>(); for (int i=0;i<slots.length;i++) { list.addAll(slots[i]); } return Collections.unmodifiableCollection( list ); } /** must be called after the slots are filled*/ protected boolean isEmpty( int column) { HTMLSmallDaySlot slot = slots[column]; return slot.isEmpty(); } public void rebuild() { List<String> headerNames; int columns = getColumnCount(); headerNames = getHeaderNames(); columnMap.clear(); rows.clear(); for ( int i=0; i<slotNames.length; i++ ) { addRow(); } // calculate the blocks Iterator<Builder> it= builders.iterator(); while (it.hasNext()) { Builder b= it.next(); b.prepareBuild(getStartDate(),getEndDate()); } // build Blocks it= builders.iterator(); while (it.hasNext()) { Builder b= it.next(); if (b.isEnabled()) { b.build(this); } } Calendar calendar = createCalendar(); calendar.setTime(getStartDate()); calendar.set( Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek()); // resource header // add headers StringBuffer result = new StringBuffer(); result.append("<table class=\"month_table\">\n"); result.append("<tr>\n"); result.append("<td class=\"week_number\" width=\"" + Math.round(getLeftColumnSize() * 100) + "%\">"); result.append(weeknumber); result.append("</td>"); String percentage = "" + Math.round(columns); int rowsize = rows.size(); slots = new HTMLSmallDaySlot[rowsize * columns]; for (int row=0;row<rowsize;row++) { for (int column=0;column < columns; column++) { List<Block> blocks = rows.get( row ); int fieldNumber = row * columns + column; slots[fieldNumber] = createField( blocks, column ); } } for (int i=0;i<columns;i++) { if (isExcluded(i)) { continue; } result.append("<td class=\"month_header\" width=\""+percentage + "%\">"); result.append("<nobr>"); result.append(headerNames.get(i)); result.append("</nobr>"); result.append("</td>"); } result.append("\n</tr>"); for (int row=0;row<rowsize;row++) { result.append("<tr>\n"); result.append("<td class=\"month_cell\" valign=\"top\" height=\"40\">\n"); if ( slotNames.length > row ) { result.append( slotNames[ row ] ); } result.append("</td>\n"); for (int column=0;column < columns; column++) { int fieldNumber = row * columns + column; if ( !isExcluded( column ) ) { result.append("<td class=\"month_cell\" valign=\"top\" height=\"40\">\n"); slots[fieldNumber].paint( result ); result.append("</td>\n"); } } result.append("</tr>\n"); } result.append("</table>"); m_html = result.toString(); } protected List<String> getHeaderNames() { List<String> headerNames = new ArrayList<String>(); blockCalendar.setTime(getStartDate()); int columnCount = getColumnCount(); for (int i=0;i<columnCount;i++) { headerNames.add (AbstractCalendar.formatDayOfWeekDateMonth (blockCalendar.getTime() ,locale ,timeZone )); blockCalendar.add(Calendar.DATE, 1); } return headerNames; } public double getLeftColumnSize() { return leftColumnSize ; } protected int getColumnCount() { return getDaysInView(); } private HTMLSmallDaySlot createField(List<Block> blocks, int column) { HTMLSmallDaySlot c = new HTMLSmallDaySlot(""); c.setStart(DateTools.addDays( getStartDate(), column)); if ( blocks != null) { Iterator<Block> it = blocks.iterator(); while (it.hasNext()){ HTMLBlock block = (HTMLBlock)it.next(); if (columnMap.get( block) == column) { c.putBlock( block ); } } } c.sort(); return c; } public void addBlock(Block block, int column,int slot) { checkBlock( block ); while ( rows.size() <= slot ) { addRow(); } List<Block> blocks = rows.get( slot ); blocks.add( block ); columnMap.put(block, column); } private void addRow() { rows.add( rows.size(), new ArrayList<Block>()); } }
04900db4-rob
src/org/rapla/components/calendarview/html/HTMLCompactWeekView.java
Java
gpl3
7,119
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview.html; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.SortedSet; import java.util.TreeSet; import org.rapla.components.calendarview.AbstractCalendar; import org.rapla.components.calendarview.Block; import org.rapla.components.calendarview.Builder; public class HTMLWeekView extends AbstractHTMLView { private int endMinutes; private int minMinute; private int maxMinute; private int startMinutes; int m_rowsPerHour = 2; HTMLDaySlot[] multSlots ; ArrayList<Block> blocks = new ArrayList<Block>(); //ArrayList<Integer> blockStart = new ArrayList<Integer>(); //ArrayList<Integer> blockSize = new ArrayList<Integer>(); String weeknumber; /** The granularity of the selection rows. * <ul> * <li>1: 1 rows per hour = 1 Hour</li> * <li>2: 2 rows per hour = 1/2 Hour</li> * <li>3: 3 rows per hour = 20 Minutes</li> * <li>4: 4 rows per hour = 15 Minutes</li> * <li>6: 6 rows per hour = 10 Minutes</li> * <li>12: 12 rows per hour = 5 Minutes</li> * </ul> * Default is 2. */ public void setRowsPerHour(int rows) { m_rowsPerHour = rows; } public int getRowsPerHour() { return m_rowsPerHour; } public void setWorktime(int startHour, int endHour) { this.startMinutes = startHour * 60; this.endMinutes = endHour * 60; } public void setWorktimeMinutes(int startMinutes, int endMinutes) { this.startMinutes = startMinutes; this.endMinutes = endMinutes; } public void setToDate(Date weekDate) { calcMinMaxDates( weekDate ); } public Collection<Block> getBlocks() { return blocks; } /** must be called after the slots are filled*/ protected boolean isEmpty( int column) { return multSlots[column].isEmpty(); } protected int getColumnCount() { return getDaysInView(); } public void rebuild() { int columns = getColumnCount(); blocks.clear(); multSlots = new HTMLDaySlot[columns]; String[] headerNames = new String[columns]; for (int i=0;i<columns;i++) { String headerName = createColumnHeader(i); headerNames[i] = headerName; } // calculate the blocks int start = startMinutes; int end = endMinutes; minuteBlock.clear(); Iterator<Builder> it= builders.iterator(); while (it.hasNext()) { Builder b= it.next(); b.prepareBuild(getStartDate(),getEndDate()); start = Math.min(b.getMinMinutes(),start); end = Math.max(b.getMaxMinutes(),end); if (start<0) throw new IllegalStateException("builder.getMin() is smaller than 0"); if (end>24*60) throw new IllegalStateException("builder.getMax() is greater than 24"); } minMinute = start ; maxMinute = end ; for (int i=0;i<multSlots.length;i++) { multSlots[i] = new HTMLDaySlot(2); } it= builders.iterator(); while (it.hasNext()) { Builder b= it.next(); if (b.isEnabled()) { b.build(this); } } StringBuffer result = new StringBuffer(); result.append("<table class=\"week_table\">\n"); result.append("<tbody>"); result.append("<tr>\n"); result.append("<th class=\"week_number\">"+weeknumber+"</th>"); for (int i=0;i<multSlots.length;i++) { if ( isExcluded ( i ) ) continue; result.append("<td class=\"week_header\" colspan=\""+ (Math.max(1,multSlots[i].size()) * 2 + 1) + "\">"); result.append("<nobr>"); result.append(headerNames[i]); result.append("</nobr>"); result.append("</td>"); } result.append("\n</tr>"); result.append("<tr></tr>"); boolean useAM_PM = org.rapla.components.calendarview.AbstractCalendar.isAmPmFormat( locale ); int firstEventMarkerId = 7; boolean firstEventMarkerSet = false; for (int minuteOfDay = minMinute;minuteOfDay<maxMinute;minuteOfDay++) { boolean isLine = (minuteOfDay ) % (60 / m_rowsPerHour) == 0; if ( isLine || minuteOfDay == minMinute) { minuteBlock.add( minuteOfDay); } } for (Integer minuteOfDay:minuteBlock) { if ( minuteBlock.last().equals( minuteOfDay)) { break; } //System.out.println("Start row " + row / m_rowsPerHour + ":" + row % m_rowsPerHour +" " + timeString ); result.append("<tr>\n"); boolean fullHour = (minuteOfDay) % 60 == 0; boolean isLine = (minuteOfDay ) % (60 / m_rowsPerHour) == 0; if ( fullHour || minuteOfDay == minMinute) { int rowspan = calcRowspan(minuteOfDay, ((minuteOfDay / 60) + 1) * 60); String timeString = formatTime(minuteOfDay, useAM_PM); result.append("<th class=\"week_times\" rowspan=\""+ rowspan +"\"><nobr>"); result.append(timeString); result.append("</nobr>"); result.append(" &#160;</th>\n"); } for (int day=0;day<columns;day++) { if (isExcluded(day)) continue; if (multSlots[day].size() == 0) { // Rapla 1.4: Make line for full hours darker than others if (fullHour ) { result.append("<td class=\"week_smallseparatorcell_black\">&nbsp;</td>"); result.append("<td class=\"week_emptycell_black\">&nbsp;</td>\n"); } else if (isLine) { result.append("<td class=\"week_smallseparatorcell\">&nbsp;</td>"); result.append("<td class=\"week_emptycell\">&nbsp;</td>\n"); } else { result.append("<td class=\"week_smallseparatornolinecell\">&nbsp;</td>"); result.append("<td class=\"week_emptynolinecell\">&nbsp;</td>\n"); } } else if ( firstEventMarkerSet) { firstEventMarkerId = day; } for (int slotnr = 0; slotnr < multSlots[day].size(); slotnr++) { // Rapla 1.4: Make line for full hours darker than others if (fullHour) { result.append("<td class=\"week_smallseparatorcell_black\">&nbsp;</td>"); } else if (isLine) { result.append("<td class=\"week_smallseparatorcell\">&nbsp;</td>"); } else { result.append("<td class=\"week_smallseparatornolinecell\"></td>"); } Slot slot = multSlots[day].getSlotAt(slotnr); Block block = slot.getBlock(minuteOfDay); if ( block != null) { blockCalendar.setTime( block.getEnd()); int endMinute = Math.min(maxMinute,blockCalendar.get(Calendar.HOUR_OF_DAY) * 60 + blockCalendar.get(Calendar.MINUTE)); int rowspan = calcRowspan(minuteOfDay, endMinute); result.append("<td valign=\"top\" class=\"week_block\""); result.append(" rowspan=\"" + rowspan + "\"" ); if (block instanceof HTMLBlock) result.append(" style=\"background-color:" + ((HTMLBlock) block).getBackgroundColor() + "\""); result.append(">"); printBlock(result, firstEventMarkerId, block); result.append("</td>"); slot.setLastEnd( endMinute); } else { // skip ? if (slot.getLastEnd() > minuteOfDay) { // Do nothing } else { // Rapla 1.4: Make line for full hours darker than others if (fullHour )//|| (!slot.isEmpty(row-1) && (row-minRow) > 0)) { result.append("<td class=\"week_emptycell_black\">&nbsp;</td>\n"); } else if (isLine) { result.append("<td class=\"week_emptycell\">&nbsp;</td>\n"); } else { result.append("<td class=\"week_emptynolinecell\"></td>\n"); } } } } // Rapla 1.4: Make line for full hours darker than others if (fullHour) { result.append("<td class=\"week_separatorcell_black\">&nbsp;</td>"); } else if ( isLine) { result.append("<td class=\"week_separatorcell\">&nbsp;</td>"); } else { result.append("<td class=\"week_separatornolinecell\"></td>\n"); } } result.append("\n</tr>\n"); } result.append("</tbody>"); result.append("</table>\n"); m_html = result.toString(); } private int calcRowspan(int start, int end) { if ( start == end) { return 0; } SortedSet<Integer> tailSet = minuteBlock.tailSet( start); int col = 0; for (Integer minute:tailSet) { if ( minute< end) { col++; } else { break; } } return col; } public String getWeeknumber() { return weeknumber; } public void setWeeknumber(String weeknumber) { this.weeknumber = weeknumber; } protected void printBlock(StringBuffer result, @SuppressWarnings("unused") int firstEventMarkerId, Block block) { String string = block.toString(); result.append(string); } protected String createColumnHeader(int i) { blockCalendar.setTime(getStartDate()); blockCalendar.add(Calendar.DATE, i); String headerName = AbstractCalendar.formatDayOfWeekDateMonth (blockCalendar.getTime() ,locale ,timeZone ); return headerName; } SortedSet<Integer> minuteBlock = new TreeSet<Integer>(); public void addBlock(Block block,int column,int slot) { checkBlock ( block ); HTMLDaySlot multiSlot =multSlots[column]; blockCalendar.setTime( block.getStart()); int startMinute = Math.max(minMinute,( blockCalendar.get(Calendar.HOUR_OF_DAY)* 60 + blockCalendar.get(Calendar.MINUTE) )); blockCalendar.setTime(block.getEnd()); int endMinute = (Math.min(maxMinute, blockCalendar.get(Calendar.HOUR_OF_DAY)* 60 + blockCalendar.get(Calendar.MINUTE) )); blocks.add(block); // startBlock.add( startMinute); // endBlock.add( endMinute); minuteBlock.add( startMinute); minuteBlock.add( endMinute); multiSlot.putBlock( block, slot, startMinute); } private String formatTime(int minuteOfDay,boolean useAM_PM) { blockCalendar.set(Calendar.MINUTE, minuteOfDay%60); int hour = minuteOfDay/60; blockCalendar.set(Calendar.HOUR_OF_DAY, hour); SimpleDateFormat format = new SimpleDateFormat(useAM_PM ? "h:mm" : "H:mm", locale); format.setTimeZone(blockCalendar.getTimeZone()); if (useAM_PM && hour == 12 && minuteOfDay%60 == 0) { return format.format(blockCalendar.getTime()) + " PM"; } else { return format.format(blockCalendar.getTime()); } } protected class HTMLDaySlot extends ArrayList<Slot> { private static final long serialVersionUID = 1L; private boolean empty = true; public HTMLDaySlot(int size) { super(size); } public void putBlock(Block block,int slotnr, int startMinute) { while (slotnr >= size()) { addSlot(); } getSlotAt(slotnr).putBlock( block, startMinute); empty = false; } public int addSlot() { Slot slot = new Slot(); add(slot); return size(); } public Slot getSlotAt(int index) { return get(index); } public boolean isEmpty() { return empty; } } protected class Slot { // int[] EMPTY = new int[]{-2}; // int[] SKIP = new int[]{-1}; int lastEnd = 0; HashMap<Integer, Block> map = new HashMap<Integer, Block>(); public Slot() { } public void putBlock( Block block, int startMinute) { map.put( startMinute, block); } Block getBlock(Integer startMinute) { return map.get( startMinute); } public int getLastEnd() { return lastEnd; } public void setLastEnd(int lastEnd) { this.lastEnd = lastEnd; } } }
04900db4-rob
src/org/rapla/components/calendarview/html/HTMLWeekView.java
Java
gpl3
13,399
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview.html; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Iterator; import org.rapla.components.calendarview.Block; import org.rapla.components.calendarview.Builder; import org.rapla.components.util.DateTools; public class HTMLMonthView extends AbstractHTMLView { public final static int ROWS = 6; //without the header row public final static int COLUMNS = 7; HTMLSmallDaySlot[] slots; public Collection<Block> getBlocks() { ArrayList<Block> list = new ArrayList<Block>(); for (int i=0;i<slots.length;i++) { list.addAll(slots[i]); } return Collections.unmodifiableCollection( list ); } protected boolean isEmpty(int column) { for ( int i=column;i < slots.length;i+=7 ) { if (!slots[i].isEmpty() ) { return false; } } return true; } public void rebuild() { // we need to clone the calendar, because we modify the calendar object int the getExclude() method Calendar counter = (Calendar) blockCalendar.clone(); // calculate the blocks Iterator<Builder> it= builders.iterator(); final Date startDate = getStartDate(); while (it.hasNext()) { Builder b= it.next(); b.prepareBuild(startDate,getEndDate()); } slots = new HTMLSmallDaySlot[ daysInMonth ]; for (int i=0;i<slots.length;i++) { slots[i] = new HTMLSmallDaySlot(String.valueOf( i + 1)); } it= builders.iterator(); while (it.hasNext()) { Builder b= it.next(); if (b.isEnabled()) { b.build(this); } } int lastRow = 0; HTMLSmallDaySlot[][] table = new HTMLSmallDaySlot[ROWS][COLUMNS]; counter.setTime(startDate); int firstDayOfWeek = getFirstWeekday(); if ( counter.get(Calendar.DAY_OF_WEEK) != firstDayOfWeek) { counter.set(Calendar.DAY_OF_WEEK, firstDayOfWeek); if ( counter.getTime().after( startDate)) { counter.add(Calendar.DATE, -7); } } Date time = counter.getTime(); int offset = (int) DateTools.countDays(counter.getTime(),startDate); // add headers counter.setTime(startDate); for (int i=0; i<daysInMonth; i++) { int column = (offset + i) % 7; int row = (counter.get(Calendar.DATE) + 6 - column ) / 7; table[row][column] = slots[i]; lastRow = row; slots[i].sort(); counter.add(Calendar.DATE,1); } StringBuffer result = new StringBuffer(); // Rapla 1.4: Show month and year in monthview SimpleDateFormat monthYearFormat = new SimpleDateFormat("MMMMM yyyy", locale); result.append("<h2 class=\"title\">" + monthYearFormat.format(startDate) + "</h2>\n"); result.append("<table class=\"month_table\">\n"); result.append("<tr>\n"); counter.setTime( time ); for (int i=0;i<COLUMNS;i++) { if (isExcluded(i)) { counter.add(Calendar.DATE, 1); continue; } int weekday = counter.get(Calendar.DAY_OF_WEEK); if ( counter.getTime().equals( startDate)) { offset = i; } result.append("<td class=\"month_header\" width=\"14%\">"); result.append("<nobr>"); String name = getWeekdayName(weekday); result.append(name); result.append("</nobr>"); result.append("</td>"); counter.add(Calendar.DATE, 1); } result.append("\n</tr>"); for (int row=0; row<=lastRow; row++) { boolean excludeRow = true; // calculate if we can exclude the row for (int column = 0; column<COLUMNS; column ++) { if ( table[row][column] != null && !isExcluded( column )) { excludeRow = false; } } if ( excludeRow ) continue; result.append("<tr>\n"); for (int column = 0; column<COLUMNS; column ++) { if ( isExcluded( column )) { continue; } HTMLSmallDaySlot slot = table[row][column]; if ( slot == null ) { result.append("<td class=\"month_cell\" height=\"40\"></td>\n"); } else { result.append("<td class=\"month_cell\" valign=\"top\" height=\"40\">\n"); slot.paint( result ); result.append("</td>\n"); } } result.append("</tr>\n"); } result.append("</table>"); m_html = result.toString(); } public void addBlock(Block block,int col,int slot) { checkBlock( block ); blockCalendar.setTime(block.getStart()); int day = blockCalendar.get(Calendar.DATE); slots[day-1].putBlock( block ); } }
04900db4-rob
src/org/rapla/components/calendarview/html/HTMLMonthView.java
Java
gpl3
6,166
package org.rapla.components.calendarview.html; import org.rapla.components.calendarview.Block; public interface HTMLBlock extends Block { String getBackgroundColor(); String toString(); }
04900db4-rob
src/org/rapla/components/calendarview/html/HTMLBlock.java
Java
gpl3
198
package org.rapla.components.calendarview; import java.text.DateFormat; import java.text.FieldPosition; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Iterator; import java.util.Locale; import java.util.TimeZone; import org.rapla.components.util.DateTools; public abstract class AbstractCalendar { private int daysInView = 7; private int firstWeekday = Calendar.getInstance().getFirstDayOfWeek(); /** shared calendar instance. Only used for temporary stored values. */ protected Calendar blockCalendar; protected Collection<Integer> excludeDays = Collections.emptySet(); private Date startDate; private Date endDate; protected Locale locale; protected TimeZone timeZone; protected int daysInMonth; protected Collection<Builder> builders = new ArrayList<Builder>(); public int getDaysInView() { return daysInView; } public void setDaysInView(int daysInView) { this.daysInView = daysInView; } public int getFirstWeekday() { return firstWeekday; } public void setFirstWeekday(int firstDayOfWeek) { this.firstWeekday = firstDayOfWeek; } public String getWeekdayName(int weekday) { SimpleDateFormat format = new SimpleDateFormat("EEEEEE",locale); Calendar calendar = createCalendar(); calendar.set(Calendar.DAY_OF_WEEK, weekday); String weekdayName = format.format(calendar.getTime()); return weekdayName; } protected boolean isExcluded(int column) { if ( daysInView == 1) { return false; } blockCalendar.set(Calendar.DAY_OF_WEEK, getFirstWeekday()); blockCalendar.add(Calendar.DATE, column); int weekday = blockCalendar.get(Calendar.DAY_OF_WEEK); if ( !excludeDays.contains(new Integer( weekday )) ) { return false; } boolean empty = isEmpty(column); return empty; } abstract protected boolean isEmpty(int column); public void setTimeZone(TimeZone timeZone) { this.timeZone = timeZone; blockCalendar = createCalendar(); } protected Calendar createCalendar() { return Calendar.getInstance(getTimeZone(),locale); } public TimeZone getTimeZone() { return timeZone; } public void setLocale(Locale locale) { this.locale = locale; // Constructor called? if (timeZone != null) { setTimeZone( timeZone ); blockCalendar = createCalendar(); } } public void setToDate(Date date) { calcMinMaxDates( date ); } public Date getStartDate() { return startDate; } public Date getEndDate() { return endDate; } protected void setStartDate(Date date) { this.startDate = date; } protected void setEndDate(Date date) { this.endDate = date; } public void setExcludeDays(Collection<Integer> excludeDays) { this.excludeDays = excludeDays; if (getStartDate() != null) calcMinMaxDates( getStartDate() ); } public void rebuild(Builder builder) { try { addBuilder( builder); rebuild(); } finally { removeBuilder( builder ); } } public void calcMinMaxDates(Date date) { Calendar blockCalendar = createCalendar(); blockCalendar.setTime( date ); blockCalendar.set(Calendar.HOUR_OF_DAY,0); blockCalendar.set(Calendar.MINUTE,0); blockCalendar.set(Calendar.SECOND,0); blockCalendar.set(Calendar.MILLISECOND,0); this.daysInMonth = blockCalendar.getActualMaximum( Calendar.DAY_OF_MONTH ) ; if ( daysInView > 14) { blockCalendar.set(Calendar.DAY_OF_MONTH, 1); this.startDate = blockCalendar.getTime(); blockCalendar.set(Calendar.MILLISECOND,1); blockCalendar.set(Calendar.MILLISECOND,0); blockCalendar.add(Calendar.DATE, this.daysInMonth); this.endDate = blockCalendar.getTime(); firstWeekday = blockCalendar.getFirstDayOfWeek(); } else { if ( daysInView >= 3) { int firstWeekday2 = getFirstWeekday(); blockCalendar.set(Calendar.DAY_OF_WEEK, firstWeekday2); if ( blockCalendar.getTime().after( date)) { blockCalendar.add(Calendar.DATE, -7); } } else { firstWeekday = blockCalendar.get( Calendar.DAY_OF_WEEK); } startDate = blockCalendar.getTime(); endDate =DateTools.addDays(startDate, daysInView); } } public abstract void rebuild(); public Iterator<Builder> getBuilders() { return builders.iterator(); } public void addBuilder(Builder b) { builders.add(b); } public void removeBuilder(Builder b) { builders.remove(b); } /** formats the date and month in the selected locale and timeZone*/ public static String formatDateMonth(Date date, Locale locale, TimeZone timeZone) { FieldPosition fieldPosition = new FieldPosition( DateFormat.YEAR_FIELD ); StringBuffer buf = new StringBuffer(); DateFormat format = DateFormat.getDateInstance( DateFormat.SHORT, locale); format.setTimeZone( timeZone ); buf = format.format(date, buf, fieldPosition ); if ( fieldPosition.getEndIndex()<buf.length() ) { buf.delete( fieldPosition.getBeginIndex(), fieldPosition.getEndIndex()+1 ); } else if ( (fieldPosition.getBeginIndex()>=0) ) { buf.delete( fieldPosition.getBeginIndex(), fieldPosition.getEndIndex() ); } char lastChar = buf.charAt(buf.length()-1); if (lastChar == '/' || lastChar == '-' ) { String result = buf.substring(0,buf.length()-1); return result; } else { String result = buf.toString(); return result; } } /** formats the day of week, date and month in the selected locale and timeZone*/ public static String formatDayOfWeekDateMonth(Date date, Locale locale, TimeZone timeZone) { SimpleDateFormat format = new SimpleDateFormat("EEE", locale); format.setTimeZone(timeZone); String datePart = format.format(date); String dateOfMonthPart = AbstractCalendar.formatDateMonth( date,locale,timeZone ); return datePart + " " + dateOfMonthPart ; } public static boolean isAmPmFormat(Locale locale) { // Determines if am-pm-format should be used. DateFormat format= DateFormat.getTimeInstance(DateFormat.SHORT, locale); FieldPosition amPmPos = new FieldPosition(DateFormat.AM_PM_FIELD); format.format(new Date(), new StringBuffer(),amPmPos); return (amPmPos.getEndIndex()>0); } }
04900db4-rob
src/org/rapla/components/calendarview/AbstractCalendar.java
Java
gpl3
7,067
<body> Provides basic functionality for displaying and editing appointment blocks, in table-like components. </body>
04900db4-rob
src/org/rapla/components/calendarview/package.html
HTML
gpl3
120
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.util; import java.util.Comparator; /** * * Reverts the Original Comparator * -1 -> 1 * 1 -> -1 * 0 -> 0 */ public class InverseComparator<T> implements Comparator<T> { Comparator<T> original; public InverseComparator( Comparator<T> original) { this.original = original; } public int compare( T arg0, T arg1 ) { return -1 * original.compare( arg0, arg1); } }
04900db4-rob
src/org/rapla/components/util/InverseComparator.java
Java
gpl3
1,371
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.util; /** Creates a new thread that successively executes the queued command objects * @see Command */ public interface CommandScheduler { public Cancelable schedule(Command object, long delay); public Cancelable schedule(Command object, long delay, long period); }
04900db4-rob
src/org/rapla/components/util/CommandScheduler.java
Java
gpl3
1,234