code
stringlengths
3
1.18M
language
stringclasses
1 value
/*--------------------------------------------------------------------------* | 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.gui.internal.view; import java.util.ArrayList; import java.util.Collection; import org.rapla.entities.Category; import org.rapla.entities.User; import org.rapla.entities.domain.Allocatable; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; class UserInfoUI extends HTMLInfo<User> { ClassificationInfoUI<Allocatable> classificationInfo; public UserInfoUI(RaplaContext sm) { super(sm); classificationInfo = new ClassificationInfoUI<Allocatable>(sm); } @Override protected String createHTMLAndFillLinks(User user,LinkController controller) { StringBuffer buf = new StringBuffer(); if (user.isAdmin()) { highlight(getString("admin"),buf); } Collection<Row> att = new ArrayList<Row>(); att.add(new Row(getString("username"), strong( encode( user.getUsername() ) ) ) ); final Allocatable person = user.getPerson(); if ( person == null) { att.add(new Row(getString("name"), encode(user.getName()))); att.add(new Row(getString("email"), encode(user.getEmail()))); } else { Collection<Row> classificationAttributes = classificationInfo.getClassificationAttributes(person, false); att.addAll(classificationAttributes); } createTable(att,buf,false); Category userGroupsCategory; try { userGroupsCategory = getQuery().getUserGroupsCategory(); } catch (RaplaException e) { // Should not happen, but null doesnt harm anyway userGroupsCategory = null; } Category[] groups = user.getGroups(); if ( groups.length > 0 ) { buf.append(getString("groups") + ":"); buf.append("<ul>"); for ( int i = 0; i < groups.length; i++ ) { buf.append("<li>"); String groupName = groups[i].getPath( userGroupsCategory , getI18n().getLocale()); encode ( groupName , buf); buf.append("</li>\n"); } buf.append("</ul>"); } return buf.toString(); } @Override public String getTooltip(User user) { return createHTMLAndFillLinks(user, null ); } }
Java
/*--------------------------------------------------------------------------* | 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.gui.internal.view; import java.awt.Component; import java.awt.Font; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import javax.swing.BorderFactory; import javax.swing.Icon; import javax.swing.JTree; import javax.swing.UIManager; import javax.swing.border.Border; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.DefaultTreeSelectionModel; import javax.swing.tree.MutableTreeNode; import javax.swing.tree.TreeCellRenderer; import javax.swing.tree.TreeModel; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; import org.rapla.components.util.Assert; import org.rapla.components.util.InverseComparator; import org.rapla.entities.Category; import org.rapla.entities.MultiLanguageName; import org.rapla.entities.Named; import org.rapla.entities.NamedComparator; import org.rapla.entities.RaplaType; import org.rapla.entities.User; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Period; import org.rapla.entities.domain.Reservation; import org.rapla.entities.domain.ReservationStartComparator; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.Classifiable; import org.rapla.entities.dynamictype.Classification; import org.rapla.entities.dynamictype.ClassificationFilter; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.DynamicTypeAnnotations; import org.rapla.entities.dynamictype.internal.DynamicTypeImpl; import org.rapla.facade.Conflict; import org.rapla.facade.internal.CalendarModelImpl; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.RaplaGUIComponent; import org.rapla.gui.TreeFactory; import org.rapla.gui.toolkit.TreeToolTipRenderer; import org.rapla.storage.StorageOperator; public class TreeFactoryImpl extends RaplaGUIComponent implements TreeFactory { public TreeFactoryImpl(RaplaContext sm) { super(sm); } class DynamicTypeComperator implements Comparator<DynamicType> { public int compare(DynamicType o1,DynamicType o2) { int rang1 = getRang(o1); int rang2 = getRang(o2); if ( rang1 < rang2) { return -1; } if ( rang1 > rang2) { return 1; } return compareIds((DynamicTypeImpl)o1, (DynamicTypeImpl)o2); } private int compareIds(DynamicTypeImpl o1, DynamicTypeImpl o2) { return o1.compareTo( o2); } private int getRang(DynamicType o1) { String t2 = o1.getAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE); if ( t2 != null && t2.equals( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE)) { return 1; } if ( t2 != null && t2.equals( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON)) { return 2; } else { return 3; } } } public TreeModel createClassifiableModel(Reservation[] classifiables) { @SuppressWarnings({ "unchecked", "rawtypes" }) Comparator<Classifiable> comp = new InverseComparator(new ReservationStartComparator(getLocale())); return createClassifiableModel( classifiables, comp,false); } public TreeModel createClassifiableModel(Allocatable[] classifiables, boolean useCategorizations) { @SuppressWarnings({ "rawtypes", "unchecked" }) Comparator<Classifiable> comp = new NamedComparator(getLocale()); return createClassifiableModel( classifiables, comp, useCategorizations); } public TreeModel createClassifiableModel(Allocatable[] classifiables) { boolean useCategorizations = true; return createClassifiableModel( classifiables, useCategorizations); } private TreeModel createClassifiableModel(Classifiable[] classifiables, Comparator<Classifiable> comp,boolean useCategorizations) { Set<DynamicType> typeSet = new LinkedHashSet<DynamicType>(); for (Classifiable classifiable: classifiables) { DynamicType type = classifiable.getClassification().getType(); typeSet.add( type); } List<DynamicType> typeList = new ArrayList<DynamicType>(typeSet); Collections.sort(typeList, new DynamicTypeComperator()); Map<DynamicType,DefaultMutableTreeNode> nodeMap = new HashMap<DynamicType,DefaultMutableTreeNode>(); for (DynamicType type: typeList) { DefaultMutableTreeNode node = new NamedNode(type); nodeMap.put(type, node); } DefaultMutableTreeNode root = new DefaultMutableTreeNode("ROOT"); Set<Classifiable> sortedClassifiable = new TreeSet<Classifiable>(comp); sortedClassifiable.addAll(Arrays.asList(classifiables)); addClassifiables(nodeMap, sortedClassifiable, useCategorizations); int count = 0; for (DynamicType type: typeList) { DefaultMutableTreeNode typeNode = nodeMap.get(type); root.insert(typeNode, count++); } return new DefaultTreeModel(root); } private Map<Classifiable, Collection<NamedNode>> addClassifiables(Map<DynamicType, DefaultMutableTreeNode > nodeMap,Collection<? extends Classifiable> classifiables,boolean useCategorizations) { Map<DynamicType,Map<Object,DefaultMutableTreeNode>> categorization = new LinkedHashMap<DynamicType, Map<Object,DefaultMutableTreeNode>>(); Map<Classifiable, Collection<NamedNode>> childMap = new HashMap<Classifiable, Collection<NamedNode>>(); Map<DynamicType,Collection<NamedNode>> uncategorized = new LinkedHashMap<DynamicType, Collection<NamedNode>>(); for ( DynamicType type: nodeMap.keySet()) { categorization.put( type, new LinkedHashMap<Object, DefaultMutableTreeNode>()); uncategorized.put( type, new ArrayList<NamedNode>()); } for (Iterator<? extends Classifiable> it = classifiables.iterator(); it.hasNext();) { Classifiable classifiable = it.next(); Classification classification = classifiable.getClassification(); Collection<NamedNode> childNodes = new ArrayList<NamedNode>(); childMap.put( classifiable, childNodes); DynamicType type = classification.getType(); Assert.notNull(type); DefaultMutableTreeNode typeNode = nodeMap.get(type); DefaultMutableTreeNode parentNode = typeNode; Attribute categorizationAtt = classification.getAttribute("categorization"); if (useCategorizations && categorizationAtt != null && classification.getValues(categorizationAtt).size() > 0) { Collection<Object> values = classification.getValues(categorizationAtt); for ( Object value:values) { NamedNode childNode = new NamedNode((Named) classifiable); childNodes.add( childNode); Map<Object, DefaultMutableTreeNode> map = categorization.get(type); parentNode = map.get( value); if ( parentNode == null) { String name = getName( value); parentNode = new DefaultMutableTreeNode(new Categorization(name)); map.put( value, parentNode); } parentNode.add(childNode); } } else { NamedNode childNode = new NamedNode((Named) classifiable); childNodes.add( childNode); Assert.notNull(typeNode); uncategorized.get(type).add( childNode); } } for ( DynamicType type:categorization.keySet()) { DefaultMutableTreeNode parentNode = nodeMap.get( type); //Attribute categorizationAtt = type.getAttribute("categorization"); Map<Object, DefaultMutableTreeNode> map = categorization.get( type); Collection<Object> sortedCats = getSortedCategorizations(map.keySet()); for ( Object cat: sortedCats) { DefaultMutableTreeNode childNode = map.get(cat); parentNode.add(childNode); } } for ( DynamicType type: uncategorized.keySet()) { DefaultMutableTreeNode parentNode = nodeMap.get( type); for (NamedNode node:uncategorized.get( type)) { parentNode.add(node); } } return childMap; } @SuppressWarnings({ "rawtypes", "unchecked" }) private Collection<Object> getSortedCategorizations(Collection<Object> unsortedCats) { ArrayList<Comparable> sortableCats = new ArrayList<Comparable>(); ArrayList<Object> unsortableCats = new ArrayList<Object>(); // All attribute values should implement Comparable but for the doubts we test if value is not comparable for ( Object cat: unsortedCats) { if ( cat instanceof Comparable) { sortableCats.add( (Comparable<?>) cat); } else { unsortableCats.add( cat); } } Collections.sort( sortableCats); List<Object> allCats = new ArrayList<Object>( sortableCats); allCats.addAll( unsortableCats); return allCats; } class Categorization implements Comparable<Categorization> { String cat; public Categorization(String cat) { this.cat = cat.intern(); } public String toString() { return cat; } public boolean equals( Object obj) { return cat.equals( obj.toString()); } public int hashCode() { return cat.hashCode(); } public int compareTo(Categorization o) { return cat.compareTo( o.cat); } } public TreeCellRenderer createConflictRenderer() { return new ConflictTreeCellRenderer(); } private boolean isInFilter(ClassificationFilter[] filter, Classifiable classifiable) { if (filter == null) return true; for (int i = 0; i < filter.length; i++) { if (filter[i].matches(classifiable.getClassification())) { return true; } } return false; } private boolean isInFilter(ClassificationFilter[] filter, DynamicType type) { if (filter == null) return true; for (int i = 0; i < filter.length; i++) { if (filter[i].getType().equals(type)) { return true; } } return false; } private boolean hasRulesFor(ClassificationFilter[] filter, DynamicType type) { if (filter == null) return false; for (int i = 0; i < filter.length; i++) { if (filter[i].getType().equals(type) && filter[i].ruleSize() > 0) { return true; } } return false; } /** * Returns the Resources root * * @param filter * @param selectedUser * @return * @throws RaplaException */ public TypeNode createResourcesModel(ClassificationFilter[] filter) throws RaplaException { TypeNode treeNode = new TypeNode(Allocatable.TYPE, CalendarModelImpl.ALLOCATABLES_ROOT, getString("resources")); Map<DynamicType,DefaultMutableTreeNode> nodeMap = new HashMap<DynamicType, DefaultMutableTreeNode>(); boolean resourcesFiltered = false; DynamicType[] types = getQuery().getDynamicTypes(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE); for (int i = 0; i < types.length; i++) { DynamicType type = types[i]; if (hasRulesFor(filter, type)) { resourcesFiltered = true; } if (!isInFilter(filter, type)) { resourcesFiltered = true; continue; } NamedNode node = new NamedNode(type); treeNode.add(node); nodeMap.put(type, node); } // creates typ folders types = getQuery().getDynamicTypes(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON); for (int i = 0; i < types.length; i++) { DynamicType type = types[i]; if (hasRulesFor(filter, type)) { resourcesFiltered = true; } if (!isInFilter(filter, type)) { resourcesFiltered = true; continue; } NamedNode node = new NamedNode(type); treeNode.add(node); nodeMap.put(type, node); } treeNode.setFiltered(resourcesFiltered); // adds elements to typ folders Allocatable[] allocatables = getQuery().getAllocatables(); Collection<Allocatable> sorted = sorted(Arrays.asList(allocatables)); Collection<Allocatable> filtered = new ArrayList<Allocatable>(); for (Allocatable classifiable: sorted) { if (!isInFilter(filter, classifiable)) { continue; } filtered.add( classifiable); } addClassifiables(nodeMap, filtered, true); for (Map.Entry<DynamicType, DefaultMutableTreeNode> entry: nodeMap.entrySet()) { MutableTreeNode value = entry.getValue(); if (value.getChildCount() == 0 && (!isAdmin() && !isRegisterer())) { treeNode.remove( value); } } return treeNode; } private <T extends Named> Collection<T> sorted(Collection<T> allocatables) { TreeSet<T> sortedList = new TreeSet<T>(new NamedComparator<T>(getLocale())); sortedList.addAll(allocatables); return sortedList; } public TypeNode createReservationsModel() throws RaplaException { TypeNode treeNode = new TypeNode(Reservation.TYPE, getString("reservation_type")); // creates typ folders DynamicType[] types = getQuery().getDynamicTypes(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION); for (int i = 0; i < types.length; i++) { DynamicType type = types[i]; NamedNode node = new NamedNode(type); treeNode.add(node); } treeNode.setFiltered(false); return treeNode; } @SuppressWarnings("deprecation") public DefaultTreeModel createModel(ClassificationFilter[] filter) throws RaplaException { DefaultMutableTreeNode root = new DefaultMutableTreeNode("ROOT"); // Resources and Persons // Add the resource types // Add the resources // Add the person types // Add the persons TypeNode resourceRoot = createResourcesModel(filter); root.add(resourceRoot); if (isAdmin()) { // If admin // Eventtypes // Add the event types // Users // Add the users // Categories (the root category) // Add the periods DefaultMutableTreeNode userRoot = new TypeNode(User.TYPE, getString("users")); User[] userList = getQuery().getUsers(); SortedSet<User> sorted = new TreeSet<User>( User.USER_COMPARATOR); sorted.addAll( Arrays.asList( userList)); for (final User user: sorted) { DefaultMutableTreeNode node = new DefaultMutableTreeNode(); node.setUserObject( user); userRoot.add(node); } root.add(userRoot); TypeNode reservationsRoot = createReservationsModel(); root.add(reservationsRoot); NamedNode categoryRoot = createRootNode( Collections.singleton(getQuery().getSuperCategory()),true); root.add(categoryRoot); // set category root name MultiLanguageName multiLanguageName = (MultiLanguageName)getQuery().getSuperCategory().getName(); // TODO try to replace hack multiLanguageName.setNameWithoutReadCheck(getI18n().getLang(), getString("categories")); // Add the periods DefaultMutableTreeNode periodRoot = new TypeNode(Period.TYPE, getString("periods")); DynamicType periodType = getQuery().getDynamicType(StorageOperator.PERIOD_TYPE); Allocatable[] periodList = getQuery().getAllocatables(periodType.newClassificationFilter().toArray()); for (final Allocatable period: sorted(Arrays.asList(periodList))) { NamedNode node = new NamedNode(period); periodRoot.add(node); } root.add(periodRoot); } return new DefaultTreeModel(root); } public DefaultTreeModel createConflictModel(Collection<Conflict> conflicts ) throws RaplaException { String conflict_number = conflicts != null ? new Integer(conflicts.size()).toString() : getString("nothing_selected") ; String conflictText = getI18n().format("conflictUC", conflict_number); DefaultMutableTreeNode treeNode = new TypeNode(Conflict.TYPE, conflictText); if ( conflicts != null ) { Map<DynamicType,DefaultMutableTreeNode> nodeMap = new LinkedHashMap<DynamicType, DefaultMutableTreeNode>(); DynamicType[] types = getQuery().getDynamicTypes(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE); for (int i = 0; i < types.length; i++) { DynamicType type = types[i]; NamedNode node = new NamedNode(type); treeNode.add(node); nodeMap.put(type, node); } // creates typ folders types = getQuery().getDynamicTypes(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON); for (int i = 0; i < types.length; i++) { DynamicType type = types[i]; NamedNode node = new NamedNode(type); treeNode.add(node); nodeMap.put(type, node); } Collection<Allocatable> allocatables = new LinkedHashSet<Allocatable>(); for (Iterator<Conflict> it = conflicts.iterator(); it.hasNext();) { Conflict conflict = it.next(); Allocatable allocatable = conflict.getAllocatable(); allocatables.add( allocatable ); } Collection<Allocatable> sorted = sorted(allocatables); Map<Classifiable, Collection<NamedNode>> childMap = addClassifiables(nodeMap, sorted, true); for (Iterator<Conflict> it = conflicts.iterator(); it.hasNext();) { Conflict conflict = it.next(); Allocatable allocatable = conflict.getAllocatable(); for(NamedNode allocatableNode : childMap.get( allocatable)) { allocatableNode.add(new NamedNode( conflict)); } } for (Map.Entry<DynamicType, DefaultMutableTreeNode> entry: nodeMap.entrySet()) { MutableTreeNode value = entry.getValue(); if (value.getChildCount() == 0 ) { treeNode.remove( value); } } } return new DefaultTreeModel(treeNode); } class TypeNode extends DefaultMutableTreeNode { private static final long serialVersionUID = 1L; boolean filtered; RaplaType type; String title; TypeNode(RaplaType type, Object userObject, String title) { this.type = type; this.title = title; setUserObject(userObject); } TypeNode(RaplaType type, Object userObject) { this(type, userObject, null); } public RaplaType getType() { return type; } public boolean isFiltered() { return filtered; } public void setFiltered(boolean filtered) { this.filtered = filtered; } public Object getTitle() { if (title != null) { return title; } else { return userObject.toString(); } } } public DefaultMutableTreeNode newNamedNode(Named element) { return new NamedNode(element); } public TreeModel createModel(Category category) { return createModel(Collections.singleton(category), true ); } public TreeModel createModel(Collection<Category> categories, boolean includeChildren) { DefaultMutableTreeNode rootNode = createRootNode(categories,includeChildren); return new DefaultTreeModel( rootNode); } protected NamedNode createRootNode( Collection<Category> categories, boolean includeChildren) { Map<Category,NamedNode> nodeMap = new HashMap<Category, NamedNode>(); Category superCategory = null; { Category persistantSuperCategory = getQuery().getSuperCategory(); for ( Category cat:categories) { if ( persistantSuperCategory.equals( cat)) { superCategory = cat; } } if (superCategory == null) { superCategory = persistantSuperCategory; } } nodeMap.put( superCategory, new NamedNode(superCategory)); LinkedHashSet<Category> uniqueCategegories = new LinkedHashSet<Category>( ); for ( Category cat:categories) { if ( includeChildren) { for( Category child:getAllChildren( cat)) { uniqueCategegories.add( child); } } uniqueCategegories.add( cat); } LinkedList<Category> list = new LinkedList<Category>(); list.addAll( uniqueCategegories); while ( !list.isEmpty()) { Category cat = list.pop(); NamedNode node = nodeMap.get( cat); if (node == null) { node = new NamedNode( cat); nodeMap.put( cat , node); } Category parent = cat.getParent(); if ( parent != null) { NamedNode parentNode = nodeMap.get( parent); if ( parentNode == null) { parentNode = new NamedNode( parent); nodeMap.put( parent , parentNode); list.push( parent); } parentNode.add( node); } } NamedNode rootNode = nodeMap.get( superCategory); while ( true) { int childCount = rootNode.getChildCount(); if ( childCount <= 0 || childCount >1) { break; } Category cat = (Category) rootNode.getUserObject(); if ( categories.contains( cat)) { break; } NamedNode firstChild = (NamedNode)rootNode.getFirstChild(); rootNode.remove( firstChild); rootNode = firstChild; } return rootNode; } private Collection<Category> getAllChildren(Category cat) { ArrayList<Category> result = new ArrayList<Category>(); for ( Category child: cat.getCategories()) { result.add( child); Collection<Category> childsOfChild = getAllChildren( child); result.addAll(childsOfChild); } return result; } public TreeModel createModelFlat(Named[] element) { DefaultMutableTreeNode root = new DefaultMutableTreeNode(""); for (int i = 0; i < element.length; i++) { root.add(new NamedNode(element[i])); } return new DefaultTreeModel(root); } public TreeToolTipRenderer createTreeToolTipRenderer() { return new RaplaTreeToolTipRenderer(); } public TreeCellRenderer createRenderer() { return new ComplexTreeCellRenderer(); } public class NamedNode extends DefaultMutableTreeNode { private static final long serialVersionUID = 1L; NamedNode(Named obj) { super(obj); } public String toString() { Named obj = (Named) getUserObject(); if (obj != null) { Locale locale = getI18n().getLocale(); if ( obj instanceof Classifiable) { Classification classification = ((Classifiable)obj).getClassification(); if ( classification.getType().getAnnotation(DynamicTypeAnnotations.KEY_NAME_FORMAT_PLANNING) != null) { return classification.getNamePlaning(locale); } } String name = obj.getName(locale); return name; } else { return super.toString(); } } public int getIndexOfUserObject(Object object) { if (children == null) { return -1; } for (int i=0;i<children.size();i++) { if (((DefaultMutableTreeNode)children.get(i)).getUserObject().equals(object)) return i; } return -1; } public TreeNode findNodeFor( Object obj ) { return findNodeFor( this, obj); } private TreeNode findNodeFor( DefaultMutableTreeNode node,Object obj ) { Object userObject = node.getUserObject(); if ( userObject != null && userObject.equals( obj ) ) return node; @SuppressWarnings("rawtypes") Enumeration e = node.children(); while (e.hasMoreElements()) { TreeNode result = findNodeFor((DefaultMutableTreeNode) e.nextElement(), obj ); if ( result != null ) { return result; } } return null; } } Icon bigFolderUsers = getIcon("icon.big_folder_users"); Icon bigFolderPeriods = getIcon("icon.big_folder_periods"); Icon bigFolderResourcesFiltered = getIcon("icon.big_folder_resources_filtered"); Icon bigFolderResourcesUnfiltered = getIcon("icon.big_folder_resources"); Icon bigFolderEvents = getIcon("icon.big_folder_events"); Icon bigFolderCategories = getIcon("icon.big_folder_categories"); Icon bigFolderConflicts = getIcon("icon.big_folder_conflicts"); Icon defaultIcon = getIcon("icon.tree.default"); Icon personIcon = getIcon("icon.tree.persons"); Icon folderClosedIcon =getIcon("icon.folder"); Icon folderOpenIcon = getIcon("icon.folder"); Icon forbiddenIcon = getIcon("icon.no_perm"); Font normalFont = UIManager.getFont("Tree.font"); Font bigFont = normalFont.deriveFont(Font.BOLD, (float) (normalFont.getSize() * 1.2)); class ComplexTreeCellRenderer extends DefaultTreeCellRenderer { private static final long serialVersionUID = 1L; Border nonIconBorder = BorderFactory.createEmptyBorder(1, 0, 1, 0); Border conflictBorder = BorderFactory.createEmptyBorder(2, 0, 2, 0); Date today; public ComplexTreeCellRenderer() { setLeafIcon(defaultIcon); today = getQuery().today(); } public void setLeaf(Object object) { Icon icon = null; if (object instanceof Allocatable) { Allocatable allocatable = (Allocatable) object; try { User user = getUser(); if ( !allocatable.canAllocate(user, today)) { icon = forbiddenIcon; } else { if (allocatable.isPerson()) { icon = personIcon; } else { icon = defaultIcon; } } } catch (RaplaException ex) { } } else if (object instanceof DynamicType) { DynamicType type = (DynamicType) object; String classificationType = type.getAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE); if (DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION.equals(classificationType)) { setBorder(conflictBorder); } else { icon = folderClosedIcon; } } if (icon == null) { setBorder(nonIconBorder); } setLeafIcon(icon); } public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { setBorder(null); setFont(normalFont); if (value != null && value instanceof TypeNode) { TypeNode typeNode = (TypeNode) value; Icon bigFolderIcon; if (typeNode.getType().equals(User.TYPE)) { bigFolderIcon = bigFolderUsers; } else if (typeNode.getType().equals(Period.TYPE)) { bigFolderIcon = bigFolderPeriods; } else if (typeNode.getType().equals(Reservation.TYPE)) { bigFolderIcon = bigFolderEvents; } else { if (typeNode.isFiltered()) { bigFolderIcon = bigFolderResourcesFiltered; } else { bigFolderIcon = bigFolderResourcesUnfiltered; } } setClosedIcon(bigFolderIcon); setOpenIcon(bigFolderIcon); setLeafIcon(bigFolderIcon); setFont(bigFont); value = typeNode.getTitle(); } else { Object nodeInfo = getUserObject(value); if (nodeInfo instanceof Category && ((Category)nodeInfo).getParent() == null) { setClosedIcon(bigFolderCategories); setOpenIcon(bigFolderCategories); setFont(bigFont); } else { setClosedIcon(folderClosedIcon); setOpenIcon(folderOpenIcon); if (leaf) { setLeaf(nodeInfo); } } } Component result = super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); return result; } } class ConflictTreeCellRenderer extends DefaultTreeCellRenderer { private static final long serialVersionUID = 1L; Border nonIconBorder = BorderFactory.createEmptyBorder(1, 0, 1, 0); Border conflictBorder = BorderFactory.createEmptyBorder(2, 0, 2, 0); public ConflictTreeCellRenderer() { setFont(normalFont); setLeafIcon(null); setBorder(conflictBorder); } protected String getText( Conflict conflict) { StringBuffer buf = new StringBuffer(); buf.append("<html>"); buf.append( getRaplaLocale().formatTimestamp(conflict.getStartDate())); // buf.append( getAppointmentFormater().getSummary(conflict.getAppointment1())); buf.append( "<br>" ); buf.append( conflict.getReservation1Name() ); buf.append( " " ); buf.append( getString("with")); buf.append( "\n" ); buf.append( "<br>" ); buf.append( conflict.getReservation2Name() ); // TOD add the rest of conflict // buf.append( ": " ); // buf.append( " " ); // buf.append( getRaplaLocale().formatTime(conflict.getAppointment1().getStart())); //// buf.append( " - "); //// buf.append( getRaplaLocale().formatTime(conflict.getAppointment1().getEnd())); // buf.append( "<br>" ); // buf.append( getString("reservation.owner") + " "); // buf.append( conflict.getUser2().getUsername()); buf.append("</html>"); String result = buf.toString(); return result; } public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { if (value != null && value instanceof TypeNode) { TypeNode typeNode = (TypeNode) value; setFont(bigFont); value = typeNode.getTitle(); setClosedIcon(bigFolderConflicts); setOpenIcon(bigFolderConflicts); } else { setClosedIcon(folderClosedIcon); setOpenIcon(folderOpenIcon); Object nodeInfo = getUserObject(value); setFont(normalFont); if (nodeInfo instanceof Conflict) { Conflict conflict = (Conflict) nodeInfo; String text = getText(conflict); value = text; } else if (nodeInfo instanceof Allocatable) { Allocatable allocatable = (Allocatable) nodeInfo; Icon icon; if (allocatable.isPerson()) { icon = personIcon; } else { icon = defaultIcon; } setClosedIcon(icon); setOpenIcon(icon); String text = allocatable.getName(getLocale()) ; if ( value instanceof TreeNode) { text+= " (" + getRecursiveChildCount(((TreeNode) value)) +")"; } value = text; } else { String text = TreeFactoryImpl.this.getName( nodeInfo); if ( value instanceof TreeNode) { //text+= " (" + getRecursiveChildCount(((TreeNode) value)) +")"; text+= " (" + getRecursiveList(((TreeNode) value)).size() +")"; } value = text; } } Component result = super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); return result; } private int getRecursiveChildCount(TreeNode treeNode) { int count = 0; int children= treeNode.getChildCount(); if ( children == 0) { return 1; } for ( int i=0;i<children;i++) { TreeNode child = treeNode.getChildAt(i); count+= getRecursiveChildCount( child); } return count; } private Set<Conflict> getRecursiveList(TreeNode treeNode) { int children= treeNode.getChildCount(); if ( children == 0) { return Collections.emptySet(); } HashSet<Conflict> set = new HashSet<Conflict>(); for ( int i=0;i<children;i++) { TreeNode child = treeNode.getChildAt(i); Object userObject = ((DefaultMutableTreeNode)child).getUserObject(); if ( userObject != null && userObject instanceof Conflict) { set.add((Conflict)userObject); } else { set.addAll(getRecursiveList( child)); } } return set; } } public TreeSelectionModel createComplexTreeSelectionModel() { return new DelegatingTreeSelectionModel() { private static final long serialVersionUID = 1L; boolean isSelectable(TreePath treePath) { Object lastPathComponent = treePath.getLastPathComponent(); Object object = getUserObject( lastPathComponent); if ( object instanceof Categorization) { return false; } return true; } }; } public TreeSelectionModel createConflictTreeSelectionModel() { return new DelegatingTreeSelectionModel() { private static final long serialVersionUID = 1L; boolean isSelectable(TreePath treePath) { Object lastPathComponent = treePath.getLastPathComponent(); Object object = getUserObject( lastPathComponent); if ( object instanceof Conflict) { return true; } if ( object instanceof Allocatable) { return true; } if ( object instanceof DynamicType) { return true; } return false; } }; } private abstract class DelegatingTreeSelectionModel extends DefaultTreeSelectionModel { abstract boolean isSelectable(TreePath treePath); private static final long serialVersionUID = 1L; private TreePath[] getSelectablePaths(TreePath[] pathList) { List<TreePath> result = new ArrayList<TreePath>(pathList.length); for (TreePath treePath : pathList) { if (isSelectable(treePath)) { result.add(treePath); } } return result.toArray(new TreePath[result.size()]); } @Override public void setSelectionPath(TreePath path) { if (isSelectable(path)) { super.setSelectionPath(path); } } @Override public void setSelectionPaths(TreePath[] paths) { paths = getSelectablePaths(paths); super.setSelectionPaths(paths); } @Override public void addSelectionPath(TreePath path) { if (isSelectable(path)) { super.addSelectionPath(path); } } @Override public void addSelectionPaths(TreePath[] paths) { paths = getSelectablePaths(paths); super.addSelectionPaths(paths); } } private static Object getUserObject(Object node) { if (node instanceof DefaultMutableTreeNode) return ((DefaultMutableTreeNode) node).getUserObject(); return node; } class RaplaTreeToolTipRenderer implements TreeToolTipRenderer { public String getToolTipText(JTree tree, int row) { Object node = tree.getPathForRow(row).getLastPathComponent(); Object value = getUserObject(node); if (value instanceof Conflict) { return null; } return getInfoFactory().getToolTip(value); } } }
Java
/*--------------------------------------------------------------------------* | 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.gui.internal.view; import java.net.MalformedURLException; import java.net.URL; import java.util.Collection; import java.util.Date; import java.util.Iterator; import org.rapla.components.util.xml.XMLWriter; import org.rapla.entities.Named; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; import org.rapla.entities.Timestamp; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.framework.RaplaLocale; public abstract class HTMLInfo<T> extends RaplaComponent { public HTMLInfo(RaplaContext sm) { super(sm); } /** performs xml-encoding of a string the output goes to the buffer*/ static public void encode(String text,StringBuffer buf) { buf.append( encode ( text )); } static public String encode(String string) { String text = XMLWriter.encode( string ); if ( text.indexOf('\n') > 0 ) { StringBuffer buf = new StringBuffer(); int size = text.length(); for ( int i= 0; i<size; i++) { char c = text.charAt(i); if ( c == '\n' ) { buf.append("<br>"); } else { buf.append( c ); } // end of switch () } // end of for () text = buf.toString(); } return text; } protected void insertModificationRow( Timestamp timestamp, StringBuffer buf ) { final Date createTime = timestamp.getCreateTime(); final Date lastChangeTime = timestamp.getLastChanged(); if ( lastChangeTime != null) { buf.append("<div style=\"font-size:7px;margin-bottom:4px;\">"); RaplaLocale raplaLocale = getRaplaLocale(); if ( createTime != null) { buf.append(getString("created_at")); buf.append(" "); buf.append(raplaLocale.formatTimestamp(createTime)); buf.append(", "); } buf.append(getString("last_changed")); buf.append(" "); buf.append(raplaLocale.formatTimestamp(lastChangeTime)); buf.append("</div>"); buf.append("\n"); } } static public void addColor(String color,StringBuffer buf) { buf.append(" color=\""); buf.append(color); buf.append('\"'); } static public void createTable(Collection<Row> attributes,StringBuffer buf,boolean encodeValues) { buf.append("<table class=\"infotable\" cellpadding=\"1\">"); Iterator<Row> it = attributes.iterator(); while (it.hasNext()) { Row att = it.next(); buf.append("<tr>\n"); buf.append("<td class=\"label\" valign=\"top\" style=\"white-space:nowrap\">"); encode(att.field,buf); if ( att.field.length() > 0) { buf.append(":"); } buf.append("</td>\n"); buf.append("<td class=\"value\" valign=\"top\">"); String value = att.value; if (value != null) { try{ int httpEnd = Math.max( value.indexOf(" ")-1, value.length()); URL url = new URL( value.substring(0,httpEnd)); buf.append("<a href=\""); buf.append(url.toExternalForm()); buf.append("\">"); if (encodeValues) encode(value,buf); else buf.append(value); buf.append("</a>"); } catch (MalformedURLException ex) { if (encodeValues) encode(value,buf); else buf.append(value); } } buf.append("</td>"); buf.append("</tr>\n"); } buf.append("</table>"); } static public String createTable(Collection<Row> attributes, boolean encodeValues) { StringBuffer buf = new StringBuffer(); createTable(attributes, buf, encodeValues); return buf.toString(); } static public void createTable(Collection<Row> attributes,StringBuffer buf) { createTable(attributes,buf,true); } static public String createTable(Collection<Row> attributes) { StringBuffer buf = new StringBuffer(); createTable(attributes,buf); return buf.toString(); } static public void highlight(String text,StringBuffer buf) { buf.append("<FONT color=\"red\">"); encode(text,buf); buf.append("</FONT>"); } static public String highlight(String text) { StringBuffer buf = new StringBuffer(); highlight(text,buf); return buf.toString(); } static public void strong(String text,StringBuffer buf) { buf.append("<strong>"); encode(text,buf); buf.append("</strong>"); } static public String strong(String text) { StringBuffer buf = new StringBuffer(); strong(text,buf); return buf.toString(); } abstract protected String createHTMLAndFillLinks(T object,LinkController controller) throws RaplaException ; protected String getTitle(T object) { StringBuffer buf = new StringBuffer(); buf.append(getString("view")); if ( object instanceof RaplaObject) { RaplaType raplaType = ((RaplaObject) object).getRaplaType(); String localName = raplaType.getLocalName(); try { String name = getString(localName); buf.append( " "); buf.append( name); } catch (Exception ex) { // in case rapla type translation not found do nothing } } if ( object instanceof Named) { buf.append(" "); buf.append( ((Named) object).getName( getLocale())); } return buf.toString(); } protected String getTooltip(T object) { if (object instanceof Named) return ((Named) object).getName(getI18n().getLocale()); return null; } static public class Row { String field; String value; Row(String field,String value) { this.field = field; this.value = value; } public String getField() { return field; } public String getValue() { return value; } } }
Java
/*--------------------------------------------------------------------------* | 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.gui.internal.view; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.Reservation; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; public class AppointmentInfoUI extends HTMLInfo<Appointment> { ReservationInfoUI parent; public AppointmentInfoUI(RaplaContext sm) { super(sm); parent = new ReservationInfoUI( sm); } public String getTooltip(Appointment appointment) { Reservation reservation = appointment.getReservation(); StringBuffer buf = new StringBuffer(); parent.insertModificationRow( reservation, buf ); insertAppointmentSummary( appointment, buf ); parent.insertClassificationTitle( reservation, buf ); createTable( parent.getAttributes( reservation, null, null, true),buf,false); return buf.toString(); } void insertAppointmentSummary(Appointment appointment, StringBuffer buf) { buf.append("<div>"); buf.append( getAppointmentFormater().getSummary( appointment ) ); buf.append("</div>"); } protected String createHTMLAndFillLinks(Appointment appointment, LinkController controller) throws RaplaException { Reservation reservation = appointment.getReservation(); return parent.createHTMLAndFillLinks(reservation, controller); } }
Java
/*--------------------------------------------------------------------------* | 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.gui.internal.view; interface LinkController { void createLink(Object object,String link,StringBuffer buf); String createLink(Object object,String link); }
Java
/*--------------------------------------------------------------------------* | 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.gui.internal.view; import java.awt.Dimension; import java.awt.Point; import java.net.URL; import java.util.HashMap; import java.util.Map; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.JScrollPane; import javax.swing.JViewport; import javax.swing.SwingUtilities; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import org.rapla.components.util.Assert; import org.rapla.entities.RaplaObject; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.RaplaGUIComponent; import org.rapla.gui.toolkit.HTMLView; import org.rapla.gui.toolkit.RaplaWidget; /**Information of the entity-classes displayed in an HTML-Component */ public class ViewTable<T> extends RaplaGUIComponent implements HyperlinkListener ,RaplaWidget ,LinkController { String title; HTMLView htmlView = new HTMLView(); JScrollPane pane = new JScrollPane(htmlView, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER) { private static final long serialVersionUID = 1L; public Dimension getPreferredSize() { Dimension pref = super.getPreferredSize(); Dimension max = getMaximumSize(); //System.out.println( "PREF: " + pref + " MAX: " + max); if ( pref.height > max.height ) return max; else return pref; } }; Map<Integer,Object> linkMap; int linkId = 0; boolean packText = true; public ViewTable(RaplaContext sm) { super( sm); linkMap = new HashMap<Integer,Object>(7); htmlView.addHyperlinkListener(this); htmlView.setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); pane.setMaximumSize( new Dimension( 600, 500 )); } /** HTML-text-component should be sized according to the displayed text. Default is true. */ public void setPackText(boolean packText) { this.packText = packText; } public JComponent getComponent() { return pane; } public String getDialogTitle() { return title; } public void updateInfo(T object) throws RaplaException { if ( object instanceof RaplaObject) { final InfoFactoryImpl infoFactory = (InfoFactoryImpl)getInfoFactory(); @SuppressWarnings("unchecked") HTMLInfo<RaplaObject<T>> createView = infoFactory.createView((RaplaObject<T>)object); @SuppressWarnings("unchecked") final HTMLInfo<T> view = (HTMLInfo<T>) createView; updateInfo(object,view); } else { updateInfoHtml( object.toString()); } } public void updateInfo(T object, HTMLInfo<T> info) throws RaplaException { linkMap.clear(); final String html = info.createHTMLAndFillLinks( object, this); setTitle (info.getTitle( object)); updateInfoHtml(html); } public void updateInfoHtml( String html) { if (html !=null ) { setText( html); } else { setText(getString("nothing_selected")); htmlView.revalidate(); htmlView.repaint(); } final JViewport viewport = pane.getViewport(); SwingUtilities.invokeLater( new Runnable() { @Override public void run() { viewport.setViewPosition(new Point(0,0)); } }); } public void setTitle(String text) { this.title = text; } public void setText(String text) { String message = HTMLView.createHTMLPage(text); htmlView.setText(message, packText); } public void createLink(Object object,String link,StringBuffer buf) { linkMap.put(new Integer(linkId),object); buf.append("<A href=\""); buf.append(linkId++); buf.append("\">"); HTMLInfo.encode(link,buf); buf.append("</A>"); } public String createLink(Object object,String link) { StringBuffer buf = new StringBuffer(); createLink(object,link,buf); return buf.toString(); } public void hyperlinkUpdate(HyperlinkEvent e) { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { if ( true) { } String link = e.getDescription(); try { Integer index= Integer.parseInt(link); getLogger().debug("Hyperlink pressed: " + link); Object object = linkMap.get(index); Assert.notNull(object,"link was not found in linkMap"); Assert.notNull(getInfoFactory()); try { getInfoFactory().showInfoDialog(object,htmlView); } catch (RaplaException ex) { showException(ex,getComponent()); } // end of try-catch } catch ( NumberFormatException ex) { try { getIOService().openUrl(new URL(link)); } catch (Exception e1) { showException(ex,getComponent()); } } } } }
Java
/*--------------------------------------------------------------------------* | 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.gui.internal.view; import org.rapla.framework.RaplaContext; class DeleteInfoUI extends HTMLInfo<Object[]> { public DeleteInfoUI(RaplaContext sm) { super(sm); } protected String createHTMLAndFillLinks(Object[] deletables,LinkController controller) { StringBuffer buf = new StringBuffer(); buf.append(getString("delete.question")); buf.append("<br>"); for (int i = 0; i<deletables.length; i++) { buf.append((i + 1)); buf.append(") "); final Object deletable = deletables[i]; controller.createLink( deletable, getName( deletable ), buf); buf.append("<br>"); } return buf.toString(); } @Override protected String getTitle(Object[] deletables){ return getString("delete.title"); } }
Java
/*--------------------------------------------------------------------------* | 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.gui.internal.view; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.Point; import java.io.IOException; import java.net.URL; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextPane; import javax.swing.JViewport; import javax.swing.SwingUtilities; import org.rapla.components.util.IOUtil; import org.rapla.framework.RaplaContext; import org.rapla.framework.internal.ConfigTools; import org.rapla.gui.RaplaGUIComponent; import org.rapla.gui.toolkit.RaplaWidget; public class LicenseUI extends RaplaGUIComponent implements RaplaWidget { JPanel panel = new JPanel(); BorderLayout borderLayout1 = new BorderLayout(); GridLayout gridLayout2 = new GridLayout(); FlowLayout flowLayout1 = new FlowLayout(); JTextPane license = new JTextPane(); JScrollPane jScrollPane = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); public LicenseUI(RaplaContext sm) { super( sm); panel.setOpaque(true); panel.setLayout(borderLayout1); panel.add(jScrollPane,BorderLayout.CENTER); license.setOpaque(false); license.setEditable(false); panel.setPreferredSize(new Dimension(640,400)); try { String text = getLicense(); license.setText(text); } catch (IOException ex) { license.setText(ex.getMessage()); } license.revalidate(); } public JComponent getComponent() { return panel; } private String getLicense() throws IOException { URL url= ConfigTools.class.getClassLoader().getResource("META-INF/license.txt"); return new String(IOUtil.readBytes(url),"UTF-8"); } public void showTop() { final JViewport viewport = new JViewport(); viewport.setView(license); jScrollPane.setViewport(viewport); SwingUtilities.invokeLater( new Runnable() { @Override public void run() { viewport.setViewPosition(new Point(0,0)); } }); } public void showBottom() { JViewport viewport = new JViewport(); viewport.setView(license); jScrollPane.setViewport(viewport); Dimension dim = viewport.getViewSize(); viewport.setViewPosition(new Point(dim.width,dim.height)); } }
Java
/*--------------------------------------------------------------------------* | 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.gui.internal.view; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Locale; import org.rapla.components.util.TimeInterval; import org.rapla.entities.User; import org.rapla.entities.domain.Allocatable; import org.rapla.framework.RaplaContext; public class AllocatableInfoUI extends ClassificationInfoUI<Allocatable> { public AllocatableInfoUI(RaplaContext sm) { super(sm); } void insertPermissions( Allocatable allocatable, StringBuffer buf ) { User user; Date today; try { user = getUser(); today = getQuery().today(); } catch (Exception ex) { return; } TimeInterval accessInterval = allocatable.getAllocateInterval( user , today); if ( accessInterval != null) { buf.append( "<strong>" ); buf.append( getString( "allocatable_in_timeframe" ) ); buf.append( ":</strong>" ); buf.append("<br>"); Date start = accessInterval.getStart(); Date end = accessInterval.getEnd(); if ( start == null && end == null ) { buf.append( getString("everytime") ); } else { if ( start != null ) { buf.append( getRaplaLocale().formatDate( start ) ); } else { buf.append(getString("open")); } buf.append(" - "); if ( end != null ) { buf.append( getRaplaLocale().formatDate( end ) ); } else { buf.append(getString("open")); } buf.append("<br>"); } } } @Override protected String createHTMLAndFillLinks(Allocatable allocatable,LinkController controller) { StringBuffer buf = new StringBuffer(); insertModificationRow( allocatable, buf ); insertClassificationTitle( allocatable, buf ); createTable( getAttributes( allocatable, controller, false),buf,false); return buf.toString(); } public List<Row> getAttributes(Allocatable allocatable,LinkController controller, boolean excludeAdditionalInfos) { ArrayList<Row> att = new ArrayList<Row>(); att.addAll( super.getClassificationAttributes( allocatable, excludeAdditionalInfos )); final Locale locale = getLocale(); User owner = allocatable.getOwner(); User lastChangeBy = allocatable.getLastChangedBy(); if ( owner != null) { final String ownerName = owner.getName(locale); String ownerText = encode(ownerName); if (controller != null) ownerText = controller.createLink(owner,ownerName); att.add( new Row(getString("resource.owner"), ownerText)); } if ( lastChangeBy != null && (owner == null || !lastChangeBy.equals(owner))) { final String lastChangedName = lastChangeBy.getName(locale); String lastChangeByText = encode(lastChangedName); if (controller != null) lastChangeByText = controller.createLink(lastChangeBy,lastChangedName); att.add( new Row(getString("last_changed_by"), lastChangeByText)); } return att; } @Override public String getTooltip(Allocatable allocatable) { StringBuffer buf = new StringBuffer(); insertClassificationTitle( allocatable, buf ); insertModificationRow( allocatable, buf ); Collection<Row> att = new ArrayList<Row>(); att.addAll(getAttributes(allocatable, null, true)); createTable(att,buf); insertPermissions( allocatable, buf ); return buf.toString(); } }
Java
/*--------------------------------------------------------------------------* | 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.gui.internal.view; import org.rapla.entities.Category; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; class CategoryInfoUI extends HTMLInfo<Category> { public CategoryInfoUI(RaplaContext sm){ super(sm); } protected String createHTMLAndFillLinks(Category category,LinkController controller) throws RaplaException{ return category.getName( getRaplaLocale().getLocale()); } }
Java
/*--------------------------------------------------------------------------* | 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.gui.internal.view; import java.awt.Component; import java.awt.Dimension; import javax.swing.JComponent; import javax.swing.JScrollPane; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import org.rapla.components.xmlbundle.LocaleChangeEvent; import org.rapla.components.xmlbundle.LocaleChangeListener; import org.rapla.components.xmlbundle.LocaleSelector; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.RaplaGUIComponent; import org.rapla.gui.toolkit.DialogUI; import org.rapla.gui.toolkit.HTMLView; import org.rapla.gui.toolkit.RaplaWidget; final public class LicenseInfoUI extends RaplaGUIComponent implements HyperlinkListener ,RaplaWidget ,LocaleChangeListener { JScrollPane scrollPane; HTMLView license; LocaleSelector localeSelector; public LicenseInfoUI(RaplaContext context) throws RaplaException { super( context); license = new HTMLView(); license.addHyperlinkListener(this); scrollPane= new JScrollPane(license); scrollPane.setOpaque(true); scrollPane.setPreferredSize(new Dimension(450, 100)); scrollPane.setBorder(null); localeSelector = context.lookup( LocaleSelector.class); localeSelector.addLocaleChangeListener(this); setLocale(); } public void localeChanged(LocaleChangeEvent evt) { setLocale(); scrollPane.invalidate(); scrollPane.repaint(); } private void setLocale() { license.setBody(getString("license.text")); } public void hyperlinkUpdate(HyperlinkEvent e) { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { String link = e.getDescription(); viewLicense(getComponent(), false, link); } } public JComponent getComponent() { return scrollPane; } public void viewLicense(Component owner,boolean modal,String link) { try { LicenseUI license = new LicenseUI( getContext()); DialogUI dialog = DialogUI.create(getContext(),owner,modal,license.getComponent(), new String[] {getString("ok")} ); dialog.setTitle(getString("licensedialog.title")); dialog.setSize(600,400); if (link.equals("warranty")) { dialog.start(); license.getComponent().revalidate(); license.showBottom(); } else { dialog.start(); license.getComponent().revalidate(); license.showTop(); } } catch (Exception ex) { showException(ex,owner); } } }
Java
/*--------------------------------------------------------------------------* | 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.gui.internal.view; import java.util.ArrayList; import java.util.Collection; import org.rapla.components.util.DateTools; import org.rapla.entities.domain.Period; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaLocale; class PeriodInfoUI extends HTMLInfo<Period> { public PeriodInfoUI(RaplaContext sm) { super(sm); } protected String createHTMLAndFillLinks(Period period,LinkController controller) { Collection<Row> att = new ArrayList<Row>(); RaplaLocale loc = getRaplaLocale(); att.add(new Row(getString("name"), strong( encode( getName( period ) )))); att.add(new Row( getString("start_date") ,loc.getWeekday( period.getStart() ) + ' ' + loc.formatDate(period.getStart()) ) ); att.add(new Row( getString("end_date"), loc.getWeekday( DateTools.subDay(period.getEnd()) ) + ' ' + loc.formatDate( DateTools.subDay(period.getEnd()) ) ) ); return createTable(att, false); } protected String getTooltip(Period object) { return createHTMLAndFillLinks( object, null); } }
Java
/*--------------------------------------------------------------------------* | 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.gui.internal.view; import java.util.Iterator; import org.rapla.entities.DependencyException; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.storage.StorageOperator; class DependencyInfoUI extends HTMLInfo<DependencyException> { public DependencyInfoUI(RaplaContext sm){ super(sm); } @Override protected String createHTMLAndFillLinks(DependencyException ex,LinkController controller) throws RaplaException{ StringBuffer buf = new StringBuffer(); buf.append(getString("error.dependencies")+":"); buf.append("<br>"); Iterator<String> it = ex.getDependencies().iterator(); int i = 0; while (it.hasNext()) { Object obj = it.next(); buf.append((++i)); buf.append(") "); buf.append( obj ); buf.append("<br>"); if (i >= StorageOperator.MAX_DEPENDENCY && it.hasNext()) { //BJO buf.append("... more"); //BJO break; } } return buf.toString(); } @Override protected String getTitle(DependencyException ex) { return getString("info") + ": " + getString("error.dependencies"); } }
Java
/*--------------------------------------------------------------------------* | 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.gui.internal.view; import java.util.ArrayList; import java.util.List; import java.util.Locale; import org.rapla.entities.User; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.Period; import org.rapla.entities.domain.Repeating; import org.rapla.entities.domain.Reservation; import org.rapla.framework.RaplaContext; public class ReservationInfoUI extends ClassificationInfoUI<Reservation> { public ReservationInfoUI(RaplaContext sm) { super(sm); } private void addRestriction(Reservation reservation, Allocatable allocatable, StringBuffer buf) { Appointment[] appointments = reservation.getRestriction(allocatable); if ( appointments.length == 0 ) return; buf.append("<small>"); buf.append(" ("); for (int i=0; i<appointments.length ; i++) { if (i >0) buf.append(", "); encode(getAppointmentFormater().getShortSummary(appointments[i]), buf ); } buf.append(")"); buf.append("</small>"); } private String allocatableList(Reservation reservation,Allocatable[] allocatables, User user, LinkController controller) { StringBuffer buf = new StringBuffer(); for (int i = 0;i<allocatables.length;i++) { Allocatable allocatable = allocatables[i]; if ( user != null && !allocatable.canReadOnlyInformation(user)) continue; if (controller != null) controller.createLink(allocatable,getName(allocatable),buf); else encode(getName(allocatable), buf); addRestriction(reservation, allocatable, buf); if (i<allocatables.length-1) { buf.append (","); } } return buf.toString(); } @Override protected String getTooltip(Reservation reservation) { StringBuffer buf = new StringBuffer(); insertModificationRow( reservation, buf ); insertClassificationTitle( reservation, buf ); createTable( getAttributes( reservation, null, null, true),buf,false); return buf.toString(); } @Override protected String createHTMLAndFillLinks(Reservation reservation,LinkController controller) { StringBuffer buf = new StringBuffer(); insertModificationRow( reservation, buf ); insertClassificationTitle( reservation, buf ); createTable( getAttributes( reservation, controller, null, false),buf,false); this.insertAllAppointments( reservation, buf ); return buf.toString(); } public List<Row> getAttributes(Reservation reservation,LinkController controller, User user, boolean excludeAdditionalInfos) { ArrayList<Row> att = new ArrayList<Row>(); att.addAll( getClassificationAttributes( reservation, excludeAdditionalInfos )); User owner = reservation.getOwner(); final Locale locale = getLocale(); if ( owner != null) { final String ownerName = owner.getName(locale); String ownerText = encode(ownerName); if (controller != null) ownerText = controller.createLink(owner,ownerName); att.add( new Row(getString("reservation.owner"), ownerText)); } User lastChangeBy = reservation.getLastChangedBy(); if ( lastChangeBy != null && (owner == null ||! lastChangeBy.equals(owner))) { final String lastChangedName = lastChangeBy.getName(locale); String lastChangeByText = encode(lastChangedName); if (controller != null) lastChangeByText = controller.createLink(lastChangeBy,lastChangedName); att.add( new Row(getString("last_changed_by"), lastChangeByText)); } Allocatable[] resources = reservation.getResources(); String resourceList = allocatableList(reservation, resources, user, controller); if (resourceList.length() > 0) { att.add (new Row( getString("resources"), resourceList )); } Allocatable[] persons = reservation.getPersons(); String personList = allocatableList(reservation, persons, user, controller); if (personList.length() > 0) { att.add (new Row( getString("persons"), personList ) ); } return att; } void insertAllAppointments(Reservation reservation, StringBuffer buf) { buf.append( "<table cellpadding=\"2\">"); buf.append( "<tr>\n" ); buf.append( "<td colspan=\"2\" class=\"label\">"); String appointmentLabel = getString("appointments"); encode(appointmentLabel, buf); buf.append( ":"); buf.append( "</td>\n" ); buf.append( "</tr>\n"); Appointment[] appointments = reservation.getAppointments(); for (int i = 0;i<appointments.length;i++) { buf.append( "<tr>\n" ); buf.append( "<td valign=\"top\">\n"); if (appointments[i].getRepeating() != null) { buf.append ("<img width=\"16\" height=\"16\" src=\"org/rapla/gui/images/repeating.png\">"); } else { buf.append ("<img width=\"16\" height=\"16\" src=\"org/rapla/gui/images/single.png\">"); } buf.append( "</td>\n"); buf.append( "<td>\n"); String appointmentSummary = getAppointmentFormater().getSummary( appointments[i] ); encode( appointmentSummary, buf ); Repeating repeating = appointments[i].getRepeating(); if ( repeating != null ) { buf.append("<br>"); buf.append("<small>"); List<Period> periods = getPeriodModel().getPeriodsFor(appointments[i].getStart()); String repeatingSummary = getAppointmentFormater().getSummary(repeating,periods); encode( repeatingSummary, buf ) ; if ( repeating.hasExceptions() ) { buf.append("<br>"); buf.append( getAppointmentFormater().getExceptionSummary(repeating) ); } buf.append("</small>"); } buf.append( "</td>\n"); buf.append( "<td></td>"); buf.append( "</tr>\n"); } buf.append( "</table>\n"); } }
Java
/*--------------------------------------------------------------------------* | 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.gui.internal.view; import java.awt.Component; import java.awt.Point; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.StringSelection; import java.awt.event.ActionEvent; import java.util.HashMap; import java.util.Map; import javax.swing.AbstractAction; import javax.swing.JComponent; import org.rapla.components.iolayer.ComponentPrinter; import org.rapla.components.iolayer.IOInterface; import org.rapla.entities.Category; import org.rapla.entities.Named; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; import org.rapla.entities.User; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.Period; import org.rapla.entities.domain.Reservation; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.InfoFactory; import org.rapla.gui.RaplaGUIComponent; import org.rapla.gui.toolkit.DialogUI; import org.rapla.gui.toolkit.HTMLView; /** The factory can creatres an information-panel or dialog for the entities of rapla. @see ViewTable*/ public class InfoFactoryImpl extends RaplaGUIComponent implements InfoFactory { Map<RaplaType,HTMLInfo> views = new HashMap<RaplaType,HTMLInfo>(); public InfoFactoryImpl(RaplaContext sm) { super( sm); views.put( DynamicType.TYPE, new DynamicTypeInfoUI(sm) ); views.put( Reservation.TYPE, new ReservationInfoUI(sm) ); views.put( Appointment.TYPE, new AppointmentInfoUI(sm) ); views.put( Allocatable.TYPE, new AllocatableInfoUI(sm) ); views.put( User.TYPE, new UserInfoUI(sm) ); views.put( Period.TYPE, new PeriodInfoUI(sm) ); views.put( Category.TYPE, new CategoryInfoUI(sm) ); } /** this method is used by the viewtable to dynamicaly create an * appropriate HTMLInfo for the passed object */ <T extends RaplaObject> HTMLInfo<T> createView( T object ) throws RaplaException { if ( object == null ) throw new RaplaException( "Could not create view for null object" ); @SuppressWarnings("unchecked") HTMLInfo<T> result = views.get( object.getRaplaType() ); if (result != null) return result; throw new RaplaException( "Could not create view for this object: " + object.getClass() ); } public <T> JComponent createInfoComponent( T object ) throws RaplaException { ViewTable<T> viewTable = new ViewTable<T>(getContext()); viewTable.updateInfo( object ); return viewTable.getComponent(); } public String getToolTip(Object obj) { return getToolTip(obj,true); } public String getToolTip(Object obj,boolean wrapHtml) { try { if ( !(obj instanceof RaplaObject)) { return null; } RaplaObject o = (RaplaObject )obj; if ( !views.containsKey( o.getRaplaType())) { return null; } String text = createView( o ).getTooltip( o); if (wrapHtml && text != null) return HTMLView.createHTMLPage( text ); else return text; } catch(RaplaException ex) { getLogger().error( ex.getMessage(), ex ); } if (obj instanceof Named) return ((Named) obj).getName(getI18n().getLocale()); return null; } /* (non-Javadoc) * @see org.rapla.gui.view.IInfoUIFactory#showInfoDialog(java.lang.Object, java.awt.Component) */ public void showInfoDialog( Object object, Component owner ) throws RaplaException { showInfoDialog( object, owner, null); } /* (non-Javadoc) * @see org.rapla.gui.view.IInfoUIFactory#showInfoDialog(java.lang.Object, java.awt.Component, java.awt.Point) */ public <T> void showInfoDialog( T object, Component owner, Point point ) throws RaplaException { final ViewTable<T> viewTable = new ViewTable<T>(getContext()); final DialogUI dlg = DialogUI.create(getContext(),owner ,false ,viewTable.getComponent() ,new String[] { getString( "copy_to_clipboard" ) ,getString( "print" ) ,getString( "back" ) }); if ( !(object instanceof RaplaObject)) { viewTable.updateInfoHtml( object.toString()); } else { @SuppressWarnings("unchecked") HTMLInfo<RaplaObject<T>> createView = createView((RaplaObject<T>)object); @SuppressWarnings("unchecked") final HTMLInfo<T> view = (HTMLInfo<T>) createView; viewTable.updateInfo( object, view ); } dlg.setTitle( viewTable.getDialogTitle() ); dlg.setDefault(2); dlg.start( point ); dlg.getButton(0).setAction( new AbstractAction() { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { try { DataFlavor.getTextPlainUnicodeFlavor(); viewTable.htmlView.selectAll(); String plainText = viewTable.htmlView.getSelectedText(); //String htmlText = viewTable.htmlView.getText(); //InfoSelection selection = new InfoSelection( htmlText, plainText ); StringSelection selection = new StringSelection( plainText ); IOInterface printTool = getService(IOInterface.class); printTool.setContents( selection, null); } catch (Exception ex) { showException(ex, dlg); } } }); dlg.getButton(1).setAction( new AbstractAction() { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { try { IOInterface printTool = getService(IOInterface.class); HTMLView htmlView = viewTable.htmlView; printTool.print( new ComponentPrinter(htmlView, htmlView.getPreferredSize()) , printTool.defaultPage() ,true ); } catch (Exception ex) { showException(ex, dlg); } } }); } /* (non-Javadoc) * @see org.rapla.gui.view.IInfoUIFactory#createDeleteDialog(java.lang.Object[], java.awt.Component) */ public DialogUI createDeleteDialog( Object[] deletables, Component owner ) throws RaplaException { ViewTable<Object[]> viewTable = new ViewTable<Object[]>(getContext()); DeleteInfoUI deleteView = new DeleteInfoUI(getContext()); DialogUI dlg = DialogUI.create(getContext(),owner ,true ,viewTable.getComponent() ,new String[] { getString( "delete.ok" ) ,getString( "delete.abort" ) }); dlg.setIcon( getIcon("icon.warning") ); dlg.getButton( 0).setIcon(getIcon("icon.delete") ); dlg.getButton( 1).setIcon(getIcon("icon.abort") ); dlg.setDefault(1); viewTable.updateInfo( deletables, deleteView ); dlg.setTitle( viewTable.getDialogTitle() ); return dlg; } }
Java
/*--------------------------------------------------------------------------* | 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.gui.internal.view; import java.util.ArrayList; import java.util.Collection; import java.util.Locale; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.AttributeAnnotations; import org.rapla.entities.dynamictype.Classifiable; import org.rapla.entities.dynamictype.Classification; import org.rapla.entities.dynamictype.internal.AttributeImpl; import org.rapla.framework.RaplaContext; class ClassificationInfoUI<T extends Classifiable> extends HTMLInfo<T> { public ClassificationInfoUI(RaplaContext sm) { super(sm); } public void insertClassificationTitle( Classifiable classifiable, StringBuffer buf ) { Classification classification = classifiable.getClassification(); buf.append( "<strong>"); Locale locale = getRaplaLocale().getLocale(); encode( classification.getType().getName(locale), buf ); buf.append( "</strong>"); } protected void insertClassification( Classifiable classifiable, StringBuffer buf ) { insertClassificationTitle( classifiable, buf ); Collection<Row> att = new ArrayList<Row>(); att.addAll(getClassificationAttributes(classifiable, false)); createTable(att,buf,false); } protected Collection<HTMLInfo.Row> getClassificationAttributes(Classifiable classifiable, boolean excludeAdditionalInfos) { Collection<Row> att = new ArrayList<Row>(); Classification classification = classifiable.getClassification(); Attribute[] attributes = classification.getAttributes(); for (int i=0; i< attributes.length; i++) { Attribute attribute = attributes[i]; String view = attribute.getAnnotation( AttributeAnnotations.KEY_EDIT_VIEW, AttributeAnnotations.VALUE_EDIT_VIEW_MAIN ); if ( view.equals(AttributeAnnotations.VALUE_EDIT_VIEW_NO_VIEW )) { continue; } if ( excludeAdditionalInfos && !view.equals( AttributeAnnotations.VALUE_EDIT_VIEW_MAIN ) ) { continue; } Collection<Object> values = classification.getValues( attribute); /* if (value == null) continue; */ String name = getName(attribute); String valueString = null; Locale locale = getRaplaLocale().getLocale(); String pre = name; for (Object value:values) { if (value instanceof Boolean) { valueString = getString(((Boolean) value).booleanValue() ? "yes":"no"); } else { valueString = ((AttributeImpl)attribute).getValueAsString( locale, value); } att.add (new Row(pre,encode(valueString))); pre = ""; } } return att; } @Override protected String getTooltip(Classifiable classifiable) { StringBuffer buf = new StringBuffer(); Collection<Row> att = new ArrayList<Row>(); att.addAll(getClassificationAttributes(classifiable, false)); createTable(att,buf,false); return buf.toString(); } @Override protected String createHTMLAndFillLinks(Classifiable classifiable,LinkController controller) { StringBuffer buf = new StringBuffer(); insertClassification( classifiable, buf ); return buf.toString(); } /** * @param object * @param controller * @return */ protected String getTitle(Object object, LinkController controller) { Classifiable classifiable = (Classifiable) object; Classification classification = classifiable.getClassification(); return getString("view") + ": " + classification.getType().getName(getLocale()); } }
Java
/*--------------------------------------------------------------------------* | 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.gui.internal.view; import java.util.ArrayList; import java.util.Collection; import org.rapla.entities.Category; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.AttributeType; import org.rapla.entities.dynamictype.ConstraintIds; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.framework.RaplaContext; class DynamicTypeInfoUI extends HTMLInfo<DynamicType> { public DynamicTypeInfoUI(RaplaContext sm) { super(sm); } protected String createHTMLAndFillLinks(DynamicType object,LinkController controller){ DynamicType dynamicType = object; StringBuffer buf = new StringBuffer(); insertModificationRow( object, buf ); Collection<Row> att = new ArrayList<Row>(); att.add(new Row(getString("dynamictype.name"), strong( encode( getName( dynamicType ) )))); Attribute[] attributes = dynamicType.getAttributes(); for (int i=0;i<attributes.length;i++) { String name = getName(attributes[i]); String type = getString("type." + attributes[i].getType()); if (attributes[i].getType().equals(AttributeType.CATEGORY)) { Category category = (Category) attributes[i].getConstraint(ConstraintIds.KEY_ROOT_CATEGORY); if (category.getParent()!=null) type = type + " " +getName(category); } att.add(new Row(encode(name), encode(type))); } createTable(att, buf, false); return buf.toString(); } protected String getTooltip(DynamicType object) { if ( this.isAdmin()) { return createHTMLAndFillLinks( object, null); } else { return null; } } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2008 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.gui.internal; import java.awt.BorderLayout; import java.awt.Component; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTree; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.TreeModel; import javax.swing.tree.TreePath; import org.rapla.components.util.TimeInterval; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; import org.rapla.entities.User; import org.rapla.entities.configuration.Preferences; import org.rapla.facade.CalendarSelectionModel; import org.rapla.facade.Conflict; import org.rapla.facade.ModificationEvent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.RaplaGUIComponent; import org.rapla.gui.TreeFactory; import org.rapla.gui.internal.common.MultiCalendarView; import org.rapla.gui.internal.view.TreeFactoryImpl; import org.rapla.gui.toolkit.RaplaTree; import org.rapla.gui.toolkit.RaplaWidget; public class ConflictSelection extends RaplaGUIComponent implements RaplaWidget { public RaplaTree treeSelection = new RaplaTree(); protected final CalendarSelectionModel model; MultiCalendarView view; protected JPanel content = new JPanel(); JLabel summary = new JLabel(); Collection<Conflict> conflicts; public ConflictSelection(RaplaContext context,final MultiCalendarView view, final CalendarSelectionModel model) throws RaplaException { super(context); this.model = model; this.view = view; conflicts = new LinkedHashSet<Conflict>( Arrays.asList(getQuery().getConflicts( ))); updateTree(); final JTree navTree = treeSelection.getTree(); content.setLayout(new BorderLayout()); content.add(treeSelection); // content.setPreferredSize(new Dimension(260,400)); content.setBorder(BorderFactory.createRaisedBevelBorder()); JTree tree = treeSelection.getTree(); tree.setRootVisible(true); tree.setShowsRootHandles(true); tree.setCellRenderer(((TreeFactoryImpl) getTreeFactory()).createConflictRenderer()); tree.setSelectionModel(((TreeFactoryImpl) getTreeFactory()).createConflictTreeSelectionModel()); navTree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { Collection<Conflict> selectedConflicts = getSelectedConflicts(); showConflicts(selectedConflicts); } }); } public RaplaTree getTreeSelection() { return treeSelection; } protected CalendarSelectionModel getModel() { return model; } public void dataChanged(ModificationEvent evt) throws RaplaException { TimeInterval invalidateInterval = evt.getInvalidateInterval(); if ( invalidateInterval != null && invalidateInterval.getStart() == null) { Conflict[] conflictArray = getQuery().getConflicts( ); conflicts = new LinkedHashSet<Conflict>( Arrays.asList(conflictArray)); updateTree(); } else if ( evt.isModified(Conflict.TYPE) || (evt.isModified( Preferences.TYPE) ) ) { Set<Conflict> changed = RaplaType.retainObjects(evt.getChanged(), conflicts);; removeAll( conflicts,changed); Set<Conflict> removed = RaplaType.retainObjects(evt.getRemoved(), conflicts); removeAll( conflicts,removed); conflicts.addAll( changed); for (RaplaObject obj:evt.getAddObjects()) { if ( obj.getRaplaType()== Conflict.TYPE) { Conflict conflict = (Conflict) obj; conflicts.add( conflict ); } } updateTree(); } else { treeSelection.repaint(); } } private void removeAll(Collection<Conflict> list, Set<Conflict> changed) { Iterator<Conflict> it = list.iterator(); while ( it.hasNext()) { if ( changed.contains(it.next())) { it.remove(); } } } public JComponent getComponent() { return content; } final protected TreeFactory getTreeFactory() { return getService(TreeFactory.class); } private void showConflicts(Collection<Conflict> selectedConflicts) { ArrayList<RaplaObject> arrayList = new ArrayList<RaplaObject>(model.getSelectedObjects()); for ( Iterator<RaplaObject> it = arrayList.iterator();it.hasNext();) { RaplaObject obj = it.next(); if (obj.getRaplaType() == Conflict.TYPE ) { it.remove(); } } arrayList.addAll( selectedConflicts); model.setSelectedObjects( arrayList); if ( !selectedConflicts.isEmpty() ) { Conflict conflict = selectedConflicts.iterator().next(); Date date = conflict.getStartDate(); if ( date != null) { model.setSelectedDate(date); } } try { view.getSelectedCalendar().update(); } catch (RaplaException e1) { getLogger().error("Can't switch to conflict dates.", e1); } } private Collection<Conflict> getSelectedConflictsInModel() { Set<Conflict> result = new LinkedHashSet<Conflict>(); for (RaplaObject obj:model.getSelectedObjects()) { if (obj.getRaplaType() == Conflict.TYPE ) { result.add( (Conflict) obj); } } return result; } private Collection<Conflict> getSelectedConflicts() { List<Object> lastSelected = treeSelection.getSelectedElements( true); Set<Conflict> selectedConflicts = new LinkedHashSet<Conflict>(); for ( Object selected:lastSelected) { if (selected instanceof Conflict) { selectedConflicts.add((Conflict)selected ); } } return selectedConflicts; } private void updateTree() throws RaplaException { Collection<Conflict> conflicts = getConflicts(); TreeModel treeModel = getTreeFactory().createConflictModel(conflicts); try { treeSelection.exchangeTreeModel(treeModel); treeSelection.getTree().expandRow(0); } finally { } summary.setText( getString("conflicts") + " (" + conflicts.size() + ") "); Collection<Conflict> selectedConflicts = new ArrayList<Conflict>(getSelectedConflicts()); Collection<Conflict> inModel = new ArrayList<Conflict>(getSelectedConflictsInModel()); if ( !selectedConflicts.equals( inModel )) { showConflicts(selectedConflicts); } } public Collection<Conflict> getConflicts() throws RaplaException { Collection<Conflict> conflicts; boolean onlyOwn = model.isOnlyCurrentUserSelected(); User conflictUser = onlyOwn ? getUser() : null; conflicts= getConflicts( conflictUser); return conflicts; } private Collection<Conflict> getConflicts( User user) { List<Conflict> result = new ArrayList<Conflict>(); for (Conflict conflict:conflicts) { if (conflict.isOwner(user)) { result.add(conflict); } } Collections.sort( result, new ConflictStartDateComparator( )); return result; } class ConflictStartDateComparator implements Comparator<Conflict> { public int compare(Conflict c1, Conflict c2) { if ( c1.equals( c2)) { return 0; } Date d1 = c1.getStartDate(); Date d2 = c2.getStartDate(); if ( d1 != null ) { if ( d2 == null) { return -1; } else { int result = d1.compareTo( d2); return result; } } else if ( d2 != null) { return 1; } return new Integer(c1.hashCode()).compareTo( new Integer(c2.hashCode())); } } public void clearSelection() { treeSelection.getTree().setSelectionPaths( new TreePath[] {}); } public Component getSummaryComponent() { return summary; } }
Java
/*--------------------------------------------------------------------------* | 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.gui.internal; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Window; import java.beans.PropertyChangeEvent; import java.beans.PropertyVetoException; import java.beans.VetoableChangeListener; import javax.swing.Box; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JMenuBar; import javax.swing.JPanel; import org.rapla.RaplaMainContainer; import org.rapla.client.ClientService; import org.rapla.entities.User; import org.rapla.facade.CalendarSelectionModel; import org.rapla.facade.ModificationEvent; import org.rapla.facade.ModificationListener; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.RaplaGUIComponent; import org.rapla.gui.internal.common.InternMenus; import org.rapla.gui.toolkit.DialogUI; import org.rapla.gui.toolkit.RaplaFrame; public class MainFrame extends RaplaGUIComponent implements ModificationListener { RaplaMenuBar menuBar; RaplaFrame frame = null; Listener listener = new Listener(); CalendarEditor cal; JLabel statusBar = new JLabel(""); public MainFrame(RaplaContext sm) throws RaplaException { super(sm); menuBar = new RaplaMenuBar(getContext()); frame = getService( ClientService.MAIN_COMPONENT ); String title = getQuery().getSystemPreferences().getEntryAsString(RaplaMainContainer.TITLE, getString("rapla.title")); // CKO TODO Title should be set in config along with the facade used frame.setTitle(title ); CalendarSelectionModel model = getService( CalendarSelectionModel.class); cal = new CalendarEditor(sm,model); getUpdateModule().addModificationListener(this); JMenuBar menuBar = getService( InternMenus.MENU_BAR); menuBar.add(Box.createHorizontalGlue()); menuBar.add(statusBar); menuBar.add(Box.createHorizontalStrut(5)); frame.setJMenuBar( menuBar ); getContentPane().setLayout( new BorderLayout() ); // getContentPane().add ( statusBar, BorderLayout.SOUTH); getContentPane().add( cal.getComponent() , BorderLayout.CENTER ); } public void show() { getLogger().debug("Creating Main-Frame"); createFrame(); //dataChanged(null); setStatus(); cal.start(); frame.setIconImage(getI18n().getIcon("icon.rapla_small").getImage()); frame.setVisible(true); getFrameList().setMainWindow(frame); } private JPanel getContentPane() { return (JPanel) frame.getContentPane(); } private void createFrame() { Dimension dimension = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); frame.setSize(new Dimension( Math.min(dimension.width,1200) ,Math.min(dimension.height-20,900) ) ); frame.addVetoableChangeListener(listener); //statusBar.setBorder( BorderFactory.createEtchedBorder()); } class Listener implements VetoableChangeListener { public void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException { if (shouldExit()) close(); else throw new PropertyVetoException("Don't close",evt); } } public Window getFrame() { return frame; } public JComponent getComponent() { return (JComponent) frame.getContentPane(); } public void dataChanged(ModificationEvent e) throws RaplaException { cal.dataChanged( e ); new StatusFader(statusBar).updateStatus(); } private void setStatus() { statusBar.setMaximumSize( new Dimension(400,20)); final StatusFader runnable = new StatusFader(statusBar); final Thread fadeThread = new Thread(runnable); fadeThread.setDaemon( true); fadeThread.start(); } class StatusFader implements Runnable{ JLabel label; StatusFader(JLabel label) { this.label=label; } public void run() { try { { User user = getUser(); final boolean admin = user.isAdmin(); String name = user.getName(); if ( name == null || name.length() == 0 ) { name = user.getUsername(); } String message = getI18n().format("rapla.welcome",name); if ( admin) { message = message + " " + getString("admin.login"); } statusBar.setText(message); fadeIn( statusBar ); } Thread.sleep(2000); { fadeOut( statusBar); if (getUserModule().isSessionActive()) { updateStatus(); } fadeIn( statusBar ); } } catch (InterruptedException ex) { //Logger.getLogger(Fader.class.getName()).log(Level.SEVERE, null, ex); } catch (RaplaException e) { } } public void updateStatus() throws RaplaException { User user = getUser(); final boolean admin = user.isAdmin(); String message = getString("user") + " "+ user.toString(); String templateName = getModification().getTemplateName(); if ( templateName != null) { message = getString("edit-templates") + " [" + templateName + "] " + message; } statusBar.setText( message); final Font boldFont = statusBar.getFont().deriveFont(Font.BOLD); statusBar.setFont( boldFont); if ( admin) { statusBar.setForeground( new Color(220,30,30)); } else { statusBar.setForeground( new Color(30,30,30) ); } } private void fadeIn(JLabel label) throws InterruptedException { int alpha=0; Color c = label.getForeground(); while(alpha<=230){ alpha+=25; final Color color = new Color(c.getRed(), c.getGreen(), c.getBlue(), alpha); label.setForeground(color); label.repaint(); Thread.sleep(200); } } private void fadeOut(JLabel label) throws InterruptedException { int alpha=250; Color c = label.getForeground(); while(alpha>0){ alpha-=25; final Color color = new Color(c.getRed(), c.getGreen(), c.getBlue(), alpha); label.setForeground(color); label.repaint(); Thread.sleep(200); } } } protected boolean shouldExit() { try { DialogUI dlg = DialogUI.create(getContext() ,frame.getRootPane() ,true ,getString("exit.title") ,getString("exit.question") ,new String[] { getString("exit.ok") ,getString("exit.abort") } ); dlg.setIcon(getIcon("icon.question")); //dlg.getButton(0).setIcon(getIcon("icon.confirm")); dlg.getButton(0).setIcon(getIcon("icon.abort")); dlg.setDefault(1); dlg.start(); return (dlg.getSelectedIndex() == 0); } catch (RaplaException e) { getLogger().error( e.getMessage(), e); return true; } } public void close() { getUpdateModule().removeModificationListener(this); frame.close(); } }
Java
package org.rapla.gui.internal; import java.awt.Component; import java.awt.Dialog; import java.awt.Frame; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JComponent; import javax.swing.JWindow; import javax.swing.event.ChangeListener; import org.rapla.components.calendar.RaplaArrowButton; import org.rapla.facade.ClassifiableFilter; import org.rapla.framework.RaplaContext; import org.rapla.gui.RaplaGUIComponent; import org.rapla.gui.internal.edit.ClassifiableFilterEdit; import org.rapla.gui.toolkit.DialogUI; public class FilterEditButton extends RaplaGUIComponent { protected RaplaArrowButton filterButton; JWindow popup; ClassifiableFilterEdit ui; public FilterEditButton(final RaplaContext context,final ClassifiableFilter filter, final ChangeListener listener, final boolean isResourceSelection) { super(context); filterButton = new RaplaArrowButton('v'); filterButton.setText(getString("filter")); filterButton.setSize(80,18); filterButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { if ( popup != null) { popup.setVisible(false); popup= null; filterButton.setChar('v'); return; } try { if ( ui != null && listener != null) { ui.removeChangeListener( listener); } ui = new ClassifiableFilterEdit( context, isResourceSelection); if ( listener != null) { ui.addChangeListener(listener); } ui.setFilter( filter); final Point locationOnScreen = filterButton.getLocationOnScreen(); final int y = locationOnScreen.y + 18; final int x = locationOnScreen.x; if ( popup == null) { Component ownerWindow = DialogUI.getOwnerWindow(filterButton); if ( ownerWindow instanceof Frame) { popup = new JWindow((Frame)ownerWindow); } else if ( ownerWindow instanceof Dialog) { popup = new JWindow((Dialog)ownerWindow); } } JComponent content = ui.getComponent(); popup.setContentPane(content ); popup.setSize( content.getPreferredSize()); popup.setLocation( x, y); //.getSharedInstance().getPopup( filterButton, ui.getComponent(), x, y); popup.setVisible(true); filterButton.setChar('^'); } catch (Exception ex) { showException(ex, getMainComponent()); } } }); } public ClassifiableFilterEdit getFilterUI() { return ui; } public RaplaArrowButton getButton() { return filterButton; } }
Java
/*--------------------------------------------------------------------------* | 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.gui; import javax.swing.Icon; import org.rapla.facade.CalendarModel; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.framework.TypedComponentRole; public interface SwingViewFactory { public TypedComponentRole<Boolean> PRINT_CONTEXT = new TypedComponentRole<Boolean>("org.rapla.PrintContext"); public SwingCalendarView createSwingView(RaplaContext context, CalendarModel model, boolean editable) throws RaplaException; public String getViewId(); /** return the key that is responsible for placing the view in the correct position in the drop down selection menu*/ public String getMenuSortKey(); public String getName(); public Icon getIcon(); }
Java
package org.rapla.gui; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.toolkit.RaplaWidget; public interface AppointmentStatusFactory { RaplaWidget createStatus(RaplaContext context, ReservationEdit reservationEdit) throws RaplaException; }
Java
/*--------------------------------------------------------------------------* | 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.gui; import java.awt.Color; import java.awt.Component; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.StringSelection; import java.awt.datatransfer.Transferable; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.security.AccessControlException; import java.text.SimpleDateFormat; import java.util.Iterator; import java.util.Map; import javax.swing.Action; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.JTable; import javax.swing.KeyStroke; import javax.swing.text.DefaultEditorKit; import javax.swing.text.JTextComponent; import org.rapla.client.ClientService; import org.rapla.components.calendar.DateRenderer; import org.rapla.components.calendar.RaplaCalendar; import org.rapla.components.calendar.RaplaTime; import org.rapla.components.calendar.TimeRenderer; import org.rapla.components.iolayer.IOInterface; import org.rapla.entities.DependencyException; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.framework.logger.Logger; import org.rapla.gui.toolkit.ErrorDialog; import org.rapla.gui.toolkit.FrameControllerList; import org.rapla.storage.RaplaNewVersionException; import org.rapla.storage.RaplaSecurityException; import org.rapla.storage.dbrm.RaplaConnectException; import org.rapla.storage.dbrm.RaplaRestartingException; import org.rapla.storage.dbrm.WrongRaplaVersionException; /** Base class for most components in the gui package. Eases access to frequently used services, e.g. {@link org.rapla.components.xmlbundle.I18nBundle}. It also provides some methods for Exception displaying. */ public class RaplaGUIComponent extends RaplaComponent { public RaplaGUIComponent(RaplaContext context) { super(context); } /** lookup FrameControllerList from the context */ final protected FrameControllerList getFrameList() { return getService(FrameControllerList.class); } /** Creates a new ErrorDialog with the specified owner and displays the exception @param ex the exception that should be displayed. @param owner the exception that should be displayed. Can be null, but providing a parent-component will lead to a more appropriate display. */ public void showException(Exception ex,Component owner) { RaplaContext context = getContext(); Logger logger = getLogger(); showException(ex, owner, context, logger); } static public void showException(Throwable ex, Component owner, RaplaContext context, Logger logger) { if ( ex instanceof RaplaConnectException) { String message = ex.getMessage(); Throwable cause = ex.getCause(); String additionalInfo = ""; if ( cause != null) { additionalInfo = " " + cause.getClass() + ":" + cause.getMessage(); } logger.warn(message + additionalInfo); if ( ex instanceof RaplaRestartingException) { return; } try { ErrorDialog dialog = new ErrorDialog(context); dialog.showWarningDialog( message, owner); } catch (RaplaException e) { } catch (Throwable e) { logger.error(e.getMessage(), e); } return; } try { ErrorDialog dialog = new ErrorDialog(context); if (ex instanceof DependencyException) { dialog.showWarningDialog( getHTML( (DependencyException)ex ), owner); } else if (isWarningOnly(ex)) { dialog.showWarningDialog( ex.getMessage(), owner); } else { dialog.showExceptionDialog(ex,owner); } } catch (RaplaException ex2) { logger.error(ex2.getMessage(),ex2); } catch (Throwable ex2) { logger.error(ex2.getMessage(),ex2); } } static public boolean isWarningOnly(Throwable ex) { return ex instanceof RaplaNewVersionException || ex instanceof RaplaSecurityException || ex instanceof WrongRaplaVersionException || ex instanceof RaplaConnectException; } static private String getHTML(DependencyException ex){ StringBuffer buf = new StringBuffer(); buf.append(ex.getMessage()+":"); buf.append("<br><br>"); Iterator<String> it = ex.getDependencies().iterator(); int i = 0; while (it.hasNext()) { Object obj = it.next(); buf.append((++i)); buf.append(") "); buf.append( obj); buf.append("<br>"); if (i == 30 && it.hasNext()) { buf.append("... " + (ex.getDependencies().size() - 30) + " more"); break; } } return buf.toString(); } /** Creates a new ErrorDialog with the specified owner and displays the waring */ public void showWarning(String warning,Component owner) { RaplaContext context = getContext(); Logger logger = getLogger(); showWarning(warning, owner, context, logger); } public static void showWarning(String warning, Component owner, RaplaContext context, Logger logger) { try { ErrorDialog dialog = new ErrorDialog(context); dialog.showWarningDialog(warning,owner); } catch (RaplaException ex2) { logger.error(ex2.getMessage(),ex2); } } public RaplaCalendar createRaplaCalendar() { RaplaCalendar cal = new RaplaCalendar( getI18n().getLocale(),getRaplaLocale().getTimeZone()); cal.setDateRenderer(getDateRenderer()); addCopyPaste(cal.getDateField()); return cal; } /** lookup DateRenderer from the serviceManager */ final protected DateRenderer getDateRenderer() { return getService(DateRenderer.class); } static Color NON_WORKTIME = new Color(0xcc, 0xcc, 0xcc); final protected TimeRenderer getTimeRenderer() { // BJO 00000070 final int start = getCalendarOptions().getWorktimeStartMinutes(); final int end = getCalendarOptions().getWorktimeEndMinutes(); // BJO 00000070 return new TimeRenderer() { public Color getBackgroundColor( int hourOfDay, int minute ) { // BJO 00000070 int worktime = hourOfDay * 60 + minute; // BJO 00000070 if ( start >= end) { // BJO 00000070 if ( worktime >= end && worktime < start) // BJO 00000070 { return NON_WORKTIME; } } // BJO 00000070 else if ( worktime < start || worktime >= end) { // BJO 00000070 return NON_WORKTIME; } return null; } public String getToolTipText( int hourOfDay, int minute ) { return null; } public String getDurationString(int durationInMinutes) { if ( durationInMinutes > 0 ) { int hours = durationInMinutes / 60; int minutes = durationInMinutes % 60; if ( hours == 0) { return "("+minutes + " " + getString("minutes.abbreviation") + ")"; } if ( minutes % 30 != 0) { return ""; } StringBuilder builder = new StringBuilder(); builder.append(" ("); if ( hours > 0) { builder.append(hours ); } if ( minutes % 60 != 0) { char c = 189; // 1/2 builder.append(c); } if ( minutes % 30 == 0) { builder.append( " " + getString((hours == 1 && minutes % 60 == 0 ? "hour.abbreviation" :"hours.abbreviation")) + ")"); } return builder.toString(); } return ""; } }; } public RaplaTime createRaplaTime() { RaplaTime cal = new RaplaTime( getI18n().getLocale(), getRaplaLocale().getTimeZone()); cal.setTimeRenderer( getTimeRenderer() ); int rowsPerHour =getCalendarOptions().getRowsPerHour() ; cal.setRowsPerHour( rowsPerHour ); addCopyPaste(cal.getTimeField()); return cal; } public Map<Object,Object> getSessionMap() { return getService( ClientService.SESSION_MAP); } protected InfoFactory getInfoFactory() { return getService( InfoFactory.class ); } /** calls getI18n().getIcon(key) */ final public ImageIcon getIcon(String key) { return getI18n().getIcon(key); } protected EditController getEditController() { return getService( EditController.class ); } protected ReservationController getReservationController() { return getService( ReservationController.class ); } public Component getMainComponent() { return getService(ClientService.MAIN_COMPONENT); } public void addCopyPaste(final JComponent component) { ActionListener pasteListener = new ActionListener() { public void actionPerformed(ActionEvent e) { paste(component, e); } }; ActionListener copyListener = new ActionListener() { public void actionPerformed(ActionEvent e) { copy(component, e); } }; final JPopupMenu menu = new JPopupMenu(); { final JMenuItem copyItem = new JMenuItem(); copyItem.addActionListener( copyListener); copyItem.setText(getString("copy")); menu.add(copyItem); } { final JMenuItem pasteItem = new JMenuItem(); pasteItem.addActionListener( pasteListener); pasteItem.setText(getString("paste")); menu.add(pasteItem); } component.add(menu); component.addMouseListener(new MouseAdapter() { private void showMenuIfPopupTrigger(MouseEvent e) { if (e.isPopupTrigger()) { menu.show(component,e.getX() + 3, e.getY() + 3); } } public void mousePressed(MouseEvent e) { showMenuIfPopupTrigger(e); } public void mouseReleased(MouseEvent e) { showMenuIfPopupTrigger(e); } } ); component.registerKeyboardAction(copyListener,getString("copy"),COPY_STROKE,JComponent.WHEN_FOCUSED); component.registerKeyboardAction(pasteListener,getString("paste"),PASTE_STROKE,JComponent.WHEN_FOCUSED); } public static KeyStroke COPY_STROKE = KeyStroke.getKeyStroke(KeyEvent.VK_C,ActionEvent.CTRL_MASK,false); public static KeyStroke PASTE_STROKE = KeyStroke.getKeyStroke(KeyEvent.VK_V,ActionEvent.CTRL_MASK,false); protected IOInterface getIOService() { try { return getService( IOInterface.class); } catch (Exception e) { return null; } } protected void copy(final JComponent component, ActionEvent e) { final Transferable transferable; if ( component instanceof JTextComponent) { String selectedText = ((JTextComponent)component).getSelectedText(); transferable = new StringSelection(selectedText); } else if ( component instanceof JTable) { JTable table = (JTable)component; transferable = getSelectedContent(table); } else { transferable = new StringSelection(component.toString()); } if ( transferable != null) { try { final IOInterface service = getIOService(); if (service != null) { service.setContents(transferable, null); } else { Action action = component.getActionMap().get(DefaultEditorKit.copyAction); if ( action != null) { action.actionPerformed(e); } } } catch (AccessControlException ex) { clipboard.set( transferable); } } } static ThreadLocal<Transferable> clipboard = new ThreadLocal<Transferable>(); /** Code from http://www.javaworld.com/javatips/jw-javatip77.html */ private static final String LINE_BREAK = "\n"; private static final String CELL_BREAK = "\t"; private StringSelection getSelectedContent(JTable table) { int numCols=table.getSelectedColumnCount(); int[] rowsSelected=table.getSelectedRows(); int[] colsSelected=table.getSelectedColumns(); // int numRows=table.getSelectedRowCount(); // if (numRows!=rowsSelected[rowsSelected.length-1]-rowsSelected[0]+1 || numRows!=rowsSelected.length || // numCols!=colsSelected[colsSelected.length-1]-colsSelected[0]+1 || numCols!=colsSelected.length) { // // JOptionPane.showMessageDialog(null, "Invalid Copy Selection", "Invalid Copy Selection", JOptionPane.ERROR_MESSAGE); // return null; // } StringBuffer excelStr=new StringBuffer(); for (int row:rowsSelected) { int j=0; for (int col:colsSelected) { Object value = table.getValueAt(row, col); String formated; Class<?> columnClass = table.getColumnClass( col); boolean isDate = columnClass.isAssignableFrom( java.util.Date.class); if ( isDate) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); format.setTimeZone( getRaplaLocale().getTimeZone()); if ( value instanceof java.util.Date) { String timestamp = format.format( (java.util.Date)value); formated = timestamp; } else { String escaped = escape(value); formated = escaped; } } else { String escaped = escape(value); formated = escaped; } excelStr.append( formated ); boolean isLast = j==numCols-1; if (!isLast) { excelStr.append(CELL_BREAK); } j++; } excelStr.append(LINE_BREAK); } String string = excelStr.toString(); StringSelection sel = new StringSelection(string); return sel; } private String escape(Object cell) { return cell.toString().replace(LINE_BREAK, " ").replace(CELL_BREAK, " "); } /** Code End */ protected void paste(final JComponent component, ActionEvent e) { try { final IOInterface service = getIOService(); if (service != null) { final Transferable transferable = service.getContents( null); Object transferData; try { transferData = transferable.getTransferData(DataFlavor.stringFlavor); if ( transferData != null) { if ( component instanceof JTextComponent) { ((JTextComponent)component).replaceSelection( transferData.toString()); } if ( component instanceof JTable) { // Paste currently not supported } } } catch (Exception ex) { } } else { Action action = component.getActionMap().get(DefaultEditorKit.pasteAction); if ( action != null) { action.actionPerformed(e); } } } catch (AccessControlException ex) { Transferable transferable =clipboard.get(); if ( transferable != null) { if ( component instanceof JTextComponent) { Object transferData; try { transferData = transferable.getTransferData(DataFlavor.stringFlavor); ((JTextComponent)component).replaceSelection( transferData.toString()); } catch (Exception e1) { getLogger().error( e1.getMessage(),e1); } } } } } }
Java
/*--------------------------------------------------------------------------* | 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.gui; import java.awt.Component; import java.awt.Point; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaDefaultContext; public class MenuContext extends RaplaDefaultContext { Collection<?> selectedObjects = Collections.EMPTY_LIST; Point p; Object focused; Component parent; public MenuContext(RaplaContext parentContext, Object focusedObject) { this( parentContext, focusedObject, null, null ); } public MenuContext(RaplaContext parentContext, Object focusedObject, Component parent,Point p) { super( parentContext); this.focused = focusedObject; this.parent= parent ; this.p = p; } public void setSelectedObjects(Collection<?> selectedObjects) { this.selectedObjects= new ArrayList<Object>(selectedObjects); } public Collection<?> getSelectedObjects() { return selectedObjects; } public Point getPoint() { return p; } public Component getComponent() { return parent; } public Object getFocusedObject() { return focused; } }
Java
package org.rapla.gui; import java.beans.PropertyChangeListener; import org.rapla.facade.CalendarSelectionModel; import org.rapla.framework.RaplaException; public interface PublishExtensionFactory { PublishExtension creatExtension(CalendarSelectionModel model, PropertyChangeListener revalidateCallback) throws RaplaException; }
Java
package org.rapla.gui; import java.util.Collection; import java.util.Date; import javax.swing.event.ChangeListener; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.Reservation; import org.rapla.framework.RaplaException; public interface ReservationEdit { boolean isModifiedSinceLastChange(); void addAppointment( Date start, Date end) throws RaplaException; Reservation getReservation(); void save() throws RaplaException; void delete() throws RaplaException; /** You can add a listener that gets notified everytime a reservation is changed: Reservation attributes, appointments or allocation changes all count*/ void addReservationChangeListener(ChangeListener listener); void removeReservationChangeListener(ChangeListener listener); void addAppointmentListener(AppointmentListener listener); void removeAppointmentListener(AppointmentListener listener); Collection<Appointment> getSelectedAppointments(); }
Java
/*--------------------------------------------------------------------------* | 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.gui; import java.util.Collection; import java.util.EventListener; import org.rapla.entities.domain.Appointment; public interface AppointmentListener extends EventListener { void appointmentAdded(Collection<Appointment> appointment); void appointmentRemoved(Collection<Appointment> appointment); void appointmentChanged(Collection<Appointment> appointment); void appointmentSelected(Collection<Appointment> appointment); }
Java
package org.rapla.gui; import java.awt.Component; import java.awt.Point; import java.util.Collection; import java.util.Date; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.AppointmentBlock; import org.rapla.entities.domain.Reservation; import org.rapla.framework.RaplaException; /** Use the ReservationController to modify or create a {@link Reservation}. This class handles all interactions with the user. Examples: <li> If you edit a reservation it will first check, if there is already is an open edit-window for the reservation and will give focus to that window instead of creating a new one. </li> <li> If you move or delete an repeating appointment it will display dialogs where the user will be asked if he wants to delete/move the complete appointment or just the occurrence on the selected date. </li> <li> If conflicts are found, a conflict panel will be displayed on saving. </li> */ public interface ReservationController { ReservationEdit edit( Reservation reservation ) throws RaplaException; ReservationEdit edit( AppointmentBlock appointmentBlock) throws RaplaException; boolean save(Reservation reservation,Component sourceComponent) throws RaplaException; public ReservationEdit[] getEditWindows(); /** copies an appointment without interaction */ Appointment copyAppointment( Appointment appointment ) throws RaplaException; void deleteAppointment( AppointmentBlock appointmentBlock, Component sourceComponent, Point point ) throws RaplaException; Appointment copyAppointment( AppointmentBlock appointmentBlock, Component sourceComponent, Point point,Collection<Allocatable> contextAllocatables ) throws RaplaException; void pasteAppointment( Date start, Component sourceComponent, Point point, boolean asNewReservation, boolean keepTime ) throws RaplaException; /** * @param keepTime when moving only the date part and not the time part is modified*/ void moveAppointment( AppointmentBlock appointmentBlock, Date newStart, Component sourceComponent, Point point, boolean keepTime ) throws RaplaException; /** * @param keepTime when moving only the date part and not the time part is modified*/ void resizeAppointment( AppointmentBlock appointmentBlock, Date newStart, Date newEnd, Component sourceComponent, Point p, boolean keepTime ) throws RaplaException; void exchangeAllocatable(AppointmentBlock appointmentBlock, Allocatable oldAlloc, Allocatable newAlloc,Date newStart, Component sourceComponent, Point p) throws RaplaException; boolean isAppointmentOnClipboard(); void deleteBlocks(Collection<AppointmentBlock> blockList, Component parent,Point point) throws RaplaException; }
Java
/*--------------------------------------------------------------------------* | 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.gui; import javax.swing.JComponent; import org.rapla.framework.RaplaException; import org.rapla.gui.toolkit.RaplaWidget; public interface SwingCalendarView extends RaplaWidget { public void update( ) throws RaplaException; /** you can provide a DateSelection component if you want */ public JComponent getDateSelection(); /** Most times you can only scroll programaticaly if the window is visible and the size of * the component is known, so this method gets called when the window is visible. * */ public void scrollToStart(); }
Java
package org.rapla.gui; import java.awt.Component; import java.awt.Point; import javax.swing.JComponent; import org.rapla.framework.RaplaException; import org.rapla.gui.toolkit.DialogUI; public interface InfoFactory { <T> JComponent createInfoComponent( T object ) throws RaplaException; /** same as getToolTip(obj, true) */ <T> String getToolTip( T obj ); /** @param wrapHtml wraps an html Page arround the tooltip */ <T> String getToolTip( T obj, boolean wrapHtml ); <T> void showInfoDialog( T object, Component owner ) throws RaplaException; <T> void showInfoDialog( T object, Component owner, Point point ) throws RaplaException; DialogUI createDeleteDialog( Object[] deletables, Component owner ) throws RaplaException; }
Java
package org.rapla.gui; import java.util.Collection; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreeCellRenderer; import javax.swing.tree.TreeModel; import org.rapla.entities.Category; import org.rapla.entities.Named; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Reservation; import org.rapla.facade.Conflict; import org.rapla.framework.RaplaException; import org.rapla.gui.toolkit.TreeToolTipRenderer; public interface TreeFactory { TreeModel createClassifiableModel(Allocatable[] classifiables, boolean useCategorizations); TreeModel createClassifiableModel(Allocatable[] classifiables); TreeModel createClassifiableModel(Reservation[] classifiables); TreeModel createConflictModel(Collection<Conflict> conflicts ) throws RaplaException; DefaultMutableTreeNode newNamedNode(Named element); TreeModel createModel(Category category); TreeModel createModel(Collection<Category> categories, boolean includeChildren); TreeModel createModelFlat(Named[] element); TreeToolTipRenderer createTreeToolTipRenderer(); TreeCellRenderer createConflictRenderer(); TreeCellRenderer createRenderer(); }
Java
package org.rapla.gui; import org.rapla.entities.Annotatable; import org.rapla.framework.RaplaException; import org.rapla.framework.TypedComponentRole; public interface AnnotationEditExtension { TypedComponentRole<AnnotationEditExtension> ATTRIBUTE_ANNOTATION_EDIT = new TypedComponentRole<AnnotationEditExtension>("org.rapla.gui.attributeAnnotation"); TypedComponentRole<AnnotationEditExtension> CATEGORY_ANNOTATION_EDIT = new TypedComponentRole<AnnotationEditExtension>("org.rapla.gui.categoryAnnotation"); TypedComponentRole<AnnotationEditExtension> DYNAMICTYPE_ANNOTATION_EDIT = new TypedComponentRole<AnnotationEditExtension>("org.rapla.gui.typeAnnotation"); EditField createEditField(Annotatable annotatable); void mapTo(EditField field,Annotatable annotatable) throws RaplaException; }
Java
/*--------------------------------------------------------------------------* | 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.gui; import java.awt.BorderLayout; import java.util.Locale; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JPanel; import org.rapla.entities.configuration.Preferences; import org.rapla.entities.configuration.RaplaConfiguration; import org.rapla.entities.configuration.internal.PreferencesImpl; import org.rapla.facade.RaplaComponent; import org.rapla.framework.Configuration; import org.rapla.framework.DefaultConfiguration; import org.rapla.framework.PluginDescriptor; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; abstract public class DefaultPluginOption extends RaplaGUIComponent implements PluginOptionPanel { public DefaultPluginOption(RaplaContext sm) { super(sm); } protected JCheckBox activate = new JCheckBox("Aktivieren"); protected Configuration config; protected Preferences preferences; JComponent container; abstract public Class<? extends PluginDescriptor<?>> getPluginClass(); /** * @throws RaplaException */ protected JPanel createPanel() throws RaplaException { JPanel panel = new JPanel(); panel.setLayout( new BorderLayout()); panel.add( activate, BorderLayout.NORTH ); return panel; } /** * @see org.rapla.gui.OptionPanel#setPreferences(org.rapla.entities.configuration.Preferences) */ public void setPreferences(Preferences preferences) { this.preferences = preferences; } /** * @see org.rapla.gui.OptionPanel#commit() */ public void commit() throws RaplaException { writePluginConfig(true); } protected void writePluginConfig(boolean addChildren) { RaplaConfiguration config = preferences.getEntry(RaplaComponent.PLUGIN_CONFIG); if ( config == null) { config = new RaplaConfiguration("org.rapla.plugin"); } String className = getPluginClass().getName(); //getDescritorClassName() RaplaConfiguration newChild = new RaplaConfiguration("plugin" ); newChild.setAttribute( "enabled", activate.isSelected()); newChild.setAttribute( "class", className); if ( addChildren) { addChildren( newChild ); } RaplaConfiguration newConfig = config.replace(config.find("class", className), newChild); preferences.putEntry( RaplaComponent.PLUGIN_CONFIG,newConfig); } /** * * @param newConfig */ protected void addChildren( DefaultConfiguration newConfig) { } /** * * @param config * @throws RaplaException */ protected void readConfig( Configuration config) { } /** * @see org.rapla.gui.OptionPanel#show() */ @SuppressWarnings("deprecation") public void show() throws RaplaException { activate.setText( getString("selected")); container = createPanel(); Class<? extends PluginDescriptor<?>> pluginClass = getPluginClass(); boolean defaultSelection = false; try { defaultSelection = ((Boolean )pluginClass.getField("ENABLE_BY_DEFAULT").get( null)); } catch (Throwable e) { } config = ((PreferencesImpl)preferences).getOldPluginConfig(pluginClass.getName()); activate.setSelected( config.getAttributeAsBoolean("enabled", defaultSelection)); readConfig( config ); } /** * @see org.rapla.gui.toolkit.RaplaWidget#getComponent() */ public JComponent getComponent() { return container; } /** * @see org.rapla.entities.Named#getName(java.util.Locale) */ public String getName(Locale locale) { return getPluginClass().getSimpleName(); } public String toString() { return getName(getLocale()); } }
Java
/*--------------------------------------------------------------------------* | 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.gui.toolkit; import java.awt.Component; import javax.swing.JComponent; import javax.swing.JMenu; import javax.swing.JMenuItem; public class RaplaMenu extends JMenu implements IdentifiableMenuEntry, MenuInterface { private static final long serialVersionUID = 1L; String id; public RaplaMenu(String id) { super(id); this.id = id; } public String getId() { return id; } public int getIndexOfEntryWithId(String id) { int size = getMenuComponentCount(); for ( int i=0;i< size;i++) { Component component = getMenuComponent( i ); if ( component instanceof IdentifiableMenuEntry) { IdentifiableMenuEntry comp = (IdentifiableMenuEntry) component; if ( id != null && id.equals( comp.getId() ) ) { return i; } } } return -1; } public void removeAllBetween(String startId, String endId) { int startIndex = getIndexOfEntryWithId( startId ); int endIndex = getIndexOfEntryWithId( endId); if ( startIndex < 0 || endIndex < 0 ) return; for ( int i= startIndex + 1; i< endIndex ;i++) { remove( startIndex + 1); } } public boolean hasId(String id) { return getIndexOfEntryWithId( id )>=0; } public void insertAfterId(Component component,String id) { if ( id == null) { getPopupMenu().add( component ); } else { int index = getIndexOfEntryWithId( id ) ; getPopupMenu().insert( component, index + 1); } } public void insertBeforeId(JComponent component,String id) { int index = getIndexOfEntryWithId( id ); getPopupMenu().insert( component, index); } @Override public JMenuItem getMenuElement() { return this; } }
Java
package org.rapla.gui.toolkit; import java.awt.Color; public class AWTColorUtil { final static public Color getAppointmentColor(int nr) { String string = RaplaColors.getAppointmentColor(nr); Color color = getColorForHex(string); return color; } public static Color getColorForHex(String hexString) throws NumberFormatException { if ( hexString == null || hexString.indexOf('#') != 0 || hexString.length()!= 7 ) throw new NumberFormatException("Can't parse HexValue " + hexString); String rString = hexString.substring(1,3).toUpperCase(); String gString = hexString.substring(3,5).toUpperCase(); String bString = hexString.substring(5,7).toUpperCase(); int r = RaplaColors.decode( rString); int g = RaplaColors.decode( gString); int b = RaplaColors.decode( bString); return new Color(r, g, b); } public static String getHexForColor(Color color) { if ( color == null) return ""; int r = color.getRed(); int g = color.getGreen(); int b = color.getBlue(); return RaplaColors.getHex(r, g, b); } }
Java
/*--------------------------------------------------------------------------* | 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.gui.toolkit; public interface FrameControllerListener { void frameClosed(FrameController frameController); void listEmpty(); }
Java
/*--------------------------------------------------------------------------* | 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.gui.toolkit; import java.awt.Component; import java.awt.Container; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Point; import java.awt.Toolkit; import java.awt.Window; import java.util.ArrayList; import java.util.Stack; import org.rapla.components.util.Assert; import org.rapla.components.util.Tools; import org.rapla.framework.logger.Logger; /**All rapla-windows are registered on the FrameControllerList. The FrameControllerList is responsible for positioning the windows and closing all open windows on exit. */ final public class FrameControllerList { private Stack<FrameController> openFrameController = new Stack<FrameController>(); private Window mainWindow = null; Point center; Logger logger = null; ArrayList<FrameControllerListener> listenerList = new ArrayList<FrameControllerListener>(); public FrameControllerList(Logger logger) { this.logger = logger; Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); center = new Point(screenSize.width / 2 ,screenSize.height / 2); } protected Logger getLogger() { return logger; } /** the center will be used by the <code>centerWindow()</code> function. */ public void setCenter(Container window) { center.x = window.getLocationOnScreen().x + window.getSize().width/2; center.y = window.getLocationOnScreen().y + window.getSize().height/2; } /** the center will be used by the <code>centerWindow(Window)</code> function. @see #centerWindow(Window) */ public void setCenter(Point center) { this.center = center; } /** the main-window will be used by the <code>placeRelativeToMain(Window)</code> function. @see #placeRelativeToMain(Window) */ public void setMainWindow(Window window) { this.mainWindow = window; } public Window getMainWindow() { return mainWindow; } /** places the window relative to the main-window if set. Otherwise the the <code>centerWindow(Window)</code> method is called. @param newWindow the window to place */ public void placeRelativeToMain(Window newWindow) { if (getLogger() != null && getLogger().isDebugEnabled() && mainWindow != null) getLogger().debug("placeRelativeToMainWindow(" + Tools.left(mainWindow.toString(),60) + ")"); if (mainWindow ==null) centerWindow(newWindow); else placeRelativeToWindow(newWindow,mainWindow); } /** adds a window to the FrameControllerList */ synchronized public void add(FrameController c) { Assert.notNull(c); Assert.isTrue(!openFrameController.contains(c),"Duplicated Entries are not allowed"); openFrameController.add(c); } /** removes a window from the FrameControllerList */ public void remove(FrameController c) { openFrameController.remove(c); String s = c.toString(); if (getLogger() != null && getLogger().isDebugEnabled()) getLogger().debug("Frame closed " + Tools.left(s,60) + "..."); fireFrameClosed(c); if (openFrameController.size() == 0) fireListEmpty(); } /** closes all windows registered on the FrameControllerList */ public void closeAll() { while (!openFrameController.empty()) { FrameController c = openFrameController.peek(); int size = openFrameController.size(); c.close(); if ( size <= openFrameController.size()) getLogger().error("removeFrameController() not called in close() in " + c); } } public void setCursor(Cursor cursor) { FrameController[] anArray = openFrameController.toArray( new FrameController[] {}); for ( FrameController frame:anArray) { frame.setCursor(cursor); } } public void addFrameControllerListener(FrameControllerListener listener) { listenerList.add(listener); } public void removeFrameControllerListener(FrameControllerListener listener) { listenerList.remove(listener); } public FrameControllerListener[] getFrameControllerListeners() { synchronized(listenerList) { return listenerList.toArray(new FrameControllerListener[]{}); } } protected void fireFrameClosed(FrameController controller) { if (listenerList.size() == 0) return; FrameControllerListener[] listeners = getFrameControllerListeners(); for (int i = 0;i<listeners.length;i++) { listeners[i].frameClosed(controller); } } protected void fireListEmpty() { if (listenerList.size() == 0) return; FrameControllerListener[] listeners = getFrameControllerListeners(); for (int i = 0;i<listeners.length;i++) { listeners[i].listEmpty(); } } /** centers the window around the specified center */ public void centerWindow(Window window) { Dimension preferredSize = window.getSize(); int x = center.x - (preferredSize.width / 2); int y = center.y - (preferredSize.height / 2); fitIntoScreen(x,y,window); } /** centers the window around the specified center */ static public void centerWindowOnScreen(Window window) { Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Dimension preferredSize = window.getSize(); int x = screenSize.width/2 - (preferredSize.width / 2); int y = screenSize.height/2 - (preferredSize.height / 2); fitIntoScreen(x,y,window); } /** Tries to place the window, that it fits into the screen. */ static public void fitIntoScreen(int x, int y, Component window) { Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Dimension windowSize = window.getSize(); if (x + windowSize.width > screenSize.width) x = screenSize.width - windowSize.width; if (y + windowSize.height > screenSize.height) y = screenSize.height - windowSize.height; if (x<0) x = 0; if (y<0) y = 0; window.setLocation(x,y); } /** places the window relative to the owner-window. The newWindow will be placed in the middle of the owner-window. @param newWindow the window to place @param owner the window to place into */ public static void placeRelativeToWindow(Window newWindow,Window owner) { placeRelativeToComponent(newWindow,owner,null); } public static void placeRelativeToComponent(Window newWindow,Component component,Point point) { if (component == null) return; Dimension dlgSize = newWindow.getSize(); Dimension parentSize = component.getSize(); Point loc = component.getLocationOnScreen(); if (point != null) { int x = loc.x + point.x - (dlgSize.width) / 2; int y = loc.y + point.y - ((dlgSize.height) * 2) / 3; //System.out.println (loc + ", " + point + " x: " + x + " y: " + y); fitIntoScreen(x,y,newWindow); } else { int x = (parentSize.width - dlgSize.width) / 2 + loc.x; int y = loc.y + 10; fitIntoScreen(x,y,newWindow); } } }
Java
/*--------------------------------------------------------------------------* | 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.gui.toolkit; /** This exception is thrown by the ErrorDialog and is used to test error-messages. @see ErrorDialog */ final public class ErrorDialogException extends RuntimeException { private static final long serialVersionUID = 1L; int type; /** @param type The type of the Error-Message. @see ErrorDialog */ public ErrorDialogException(Throwable throwable,int type) { super(String.valueOf(type),throwable); this.type = type; } /** returns the type of the Error-Message. @see ErrorDialog */ public int getType() { return type; } }
Java
package org.rapla.gui.toolkit; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Icon; import javax.swing.JComponent; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.MenuSelectionManager; import javax.swing.Timer; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.PopupMenuEvent; import javax.swing.event.PopupMenuListener; /** * Found on http://tips4java.wordpress.com/2009/02/01/menu-scroller/ * Does not have copyright information * A class that provides scrolling capabilities to a long menu dropdown or * popup menu. A number of items can optionally be frozen at the top and/or * bottom of the menu. * <P> * <B>Implementation note:</B> The default number of items to display * at a time is 15, and the default scrolling interval is 125 milliseconds. * <P> * * @version 1.5.0 04/05/12 * @author Darryl Burke */ public class MenuScroller { //private JMenu menu; private JPopupMenu menu; private Component[] menuItems; private MenuScrollItem upItem; private MenuScrollItem downItem; private final MenuScrollListener menuListener = new MenuScrollListener(); private int scrollCount; private int interval; private int topFixedCount; private int bottomFixedCount; private int firstIndex = 0; private int keepVisibleIndex = -1; /** * Registers a menu to be scrolled with the default number of items to * display at a time and the default scrolling interval. * * @param menu the menu * @return the MenuScroller */ public static MenuScroller setScrollerFor(JMenu menu) { return new MenuScroller(menu); } /** * Registers a popup menu to be scrolled with the default number of items to * display at a time and the default scrolling interval. * * @param menu the popup menu * @return the MenuScroller */ public static MenuScroller setScrollerFor(JPopupMenu menu) { return new MenuScroller(menu); } /** * Registers a menu to be scrolled with the default number of items to * display at a time and the specified scrolling interval. * * @param menu the menu * @param scrollCount the number of items to display at a time * @return the MenuScroller * @throws IllegalArgumentException if scrollCount is 0 or negative */ public static MenuScroller setScrollerFor(JMenu menu, int scrollCount) { return new MenuScroller(menu, scrollCount); } /** * Registers a popup menu to be scrolled with the default number of items to * display at a time and the specified scrolling interval. * * @param menu the popup menu * @param scrollCount the number of items to display at a time * @return the MenuScroller * @throws IllegalArgumentException if scrollCount is 0 or negative */ public static MenuScroller setScrollerFor(JPopupMenu menu, int scrollCount) { return new MenuScroller(menu, scrollCount); } /** * Registers a menu to be scrolled, with the specified number of items to * display at a time and the specified scrolling interval. * * @param menu the menu * @param scrollCount the number of items to be displayed at a time * @param interval the scroll interval, in milliseconds * @return the MenuScroller * @throws IllegalArgumentException if scrollCount or interval is 0 or negative */ public static MenuScroller setScrollerFor(JMenu menu, int scrollCount, int interval) { return new MenuScroller(menu, scrollCount, interval); } /** * Registers a popup menu to be scrolled, with the specified number of items to * display at a time and the specified scrolling interval. * * @param menu the popup menu * @param scrollCount the number of items to be displayed at a time * @param interval the scroll interval, in milliseconds * @return the MenuScroller * @throws IllegalArgumentException if scrollCount or interval is 0 or negative */ public static MenuScroller setScrollerFor(JPopupMenu menu, int scrollCount, int interval) { return new MenuScroller(menu, scrollCount, interval); } /** * Registers a menu to be scrolled, with the specified number of items * to display in the scrolling region, the specified scrolling interval, * and the specified numbers of items fixed at the top and bottom of the * menu. * * @param menu the menu * @param scrollCount the number of items to display in the scrolling portion * @param interval the scroll interval, in milliseconds * @param topFixedCount the number of items to fix at the top. May be 0. * @param bottomFixedCount the number of items to fix at the bottom. May be 0 * @throws IllegalArgumentException if scrollCount or interval is 0 or * negative or if topFixedCount or bottomFixedCount is negative * @return the MenuScroller */ public static MenuScroller setScrollerFor(JMenu menu, int scrollCount, int interval, int topFixedCount, int bottomFixedCount) { return new MenuScroller(menu, scrollCount, interval, topFixedCount, bottomFixedCount); } /** * Registers a popup menu to be scrolled, with the specified number of items * to display in the scrolling region, the specified scrolling interval, * and the specified numbers of items fixed at the top and bottom of the * popup menu. * * @param menu the popup menu * @param scrollCount the number of items to display in the scrolling portion * @param interval the scroll interval, in milliseconds * @param topFixedCount the number of items to fix at the top. May be 0 * @param bottomFixedCount the number of items to fix at the bottom. May be 0 * @throws IllegalArgumentException if scrollCount or interval is 0 or * negative or if topFixedCount or bottomFixedCount is negative * @return the MenuScroller */ public static MenuScroller setScrollerFor(JPopupMenu menu, int scrollCount, int interval, int topFixedCount, int bottomFixedCount) { return new MenuScroller(menu, scrollCount, interval, topFixedCount, bottomFixedCount); } /** * Constructs a <code>MenuScroller</code> that scrolls a menu with the * default number of items to display at a time, and default scrolling * interval. * * @param menu the menu */ public MenuScroller(JMenu menu) { this(menu, 15); } /** * Constructs a <code>MenuScroller</code> that scrolls a popup menu with the * default number of items to display at a time, and default scrolling * interval. * * @param menu the popup menu */ public MenuScroller(JPopupMenu menu) { this(menu, 15); } /** * Constructs a <code>MenuScroller</code> that scrolls a menu with the * specified number of items to display at a time, and default scrolling * interval. * * @param menu the menu * @param scrollCount the number of items to display at a time * @throws IllegalArgumentException if scrollCount is 0 or negative */ public MenuScroller(JMenu menu, int scrollCount) { this(menu, scrollCount, 150); } /** * Constructs a <code>MenuScroller</code> that scrolls a popup menu with the * specified number of items to display at a time, and default scrolling * interval. * * @param menu the popup menu * @param scrollCount the number of items to display at a time * @throws IllegalArgumentException if scrollCount is 0 or negative */ public MenuScroller(JPopupMenu menu, int scrollCount) { this(menu, scrollCount, 150); } /** * Constructs a <code>MenuScroller</code> that scrolls a menu with the * specified number of items to display at a time, and specified scrolling * interval. * * @param menu the menu * @param scrollCount the number of items to display at a time * @param interval the scroll interval, in milliseconds * @throws IllegalArgumentException if scrollCount or interval is 0 or negative */ public MenuScroller(JMenu menu, int scrollCount, int interval) { this(menu, scrollCount, interval, 0, 0); } /** * Constructs a <code>MenuScroller</code> that scrolls a popup menu with the * specified number of items to display at a time, and specified scrolling * interval. * * @param menu the popup menu * @param scrollCount the number of items to display at a time * @param interval the scroll interval, in milliseconds * @throws IllegalArgumentException if scrollCount or interval is 0 or negative */ public MenuScroller(JPopupMenu menu, int scrollCount, int interval) { this(menu, scrollCount, interval, 0, 0); } /** * Constructs a <code>MenuScroller</code> that scrolls a menu with the * specified number of items to display in the scrolling region, the * specified scrolling interval, and the specified numbers of items fixed at * the top and bottom of the menu. * * @param menu the menu * @param scrollCount the number of items to display in the scrolling portion * @param interval the scroll interval, in milliseconds * @param topFixedCount the number of items to fix at the top. May be 0 * @param bottomFixedCount the number of items to fix at the bottom. May be 0 * @throws IllegalArgumentException if scrollCount or interval is 0 or * negative or if topFixedCount or bottomFixedCount is negative */ public MenuScroller(JMenu menu, int scrollCount, int interval, int topFixedCount, int bottomFixedCount) { this(menu.getPopupMenu(), scrollCount, interval, topFixedCount, bottomFixedCount); } /** * Constructs a <code>MenuScroller</code> that scrolls a popup menu with the * specified number of items to display in the scrolling region, the * specified scrolling interval, and the specified numbers of items fixed at * the top and bottom of the popup menu. * * @param menu the popup menu * @param scrollCount the number of items to display in the scrolling portion * @param interval the scroll interval, in milliseconds * @param topFixedCount the number of items to fix at the top. May be 0 * @param bottomFixedCount the number of items to fix at the bottom. May be 0 * @throws IllegalArgumentException if scrollCount or interval is 0 or * negative or if topFixedCount or bottomFixedCount is negative */ public MenuScroller(JPopupMenu menu, int scrollCount, int interval, int topFixedCount, int bottomFixedCount) { if (scrollCount <= 0 || interval <= 0) { throw new IllegalArgumentException("scrollCount and interval must be greater than 0"); } if (topFixedCount < 0 || bottomFixedCount < 0) { throw new IllegalArgumentException("topFixedCount and bottomFixedCount cannot be negative"); } upItem = new MenuScrollItem(MenuIcon.UP, -1); downItem = new MenuScrollItem(MenuIcon.DOWN, +1); setScrollCount(scrollCount); setInterval(interval); setTopFixedCount(topFixedCount); setBottomFixedCount(bottomFixedCount); this.menu = menu; menu.addPopupMenuListener(menuListener); } /** * Returns the scroll interval in milliseconds * * @return the scroll interval in milliseconds */ public int getInterval() { return interval; } /** * Sets the scroll interval in milliseconds * * @param interval the scroll interval in milliseconds * @throws IllegalArgumentException if interval is 0 or negative */ public void setInterval(int interval) { if (interval <= 0) { throw new IllegalArgumentException("interval must be greater than 0"); } upItem.setInterval(interval); downItem.setInterval(interval); this.interval = interval; } /** * Returns the number of items in the scrolling portion of the menu. * * @return the number of items to display at a time */ public int getscrollCount() { return scrollCount; } /** * Sets the number of items in the scrolling portion of the menu. * * @param scrollCount the number of items to display at a time * @throws IllegalArgumentException if scrollCount is 0 or negative */ public void setScrollCount(int scrollCount) { if (scrollCount <= 0) { throw new IllegalArgumentException("scrollCount must be greater than 0"); } this.scrollCount = scrollCount; MenuSelectionManager.defaultManager().clearSelectedPath(); } /** * Returns the number of items fixed at the top of the menu or popup menu. * * @return the number of items */ public int getTopFixedCount() { return topFixedCount; } /** * Sets the number of items to fix at the top of the menu or popup menu. * * @param topFixedCount the number of items */ public void setTopFixedCount(int topFixedCount) { if (firstIndex <= topFixedCount) { firstIndex = topFixedCount; } else { firstIndex += (topFixedCount - this.topFixedCount); } this.topFixedCount = topFixedCount; } /** * Returns the number of items fixed at the bottom of the menu or popup menu. * * @return the number of items */ public int getBottomFixedCount() { return bottomFixedCount; } /** * Sets the number of items to fix at the bottom of the menu or popup menu. * * @param bottomFixedCount the number of items */ public void setBottomFixedCount(int bottomFixedCount) { this.bottomFixedCount = bottomFixedCount; } /** * Scrolls the specified item into view each time the menu is opened. Call this method with * <code>null</code> to restore the default behavior, which is to show the menu as it last * appeared. * * @param item the item to keep visible * @see #keepVisible(int) */ public void keepVisible(JMenuItem item) { if (item == null) { keepVisibleIndex = -1; } else { int index = menu.getComponentIndex(item); keepVisibleIndex = index; } } /** * Scrolls the item at the specified index into view each time the menu is opened. Call this * method with <code>-1</code> to restore the default behavior, which is to show the menu as * it last appeared. * * @param index the index of the item to keep visible * @see #keepVisible(javax.swing.JMenuItem) */ public void keepVisible(int index) { keepVisibleIndex = index; } /** * Removes this MenuScroller from the associated menu and restores the * default behavior of the menu. */ public void dispose() { if (menu != null) { menu.removePopupMenuListener(menuListener); menu = null; } } /** * Ensures that the <code>dispose</code> method of this MenuScroller is * called when there are no more refrences to it. * * @exception Throwable if an error occurs. * @see MenuScroller#dispose() */ @Override public void finalize() throws Throwable { dispose(); } private void refreshMenu() { if (menuItems != null && menuItems.length > 0) { firstIndex = Math.max(topFixedCount, firstIndex); firstIndex = Math.min(menuItems.length - bottomFixedCount - scrollCount, firstIndex); upItem.setEnabled(firstIndex > topFixedCount); downItem.setEnabled(firstIndex + scrollCount < menuItems.length - bottomFixedCount); menu.removeAll(); for (int i = 0; i < topFixedCount; i++) { menu.add(menuItems[i]); } if (topFixedCount > 0) { menu.addSeparator(); } menu.add(upItem); for (int i = firstIndex; i < scrollCount + firstIndex; i++) { menu.add(menuItems[i]); } menu.add(downItem); if (bottomFixedCount > 0) { menu.addSeparator(); } for (int i = menuItems.length - bottomFixedCount; i < menuItems.length; i++) { menu.add(menuItems[i]); } JComponent parent = (JComponent) upItem.getParent(); parent.revalidate(); parent.repaint(); } } private class MenuScrollListener implements PopupMenuListener { @Override public void popupMenuWillBecomeVisible(PopupMenuEvent e) { setMenuItems(); } @Override public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { restoreMenuItems(); } @Override public void popupMenuCanceled(PopupMenuEvent e) { restoreMenuItems(); } private void setMenuItems() { menuItems = menu.getComponents(); if (keepVisibleIndex >= topFixedCount && keepVisibleIndex <= menuItems.length - bottomFixedCount && (keepVisibleIndex > firstIndex + scrollCount || keepVisibleIndex < firstIndex)) { firstIndex = Math.min(firstIndex, keepVisibleIndex); firstIndex = Math.max(firstIndex, keepVisibleIndex - scrollCount + 1); } if (menuItems.length > topFixedCount + scrollCount + bottomFixedCount) { refreshMenu(); } } private void restoreMenuItems() { menu.removeAll(); for (Component component : menuItems) { menu.add(component); } } } private class MenuScrollTimer extends Timer { private static final long serialVersionUID = 1L; public MenuScrollTimer(final int increment, int interval) { super(interval, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { firstIndex += increment; refreshMenu(); } }); } } private class MenuScrollItem extends JMenuItem implements ChangeListener { private static final long serialVersionUID = 1L; private MenuScrollTimer timer; public MenuScrollItem(MenuIcon icon, int increment) { setIcon(icon); setDisabledIcon(icon); timer = new MenuScrollTimer(increment, interval); addChangeListener(this); } public void setInterval(int interval) { timer.setDelay(interval); } @Override public void stateChanged(ChangeEvent e) { if (isArmed() && !timer.isRunning()) { timer.start(); } if (!isArmed() && timer.isRunning()) { timer.stop(); } } } private static enum MenuIcon implements Icon { UP(9, 1, 9), DOWN(1, 9, 1); final int[] xPoints = {1, 5, 9}; final int[] yPoints; MenuIcon(int... yPoints) { this.yPoints = yPoints; } @Override public void paintIcon(Component c, Graphics g, int x, int y) { Dimension size = c.getSize(); Graphics g2 = g.create(size.width / 2 - 5, size.height / 2 - 5, 10, 10); g2.setColor(Color.GRAY); g2.drawPolygon(xPoints, yPoints, 3); if (c.isEnabled()) { g2.setColor(Color.BLACK); g2.fillPolygon(xPoints, yPoints, 3); } g2.dispose(); } @Override public int getIconWidth() { return 0; } @Override public int getIconHeight() { return 10; } } }
Java
/*--------------------------------------------------------------------------* | 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.gui.toolkit; import java.awt.Component; import java.util.ArrayList; import java.util.Iterator; import javax.swing.JMenuBar; public class RaplaMenubar extends JMenuBar { private static final long serialVersionUID = 1L; public RaplaMenubar() { super(); } /** returns -1 if there is no */ private int getIndexOfEntryWithId(String id) { int size = getComponentCount(); for ( int i=0;i< size;i++) { Component component = getComponent( i ); if ( component instanceof IdentifiableMenuEntry) { IdentifiableMenuEntry comp = (IdentifiableMenuEntry) component; if ( id != null && id.equals( comp.getId() ) ) { return i; } } } return -1; } public void insertAfterId(String id,Component component) { int index = getIndexOfEntryWithId( id ) + 1; insert( component, index); } public void insertBeforeId(String id,Component component) { int index = getIndexOfEntryWithId( id ); insert( component, index); } private void insert(Component component, int index) { int size = getComponentCount(); ArrayList<Component> list = new ArrayList<Component>(); // save the components begining with index for (int i = index ; i < size; i++) { list.add( getComponent(index) ); } // now remove all components begining with index for (int i = index ; i < size; i++) { remove(index); } // now add the new component add( component ); // and the removed components for (Iterator<Component> it = list.iterator();it.hasNext();) { add( it.next() ); } } }
Java
/*--------------------------------------------------------------------------* | 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.gui.toolkit; import javax.swing.JComponent; /** Should be implemented by all rapla-gui-components that have a view.*/ public interface RaplaWidget { public JComponent getComponent(); }
Java
/*--------------------------------------------------------------------------* | 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.gui.toolkit; import java.util.ArrayList; import java.util.Arrays; import java.util.Random; /** WARNING: This class is about to change its API. Dont use it */ final public class RaplaColors { private final static String[] COLORS= { /* * using hex codes of colorsis easier than using * the Color constructor with separated r, g and b values * * thus we decided to use the getColorForHex method * which takes a hex String and returns a new Color object * * in the end this is an array of seven different colors * */ "#a3ddff", // light blue "#b5e97e", // light green "#ffb85e", // orange "#b099dc", // violet "#cccccc", // light grey "#fef49d", // yellow "#fc9992", // red }; public final static String DEFAULT_COLOR_AS_STRING = COLORS[0]; private static ArrayList<String> colors = new ArrayList<String>(Arrays.asList(COLORS)); private static Random randomA = null; private static Random randomB = null; static private float rndA() { if (randomA == null) randomA = new Random(7913); return (float) (0.45 + randomA.nextFloat()/2.0); } static float rndB() { if (randomB == null) randomB = new Random(5513); return (float) (0.4 + randomB.nextFloat()/2.0); } final static public String getResourceColor(int nr) { if (colors.size()<=nr) { int fillSize = nr - colors.size() + 1; for (int i=0;i<fillSize;i++) { int r = (int) ((float) (0.1 + rndA() /1.1) * 255); int g = (int) (rndA() * 255); int b = (int) (rndA() * 255); String color = getHex( r , g, b); colors.add ( color); } } return colors.get(nr); } private final static String[] APPOINTMENT_COLORS= { "#eeeecc", "#cc99cc", "#adaca2", "#ccaa66", "#ccff88" }; static ArrayList<String> appointmentColors = new ArrayList<String>(Arrays.asList(APPOINTMENT_COLORS)); final static public String getAppointmentColor(int nr) { if (appointmentColors.size()<=nr) { int fillSize = nr - appointmentColors.size() + 1; for (int i=0;i<fillSize;i++) { int r = (int) ((float) (0.1 + rndB() /1.1) * 255); int g = (int) (rndB() * 255); int b = (int) (rndB() * 255); String color = getHex( r , g, b); appointmentColors.add( color ); } } return appointmentColors.get(nr); } public static String getHex(int r, int g, int b) { StringBuffer buf = new StringBuffer(); buf.append("#"); printHex( buf, r, 2 ); printHex( buf, g, 2 ); printHex( buf, b, 2 ); return buf.toString(); } /** Converts int to hex string. If the resulting string is smaller than size, * it will be filled with leading zeros. Example: * <code>printHex( buf,10, 2 )</code> appends "0A" to the string buffer.*/ static void printHex(StringBuffer buf,int value,int size) { String hexString = Integer.toHexString(value); int fill = size - hexString.length(); if (fill>0) { for (int i=0;i<fill;i ++) buf.append('0'); } buf.append(hexString); } static int decode(String value) { int result = 0; int basis = 1; for ( int i=value.length()-1;i>=0;i --) { char c = value.charAt( i ); int number; if ( c >= '0' && c<='9') { number = c - '0'; } else if ( c >= 'A' && c<='F') { number = (c - 'A') + 10; } else { throw new NumberFormatException("Can't parse HexValue " + value); } result += number * basis; basis = basis * 16; } return result; } }
Java
/*--------------------------------------------------------------------------* | 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.gui.toolkit; import java.awt.Point; import java.util.EventObject; public class PopupEvent extends EventObject { private static final long serialVersionUID = 1L; Point m_point; Object m_selectedObject; public PopupEvent(Object source, Object selectedObject, Point p) { super(source); m_selectedObject = selectedObject; m_point = p; } public Object getSelectedObject() { return m_selectedObject; } public Point getPoint() { return m_point; } }
Java
package org.rapla.gui.toolkit; import javax.swing.MenuElement; /** Adds an id to the standard Swing Menu Component as JSeperator, JMenuItem and JMenu*/ public interface IdentifiableMenuEntry { String getId(); MenuElement getMenuElement(); }
Java
/*--------------------------------------------------------------------------* | 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.gui.toolkit; import java.net.URL; import javax.swing.JTextPane; final public class HTMLView extends JTextPane { private static final long serialVersionUID = 1L; public HTMLView() { setOpaque(false); setEditable(false); setContentType("text/html"); setDefaultDocBase(); } public static String DEFAULT_STYLE = "body {font-family:SansSerif;font-size:12;}\n" + ".infotable{padding:0px;margin:0px;}\n" + ".label {vertical-align:top;}\n" + ".value {vertical-align:top;}\n" ; private static URL base; private static Exception error = null; /** will only work for resources inside the same jar as org/rapla/gui/images/repeating.png */ private void setDefaultDocBase() { if (base == null && error == null) { try { String marker = "org/rapla/gui/images/repeating.png"; URL url= HTMLView.class.getClassLoader().getResource(marker); if (url == null) { System.err.println("Marker not found " + marker); return; } //System.out.println("resource:" + url); String urlPath = url.toString(); base = new URL(urlPath.substring(0,urlPath.lastIndexOf(marker))); //System.out.println("document-base:" + base); } catch (Exception ex) { error = ex; System.err.println("Can't get document-base: " + ex + " in class: " + HTMLView.class.getName()); } } if (error == null) ((javax.swing.text.html.HTMLDocument)getDocument()).setBase(base); } /** calls setText(createHTMLPage(body)) */ public void setBody(String body) { try { setText(createHTMLPage(body)); } catch (Exception ex) { setText(body); } } static public String createHTMLPage(String body,String styles) { StringBuffer buf = new StringBuffer(); buf.append("<html>"); buf.append("<head>"); buf.append("<style type=\"text/css\">"); buf.append(styles); buf.append("</style>"); buf.append("</head>"); buf.append("<body>"); buf.append(body); buf.append("</body>"); buf.append("</html>"); return buf.toString(); } static public String createHTMLPage(String body) { return createHTMLPage(body,DEFAULT_STYLE); } public void setText( String message, boolean packText ) { if (packText) { JEditorPaneWorkaround.packText(this, message ,600); } else { setText( message); } } }
Java
/*--------------------------------------------------------------------------* | 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.gui.toolkit; import java.awt.AWTEvent; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Container; import java.awt.Dialog; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.GridLayout; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.awt.event.WindowEvent; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.Icon; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.KeyStroke; import javax.swing.LayoutFocusTraversalPolicy; 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.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; public class DialogUI extends JDialog implements FrameController ,LocaleChangeListener { private static final long serialVersionUID = 1L; protected RaplaButton[] buttons; protected JComponent content; private JPanel jPanelButtonFrame = new JPanel(); private JLabel label = null; private boolean useDefaultOptions = false; private boolean bClosed = false; private Component parent; private int selectedIndex = -1; private FrameControllerList frameList = null; protected boolean packFrame = true; private LocaleSelector localeSelector; private I18nBundle i18n; private RaplaContext context = null; private ButtonListener buttonListener = new ButtonListener(); private boolean m_modal; private Action abortAction = new AbstractAction() { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent evt) { close(); } }; public static Component getOwnerWindow(Component component) { if (component == null) return getInvisibleSharedFrame(); if (component instanceof Dialog) return component; if (component instanceof Frame) return component; Container owner = component.getParent(); return getOwnerWindow(owner); } private static String[] getDefaultOptions() { return new String[] {"OK"}; } public DialogUI(RaplaContext sm, Dialog parent) throws RaplaException { super( parent ); service( sm ); } public DialogUI(RaplaContext sm, Frame parent) throws RaplaException { super( parent ); service( sm ); } /** @see #getInvisibleSharedFrame */ private static JFrame invisibleSharedFrame; /** @see #getInvisibleSharedFrame */ private static int referenceCounter = 0; /** If a dialogs owner is null this frame will be used as owner. A call to this method will increase the referenceCounter. A new shared frame is created when the referenceCounter is 1. The frame gets disposed if the refernceCounter is 0. The referenceCounter is decreased in the dispose method. */ private static Frame getInvisibleSharedFrame() { referenceCounter ++; if (referenceCounter == 1) { invisibleSharedFrame = new JFrame(); invisibleSharedFrame.setSize(400,400); FrameControllerList.centerWindowOnScreen(invisibleSharedFrame); } return invisibleSharedFrame; } public static DialogUI create(RaplaContext context,Component owner,boolean modal,JComponent content,String[] options) throws RaplaException { DialogUI dlg; Component topLevel = getOwnerWindow(owner); if ( topLevel instanceof Dialog) dlg = new DialogUI(context,(Dialog)topLevel); else dlg = new DialogUI(context,(Frame)topLevel); dlg.parent = owner; dlg.init(modal,content,options); return dlg; } public static DialogUI create(RaplaContext context,Component owner,boolean modal,String title,String text,String[] options) throws RaplaException { DialogUI dlg= create(context,owner,modal,new JPanel(),options); dlg.createMessagePanel(text); dlg.setTitle(title); return dlg; } public static DialogUI create(RaplaContext context,Component owner,boolean modal,String title,String text) throws RaplaException { DialogUI dlg = create(context,owner,modal,title,text,getDefaultOptions()); dlg.useDefaultOptions = true; return dlg; } public RaplaButton getButton(int index) { return buttons[index]; } protected void init(boolean modal,JComponent content,String[] options) { super.setModal(modal); m_modal = modal; this.setFocusTraversalPolicy( new LayoutFocusTraversalPolicy() { private static final long serialVersionUID = 1L; protected boolean accept(Component component) { return !(component instanceof HTMLView) ; } } ); this.content = content; this.enableEvents(AWTEvent.WINDOW_EVENT_MASK); JPanel contentPane = (JPanel) this.getContentPane(); contentPane.setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); contentPane.setLayout(new BorderLayout()); contentPane.add(content, BorderLayout.CENTER); contentPane.add(jPanelButtonFrame,BorderLayout.SOUTH); jPanelButtonFrame.setLayout(new FlowLayout(FlowLayout.CENTER)); setButtons(options); contentPane.setVisible(true); /* We enable the escape-key for executing the abortCmd. Many thanks to John Zukowski. <a href="http://www.javaworld.com/javaworld/javatips/jw-javatip72.html">Java-Tip 72</a> */ KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); contentPane.getActionMap().put("abort",buttonListener); contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(stroke,"abort"); } protected void setButtons(String[] options) { buttons = new RaplaButton[options.length]; for (int i=0;i<options.length;i++) { buttons[i] = new RaplaButton(options[i],RaplaButton.DEFAULT); buttons[i].addActionListener(buttonListener); buttons[i].setAction(abortAction); buttons[i].setDefaultCapable(true); } jPanelButtonFrame.removeAll(); jPanelButtonFrame.add(createButtonPanel()); if (options.length>0) setDefault(0); jPanelButtonFrame.invalidate(); } protected JComponent createButtonPanel() { GridLayout gridLayout = new GridLayout(); JPanel jPanelButtons = new JPanel(); jPanelButtons.setLayout(gridLayout); gridLayout.setRows(1); gridLayout.setHgap(10); gridLayout.setVgap(5); gridLayout.setColumns(buttons.length); for (int i=0;i<buttons.length;i++) { jPanelButtons.add(buttons[i]); } return jPanelButtons; } class ButtonListener extends AbstractAction { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent evt) { for (int i=0;i<buttons.length;i++) { if (evt.getSource() == buttons[i]) { selectedIndex = i; return; } } selectedIndex = -1; abortAction.actionPerformed(new ActionEvent(DialogUI.this, ActionEvent.ACTION_PERFORMED,"")); } } public int getSelectedIndex() { return selectedIndex; } public void setAbortAction(Action action) { abortAction = action; } private void service(RaplaContext context) throws RaplaException { this.context = context; i18n = context.lookup(RaplaComponent.RAPLA_RESOURCES); if (useDefaultOptions) { if (buttons.length > 1) { getButton(0).setText(i18n.getString("ok")); getButton(1).setIcon(i18n.getIcon("icon.abort")); getButton(1).setText(i18n.getString("abort")); } else { getButton(0).setText(i18n.getString("ok")); } } localeSelector = context.lookup( LocaleSelector.class); localeSelector.addLocaleChangeListener(this); frameList = context.lookup(FrameControllerList.class); frameList.add(this); } protected I18nBundle getI18n() { return i18n; } protected RaplaContext getContext() { return context; } /** the default implementation does nothing. Override this method if you want to react on a locale change.*/ public void localeChanged(LocaleChangeEvent evt) { } public void setIcon(Icon icon) { try { if (label != null) label.setIcon(icon); } catch (Exception ex) { } } FrameControllerList getFrameList() { return frameList; } /** close and set the selectedIndex to the index Value. Usefull for modal dialogs*/ public void close(int index) { selectedIndex = index; close(); } // The implementation of the FrameController Interface public void close() { if (bClosed) return; dispose(); } public void dispose() { bClosed = true; try { if (getOwner() == invisibleSharedFrame) referenceCounter --; super.dispose(); if (referenceCounter == 0 && invisibleSharedFrame!= null) invisibleSharedFrame.dispose(); if (frameList != null) frameList.remove(this); if ( localeSelector != null ) localeSelector.removeLocaleChangeListener(this); } catch (Exception ex) { ex.printStackTrace(); } } // The implementation of the DialogController Interface public void setDefault(int index) { this.getRootPane().setDefaultButton(getButton(index)); } public void setTitle(String title) { super.setTitle(title); } public boolean isClosed() { return bClosed; } public void start(Point p) { //Validate frames that have preset sizes //Pack frames that have useful preferred size info, e.g. from their layout if (packFrame) { this.pack(); } else { this.validate(); } if (parent != null) { FrameControllerList.placeRelativeToComponent(this,parent,p); } else { getFrameList().placeRelativeToMain(this); } if ( initFocusComponent != null) { initFocusComponent.requestFocus(); } // okButton.requestFocus(); bClosed = false; super.setVisible( true ); if (m_modal) { dispose(); } } Component initFocusComponent; public void setInitFocus(Component component) { initFocusComponent = component; } public void start() { start(null); } public void startNoPack() { packFrame = false; start(null); } protected void processWindowEvent(WindowEvent e) { if (e.getID() == WindowEvent.WINDOW_CLOSING) { abortAction.actionPerformed(new ActionEvent(this,ActionEvent.ACTION_PERFORMED,"")); } else if (e.getID() == WindowEvent.WINDOW_CLOSED) { close(); } } private void createMessagePanel(String text) { JPanel panel = (JPanel) content; panel.setLayout(new BoxLayout(panel,BoxLayout.X_AXIS)); label = new JLabel(); HTMLView textView = new HTMLView(); JEditorPaneWorkaround.packText(textView, HTMLView.createHTMLPage(text) ,450); JPanel jContainer = new JPanel(); jContainer.setLayout(new BorderLayout()); panel.add(jContainer); jContainer.add(label,BorderLayout.NORTH); panel.add(textView); } }
Java
/*--------------------------------------------------------------------------* | 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.gui.toolkit; import java.awt.AWTEvent; import java.awt.event.WindowEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyVetoException; import java.beans.VetoableChangeListener; import java.util.ArrayList; import javax.swing.JFrame; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; public class RaplaFrame extends JFrame implements FrameController { private static final long serialVersionUID = 1L; FrameControllerList frameList = null; ArrayList<VetoableChangeListener> listenerList = new ArrayList<VetoableChangeListener>(); /** This frame registers itself on the FrameControllerList on <code>contextualzize</code> and unregisters upon <code>dispose()</code>. Use addVetoableChangeListener() to get notified on a window-close event (and throw a veto if necessary. * @throws RaplaException */ public RaplaFrame(RaplaContext sm) throws RaplaException { enableEvents(AWTEvent.WINDOW_EVENT_MASK); /* AWTAdapterFactory fact = AWTAdapterFactory.getFactory(); if (fact != null) { fact.createFocusAdapter( this ).ignoreFocusComponents(new FocusTester() { public boolean accept(Component component) { return !(component instanceof HTMLView) ; } }); }*/ frameList = sm.lookup(FrameControllerList.class); frameList.add(this); } protected void processWindowEvent(WindowEvent e) { if (e.getID() == WindowEvent.WINDOW_CLOSING) { try { fireFrameClosing(); close(); } catch (PropertyVetoException ex) { return; } } super.processWindowEvent(e); } public void addVetoableChangeListener(VetoableChangeListener listener) { listenerList.add(listener); } public void removeVetoableChangeListener(VetoableChangeListener listener) { listenerList.remove(listener); } public VetoableChangeListener[] getVetoableChangeListeners() { return listenerList.toArray(new VetoableChangeListener[]{}); } protected void fireFrameClosing() throws PropertyVetoException { if (listenerList.size() == 0) return; // The propterychange event indicates that the window // is closing. PropertyChangeEvent evt = new PropertyChangeEvent( this ,"visible" ,new Boolean(true) ,new Boolean(false) ) ; VetoableChangeListener[] listeners = getVetoableChangeListeners(); for (int i = 0;i<listeners.length; i++) { listeners[i].vetoableChange(evt); } } final public void place(boolean placeRelativeToMain,boolean packFrame) { //Validate frames that have preset sizes //Pack frames that have useful preferred size info, e.g. from their layout if (packFrame) { this.pack(); } else { this.validate(); } if (placeRelativeToMain) frameList.placeRelativeToMain(this); } public void dispose() { super.dispose(); frameList.remove(this); } public void close() { dispose(); } }
Java
/*--------------------------------------------------------------------------* | 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.gui.toolkit; import java.util.Locale; import javax.swing.DefaultComboBoxModel; import javax.swing.JComboBox; import org.rapla.components.calendarview.MonthMapper; /** ComboBox that displays the month in long format */ public final class MonthChooser extends JComboBox { private static final long serialVersionUID = 1L; MonthMapper mapper; public MonthChooser() { this( Locale.getDefault() ); } public MonthChooser( Locale locale ) { setLocale( locale ); } @SuppressWarnings("unchecked") public void setLocale( Locale locale ) { super.setLocale( locale ); if ( locale == null ) return; mapper = new MonthMapper( locale ); DefaultComboBoxModel aModel = new DefaultComboBoxModel( mapper.getNames() ); setModel( aModel ); } public void selectMonth( int month ) { setSelectedIndex( month ); } /** returns the selected day or -1 if no day is selected. @see java.util.Calendar */ public int getSelectedMonth() { if ( getSelectedIndex() == -1 ) return -1; else return getSelectedIndex(); } }
Java
/*--------------------------------------------------------------------------* | 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.gui.toolkit; import java.util.Locale; import javax.swing.DefaultComboBoxModel; import javax.swing.JComboBox; import org.rapla.components.calendarview.WeekdayMapper; /** ComboBox that displays the weekdays in long format @see WeekdayMapper */ public final class WeekdayChooser extends JComboBox { private static final long serialVersionUID = 1L; WeekdayMapper mapper; public WeekdayChooser() { this( Locale.getDefault() ); } public WeekdayChooser(Locale locale) { setLocale(locale); } @SuppressWarnings("unchecked") public void setLocale(Locale locale) { super.setLocale(locale); if (locale == null) return; mapper = new WeekdayMapper(locale); DefaultComboBoxModel aModel = new DefaultComboBoxModel(mapper.getNames()); setModel(aModel); } public void selectWeekday(int weekday) { setSelectedIndex(mapper.indexForDay(weekday)); } /** returns the selected day or -1 if no day is selected. @see java.util.Calendar */ public int getSelectedWeekday() { if (getSelectedIndex() == -1) return -1; else return mapper.dayForIndex(getSelectedIndex()); } }
Java
/*--------------------------------------------------------------------------* | 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.gui.toolkit; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.lang.reflect.Method; import javax.swing.DefaultListModel; import javax.swing.JCheckBox; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; final public class ErrorDialog extends RaplaComponent { /** * @param context * @throws RaplaException */ public ErrorDialog(RaplaContext context) throws RaplaException { super(context); } public static final int WARNING_MESSAGE = 1; public static final int ERROR_MESSAGE = 2; public static final int EXCEPTION_MESSAGE = 3; /** This is for the test-cases only. If this flag is set the ErrorDialog throws an ErrorDialogException instead of displaying the dialog. This is useful for testing. */ public static boolean THROW_ERROR_DIALOG_EXCEPTION = false; private void test(String message,int type) { if (THROW_ERROR_DIALOG_EXCEPTION) { throw new ErrorDialogException(new RaplaException(message),type); } } private void test(Throwable ex,int type) { if (THROW_ERROR_DIALOG_EXCEPTION) { throw new ErrorDialogException(ex,type); } } private String createTitle(String key) { return getI18n().format("exclamation.format",getI18n().getString(key)); } public void show(String message) { test(message,ERROR_MESSAGE); try { showDialog(createTitle("error"),message,null); } catch (Exception ex) { getLogger().error(message); } } public void showWarningDialog(String message,Component owner) { test(message,WARNING_MESSAGE); try { showWarningDialog(createTitle("warning"),message,owner); } catch (Exception ex) { getLogger().error(message); } } static private String getCause(Throwable e) { String message = e.getMessage(); if (message != null && message.length() > 0) { return message; } Throwable cause = e.getCause(); if (cause != null) message = getCause( cause ); return message; } static public String getMessage(Throwable e) { String message = getCause(e); if (message == null || message.length() == 0) message = e.toString(); return message; } public void showExceptionDialog(Throwable e,Component owner) { test(e,EXCEPTION_MESSAGE); try { String message = getMessage(e); if ( getLogger() != null ) getLogger().error(message, e); JPanel component = new JPanel(); component.setLayout( new BorderLayout()); HTMLView textView = new HTMLView(); JEditorPaneWorkaround.packText(textView, HTMLView.createHTMLPage(message) ,450); component.add( textView,BorderLayout.NORTH); boolean showStacktrace = true; Throwable nestedException = e; do { if ( nestedException instanceof RaplaException) { showStacktrace = false; nestedException = ((RaplaException) nestedException).getCause(); } else { showStacktrace = true; } } while ( nestedException != null && !showStacktrace); if ( showStacktrace) { try { Method getStackTrace =Exception.class.getMethod("getStackTrace",new Class[] {}); final Object[] stackTrace = (Object[])getStackTrace.invoke( e, new Object[] {} ); final JList lister = new JList( ); final JScrollPane list = new JScrollPane(lister, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); list.setBorder( null); JPanel stackTracePanel = new JPanel(); final JCheckBox stackTraceChooser = new JCheckBox("show stacktrace"); stackTracePanel.setLayout( new BorderLayout()); stackTracePanel.add( stackTraceChooser, BorderLayout.NORTH); stackTracePanel.add( list, BorderLayout.CENTER); stackTracePanel.setPreferredSize( new Dimension(300,200)); stackTracePanel.setMinimumSize( new Dimension(300,200)); component.add( stackTracePanel,BorderLayout.CENTER); lister.setVisible( false ); stackTraceChooser.addActionListener( new ActionListener() { @SuppressWarnings("unchecked") public void actionPerformed(ActionEvent e) { DefaultListModel model =new DefaultListModel(); if (stackTraceChooser.isSelected() ) { for ( int i=0;i< stackTrace.length;i++) { model.addElement( stackTrace[i]); } } lister.setModel( model ); lister.setVisible( stackTraceChooser.isSelected()); } }); } catch (Exception ex) { } } DialogUI dlg = DialogUI.create(getContext(),owner,true,component, new String[] {getI18n().getString("ok")}); dlg.setTitle(createTitle("error")); dlg.setIcon(getI18n().getIcon("icon.error")); dlg.start(); } catch (Exception ex) { getLogger().error( e.getMessage(), e); getLogger().error("Can't show errorDialog " + ex); } } private void showDialog(String title, String message,Component owner) { try { DialogUI dlg = DialogUI.create(getContext(),owner,true,title,message); dlg.setIcon(getI18n().getIcon("icon.error")); dlg.start(); } catch (Exception ex2) { getLogger().error(ex2.getMessage()); } } public void showWarningDialog(String title, String message,Component owner) { try { DialogUI dlg = DialogUI.create(getContext(),owner,true,title,message); dlg.setIcon(getI18n().getIcon("icon.warning")); dlg.start(); } catch (Exception ex2) { getLogger().error(ex2.getMessage()); } } }
Java
package org.rapla.gui.toolkit; import java.awt.Component; import javax.swing.JComponent; import javax.swing.JMenuItem; /** JPopupMenu and JMenu don't have a common interface, so this is a common interface * for RaplaMenu and RaplaPopupMenu */ public interface MenuInterface { JMenuItem add(JMenuItem item); void remove(JMenuItem item); void addSeparator(); void removeAll(); void removeAllBetween(String startId, String endId); void insertAfterId(Component component,String id); void insertBeforeId(JComponent component,String id); }
Java
/*--------------------------------------------------------------------------* | 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.gui.toolkit; import java.awt.Component; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import javax.swing.JSeparator; import javax.swing.MenuElement; import javax.swing.MenuSelectionManager; public class RaplaSeparator extends JSeparator implements IdentifiableMenuEntry, MenuElement { private static final long serialVersionUID = 1L; String id; public RaplaSeparator(String id) { super(); this.id = id; } public String getId() { return id; } public MenuElement getMenuElement() { return this; } public void processMouseEvent(MouseEvent event, MenuElement[] path, MenuSelectionManager manager) { } public void processKeyEvent(KeyEvent event, MenuElement[] path, MenuSelectionManager manager) { } public void menuSelectionChanged(boolean isIncluded) { } public MenuElement[] getSubElements() { return new MenuElement[] {}; } public Component getComponent() { return this; } }
Java
/*--------------------------------------------------------------------------* | 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.gui.toolkit; import java.awt.Component; import javax.swing.JComponent; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; public class RaplaPopupMenu extends JPopupMenu implements MenuInterface { private static final long serialVersionUID = 1L; public RaplaPopupMenu() { super(); } private int getIndexOfEntryWithId(String id) { int size = getComponentCount(); for ( int i=0;i< size;i++) { Component component = getComponent( i ); if ( component instanceof IdentifiableMenuEntry) { IdentifiableMenuEntry comp = (IdentifiableMenuEntry) component; if ( id != null && id.equals( comp.getId() ) ) { return i; } } } return -1; } public void removeAllBetween(String startId, String endId) { int startIndex = getIndexOfEntryWithId( startId ); int endIndex = getIndexOfEntryWithId( endId); if ( startIndex < 0 || endIndex < 0 ) return; for ( int i= startIndex + 1; i< endIndex ;i++) { remove( startIndex ); } } public void insertAfterId(Component component,String id) { if ( id == null) { add ( component ); } else { int index = getIndexOfEntryWithId( id ) ; insert( component, index +1); } } public void insertBeforeId(JComponent component,String id) { int index = getIndexOfEntryWithId( id ); insert( component, index); } public void remove( JMenuItem item ) { super.remove( item ); } }
Java
/*--------------------------------------------------------------------------* | 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.gui.toolkit; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dialog; import java.awt.Dimension; import java.awt.Frame; import javax.swing.ActionMap; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.JPanel; import org.rapla.components.layout.TableLayout; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; /** displays a wizard dialog with four buttons and a HTML help. */ public class WizardDialog extends DialogUI { private static final long serialVersionUID = 1L; protected WizardPanel wizardPanel; protected HTMLView helpView; static public String[] options = new String[] { WizardPanel.ABORT ,WizardPanel.PREV ,WizardPanel.NEXT ,WizardPanel.FINISH }; public static WizardDialog createWizard(RaplaContext sm,Component owner,boolean modal) throws RaplaException { WizardDialog dlg; Component topLevel = getOwnerWindow(owner); if (topLevel instanceof Dialog) dlg = new WizardDialog(sm,(Dialog)topLevel); else dlg = new WizardDialog(sm,(Frame)topLevel); dlg.init(modal); return dlg; } protected WizardDialog(RaplaContext sm,Dialog owner) throws RaplaException { super(sm,owner); } protected WizardDialog(RaplaContext sm,Frame owner) throws RaplaException { super(sm,owner); } private void init(boolean modal) { super.init(modal, new JPanel(), options); content.setLayout(new BorderLayout()); helpView = new HTMLView(); helpView.setBorder( BorderFactory.createCompoundBorder( BorderFactory.createEmptyBorder(0,0,3,0) , BorderFactory.createCompoundBorder( BorderFactory.createEtchedBorder() ,BorderFactory.createEmptyBorder(4,4,4,4) ) ) ); helpView.setOpaque(true); content.add(helpView,BorderLayout.WEST); helpView.setPreferredSize(new Dimension(220,300)); packFrame=false; } protected JComponent createButtonPanel() { TableLayout tableLayout = new TableLayout(new double[][] { {10,0.2,10,0.2,5,0.4,10,0.2,10} ,{5,TableLayout.PREFERRED,5} }); JPanel jPanelButtons = new JPanel(); jPanelButtons.setLayout(tableLayout); jPanelButtons.add(buttons[0],"1,1,l,c"); jPanelButtons.add(buttons[1],"3,1,r,c"); jPanelButtons.add(buttons[2],"5,1,l,c"); jPanelButtons.add(buttons[3],"7,1"); return jPanelButtons; } public WizardPanel getActivePanel() { return wizardPanel; } public void start(WizardPanel newPanel) { if (!isVisible()) start(); if (wizardPanel != null) content.remove(wizardPanel.getComponent()); wizardPanel = newPanel; if (wizardPanel == null) close(); content.add(wizardPanel.getComponent(),BorderLayout.CENTER); wizardPanel.getComponent().setBorder(BorderFactory.createEmptyBorder(0,4,0,4)); if (wizardPanel.getHelp() != null) helpView.setBody(wizardPanel.getHelp()); String defaultAction = wizardPanel.getDefaultAction(); content.revalidate(); content.repaint(); // set actions ActionMap actionMap = wizardPanel.getActionMap(); getButton(0).setAction(actionMap.get(WizardPanel.ABORT)); getButton(0).setActionCommand(WizardPanel.ABORT); if (defaultAction.equals(WizardPanel.ABORT)) setDefault(0); getButton(1).setAction(actionMap.get(WizardPanel.PREV)); getButton(1).setActionCommand(WizardPanel.PREV); if (defaultAction.equals(WizardPanel.PREV)) setDefault(1); getButton(2).setAction(actionMap.get(WizardPanel.NEXT)); getButton(2).setActionCommand(WizardPanel.NEXT); if (defaultAction.equals(WizardPanel.NEXT)) setDefault(2); getButton(3).setAction(actionMap.get(WizardPanel.FINISH)); getButton(3).setActionCommand(WizardPanel.FINISH); if (defaultAction.equals(WizardPanel.FINISH)) setDefault(3); } }
Java
/*--------------------------------------------------------------------------* | 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.gui.toolkit; import java.awt.Color; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Stack; import javax.swing.BorderFactory; import javax.swing.JScrollPane; import javax.swing.JTree; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeModel; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; import org.rapla.components.util.Tools; /** Encapsulates the complex tree class and provides some basic functionality like * life model exchanging while keeping the Tree state or the integration of the popup listener. */ final public class RaplaTree extends JScrollPane { private static final long serialVersionUID = 1L; ArrayList<PopupListener> m_popupListeners = new ArrayList<PopupListener>(); ArrayList<ActionListener> m_doubleclickListeners = new ArrayList<ActionListener>(); ArrayList<ChangeListener> m_changeListeners = new ArrayList<ChangeListener>(); JTree jTree = new JTree() { private static final long serialVersionUID = 1L; public String getToolTipText(MouseEvent evt) { if (toolTipRenderer == null) { return super.getToolTipText(evt); } int row = getRowForLocation(evt.getX(),evt.getY()); if (row >=0) { return toolTipRenderer.getToolTipText(this,row); } return super.getToolTipText(evt); } public Point getToolTipLocation(MouseEvent evt) { return new Point(getWidth(), 0); } /** * Overwrite the standard method for performance reasons. * * @see javax.swing.JTree#getExpandedDescendants(javax.swing.tree.TreePath) */ // @Override // public Enumeration getExpandedDescendants(final TreePath parent) { // return null; // } }; Listener listener = new Listener(); private boolean treeSelectionListenerBlocked = false; private boolean bMultiSelect = false; TreePath selectedPath = null; TreeToolTipRenderer toolTipRenderer; public RaplaTree() { jTree.setBorder( BorderFactory.createEtchedBorder(Color.white,new Color(178, 178, 178))); jTree.setRootVisible(false); jTree.setShowsRootHandles(true); //jTree.putClientProperty("JTree.lineStyle", "None"); getViewport().add(jTree, null); jTree.addTreeSelectionListener( listener ); jTree.addMouseListener( listener ); setMultiSelect(bMultiSelect); } public void setToolTipRenderer(TreeToolTipRenderer renderer) { toolTipRenderer = renderer; } public void addChangeListener(ChangeListener listener) { m_changeListeners.add(listener); } public void removeChangeListener(ChangeListener listener) { m_changeListeners.remove(listener); } /** An ChangeEvent will be fired to every registered ChangeListener * when the selection has changed. */ protected void fireValueChanged() { if (m_changeListeners.size() == 0) return; ChangeListener[] listeners = getChangeListeners(); ChangeEvent evt = new ChangeEvent(this); for (int i = 0;i<listeners.length;i++) { listeners[i].stateChanged(evt); } } public ChangeListener[] getChangeListeners() { return m_changeListeners.toArray(new ChangeListener[]{}); } public TreeToolTipRenderer getToolTipRenderer() { return toolTipRenderer; } public void addDoubleclickListeners(ActionListener listener) { m_doubleclickListeners.add(listener); } public void removeDoubleclickListeners(ActionListener listener) { m_doubleclickListeners.remove(listener); } public ActionListener[] getDoubleclickListeners() { return m_doubleclickListeners.toArray(new ActionListener[]{}); } public void addPopupListener(PopupListener listener) { m_popupListeners.add(listener); } public void removePopupListener(PopupListener listener) { m_popupListeners.remove(listener); } public PopupListener[] getPopupListeners() { return m_popupListeners.toArray(new PopupListener[]{}); } /** An PopupEvent will be fired to every registered PopupListener * when the popup is selected */ protected void firePopup(MouseEvent me) { Point p = new Point(me.getX(), me.getY()); if (m_popupListeners.size() == 0) return; PopupListener[] listeners = getPopupListeners(); Object selectedObject = null; TreePath path = getTree().getPathForLocation(p.x,p.y); if (path != null) { Object node = path.getLastPathComponent(); if (node != null) { if (node instanceof DefaultMutableTreeNode) selectedObject = ((DefaultMutableTreeNode)node).getUserObject(); } } Point upperLeft = getViewport().getViewPosition(); Point newPoint = new Point(p.x - upperLeft.x + 10 ,p.y-upperLeft.y); PopupEvent evt = new PopupEvent(this, selectedObject, newPoint); for (int i = 0;i<listeners.length;i++) { listeners[i].showPopup(evt); } } protected void fireEdit(MouseEvent me) { Point p = new Point(me.getX(), me.getY()); if (m_doubleclickListeners.size() == 0) return; ActionListener[] listeners = getDoubleclickListeners(); Object selectedObject = null; TreePath path = getTree().getPathForLocation(p.x,p.y); if (path != null) { Object node = path.getLastPathComponent(); if (node != null) { if (node instanceof DefaultMutableTreeNode) { selectedObject = ((DefaultMutableTreeNode)node).getUserObject(); } } } if (selectedObject != null) { ActionEvent evt = new ActionEvent( selectedObject, ActionEvent.ACTION_PERFORMED, ""); for (int i = 0;i<listeners.length;i++) { listeners[i].actionPerformed(evt); } } } public JTree getTree() { return jTree; } class Listener implements MouseListener,TreeSelectionListener { public void valueChanged(TreeSelectionEvent event) { if ( event.getSource() == jTree && ! treeSelectionListenerBlocked) { selectedPath = event.getNewLeadSelectionPath(); fireValueChanged(); } } public void mouseEntered(MouseEvent me) { } public void mouseExited(MouseEvent me) { } public void mousePressed(MouseEvent me) { if (me.isPopupTrigger()) firePopup(me); } public void mouseReleased(MouseEvent me) { if (me.isPopupTrigger()) firePopup(me); } public void mouseClicked(MouseEvent me) { TreePath selectionPath = jTree.getSelectionPath(); if (me.getClickCount() == 2 && selectionPath != null ) { final Object lastPathComponent = selectionPath.getLastPathComponent(); if ( lastPathComponent instanceof TreeNode) { if (( (TreeNode) lastPathComponent).isLeaf()) { fireEdit(me); } } // System.out.println("mouse Clicked > 1"); // System.out.println("Button= " + me.getButton() + "Cliks= " + me.getClickCount() + " " + me.getComponent().getClass().getName()); } } } public void setEnabled(boolean enabled) { jTree.setEnabled(enabled); } private Object getFromNode(TreeNode node) { if (node == null) return null; return getObject(node); } private Object getLastSelectedElement() { if (selectedPath != null) { TreeNode node = (TreeNode) selectedPath.getLastPathComponent(); return getFromNode(node); } else { return null; } } private static Object getObject(Object treeNode) { try { if (treeNode == null) return null; if (treeNode instanceof DefaultMutableTreeNode) return ((DefaultMutableTreeNode) treeNode).getUserObject(); return treeNode.getClass().getMethod("getUserObject",Tools.EMPTY_CLASS_ARRAY).invoke(treeNode, Tools.EMPTY_ARRAY); } catch (Exception ex) { return null; } } public void exchangeTreeModel(TreeModel model) { boolean notifySelection; try { treeSelectionListenerBlocked = true; notifySelection = exchangeTreeModel( model, jTree ) ; } finally { treeSelectionListenerBlocked = false; } if ( notifySelection ) { this.fireValueChanged(); } } public void exchangeTreeModel2(TreeModel model) { try { treeSelectionListenerBlocked = true; jTree.setModel(model); } finally { treeSelectionListenerBlocked = false; } } /** Exchanges the tree-model while trying to preserve the selection an expansion state. * Returns if the selection has been affected by the excahnge.*/ public static boolean exchangeTreeModel(TreeModel model,JTree tree) { Collection<Object> expanded = new LinkedHashSet<Object>(); Collection<Object> selected = new LinkedHashSet<Object>(); int rowCount = tree.getRowCount(); for (int i=0;i<rowCount;i++) { if (tree.isExpanded(i)) { Object obj = getObject( tree.getPathForRow(i).getLastPathComponent() ); if (obj != null ) expanded.add( obj ); } if (tree.isRowSelected(i)) { Object obj = getObject( tree.getPathForRow(i).getLastPathComponent() ); if (obj != null ) selected.add( obj ); } } tree.setModel(model); if ( model instanceof DefaultTreeModel ) { ((DefaultTreeModel)model).reload(); } if (expanded.size() ==0 && selected.size() == 0) { TreeNode root = (TreeNode)model.getRoot(); if (root.getChildCount()<2) { tree.expandRow(0); } } ArrayList<TreePath> selectedList = new ArrayList<TreePath>(); for (int i=0;i<rowCount;i++) { TreePath treePath = tree.getPathForRow(i); if (treePath != null) { Object obj = getObject( treePath.getLastPathComponent() ); if (obj == null) continue; if (expanded.contains( obj )) { expanded.remove( obj ); tree.expandRow(i); } if (selected.contains( obj )) { selected.remove( obj ); selectedList.add(treePath); } } } tree.setSelectionPaths(selectedList.toArray(new TreePath[selectedList.size()])); return selectedList.size() != selected.size(); } public void setMultiSelect(boolean bMultiSelect) { this.bMultiSelect = bMultiSelect; if ( bMultiSelect) { jTree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION); } else { jTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); } // end of else } public static class TreeIterator implements Iterator<TreeNode> { Stack<TreeNode> nodeStack = new Stack<TreeNode>(); public TreeIterator(TreeNode node) { nodeStack.push(node); } public boolean hasNext() { return !nodeStack.isEmpty(); } public TreeNode next() { TreeNode node = nodeStack.pop(); int count = node.getChildCount(); for (int i=count-1;i>=0;i--) { nodeStack.push(node.getChildAt(i)); } return node; } public void remove() { throw new UnsupportedOperationException(); } } private TreePath getPath(TreeNode node) { if (node.getParent() == null) return new TreePath(node); else return getPath(node.getParent()).pathByAddingChild(node); } public void select(Collection<Object> selectedObjects) { Collection<TreeNode> selectedNodes = new ArrayList<TreeNode>(); Collection<Object> selectedToRemove = new LinkedHashSet<Object>( ); selectedToRemove.addAll( selectedObjects); Iterator<TreeNode> it = new TreeIterator((TreeNode)jTree.getModel().getRoot()); while (it.hasNext()) { TreeNode node = it.next(); Object object = getObject(node); if (node != null && selectedToRemove.contains( object )) { selectedNodes.add(node); selectedToRemove.remove( object); } } TreePath[] path = new TreePath[selectedNodes.size()]; int i=0; it = selectedNodes.iterator(); while (it.hasNext()) { path[i] = getPath(it.next()); jTree.expandPath(path[i]); i++; } jTree.setSelectionPaths(path); } public Object getSelectedElement() { Collection<Object> col = getSelectedElements(); if ( col.size()>0) { return col.iterator().next(); } else { return null; } // end of else } public List<Object> getSelectedElements() { return getSelectedElements( false); } public List<Object> getSelectedElements(boolean includeChilds) { TreePath[] path = jTree.getSelectionPaths(); List<Object> list = new LinkedList<Object>(); if ( path == null) { return list; } for (TreePath p:path) { TreeNode node = (TreeNode) p.getLastPathComponent(); Object obj = getFromNode(node); if (obj != null) list.add(obj); if ( includeChilds ) { addChildNodeObjects(list, node); } } return list; } protected void addChildNodeObjects(List<Object> list, TreeNode node) { int childCount = node.getChildCount(); for ( int i = 0;i<childCount;i++) { TreeNode child = node.getChildAt( i); Object obj = getFromNode(child); if (obj != null) list.add(obj); addChildNodeObjects(list, child); } } public Object getInfoElement() { if ( bMultiSelect) { return getLastSelectedElement(); } else { return getSelectedElement(); } // end of else } public void unselectAll() { jTree.setSelectionInterval(-1,-1); } public void requestFocus() { jTree.requestFocus(); } public void expandAll() { int i = 0; while (i<jTree.getRowCount()) { jTree.expandRow(i); i++; } } }
Java
package org.rapla.gui.toolkit; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import org.rapla.framework.Disposable; /** Disposes an object on window close. Must be added as a WindowListener to the target window*/ final public class DisposingTool extends WindowAdapter { Disposable m_objectToDispose; public DisposingTool(Disposable objectToDispose) { m_objectToDispose = objectToDispose; } public void windowClosed(WindowEvent e) { m_objectToDispose.dispose(); } }
Java
package org.rapla.gui.toolkit; import javax.swing.JComboBox; import org.rapla.entities.Named; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaContextException; import org.rapla.framework.RaplaLocale; import org.rapla.gui.internal.common.NamedListCellRenderer; public final class RaplaListComboBox extends JComboBox { private static final long serialVersionUID = 1L; // copied the coe from tree table String cachedSearchKey = ""; RaplaContext context; public RaplaListComboBox(RaplaContext context) { init(context); } @SuppressWarnings("unchecked") public RaplaListComboBox(RaplaContext context,Object[] named) { super(named); init(context); } @SuppressWarnings("unchecked") public void init(RaplaContext context) { this.context = context; try { setRenderer(new NamedListCellRenderer(context.lookup(RaplaLocale.class).getLocale())); } catch (RaplaContextException e) { throw new IllegalStateException(e); } } protected boolean processKeyBinding(javax.swing.KeyStroke ks, java.awt.event.KeyEvent e, int condition, boolean pressed) { // live search in current parent node if ((Character.isLetterOrDigit(e.getKeyChar())) && ks.isOnKeyRelease()) { char keyChar = e.getKeyChar(); // search term String search = ("" + keyChar).toLowerCase(); // try to find node with matching searchterm plus the search before int nextIndexMatching = getNextIndexMatching(cachedSearchKey + search); // if we did not find anything, try to find search term only: restart! if (nextIndexMatching <0 ) { nextIndexMatching = getNextIndexMatching(search); cachedSearchKey = ""; } // if we found a node, select it, make it visible and return true if (nextIndexMatching >=0 ) { // store found treepath cachedSearchKey = cachedSearchKey + search; setSelectedIndex(nextIndexMatching); return true; } cachedSearchKey = ""; return true; } return super.processKeyBinding(ks,e,condition,pressed); } private int getNextIndexMatching(String string) { int i = 0; while ( i< getItemCount()) { Object item = getItemAt( i ); String toString; if ( item instanceof Named) { toString = ((Named) item).getName( getLocale()); } else if ( item != null) { toString = item.toString(); } else { toString = null; } if ( toString != null && toString.toLowerCase().startsWith( string.toLowerCase())) { return i; } i++; } return -1; } }
Java
/*--------------------------------------------------------------------------* | 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.gui.toolkit; import javax.swing.JMenuItem; public class RaplaMenuItem extends JMenuItem implements IdentifiableMenuEntry { private static final long serialVersionUID = 1L; String id; public RaplaMenuItem(String id) { super(); this.id = id; } public String getId() { return id; } public static RaplaMenuItem[] EMPTY_ARRAY = new RaplaMenuItem[] {}; public JMenuItem getMenuElement() { return this; } }
Java
/*--------------------------------------------------------------------------* | 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.gui.toolkit; import java.awt.Insets; import javax.swing.Action; import javax.swing.JButton; public class RaplaButton extends JButton { private static final long serialVersionUID = 1L; public static int SMALL= -1; public static int LARGE = 1; public static int DEFAULT = 0; private static Insets smallInsets = new Insets(0,0,0,0); private static Insets largeInsets = new Insets(5,10,5,10); public RaplaButton(String text,int style) { this(style); setText(text); } public RaplaButton(int style) { if (style == SMALL) { setMargin(smallInsets); } else if (style == LARGE) { setMargin(largeInsets); } else { setMargin(null); } } public void setAction(Action action) { String oldText = null; if (action.getValue(Action.NAME) == null) oldText = getText(); super.setAction(action); if (oldText != null) setText(oldText); } public RaplaButton() { } }
Java
/*--------------------------------------------------------------------------* | 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.gui.toolkit; import javax.swing.ActionMap; public interface WizardPanel extends RaplaWidget { String NEXT = "next"; String ABORT = "abort"; String PREV = "prev"; String FINISH = "finish"; public ActionMap getActionMap(); public String getHelp(); public String getDefaultAction(); }
Java
/*--------------------------------------------------------------------------* | 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.gui.toolkit; import java.awt.Cursor; /** All classes implementing this Interface must call FrameControllerList.addFrameController(this) on initialization FrameControllerList.removeFrameController(this) on close This Class is used for automated close of all Frames on Logout. */ public interface FrameController { void close(); // must call FrameControllerList.remove(this); void setCursor(Cursor cursor); }
Java
/*--------------------------------------------------------------------------* | 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.gui.toolkit; import javax.swing.JTree; public interface TreeToolTipRenderer { public String getToolTipText(JTree table, int row); }
Java
/** * */ package org.rapla.gui.toolkit; import java.awt.Color; import java.awt.Component; import java.awt.Graphics; import java.awt.Insets; import javax.swing.border.Border; public class EmptyLineBorder implements Border { Insets insets = new Insets(0,0,0,0); Color COLOR = Color.LIGHT_GRAY; public void paintBorder( Component c, Graphics g, int x, int y, int width, int height ) { g.setColor( COLOR ); g.drawLine(30,8, c.getWidth(), 8); } public Insets getBorderInsets( Component c ) { return insets; } public boolean isBorderOpaque() { return true; } }
Java
/*--------------------------------------------------------------------------* | 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.gui.toolkit; import java.awt.Dimension; import java.awt.FontMetrics; import javax.swing.JEditorPane; /** #BUGFIX * This is a workaround for a bug in the Sun JDK * that don't calculate the correct size of an JEditorPane. * The first version of this workaround caused a NullPointerException * on JDK 1.2.2 sometimes, so this is a workaround for a workaround: * A zero-sized component is added to the StartFrame- Window * This component will be used to calculate the size of * the JEditorPane Components. */ final class JEditorPaneWorkaround { static public void packText(JEditorPane jText,String text,int width) { int height; if (width <=0 ) return; try { jText.setSize(new Dimension(width,100)); jText.setText(text); height = jText.getPreferredScrollableViewportSize().height; } catch ( NullPointerException e) { jText.setSize(new Dimension(width,100)); jText.setText(text); FontMetrics fm = jText.getFontMetrics(jText.getFont()); height = fm.stringWidth(text)/width * fm.getHeight() + 50; } // end of try-catch jText.setSize(new Dimension(width,height)); jText.setPreferredSize(new Dimension(width,height)); } }
Java
/*--------------------------------------------------------------------------* | 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.gui.toolkit; public interface PopupListener { public void showPopup(PopupEvent evt); }
Java
/*--------------------------------------------------------------------------* | 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.gui; import org.rapla.entities.Named; import org.rapla.entities.configuration.Preferences; import org.rapla.framework.RaplaException; import org.rapla.gui.toolkit.RaplaWidget; public interface OptionPanel extends RaplaWidget, Named { void setPreferences(Preferences preferences); /** commits the changes in the option Dialog.*/ void commit() throws RaplaException; /** called when the option Panel is selected for displaying.*/ void show() throws RaplaException; }
Java
package org.rapla.gui; import java.awt.Component; import org.rapla.entities.domain.Reservation; import org.rapla.framework.RaplaException; /** performs a check, if the reservation is entered correctly. An example of a reservation check is the conflict checker*/ public interface ReservationCheck { /** @param sourceComponent * @return true if the reservation check is successful and false if the save dialog should be aborted*/ boolean check(Reservation reservation, Component sourceComponent) throws RaplaException; }
Java
/*--------------------------------------------------------------------------* | 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.gui; import javax.swing.event.ChangeListener; import org.rapla.gui.toolkit.RaplaWidget; /** Base class for most rapla edit fields. Provides some mapping functionality such as reflection invocation of getters/setters. A fieldName "username" will result in a getUsername() and setUsername() method. */ public interface EditField extends RaplaWidget { public String getFieldName(); /** registers new ChangeListener for this component. * An ChangeEvent will be fired to every registered ChangeListener * when the component info changes. * @see javax.swing.event.ChangeListener * @see javax.swing.event.ChangeEvent */ public void addChangeListener(ChangeListener listener); /** removes a listener from this component.*/ public void removeChangeListener(ChangeListener listener); }
Java
package org.rapla.gui; import java.awt.Component; import org.rapla.entities.Entity; import org.rapla.framework.RaplaException; public interface EditController { <T extends Entity> EditComponent<T> createUI( T obj ) throws RaplaException; <T extends Entity> void edit( T obj, Component owner ) throws RaplaException; <T extends Entity> void editNew( T obj, Component owner ) throws RaplaException; <T extends Entity> void edit( T obj, String title, Component owner ) throws RaplaException; // neue Methoden zur Bearbeitung von mehreren gleichartigen Elementen (Entities-Array) // orientieren sich an den oberen beiden Methoden zur Bearbeitung von einem Element <T extends Entity> void edit( T[] obj, Component owner ) throws RaplaException; <T extends Entity> void edit( T[] obj, String title, Component owner ) throws RaplaException; }
Java
/*--------------------------------------------------------------------------* | 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.gui; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import javax.swing.Action; import org.rapla.framework.RaplaContext; public abstract class RaplaAction extends RaplaGUIComponent implements Action { private Map<String,Object> values = new HashMap<String,Object>(); private ArrayList<PropertyChangeListener> listenerList = new ArrayList<PropertyChangeListener>(); public RaplaAction(RaplaContext sm) { super( sm ); setEnabled(true); } public Object getValue(String key) { return values.get(key); } public void putValue(String key,Object value) { Object oldValue = getValue(key); values.put(key,value); firePropertyChange(key,oldValue,value); } public void addPropertyChangeListener(PropertyChangeListener listener) { listenerList.add(listener); } public void removePropertyChangeListener(PropertyChangeListener listener) { listenerList.remove(listener); } protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) { if (listenerList.size() == 0) return; if (oldValue == newValue) return; // if (oldValue != null && newValue != null && oldValue.equals(newValue)) //return; PropertyChangeEvent evt = new PropertyChangeEvent(this,propertyName,oldValue,newValue); PropertyChangeListener[] listeners = getPropertyChangeListeners(); for (int i = 0;i<listeners.length; i++) { listeners[i].propertyChange(evt); } } public PropertyChangeListener[] getPropertyChangeListeners() { return listenerList.toArray(new PropertyChangeListener[]{}); } public void setEnabled(boolean enabled) { putValue("enabled", new Boolean(enabled)); } public boolean isEnabled() { Boolean enabled = (Boolean)getValue("enabled"); return (enabled != null && enabled.booleanValue()); } }
Java
package org.rapla.gui; import javax.swing.JPanel; import javax.swing.JTextField; import org.rapla.plugin.autoexport.AutoExportPlugin; public interface PublishExtension { JPanel getPanel(); /** can return null if no url status should be displayed */ JTextField getURLField(); void mapOptionTo(); /** returns if getAddress can be used to generate an address */ boolean hasAddressCreationStrategy(); /** returns the generated address */ String getAddress( String filename, String generator); /** returns the generator (pagename) for the file. * * For the htmlexport plugin for example is this AutoExportPlugin.CALENDAR_GENERATOR * @see AutoExportPlugin **/ String getGenerator(); }
Java
/*--------------------------------------------------------------------------* | 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.gui; import java.util.List; import org.rapla.framework.RaplaException; import org.rapla.gui.toolkit.RaplaWidget; public interface EditComponent<T> extends RaplaWidget { /** maps all fields back to the current object.*/ public void mapToObjects() throws RaplaException; public List<T> getObjects(); public void setObjects(List<T> o) throws RaplaException; }
Java
package org.rapla.gui; import org.rapla.entities.RaplaObject; import org.rapla.gui.toolkit.RaplaMenuItem; public interface ObjectMenuFactory { RaplaMenuItem[] create(MenuContext menuContext,RaplaObject focusedObject); }
Java
/*--------------------------------------------------------------------------* | 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; import java.net.MalformedURLException; import java.net.URL; import org.rapla.components.util.IOUtil; import org.rapla.components.util.JNLPUtil; import org.rapla.framework.Configuration; import org.rapla.framework.RaplaException; import org.rapla.framework.StartupEnvironment; import org.rapla.framework.internal.ConfigTools; import org.rapla.framework.logger.ConsoleLogger; import org.rapla.framework.logger.Logger; final public class RaplaStartupEnvironment implements StartupEnvironment { private int startupMode = CONSOLE; //private LoadingProgress progressbar; private Logger bootstrapLogger = new ConsoleLogger( ConsoleLogger.LEVEL_WARN ); private URL configURL; private URL contextRootURL; private URL downloadURL; public Configuration getStartupConfiguration() throws RaplaException { return ConfigTools.createConfig( getConfigURL().toExternalForm() ); } public URL getConfigURL() throws RaplaException { if ( configURL != null ) { return configURL; } else { return ConfigTools.configFileToURL( null, "rapla.xconf" ); } } public Logger getBootstrapLogger() { return bootstrapLogger; } public void setStartupMode( int startupMode ) { this.startupMode = startupMode; } /* (non-Javadoc) * @see org.rapla.framework.IStartupEnvironment#getStartupMode() */ public int getStartupMode() { return startupMode; } public void setBootstrapLogger( Logger logger ) { bootstrapLogger = logger; } public void setConfigURL( URL configURL ) { this.configURL = configURL; } public URL getContextRootURL() throws RaplaException { if ( contextRootURL != null ) return contextRootURL; return IOUtil.getBase( getConfigURL() ); } public void setContextRootURL(URL contextRootURL) { this.contextRootURL = contextRootURL; } public URL getDownloadURL() throws RaplaException { if ( downloadURL != null ) { return downloadURL; } if ( startupMode == WEBSTART ) { try { return JNLPUtil.getCodeBase(); } catch ( Exception e ) { throw new RaplaException( e ); } } else { URL base = IOUtil.getBase( getConfigURL() ); if ( base != null) { return base; } try { return new URL( "http://localhost:8051" ); } catch ( MalformedURLException e ) { throw new RaplaException( "Invalid URL" ); } } } public void setDownloadURL( URL downloadURL ) { this.downloadURL = downloadURL; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2013 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.plugin.tempatewizard; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.TreeSet; import javax.swing.MenuElement; import org.rapla.entities.EntityNotFoundException; import org.rapla.entities.User; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Reservation; import org.rapla.facade.CalendarModel; import org.rapla.facade.ModificationEvent; import org.rapla.facade.ModificationListener; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.RaplaGUIComponent; import org.rapla.gui.internal.edit.SaveUndo; import org.rapla.gui.toolkit.IdentifiableMenuEntry; import org.rapla.gui.toolkit.MenuScroller; import org.rapla.gui.toolkit.RaplaMenu; import org.rapla.gui.toolkit.RaplaMenuItem; /** This ReservationWizard displays no wizard and directly opens a ReservationEdit Window */ public class TemplateWizard extends RaplaGUIComponent implements IdentifiableMenuEntry, ActionListener, ModificationListener { Map<Component,String> componentMap = new HashMap<Component, String>(); Collection<String> templateNames; public TemplateWizard(RaplaContext context) throws RaplaException{ super(context); getUpdateModule().addModificationListener( this); updateTemplateNames(); } public String getId() { return "020_templateWizard"; } @Override public void dataChanged(ModificationEvent evt) throws RaplaException { if ( evt.getInvalidateInterval() != null) { updateTemplateNames(); } } private Collection<String> updateTemplateNames() throws RaplaException { return templateNames = getQuery().getTemplateNames(); } public MenuElement getMenuElement() { componentMap.clear(); boolean canCreateReservation = canCreateReservation(); MenuElement element; if (templateNames.size() == 0) { return null; } if ( templateNames.size() == 1) { RaplaMenuItem item = new RaplaMenuItem( getId()); item.setEnabled( canAllocate() && canCreateReservation); item.setText(getString("new_reservations_from_template")); item.setIcon( getIcon("icon.new")); item.addActionListener( this); String template = templateNames.iterator().next(); componentMap.put( item, template); element = item; } else { RaplaMenu item = new RaplaMenu( getId()); item.setEnabled( canAllocate() && canCreateReservation); item.setText(getString("new_reservations_from_template")); item.setIcon( getIcon("icon.new")); Set<String> templateSet = new TreeSet<String>(templateNames); SortedMap<String, Set<String>> keyGroup = new TreeMap<String, Set<String>>(); if ( templateSet.size() > 10) { for ( String string:templateSet) { if (string.length() == 0) { continue; } String firstChar = string.substring( 0,1); Set<String> group = keyGroup.get( firstChar); if ( group == null) { group = new TreeSet<String>(); keyGroup.put( firstChar, group); } group.add(string); } SortedMap<String, Set<String>> merged = merge( keyGroup); for ( String subMenuName: merged.keySet()) { RaplaMenu subMenu = new RaplaMenu( getId()); item.setIcon( getIcon("icon.new")); subMenu.setText( subMenuName); Set<String> set = merged.get( subMenuName); int maxItems = 20; if ( set.size() >= maxItems) { int millisToScroll = 40; MenuScroller.setScrollerFor( subMenu, maxItems , millisToScroll); } addTemplates(subMenu, set); item.add( subMenu); } } else { addTemplates( item, templateSet); } element = item; } return element; } public void addTemplates(RaplaMenu item, Set<String> templateSet) { for ( String templateName:templateSet) { RaplaMenuItem newItem = new RaplaMenuItem(templateName); componentMap.put( newItem, templateName); newItem.setText( templateName ); item.add( newItem); newItem.addActionListener( this); } } private SortedMap<String, Set<String>> merge( SortedMap<String, Set<String>> keyGroup) { SortedMap<String,Set<String>> result = new TreeMap<String, Set<String>>(); String beginnChar = null; String currentChar = null; Set<String> currentSet = null; for ( String key: keyGroup.keySet() ) { Set<String> set = keyGroup.get( key); if ( currentSet == null) { currentSet = new TreeSet<String>(); beginnChar = key; currentChar = key; } if ( !key.equals( currentChar)) { if ( set.size() + currentSet.size() > 10) { String storeKey; if ( beginnChar != null && !beginnChar.equals(currentChar)) { storeKey = beginnChar + "-" + currentChar; } else { storeKey = currentChar; } result.put( storeKey, currentSet); currentSet = new TreeSet<String>(); beginnChar = key; currentChar = key; } else { currentChar = key; } } currentSet.addAll( set); } String storeKey; if ( beginnChar != null) { if ( !beginnChar.equals(currentChar)) { storeKey = beginnChar + "-" + currentChar; } else { storeKey = currentChar; } result.put( storeKey, currentSet); } return result; } public void actionPerformed(ActionEvent e) { try { CalendarModel model = getService(CalendarModel.class); Date beginn = getStartDate( model); Object source = e.getSource(); String templateName = componentMap.get( source); List<Reservation> newReservations; Collection<Reservation> reservations = getQuery().getTemplateReservations(templateName); if (reservations.size() > 0) { newReservations = copy( reservations, beginn); Collection<Allocatable> markedAllocatables = model.getMarkedAllocatables(); if (markedAllocatables != null ) { for (Reservation event: newReservations) { if ( event.getAllocatables().length == 0) { for ( Allocatable alloc:markedAllocatables) { if (!event.hasAllocated(alloc)) { event.addAllocatable( alloc); } } } } } } else { showException(new EntityNotFoundException("Template " + templateName + " not found"), getMainComponent()); return; } if ( newReservations.size() == 1) { Reservation next = newReservations.iterator().next(); getReservationController().edit( next); } else { Collection<Reservation> list = new ArrayList<Reservation>(); for ( Reservation reservation:newReservations) { Reservation cast = reservation; User lastChangedBy = cast.getLastChangedBy(); if ( lastChangedBy != null && !lastChangedBy.equals(getUser())) { throw new RaplaException("Reservation " + cast + " has wrong user " + lastChangedBy); } list.add( cast); } SaveUndo<Reservation> saveUndo = new SaveUndo<Reservation>(getContext(), list, null); getModification().getCommandHistory().storeAndExecute( saveUndo); } } catch (RaplaException ex) { showException( ex, getMainComponent()); } } }
Java
/*--------------------------------------------------------------------------* | 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.plugin.tempatewizard; import org.rapla.client.ClientServiceContainer; import org.rapla.client.RaplaClientExtensionPoints; import org.rapla.framework.Configuration; import org.rapla.framework.PluginDescriptor; public class TempateWizardPlugin implements PluginDescriptor<ClientServiceContainer> { public static final String PLUGIN_CLASS = TempateWizardPlugin.class.getName(); public static boolean ENABLE_BY_DEFAULT = true; public void provideServices(ClientServiceContainer container, Configuration config) { if ( !config.getAttributeAsBoolean("enabled", ENABLE_BY_DEFAULT) ) return; container.addContainerProvidedComponent( RaplaClientExtensionPoints.RESERVATION_WIZARD_EXTENSION, TemplateWizard.class); } }
Java
/*--------------------------------------------------------------------------* | 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.plugin.setowner; import org.rapla.client.ClientServiceContainer; import org.rapla.client.RaplaClientExtensionPoints; import org.rapla.components.xmlbundle.I18nBundle; import org.rapla.components.xmlbundle.impl.I18nBundleImpl; import org.rapla.framework.Configuration; import org.rapla.framework.PluginDescriptor; import org.rapla.framework.TypedComponentRole; public class SetOwnerPlugin implements PluginDescriptor<ClientServiceContainer> { public final static boolean ENABLE_BY_DEFAULT = false; public static final TypedComponentRole<I18nBundle> RESOURCE_FILE = new TypedComponentRole<I18nBundle>(SetOwnerPlugin.class.getPackage().getName() + ".SetOwnerResources"); public String toString() { return "Set Owner"; } public void provideServices(ClientServiceContainer container, Configuration config) { if ( !config.getAttributeAsBoolean("enabled", ENABLE_BY_DEFAULT) ) return; container.addContainerProvidedComponent( RESOURCE_FILE, I18nBundleImpl.class, I18nBundleImpl.createConfig( RESOURCE_FILE.getId() ) ); container.addContainerProvidedComponent( RaplaClientExtensionPoints.OBJECT_MENU_EXTENSION, SetOwnerMenuFactory.class); } }
Java
package org.rapla.plugin.setowner; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.TreeSet; import javax.swing.JTree; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import org.rapla.entities.Entity; import org.rapla.entities.Named; import org.rapla.entities.NamedComparator; import org.rapla.entities.Ownable; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; import org.rapla.entities.User; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.AppointmentBlock; import org.rapla.entities.domain.Reservation; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.MenuContext; import org.rapla.gui.ObjectMenuFactory; import org.rapla.gui.RaplaGUIComponent; import org.rapla.gui.TreeFactory; import org.rapla.gui.toolkit.DialogUI; import org.rapla.gui.toolkit.RaplaMenuItem; import org.rapla.gui.toolkit.RaplaTree; public class SetOwnerMenuFactory extends RaplaGUIComponent implements ObjectMenuFactory { public SetOwnerMenuFactory( RaplaContext context) { super( context ); setChildBundleName( SetOwnerPlugin.RESOURCE_FILE); } public RaplaMenuItem[] create( final MenuContext menuContext, final RaplaObject focusedObject ) { if (!isAdmin()) { return RaplaMenuItem.EMPTY_ARRAY; } Collection<Object> selectedObjects = new HashSet<Object>(); Collection<?> selected = menuContext.getSelectedObjects(); if ( selected.size() != 0) { selectedObjects.addAll( selected); } if ( focusedObject != null) { selectedObjects.add( focusedObject); } final Collection<Entity<? extends Entity>> ownables = new HashSet<Entity<? extends Entity>>(); for ( Object obj: selectedObjects) { final Entity<? extends Entity> ownable; if ( obj instanceof AppointmentBlock) { ownable = ((AppointmentBlock) obj).getAppointment().getReservation(); } else if ( obj instanceof Entity ) { RaplaType raplaType = ((RaplaObject)obj).getRaplaType(); if ( raplaType == Appointment.TYPE ) { Appointment appointment = (Appointment) obj; ownable = appointment.getReservation(); } else if ( raplaType == Reservation.TYPE) { ownable = (Reservation) obj; } else if ( raplaType == Allocatable.TYPE) { ownable = (Allocatable) obj; } else { ownable = null; } } else { ownable = null; } if ( ownable != null) { ownables.add( ownable); } } if ( ownables.size() == 0 ) { return RaplaMenuItem.EMPTY_ARRAY; } // create the menu entry final RaplaMenuItem setOwnerItem = new RaplaMenuItem("SETOWNER"); setOwnerItem.setText(getI18n().getString("changeowner")); setOwnerItem.setIcon(getI18n().getIcon("icon.tree.persons")); setOwnerItem.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { try { User newOwner = showAddDialog(); if(newOwner != null) { ArrayList<Entity<?>> toStore = new ArrayList<Entity<?>>(); for ( Entity<? extends Entity> ownable: ownables) { Entity<?> editableOwnables = getClientFacade().edit( ownable); Ownable casted = (Ownable)editableOwnables; casted.setOwner(newOwner); toStore.add( editableOwnables); } //((SimpleEntity) editableEvent).setLastChangedBy(newOwner); getClientFacade().storeObjects( toStore.toArray( Entity.ENTITY_ARRAY) ); } } catch (RaplaException ex ) { showException( ex, menuContext.getComponent()); } } }); return new RaplaMenuItem[] {setOwnerItem }; } final private TreeFactory getTreeFactory() { return getService(TreeFactory.class); } private User showAddDialog() throws RaplaException { final DialogUI dialog; RaplaTree treeSelection = new RaplaTree(); treeSelection.setMultiSelect(true); treeSelection.getTree().setCellRenderer(getTreeFactory().createRenderer()); DefaultMutableTreeNode userRoot = new DefaultMutableTreeNode("ROOT"); //DefaultMutableTreeNode userRoot = TypeNode(User.TYPE, getString("users")); User[] userList = getQuery().getUsers(); for (final User user: sorted(userList)) { DefaultMutableTreeNode node = new DefaultMutableTreeNode(); node.setUserObject( user ); userRoot.add(node); } treeSelection.exchangeTreeModel(new DefaultTreeModel(userRoot)); treeSelection.setMinimumSize(new java.awt.Dimension(300, 200)); treeSelection.setPreferredSize(new java.awt.Dimension(400, 260)); dialog = DialogUI.create( getContext() ,getMainComponent() ,true ,treeSelection ,new String[] { getString("apply"),getString("cancel")}); dialog.setTitle(getI18n().getString("changeownerto")); dialog.getButton(0).setEnabled(false); final JTree tree = treeSelection.getTree(); tree.addMouseListener(new MouseAdapter() { // End dialog when a leaf is double clicked public void mousePressed(MouseEvent e) { TreePath selPath = tree.getPathForLocation(e.getX(), e.getY()); if (selPath != null && e.getClickCount() == 2) { final Object lastPathComponent = selPath.getLastPathComponent(); if (((TreeNode) lastPathComponent).isLeaf() ) { dialog.getButton(0).doClick(); return; } } else if (selPath != null && e.getClickCount() == 1) { final Object lastPathComponent = selPath.getLastPathComponent(); if (((TreeNode) lastPathComponent).isLeaf() ) { dialog.getButton(0).setEnabled(true); return; } } tree.removeSelectionPath(selPath); } }); dialog.start(); if (dialog.getSelectedIndex() == 1) { return null; } return (User) treeSelection.getSelectedElement(); } private <T extends Named> Collection<T> sorted(T[] allocatables) { TreeSet<T> sortedList = new TreeSet<T>(new NamedComparator<T>(getLocale())); sortedList.addAll(Arrays.asList(allocatables)); return sortedList; } }
Java
/*--------------------------------------------------------------------------* | 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.plugin.dayresource; import java.awt.Point; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.swing.JComponent; import javax.swing.JLabel; import org.rapla.components.calendarview.Block; import org.rapla.components.calendarview.CalendarView; import org.rapla.components.calendarview.swing.AbstractSwingCalendar; import org.rapla.components.calendarview.swing.SelectionHandler.SelectionStrategy; import org.rapla.components.calendarview.swing.SwingWeekView; import org.rapla.components.calendarview.swing.ViewListener; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.AppointmentBlock; import org.rapla.facade.CalendarModel; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.plugin.abstractcalendar.AbstractRaplaBlock; import org.rapla.plugin.abstractcalendar.GroupAllocatablesStrategy; import org.rapla.plugin.abstractcalendar.RaplaBuilder; import org.rapla.plugin.abstractcalendar.RaplaCalendarViewListener; import org.rapla.plugin.weekview.SwingDayCalendar; public class SwingDayResourceCalendar extends SwingDayCalendar { public SwingDayResourceCalendar( RaplaContext sm, CalendarModel model, boolean editable ) throws RaplaException { super( sm, model, editable ); } protected AbstractSwingCalendar createView(boolean showScrollPane) { /** renderer for dates in weekview */ SwingWeekView wv = new SwingWeekView( showScrollPane ) { { selectionHandler.setSelectionStrategy(SelectionStrategy.BLOCK); } @Override protected JComponent createSlotHeader(Integer column) { JLabel component = (JLabel) super.createSlotHeader(column); try { List<Allocatable> sortedAllocatables = getSortedAllocatables(); Allocatable allocatable = sortedAllocatables.get(column); String name = allocatable.getName( getLocale()); component.setText( name); component.setToolTipText(name); } catch (RaplaException e) { } return component; } @Override protected int getColumnCount() { try { Allocatable[] selectedAllocatables =model.getSelectedAllocatables(); return selectedAllocatables.length; } catch (RaplaException e) { return 0; } } @Override public void rebuild() { super.rebuild(); String dateText = getRaplaLocale().formatDateShort(getStartDate()); weekTitle.setText( dateText); } }; return wv; } protected RaplaBuilder createBuilder() throws RaplaException { RaplaBuilder builder = super.createBuilder(); builder.setSplitByAllocatables( true ); final List<Allocatable> allocatables = getSortedAllocatables(); builder.selectAllocatables(allocatables); GroupAllocatablesStrategy strategy = new GroupAllocatablesStrategy( getRaplaLocale().getLocale() ) { @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) { int index = getIndex(allocatables, block); if ( index >= 0 ) { map.put( block, index ); } } return map; } else { return super.getBlockMap(wv, blocks); } } }; strategy.setResolveConflictsEnabled( true ); builder.setBuildStrategy( strategy ); return builder; } protected ViewListener createListener() throws RaplaException { return new RaplaCalendarViewListener(getContext(), model, view.getComponent()) { @Override protected Collection<Allocatable> getMarkedAllocatables() { final List<Allocatable> selectedAllocatables = getSortedAllocatables(); Set<Allocatable> allSelected = new HashSet<Allocatable>(); if ( selectedAllocatables.size() == 1 ) { allSelected.add(selectedAllocatables.get(0)); } for ( int i =0 ;i< selectedAllocatables.size();i++) { if ( view.isSelected(i)) { allSelected.add(selectedAllocatables.get(i)); } } return allSelected; } @Override public void moved(Block block, Point p, Date newStart, int slotNr) { int column= slotNr;//getIndex( selectedAllocatables, block ); if ( column < 0) { return; } try { final List<Allocatable> selectedAllocatables = getSortedAllocatables(); Allocatable newAlloc = selectedAllocatables.get(column); AbstractRaplaBlock raplaBlock = (AbstractRaplaBlock)block; Allocatable oldAlloc = raplaBlock.getGroupAllocatable(); if ( newAlloc != null && oldAlloc != null && !newAlloc.equals(oldAlloc)) { AppointmentBlock appointmentBlock= raplaBlock.getAppointmentBlock(); getReservationController().exchangeAllocatable(appointmentBlock, oldAlloc,newAlloc,newStart, getMainComponent(),p); } else { super.moved(block, p, newStart, slotNr); } } catch (RaplaException ex) { showException(ex, getMainComponent()); } } }; } private int getIndex(final List<Allocatable> allocatables, Block block) { AbstractRaplaBlock b = (AbstractRaplaBlock)block; Allocatable a = b.getGroupAllocatable(); int index = a != null ? allocatables.indexOf( a ) : -1; return index; } }
Java
/*--------------------------------------------------------------------------* | 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.plugin.dayresource; import javax.swing.Icon; import org.rapla.facade.CalendarModel; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.SwingCalendarView; import org.rapla.gui.SwingViewFactory; import org.rapla.gui.images.Images; public class DayResourceViewFactory extends RaplaComponent implements SwingViewFactory { public DayResourceViewFactory( RaplaContext context ) { super( context ); } public final static String DAY_RESOURCE_VIEW = "day_resource"; public SwingCalendarView createSwingView(RaplaContext context, CalendarModel model, boolean editable) throws RaplaException { return new SwingDayResourceCalendar( context, model, editable); } public String getViewId() { return DAY_RESOURCE_VIEW; } public String getName() { return getString(DAY_RESOURCE_VIEW); } Icon icon; public Icon getIcon() { if ( icon == null) { icon = Images.getIcon("/org/rapla/plugin/dayresource/images/day_resource.png"); } return icon; } public String getMenuSortKey() { return "A"; } }
Java
/*--------------------------------------------------------------------------* | 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.plugin.dayresource; import org.rapla.client.ClientServiceContainer; import org.rapla.client.RaplaClientExtensionPoints; import org.rapla.framework.Configuration; import org.rapla.framework.PluginDescriptor; public class DayResourceViewPlugin implements PluginDescriptor<ClientServiceContainer> { final public static boolean ENABLE_BY_DEFAULT = true; public void provideServices(ClientServiceContainer container, Configuration config) { if ( !config.getAttributeAsBoolean("enabled", ENABLE_BY_DEFAULT) ) return; container.addContainerProvidedComponent(RaplaClientExtensionPoints.CALENDAR_VIEW_EXTENSION,DayResourceViewFactory.class); } }
Java
/*--------------------------------------------------------------------------* | 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.plugin.dayresource.server; import org.rapla.facade.CalendarModel; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.plugin.abstractcalendar.server.HTMLViewFactory; import org.rapla.servletpages.RaplaPageGenerator; public class DayResourceHTMLViewFactory extends RaplaComponent implements HTMLViewFactory { public DayResourceHTMLViewFactory( RaplaContext context ) { super( context ); } public final static String DAY_RESOURCE_VIEW = "day_resource"; public RaplaPageGenerator createHTMLView(RaplaContext context, CalendarModel model) throws RaplaException { return new HTMLDayResourcePage( context, model); } public String getViewId() { return DAY_RESOURCE_VIEW; } public String getName() { return getString(DAY_RESOURCE_VIEW); } }
Java
package org.rapla.plugin.dayresource.server; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.rapla.components.calendarview.Block; import org.rapla.components.calendarview.CalendarView; import org.rapla.components.calendarview.html.AbstractHTMLView; import org.rapla.components.calendarview.html.HTMLWeekView; import org.rapla.entities.domain.Allocatable; import org.rapla.facade.CalendarModel; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.plugin.abstractcalendar.AbstractRaplaBlock; import org.rapla.plugin.abstractcalendar.GroupAllocatablesStrategy; import org.rapla.plugin.abstractcalendar.RaplaBuilder; import org.rapla.plugin.weekview.server.HTMLDayViewPage; public class HTMLDayResourcePage extends HTMLDayViewPage { public HTMLDayResourcePage(RaplaContext context, CalendarModel calendarModel) { super(context, calendarModel); } protected AbstractHTMLView createCalendarView() { HTMLWeekView weekView = new HTMLWeekView(){ @Override protected String createColumnHeader(int i) { try { Allocatable allocatable = getSortedAllocatables().get(i); return allocatable.getName( getLocale()); } catch (RaplaException e) { return ""; } } @Override protected int getColumnCount() { try { Allocatable[] selectedAllocatables =model.getSelectedAllocatables(); return selectedAllocatables.length; } catch (RaplaException e) { return 0; } } public void rebuild() { setWeeknumber(getRaplaLocale().formatDateShort(getStartDate())); super.rebuild(); } }; return weekView; } private int getIndex(final List<Allocatable> allocatables, Block block) { AbstractRaplaBlock b = (AbstractRaplaBlock)block; Allocatable a = b.getGroupAllocatable(); int index = a != null ? allocatables.indexOf( a ) : -1; return index; } protected RaplaBuilder createBuilder() throws RaplaException { RaplaBuilder builder = super.createBuilder(); final List<Allocatable> allocatables = getSortedAllocatables(); builder.setSplitByAllocatables( true ); builder.selectAllocatables(allocatables); GroupAllocatablesStrategy strategy = new GroupAllocatablesStrategy( getRaplaLocale().getLocale() ) { @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) { int index = getIndex(allocatables, block); if ( index >= 0 ) { map.put( block, index ); } } return map; } else { return super.getBlockMap(wv, blocks); } } }; strategy.setResolveConflictsEnabled( true ); builder.setBuildStrategy( strategy ); return builder; } }
Java
/*--------------------------------------------------------------------------* | 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.plugin.dayresource.server; import org.rapla.framework.Configuration; import org.rapla.framework.PluginDescriptor; import org.rapla.plugin.dayresource.DayResourceViewPlugin; import org.rapla.server.RaplaServerExtensionPoints; import org.rapla.server.ServerServiceContainer; public class DayResourceViewServerPlugin implements PluginDescriptor<ServerServiceContainer> { public void provideServices(ServerServiceContainer container, Configuration config) { if ( !config.getAttributeAsBoolean("enabled", DayResourceViewPlugin.ENABLE_BY_DEFAULT) ) return; container.addContainerProvidedComponent(RaplaServerExtensionPoints.HTML_CALENDAR_VIEW_EXTENSION,DayResourceHTMLViewFactory.class); } }
Java
package org.rapla.plugin.autoexport; import java.awt.BorderLayout; import java.util.Locale; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPanel; import org.rapla.components.layout.TableLayout; import org.rapla.framework.Configuration; import org.rapla.framework.DefaultConfiguration; import org.rapla.framework.PluginDescriptor; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.DefaultPluginOption; public class AutoExportPluginOption extends DefaultPluginOption { JCheckBox booleanField = new JCheckBox(); // public AutoExportPluginOption( RaplaContext sm ) { super( sm ); } protected JPanel createPanel() throws RaplaException { JPanel panel = super.createPanel(); JPanel content = new JPanel(); double[][] sizes = new double[][] { {5,TableLayout.PREFERRED, 5,TableLayout.FILL,5} ,{TableLayout.PREFERRED,5,TableLayout.PREFERRED, 5, TableLayout.PREFERRED, 5, TableLayout.PREFERRED, 5, TableLayout.PREFERRED} }; TableLayout tableLayout = new TableLayout(sizes); content.setLayout(tableLayout); content.add(new JLabel("Show list of exported calendars im HTML Menu"), "1,4"); content.add(booleanField,"3,4"); panel.add( content, BorderLayout.CENTER); return panel; } protected void addChildren( DefaultConfiguration newConfig) { newConfig.setAttribute( AutoExportPlugin.SHOW_CALENDAR_LIST_IN_HTML_MENU, booleanField.isSelected() ); } protected void readConfig( Configuration config) { booleanField.setSelected( config.getAttributeAsBoolean(AutoExportPlugin.SHOW_CALENDAR_LIST_IN_HTML_MENU, false)); } public Class<? extends PluginDescriptor<?>> getPluginClass() { return AutoExportPlugin.class; } @Override public String getName(Locale locale) { return "HTML Export Plugin"; } }
Java
/*--------------------------------------------------------------------------* | 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.plugin.autoexport; import org.rapla.client.ClientServiceContainer; import org.rapla.client.RaplaClientExtensionPoints; import org.rapla.components.xmlbundle.I18nBundle; import org.rapla.components.xmlbundle.impl.I18nBundleImpl; import org.rapla.entities.configuration.CalendarModelConfiguration; import org.rapla.entities.configuration.RaplaMap; import org.rapla.framework.Configuration; import org.rapla.framework.PluginDescriptor; import org.rapla.framework.RaplaContextException; import org.rapla.framework.TypedComponentRole; public class AutoExportPlugin implements PluginDescriptor<ClientServiceContainer> { public static final String CALENDAR_GENERATOR = "calendar"; public static final TypedComponentRole<I18nBundle> AUTOEXPORT_PLUGIN_RESOURCE = new TypedComponentRole<I18nBundle>( AutoExportPlugin.class.getPackage().getName() + ".AutoExportResources"); public static final TypedComponentRole<RaplaMap<CalendarModelConfiguration>> PLUGIN_ENTRY = CalendarModelConfiguration.EXPORT_ENTRY; public static final String HTML_EXPORT= PLUGIN_ENTRY + ".selected"; public static final String SHOW_CALENDAR_LIST_IN_HTML_MENU = "show_calendar_list_in_html_menu"; public static final boolean ENABLE_BY_DEFAULT = true; public void provideServices(ClientServiceContainer container, Configuration config) throws RaplaContextException { container.addContainerProvidedComponent( AUTOEXPORT_PLUGIN_RESOURCE, I18nBundleImpl.class, I18nBundleImpl.createConfig( AUTOEXPORT_PLUGIN_RESOURCE.getId() ) ); container.addContainerProvidedComponent( RaplaClientExtensionPoints.PLUGIN_OPTION_PANEL_EXTENSION, AutoExportPluginOption.class); if ( !config.getAttributeAsBoolean("enabled", ENABLE_BY_DEFAULT) ) return; container.addContainerProvidedComponent( RaplaClientExtensionPoints.PUBLISH_EXTENSION_OPTION, HTMLPublicExtensionFactory.class); } }
Java
package org.rapla.plugin.autoexport; import java.beans.PropertyChangeListener; import org.rapla.facade.CalendarSelectionModel; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.PublishExtension; import org.rapla.gui.PublishExtensionFactory; public class HTMLPublicExtensionFactory extends RaplaComponent implements PublishExtensionFactory { public HTMLPublicExtensionFactory(RaplaContext context) { super(context); } public PublishExtension creatExtension(CalendarSelectionModel model,PropertyChangeListener revalidateCallback) throws RaplaException { return new HTMLPublishExtension(getContext(), model); } }
Java
package org.rapla.plugin.autoexport.server; import org.rapla.components.xmlbundle.I18nBundle; import org.rapla.framework.RaplaContext; import org.rapla.plugin.autoexport.AutoExportPlugin; import org.rapla.servletpages.DefaultHTMLMenuEntry; public class ExportMenuEntry extends DefaultHTMLMenuEntry { public ExportMenuEntry(RaplaContext context) { super(context); } @Override public String getName() { I18nBundle i18n = getService( AutoExportPlugin.AUTOEXPORT_PLUGIN_RESOURCE ); return i18n.getString( "calendar_list"); } @Override public String getLinkName() { return "rapla?page=calendarlist"; } }
Java
/*--------------------------------------------------------------------------* | 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.plugin.autoexport.server; import java.io.IOException; import java.util.Collections; 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.components.util.IOUtil; import org.rapla.components.util.ParseDateException; import org.rapla.entities.EntityNotFoundException; import org.rapla.entities.User; import org.rapla.entities.domain.Allocatable; import org.rapla.facade.CalendarNotFoundExeption; import org.rapla.facade.CalendarSelectionModel; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaContextException; import org.rapla.plugin.abstractcalendar.server.HTMLViewFactory; import org.rapla.plugin.autoexport.AutoExportPlugin; import org.rapla.server.RaplaServerExtensionPoints; import org.rapla.servletpages.RaplaPageGenerator; /******* USAGE: ************ * ReadOnly calendarview view. * You will need the autoexport plugin to create a calendarview-view. * * Call: * rapla?page=calendar&user=<username>&file=<export_name> * * Optional Parameters: * * &hide_nav: will hide the navigation bar. * &day=<day>: int-value of the day of month that should be displayed * &month=<month>: int-value of the month * &year=<year>: int-value of the year * &today: will set the view to the current day. Ignores day, month and year */ public class CalendarPageGenerator extends RaplaComponent implements RaplaPageGenerator { private Map<String,HTMLViewFactory> factoryMap = new HashMap<String, HTMLViewFactory>(); public CalendarPageGenerator(RaplaContext context) throws RaplaContextException { super(context); for (HTMLViewFactory fact: getContainer().lookupServicesFor(RaplaServerExtensionPoints.HTML_CALENDAR_VIEW_EXTENSION)) { String id = fact.getViewId(); factoryMap.put( id , fact); } } public void generatePage( ServletContext servletContext, HttpServletRequest request, HttpServletResponse response ) throws IOException, ServletException { try { String username = request.getParameter( "user" ); String filename = request.getParameter( "file" ); CalendarSelectionModel model = null; User user; try { user = getQuery().getUser( username ); } catch (EntityNotFoundException ex) { String message = "404 Calendar not availabe " + username +"/" + filename ; write404(response, message); getLogger().getChildLogger("html.404").warn("404 User not found "+ username); return; } try { model = getModification().newCalendarModel( user ); model.load(filename); } catch (CalendarNotFoundExeption ex) { String message = "404 Calendar not availabe " + user +"/" + filename ; write404(response, message); return; } String allocatableId = request.getParameter( "allocatable_id" ); if ( allocatableId != null) { Allocatable[] selectedAllocatables = model.getSelectedAllocatables(); Allocatable foundAlloc = null; for ( Allocatable alloc:selectedAllocatables) { if (alloc.getId().equals( allocatableId)) { foundAlloc = alloc; break; } } if ( foundAlloc != null) { model.setSelectedObjects( Collections.singleton(foundAlloc)); request.setAttribute("allocatable_id", allocatableId); } else { String message = "404 allocatable with id '" + allocatableId + "' not found for calendar " + user + "/" + filename ; write404(response, message); return; } } final Object isSet = model.getOption(AutoExportPlugin.HTML_EXPORT); if( isSet == null || isSet.equals("false")) { String message = "404 Calendar not published " + username + "/" + filename ; write404(response, message); return; } final String viewId = model.getViewId(); HTMLViewFactory factory = getFactory(viewId); if ( factory != null ) { RaplaPageGenerator currentView = factory.createHTMLView( getContext(), model ); if ( currentView != null ) { try { currentView.generatePage( servletContext, request, response ); } catch ( ServletException ex) { Throwable cause = ex.getCause(); if ( cause instanceof ParseDateException) { write404( response, cause.getMessage() + " in calendar " + user + "/" + filename); } else { throw ex; } } } else { write404( response, "No view available for calendar " + user + "/" + filename + ". Rapla has currently no html support for the view with the id '" + viewId + "'." ); } } else { writeError( response, "No view available for exportfile '" + filename + "'. Please install and select the plugin for " + viewId ); } } catch ( Exception ex ) { writeStacktrace(response, ex); throw new ServletException( ex ); } } protected HTMLViewFactory getFactory(final String viewId) { return factoryMap.get( viewId ); } private void writeStacktrace(HttpServletResponse response, Exception ex) throws IOException { response.setContentType( "text/html; charset=" + getRaplaLocale().getCharsetNonUtf() ); java.io.PrintWriter out = response.getWriter(); out.println( IOUtil.getStackTraceAsString( ex ) ); out.close(); } protected void write404(HttpServletResponse response, String message) throws IOException { response.setStatus( 404 ); response.getWriter().print(message); getLogger().getChildLogger("html.404").warn( message); response.getWriter().close(); } private void writeError( HttpServletResponse response, String message ) throws IOException { response.setStatus( 500 ); response.setContentType( "text/html; charset=" + getRaplaLocale().getCharsetNonUtf() ); java.io.PrintWriter out = response.getWriter(); out.println( message ); out.close(); } }
Java
/*--------------------------------------------------------------------------* | 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.plugin.autoexport.server; import org.rapla.components.xmlbundle.impl.I18nBundleImpl; import org.rapla.framework.Configuration; import org.rapla.framework.PluginDescriptor; import org.rapla.framework.RaplaContextException; import org.rapla.plugin.autoexport.AutoExportPlugin; import org.rapla.server.RaplaServerExtensionPoints; import org.rapla.server.ServerServiceContainer; public class AutoExportServerPlugin implements PluginDescriptor<ServerServiceContainer> { public void provideServices(ServerServiceContainer container, Configuration config) throws RaplaContextException { container.addContainerProvidedComponent( AutoExportPlugin.AUTOEXPORT_PLUGIN_RESOURCE, I18nBundleImpl.class, I18nBundleImpl.createConfig( AutoExportPlugin.AUTOEXPORT_PLUGIN_RESOURCE.getId() ) ); if ( !config.getAttributeAsBoolean("enabled", AutoExportPlugin.ENABLE_BY_DEFAULT) ) return; container.addWebpage(AutoExportPlugin.CALENDAR_GENERATOR,CalendarPageGenerator.class); //RaplaResourcePageGenerator resourcePageGenerator = container.getContext().lookup(RaplaResourcePageGenerator.class); // registers the standard calendar files //resourcePageGenerator.registerResource( "calendar.css", "text/css", this.getClass().getResource("/org/rapla/plugin/autoexport/server/calendar.css")); // look if we should add a menu entry of exported lists if (config.getAttributeAsBoolean(AutoExportPlugin.SHOW_CALENDAR_LIST_IN_HTML_MENU, false)) { container.addWebpage("calendarlist",CalendarListPageGenerator.class); container.addContainerProvidedComponent( RaplaServerExtensionPoints.HTML_MAIN_MENU_EXTENSION_POINT, ExportMenuEntry.class); } } }
Java
/*--------------------------------------------------------------------------* | 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.plugin.autoexport.server; import java.io.IOException; import java.net.URLEncoder; import java.util.Arrays; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.TreeSet; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.rapla.RaplaMainContainer; import org.rapla.components.util.IOUtil; import org.rapla.entities.User; import org.rapla.entities.configuration.CalendarModelConfiguration; import org.rapla.entities.configuration.Preferences; import org.rapla.entities.configuration.RaplaMap; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.plugin.autoexport.AutoExportPlugin; import org.rapla.servletpages.RaplaPageGenerator; public class CalendarListPageGenerator extends RaplaComponent implements RaplaPageGenerator { public CalendarListPageGenerator( RaplaContext context ) { super( context ); setChildBundleName( AutoExportPlugin.AUTOEXPORT_PLUGIN_RESOURCE ); } public void generatePage( ServletContext servletContext, HttpServletRequest request, HttpServletResponse response ) throws IOException, ServletException { java.io.PrintWriter out = response.getWriter(); try { String username = request.getParameter( "user" ); response.setContentType("text/html; charset=" + getRaplaLocale().getCharsetNonUtf() ); User[] users = getQuery().getUsers(); Set<User> sortedUsers =new TreeSet<User>( Arrays.asList( users)); if ( username != null) { users = new User[] { getQuery().getUser( username )}; } String calendarName = getQuery().getSystemPreferences().getEntryAsString(RaplaMainContainer.TITLE, getString("rapla.title")); out.println( "<html>" ); out.println( "<head>" ); out.println( "<title>" + calendarName + "</title>" ); out.println( "</head>" ); out.println( "<body>" ); out.println( "<h2>" + getString("webserver") + ": " + calendarName + "</h2>"); for (User user : sortedUsers) { Preferences preferences = getQuery().getPreferences( user ); LinkedHashMap<String, CalendarModelConfiguration> completeMap = new LinkedHashMap<String, CalendarModelConfiguration>(); CalendarModelConfiguration defaultConf = preferences.getEntry( CalendarModelConfiguration.CONFIG_ENTRY ); if ( defaultConf != null) { completeMap.put( getString("default"), defaultConf); } final RaplaMap<CalendarModelConfiguration> raplaMap = preferences.getEntry( AutoExportPlugin.PLUGIN_ENTRY ); if ( raplaMap != null) { for ( Map.Entry<String, CalendarModelConfiguration> entry: raplaMap.entrySet()) { CalendarModelConfiguration value = entry.getValue(); completeMap.put(entry.getKey(),value); } } SortedMap<String,CalendarModelConfiguration> sortedMap = new TreeMap<String,CalendarModelConfiguration>( new TitleComparator( completeMap)); sortedMap.putAll( completeMap); Iterator<Map.Entry<String, CalendarModelConfiguration>> it = sortedMap.entrySet().iterator(); int count =0; while ( it.hasNext()) { Map.Entry<String,CalendarModelConfiguration> entry = it.next(); String key = entry.getKey(); CalendarModelConfiguration conf = entry.getValue(); final Object isSet = conf.getOptionMap().get(AutoExportPlugin.HTML_EXPORT); if( isSet != null && isSet.equals("false")) { it.remove(); continue; } if(count == 0) { String userName = user.getName(); if(username == null || userName.trim().length() ==0) userName = user.getUsername(); out.println( "<h3>" + userName + "</h3>" ); //BJO out.println( "<ul>" ); } count++; String title = getTitle(key, conf); String filename =URLEncoder.encode( key, "UTF-8" ); out.print( "<li>" ); out.print( "<a href=\"?page=calendar&user=" + user.getUsername() + "&file=" + filename + "&details=*" + "&folder=true" + "\">"); out.print( title); out.print( "</a>" ); out.println( "</li>" ); } if (count > 0) { out.println( "</ul>" ); } } out.println( "</body>" ); out.println( "</html>" ); } catch ( Exception ex ) { out.println( IOUtil.getStackTraceAsString( ex ) ); throw new ServletException( ex ); } finally { out.close(); } } private String getTitle(String key, CalendarModelConfiguration conf) { String title = conf.getTitle() ; if ( title == null || title.trim().length() == 0) { title = key; } return title; } class TitleComparator implements Comparator<String> { Map<String,CalendarModelConfiguration> base; public TitleComparator(Map<String,CalendarModelConfiguration> base) { this.base = base; } public int compare(String a, String b) { final String title1 = getTitle(a,base.get(a)); final String title2 = getTitle(b,base.get(b)); int result = title1.compareToIgnoreCase( title2); if ( result != 0) { return result; } return a.compareToIgnoreCase( b); } } }
Java
package org.rapla.plugin.autoexport; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.rapla.components.layout.TableLayout; import org.rapla.facade.CalendarModel; import org.rapla.facade.CalendarSelectionModel; import org.rapla.framework.RaplaContext; import org.rapla.gui.PublishExtension; import org.rapla.gui.RaplaGUIComponent; import org.rapla.gui.toolkit.RaplaButton; class HTMLPublishExtension extends RaplaGUIComponent implements PublishExtension { JPanel panel = new JPanel(); CalendarSelectionModel model; final JCheckBox showNavField; final JCheckBox saveSelectedDateField; final JTextField htmlURL; final JCheckBox checkbox; final JTextField titleField; final JPanel statusHtml; final JCheckBox onlyAllocationInfoField; public HTMLPublishExtension(RaplaContext context,CalendarSelectionModel model) { super(context); setChildBundleName( AutoExportPlugin.AUTOEXPORT_PLUGIN_RESOURCE); this.model = model; panel.setLayout(new TableLayout( new double[][] {{TableLayout.PREFERRED,5,TableLayout.PREFERRED,5,TableLayout.FILL}, {TableLayout.PREFERRED,5,TableLayout.PREFERRED,5,TableLayout.PREFERRED,5,TableLayout.PREFERRED,5,TableLayout.PREFERRED, 5, TableLayout.PREFERRED }})); titleField = new JTextField(20); addCopyPaste(titleField); showNavField = new JCheckBox(); saveSelectedDateField = new JCheckBox(); onlyAllocationInfoField = new JCheckBox(); htmlURL = new JTextField(); checkbox = new JCheckBox("HTML " + getString("publish")); statusHtml = createStatus( htmlURL); panel.add(checkbox,"0,0"); checkbox.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { updateCheck(); } }); panel.add(new JLabel(getString("weekview.print.title_textfield") +":"),"2,2"); panel.add( titleField, "4,2"); panel.add(new JLabel(getString("show_navigation")),"2,4"); panel.add( showNavField, "4,4"); String dateString = getRaplaLocale().formatDate(model.getSelectedDate()); panel.add(new JLabel(getI18n().format("including_date",dateString)),"2,6"); panel.add( saveSelectedDateField, "4,6"); panel.add(new JLabel(getI18n().getString("only_allocation_info")),"2,8"); panel.add( onlyAllocationInfoField, "4,8"); panel.add( statusHtml, "2,10,4,1"); { final String entry = model.getOption(AutoExportPlugin.HTML_EXPORT); checkbox.setSelected( entry != null && entry.equals("true")); } { final String entry = model.getOption(CalendarModel.SHOW_NAVIGATION_ENTRY); showNavField.setSelected( entry == null || entry.equals("true")); } { final String entry = model.getOption(CalendarModel.ONLY_ALLOCATION_INFO); onlyAllocationInfoField.setSelected( entry != null && entry.equals("true")); } { final String entry = model.getOption(CalendarModel.SAVE_SELECTED_DATE); if(entry != null) saveSelectedDateField.setSelected( entry.equals("true")); } updateCheck(); final String title = model.getTitle(); titleField.setText(title); } protected void updateCheck() { boolean htmlEnabled = checkbox.isSelected() && checkbox.isEnabled(); titleField.setEnabled( htmlEnabled); showNavField.setEnabled( htmlEnabled); saveSelectedDateField.setEnabled( htmlEnabled); statusHtml.setEnabled( htmlEnabled); } JPanel createStatus( final JTextField urlLabel) { addCopyPaste(urlLabel); final RaplaButton copyButton = new RaplaButton(); JPanel status = new JPanel() { private static final long serialVersionUID = 1L; public void setEnabled(boolean enabled) { super.setEnabled(enabled); urlLabel.setEnabled( enabled); copyButton.setEnabled( enabled); } }; status.setLayout( new BorderLayout()); urlLabel.setText( ""); urlLabel.setEditable( true ); urlLabel.setFont( urlLabel.getFont().deriveFont( (float)10.0)); status.add( new JLabel("URL: "), BorderLayout.WEST ); status.add( urlLabel, BorderLayout.CENTER ); copyButton.setBorder(BorderFactory.createEmptyBorder(2,2,2,2)); copyButton.setFocusable(false); copyButton.setRolloverEnabled(false); copyButton.setIcon(getIcon("icon.copy")); copyButton.setToolTipText(getString("copy_to_clipboard")); copyButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { urlLabel.requestFocus(); urlLabel.selectAll(); copy(urlLabel,e); } }); status.add(copyButton, BorderLayout.EAST); return status; } public void mapOptionTo() { String title = titleField.getText().trim(); if ( title.length() > 0) { model.setTitle( title ); } else { model.setTitle( null); } String showNavEntry = showNavField.isSelected() ? "true" : "false"; model.setOption( CalendarModel.SHOW_NAVIGATION_ENTRY, showNavEntry); String saveSelectedDate = saveSelectedDateField.isSelected() ? "true" : "false"; model.setOption( CalendarModel.SAVE_SELECTED_DATE, saveSelectedDate); String onlyAlloactionInfo = onlyAllocationInfoField.isSelected() ? "true" : "false"; model.setOption( CalendarModel.ONLY_ALLOCATION_INFO, onlyAlloactionInfo); final String htmlSelected = checkbox.isSelected() ? "true" : "false"; model.setOption( AutoExportPlugin.HTML_EXPORT, htmlSelected); } public JPanel getPanel() { return panel; } public JTextField getURLField() { return htmlURL; } public boolean hasAddressCreationStrategy() { return false; } public String getAddress(String filename, String generator) { return null; } public String getGenerator() { return AutoExportPlugin.CALENDAR_GENERATOR; } }
Java
package org.rapla.plugin.appointmentcounter; import java.awt.Font; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.swing.JComponent; import javax.swing.JLabel; import org.rapla.components.util.DateTools; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.AppointmentBlock; import org.rapla.entities.domain.Repeating; import org.rapla.entities.domain.Reservation; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.AppointmentListener; import org.rapla.gui.AppointmentStatusFactory; import org.rapla.gui.RaplaGUIComponent; import org.rapla.gui.ReservationEdit; import org.rapla.gui.toolkit.RaplaWidget; public class AppointmentCounterFactory implements AppointmentStatusFactory { public RaplaWidget createStatus(RaplaContext context, ReservationEdit reservationEdit) throws RaplaException { return new AppointmentCounter(context, reservationEdit); } class AppointmentCounter extends RaplaGUIComponent implements RaplaWidget { JLabel statusBar = new JLabel(); ReservationEdit reservationEdit; public AppointmentCounter(final RaplaContext context, final ReservationEdit reservationEdit) { super(context); Font font = statusBar.getFont().deriveFont( (float)9.0); statusBar.setFont( font ); this.reservationEdit = reservationEdit; reservationEdit.addAppointmentListener( new AppointmentListener() { public void appointmentRemoved(Collection<Appointment> appointment) { updateStatus(); } public void appointmentChanged(Collection<Appointment> appointment) { updateStatus(); } public void appointmentAdded(Collection<Appointment> appointment) { updateStatus(); } public void appointmentSelected(Collection<Appointment> appointment) { updateStatus(); } }); updateStatus(); } private void updateStatus() { Reservation event = reservationEdit.getReservation(); if ( event == null) { return; } Appointment[] appointments = event.getAppointments(); int count = 0; for (int i = 0; i<appointments.length; i++) { Appointment appointment = appointments[i]; Repeating repeating = appointment.getRepeating(); if ( repeating == null ) { count ++; continue; } if ( repeating.getEnd() == null ){ // Repeats foreever ? count = -1; break; } List<AppointmentBlock> blocks = new ArrayList<AppointmentBlock>(); appointment.createBlocks( appointment.getStart(), DateTools.fillDate(repeating.getEnd()), blocks); count += blocks.size(); } String status = ""; if (count >= 0) status = getString("total_occurances")+ ": " + count; else status = getString("total_occurances")+ ": ? "; // uncomment for selection change test // status += "Selected Appointments " + reservationEdit.getSelectedAppointments(); statusBar.setText( status ); } public JComponent getComponent() { return statusBar; } } }
Java
/*--------------------------------------------------------------------------* | 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.plugin.appointmentcounter; import org.rapla.client.ClientServiceContainer; import org.rapla.client.RaplaClientExtensionPoints; import org.rapla.framework.Configuration; import org.rapla.framework.PluginDescriptor; public class AppointmentCounterPlugin implements PluginDescriptor<ClientServiceContainer> { public final static boolean ENABLE_BY_DEFAULT = true; public String toString() { return "Appointment Counter"; } public void provideServices(ClientServiceContainer container, Configuration config) { if ( !config.getAttributeAsBoolean("enabled", ENABLE_BY_DEFAULT) ) return; container.addContainerProvidedComponent( RaplaClientExtensionPoints.APPOINTMENT_STATUS, AppointmentCounterFactory.class, config); } }
Java
/*--------------------------------------------------------------------------* | 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.plugin.weekview; import javax.swing.Icon; import org.rapla.facade.CalendarModel; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.SwingCalendarView; import org.rapla.gui.SwingViewFactory; import org.rapla.gui.images.Images; public class WeekViewFactory extends RaplaComponent implements SwingViewFactory { public WeekViewFactory( RaplaContext context ) { super( context ); } public final static String WEEK_VIEW = "week"; public SwingCalendarView createSwingView(RaplaContext context, CalendarModel model, boolean editable) throws RaplaException { return new SwingWeekCalendar( context, model, editable); } public String getViewId() { return WEEK_VIEW; } public String getName() { return getString(WEEK_VIEW); } Icon icon; public Icon getIcon() { if ( icon == null) { icon = Images.getIcon("/org/rapla/plugin/weekview/images/week.png"); } return icon; } public String getMenuSortKey() { return "B"; } }
Java
/*--------------------------------------------------------------------------* | 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.plugin.weekview; import java.util.Calendar; import org.rapla.facade.CalendarModel; import org.rapla.facade.CalendarOptions; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; public class SwingDayCalendar extends SwingWeekCalendar { public SwingDayCalendar( RaplaContext sm, CalendarModel model, boolean editable ) throws RaplaException { super( sm, model, editable ); } @Override protected int getDays( CalendarOptions calendarOptions) { return 1; } public int getIncrementSize() { return Calendar.DAY_OF_YEAR; } }
Java
/*--------------------------------------------------------------------------* | 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.plugin.weekview; import org.rapla.client.ClientServiceContainer; import org.rapla.client.RaplaClientExtensionPoints; import org.rapla.framework.Configuration; import org.rapla.framework.PluginDescriptor; public class WeekViewPlugin implements PluginDescriptor<ClientServiceContainer> { public static final boolean ENABLE_BY_DEFAULT = true; public void provideServices(ClientServiceContainer container, Configuration config) { if ( !config.getAttributeAsBoolean("enabled", ENABLE_BY_DEFAULT) ) return; container.addContainerProvidedComponent(RaplaClientExtensionPoints.CALENDAR_VIEW_EXTENSION,WeekViewFactory.class); container.addContainerProvidedComponent(RaplaClientExtensionPoints.CALENDAR_VIEW_EXTENSION,DayViewFactory.class); } }
Java
/*--------------------------------------------------------------------------* | 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.plugin.weekview; import java.awt.Font; import java.text.MessageFormat; import java.util.Calendar; import java.util.Date; import java.util.HashSet; import java.util.Set; import javax.swing.JComponent; import javax.swing.JLabel; import org.rapla.components.calendar.DateChangeEvent; import org.rapla.components.calendar.DateRenderer; import org.rapla.components.calendar.DateRenderer.RenderingInfo; import org.rapla.components.calendar.DateRendererAdapter; import org.rapla.components.calendarview.swing.AbstractSwingCalendar; import org.rapla.components.calendarview.swing.SwingWeekView; import org.rapla.components.util.DateTools; import org.rapla.facade.CalendarModel; import org.rapla.facade.CalendarOptions; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.plugin.abstractcalendar.AbstractRaplaSwingCalendar; import org.rapla.plugin.abstractcalendar.RaplaBuilder; public class SwingWeekCalendar extends AbstractRaplaSwingCalendar { public SwingWeekCalendar( RaplaContext context, CalendarModel model, boolean editable ) throws RaplaException { super( context, model, editable ); } protected AbstractSwingCalendar createView(boolean showScrollPane) { final DateRenderer dateRenderer; final DateRendererAdapter dateRendererAdapter; dateRenderer = getService(DateRenderer.class); dateRendererAdapter = new DateRendererAdapter(dateRenderer, getRaplaLocale().getTimeZone(), getRaplaLocale().getLocale()); final SwingWeekView wv = new SwingWeekView( showScrollPane ) { protected JComponent createSlotHeader(Integer column) { JLabel component = (JLabel) super.createSlotHeader(column); Date date = getDateFromColumn(column); boolean today = DateTools.isSameDay(getQuery().today().getTime(), date.getTime()); if ( today) { component.setFont(component.getFont().deriveFont( Font.BOLD)); } if (isEditable() ) { component.setOpaque(true); RenderingInfo info = dateRendererAdapter.getRenderingInfo(date); if (info.getBackgroundColor() != null) { component.setBackground(info.getBackgroundColor()); } if (info.getForegroundColor() != null) { component.setForeground(info.getForegroundColor()); } if (info.getTooltipText() != null) { component.setToolTipText(info.getTooltipText()); } } return component; } @Override public void rebuild() { // update week weekTitle.setText(MessageFormat.format(getString("calendarweek.abbreviation"), getStartDate())); super.rebuild(); } }; return wv; } public void dateChanged(DateChangeEvent evt) { super.dateChanged( evt ); ((SwingWeekView)view).scrollDateVisible( evt.getDate()); } protected RaplaBuilder createBuilder() throws RaplaException { RaplaBuilder builder = super.createBuilder(); return builder; } @Override protected void configureView() { SwingWeekView view = (SwingWeekView) this.view; CalendarOptions calendarOptions = getCalendarOptions(); int rowsPerHour = calendarOptions.getRowsPerHour(); int startMinutes = calendarOptions.getWorktimeStartMinutes(); int endMinutes = calendarOptions.getWorktimeEndMinutes(); int hours = Math.max(1, (endMinutes - startMinutes) / 60); view.setRowsPerHour( rowsPerHour ); if ( rowsPerHour == 1 ) { if ( hours < 10) { view.setRowSize( 80); } else if ( hours < 15) { view.setRowSize( 60); } else { view.setRowSize( 30); } } else if ( rowsPerHour == 2 ) { if ( hours < 10) { view.setRowSize( 40); } else { view.setRowSize( 20); } } else if ( rowsPerHour >= 4 ) { view.setRowSize( 15); } view.setWorktimeMinutes(startMinutes, endMinutes); int days = getDays( calendarOptions); view.setDaysInView( days); Set<Integer> excludeDays = calendarOptions.getExcludeDays(); if ( days <3) { excludeDays = new HashSet<Integer>(); } view.setExcludeDays( excludeDays ); view.setFirstWeekday( calendarOptions.getFirstDayOfWeek()); view.setToDate(model.getSelectedDate()); // if ( !view.isEditable() ) { // view.setSlotSize( model.getSize()); // } else { // view.setSlotSize( 135 ); // } } /** overide this for dayly views*/ protected int getDays(CalendarOptions calendarOptions) { return calendarOptions.getDaysInWeekview(); } public void scrollToStart() { ((SwingWeekView)view).scrollToStart(); } public int getIncrementSize() { return Calendar.WEEK_OF_YEAR; } }
Java
/*--------------------------------------------------------------------------* | 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.plugin.weekview.server; import org.rapla.facade.CalendarModel; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.plugin.abstractcalendar.server.HTMLViewFactory; import org.rapla.servletpages.RaplaPageGenerator; public class HTMLWeekViewFactory extends RaplaComponent implements HTMLViewFactory { public HTMLWeekViewFactory( RaplaContext context ) { super( context ); } public final static String WEEK_VIEW = "week"; public RaplaPageGenerator createHTMLView(RaplaContext context, CalendarModel model) throws RaplaException { return new HTMLWeekViewPage( context, model); } public String getViewId() { return WEEK_VIEW; } public String getName() { return getString(WEEK_VIEW); } }
Java
/*--------------------------------------------------------------------------* | 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.plugin.weekview.server; import org.rapla.framework.Configuration; import org.rapla.framework.PluginDescriptor; import org.rapla.server.RaplaServerExtensionPoints; import org.rapla.server.ServerServiceContainer; public class WeekViewServerPlugin implements PluginDescriptor<ServerServiceContainer> { static boolean ENABLE_BY_DEFAULT = true; public String toString() { return "Week View"; } public void provideServices(ServerServiceContainer container, Configuration config) { if ( !config.getAttributeAsBoolean("enabled", ENABLE_BY_DEFAULT) ) return; container.addContainerProvidedComponent(RaplaServerExtensionPoints.HTML_CALENDAR_VIEW_EXTENSION,HTMLWeekViewFactory.class); container.addContainerProvidedComponent(RaplaServerExtensionPoints.HTML_CALENDAR_VIEW_EXTENSION,HTMLDayViewFactory.class); } }
Java