code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
/*--------------------------------------------------------------------------* | 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.edit.reservation; import java.util.ArrayList; import java.util.Collection; import org.rapla.entities.domain.Appointment; import org.rapla.framework.RaplaContext; import org.rapla.gui.AppointmentListener; import org.rapla.gui.RaplaGUIComponent; /** Provides AppointmentListener handling.*/ public class AbstractAppointmentEditor extends RaplaGUIComponent { ArrayList<AppointmentListener> listenerList = new ArrayList<AppointmentListener>(); public AbstractAppointmentEditor(RaplaContext sm) { super(sm); } public void addAppointmentListener(AppointmentListener listener) { listenerList.add(listener); } public void removeAppointmentListener(AppointmentListener listener) { listenerList.remove(listener); } public AppointmentListener[] getAppointmentListeners() { return listenerList.toArray(new AppointmentListener[]{}); } protected void fireAppointmentAdded(Collection<Appointment> appointment) { AppointmentListener[] listeners = getAppointmentListeners(); for (int i = 0;i<listeners.length; i++) { listeners[i].appointmentAdded(appointment); } } protected void fireAppointmentRemoved(Collection<Appointment> appointment) { AppointmentListener[] listeners = getAppointmentListeners(); for (int i = 0;i<listeners.length; i++) { listeners[i].appointmentRemoved(appointment); } } protected void fireAppointmentChanged(Collection<Appointment> appointment) { AppointmentListener[] listeners = getAppointmentListeners(); for (int i = 0;i<listeners.length; i++) { listeners[i].appointmentChanged(appointment); } } protected void fireAppointmentSelected(Collection<Appointment> appointment) { AppointmentListener[] listeners = getAppointmentListeners(); for (int i = 0;i<listeners.length; i++) { listeners[i].appointmentSelected(appointment); } } }
04900db4-rob
src/org/rapla/gui/internal/edit/reservation/AbstractAppointmentEditor.java
Java
gpl3
2,904
/*--------------------------------------------------------------------------* | 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.edit.reservation; import java.awt.BorderLayout; import java.awt.Cursor; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyVetoException; import java.beans.VetoableChangeListener; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.ActionMap; import javax.swing.BorderFactory; import javax.swing.ComponentInputMap; import javax.swing.InputMap; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.JToolBar; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.border.Border; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.plaf.ActionMapUIResource; import org.rapla.client.RaplaClientExtensionPoints; import org.rapla.components.layout.TableLayout; import org.rapla.components.util.undo.CommandHistory; import org.rapla.components.util.undo.CommandHistoryChangedListener; import org.rapla.components.util.undo.CommandUndo; import org.rapla.entities.EntityNotFoundException; 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.facade.ModificationEvent; import org.rapla.facade.ModificationModule; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.AppointmentListener; import org.rapla.gui.AppointmentStatusFactory; import org.rapla.gui.ReservationController; import org.rapla.gui.ReservationEdit; import org.rapla.gui.toolkit.DialogUI; import org.rapla.gui.toolkit.EmptyLineBorder; import org.rapla.gui.toolkit.RaplaButton; import org.rapla.gui.toolkit.RaplaFrame; import org.rapla.gui.toolkit.RaplaWidget; class ReservationEditImpl extends AbstractAppointmentEditor implements ReservationEdit { ArrayList<ChangeListener> changeListenerList = new ArrayList<ChangeListener>(); protected Reservation mutableReservation; private Reservation original; CommandHistory commandHistory; JToolBar toolBar = new JToolBar(); RaplaButton saveButtonTop = new RaplaButton(); RaplaButton saveButton = new RaplaButton(); RaplaButton deleteButton = new RaplaButton(); RaplaButton closeButton = new RaplaButton(); Action undoAction = new AbstractAction() { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { try { commandHistory.undo(); } catch (Exception ex) { showException(ex, getMainComponent()); } } }; Action redoAction = new AbstractAction() { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { try { commandHistory.redo(); } catch (Exception ex) { showException(ex, getMainComponent()); } } }; JPanel mainContent = new JPanel(); //JPanel split = new JSplitPane(JSplitPane.VERTICAL_SPLIT); RaplaFrame frame; ReservationInfoEdit reservationInfo; AppointmentListEdit appointmentEdit ; AllocatableSelection allocatableEdit; boolean bSaving = false; boolean bDeleting = false; boolean bSaved; boolean bNew; TableLayout tableLayout = new TableLayout(new double[][] { {TableLayout.FILL} ,{TableLayout.PREFERRED,TableLayout.PREFERRED,TableLayout.FILL} } ); private final Listener listener = new Listener(); List<AppointmentListener> appointmentListeners = new ArrayList<AppointmentListener>(); ReservationEditImpl(RaplaContext sm) throws RaplaException { super( sm); commandHistory = new CommandHistory(); reservationInfo = new ReservationInfoEdit(sm, commandHistory); appointmentEdit = new AppointmentListEdit(sm, commandHistory); allocatableEdit = new AllocatableSelection(sm,true, commandHistory); // horizontalSplit.setTopComponent(appointmentEdit.getComponent()); //horizontalSplit.setBottomComponent(allocatableEdit.getComponent()); /* try { // If run on jdk < 1.3 this will throw a MethodNotFoundException // horizontalSplit.setResizeWeight(0.1); JSplitPane.class.getMethod("setResizeWeight",new Class[] {double.class}).invoke(horizontalSplit,new Object[] {new Double(0.1)}); } catch (Exception ex) { } */ frame = new RaplaFrame(sm); mainContent.setLayout( tableLayout ); mainContent.add(reservationInfo.getComponent(),"0,0"); mainContent.add(appointmentEdit.getComponent(),"0,1"); mainContent.add(allocatableEdit.getComponent(),"0,2"); //allocatableEdit.getComponent().setVisible(false); saveButtonTop.setAction( listener ); saveButton.setAction( listener ); toolBar.setFloatable(false); saveButton.setAlignmentY(JButton.CENTER_ALIGNMENT); deleteButton.setAlignmentY(JButton.CENTER_ALIGNMENT); closeButton.setAlignmentY(JButton.CENTER_ALIGNMENT); JPanel buttonsPanel = new JPanel(); //buttonsPanel.add(deleteButton); buttonsPanel.add(saveButton); buttonsPanel.add(closeButton); toolBar.add(saveButtonTop); toolBar.add(deleteButton); deleteButton.setAction( listener ); RaplaButton vor = new RaplaButton(); RaplaButton back = new RaplaButton(); // Undo-Buttons in Toolbar // final JPanel undoContainer = new JPanel(); redoAction.setEnabled(false); undoAction.setEnabled(false); vor.setAction( redoAction); back.setAction( undoAction); final KeyStroke undoKeyStroke = KeyStroke.getKeyStroke( KeyEvent.VK_Z, ActionEvent.CTRL_MASK ); setAccelerator(back, undoAction, undoKeyStroke); final KeyStroke redoKeyStroke = KeyStroke.getKeyStroke( KeyEvent.VK_Y, ActionEvent.CTRL_MASK ); setAccelerator(vor, redoAction, redoKeyStroke); commandHistory.addCommandHistoryChangedListener(new CommandHistoryChangedListener() { public void historyChanged() { redoAction.setEnabled(commandHistory.canRedo()); boolean canUndo = commandHistory.canUndo(); undoAction.setEnabled(canUndo); String modifier = KeyEvent.getKeyModifiersText(ActionEvent.CTRL_MASK); String redoKeyString =modifier+ "-Y"; String undoKeyString = modifier+ "-Z"; redoAction.putValue(Action.SHORT_DESCRIPTION,getString("redo") + ": " + commandHistory.getRedoText() + " " + redoKeyString); undoAction.putValue(Action.SHORT_DESCRIPTION,getString("undo") + ": " + commandHistory.getUndoText() + " " + undoKeyString); } }); toolBar.add(back); toolBar.add(vor); closeButton.addActionListener(listener); appointmentEdit.addAppointmentListener(allocatableEdit); appointmentEdit.addAppointmentListener(listener); allocatableEdit.addChangeListener(listener); reservationInfo.addChangeListener(listener); reservationInfo.addDetailListener(listener); frame.addVetoableChangeListener(listener); frame.setIconImage( getI18n().getIcon("icon.edit_window_small").getImage()); JPanel contentPane = (JPanel) frame.getContentPane(); contentPane.setLayout(new BorderLayout()); mainContent.setBorder(BorderFactory.createLoweredBevelBorder()); contentPane.add(toolBar, BorderLayout.NORTH); contentPane.add(buttonsPanel, BorderLayout.SOUTH); contentPane.add(mainContent, BorderLayout.CENTER); Dimension dimension = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); frame.setSize(new Dimension( Math.min(dimension.width,990) // BJO 00000032 temp fix for filter out of frame bounds ,Math.min(dimension.height-10,720) //,Math.min(dimension.height-10,1000) ) ); Border emptyLineBorder = new EmptyLineBorder(); //BorderFactory.createEmptyBorder(); Border border2 = BorderFactory.createTitledBorder(emptyLineBorder,getString("reservation.appointments")); Border border3 = BorderFactory.createTitledBorder(emptyLineBorder,getString("reservation.allocations")); appointmentEdit.getComponent().setBorder(border2); allocatableEdit.getComponent().setBorder(border3); saveButton.setText(getString("save")); saveButton.setIcon(getIcon("icon.save")); saveButtonTop.setText(getString("save")); saveButtonTop.setMnemonic(KeyEvent.VK_S); saveButtonTop.setIcon(getIcon("icon.save")); deleteButton.setText(getString("delete")); deleteButton.setIcon(getIcon("icon.delete")); closeButton.setText(getString("abort")); closeButton.setIcon(getIcon("icon.abort")); vor.setToolTipText(getString("redo")); vor.setIcon(getIcon("icon.redo")); back.setToolTipText(getString("undo")); back.setIcon(getIcon("icon.undo")); } protected void setAccelerator(JButton button, Action yourAction, KeyStroke keyStroke) { InputMap keyMap = new ComponentInputMap(button); keyMap.put(keyStroke, "action"); ActionMap actionMap = new ActionMapUIResource(); actionMap.put("action", yourAction); SwingUtilities.replaceUIActionMap(button, actionMap); SwingUtilities.replaceUIInputMap(button, JComponent.WHEN_IN_FOCUSED_WINDOW, keyMap); } protected void setSaved(boolean flag) { bSaved = flag; saveButton.setEnabled(!flag); saveButtonTop.setEnabled(!flag); } /* (non-Javadoc) * @see org.rapla.gui.edit.reservation.IReservationEdit#isModifiedSinceLastChange() */ public boolean isModifiedSinceLastChange() { return !bSaved; } final private ReservationControllerImpl getPrivateReservationController() { return (ReservationControllerImpl) getService(ReservationController.class); } public void addAppointment( Date start, Date end) throws RaplaException { Appointment appointment = getModification().newAppointment( start, end ); AppointmentController controller = appointmentEdit.getAppointmentController(); Repeating repeating= controller.getRepeating(); if ( repeating!= null ) { appointment.setRepeatingEnabled(true); appointment.getRepeating().setFrom(repeating); } appointmentEdit.addAppointment( appointment); } void deleteReservation() throws RaplaException { if (bDeleting) return; getLogger().debug("Reservation has been deleted."); DialogUI dlg = DialogUI.create( getContext() ,mainContent ,true ,getString("warning") ,getString("warning.reservation.delete") ); dlg.setIcon(getIcon("icon.warning")); dlg.start(); closeWindow(); } void updateReservation(Reservation newReservation) throws RaplaException { if (bSaving) return; getLogger().debug("Reservation has been changed."); DialogUI dlg = DialogUI.create( getContext() ,mainContent ,true ,getString("warning") ,getString("warning.reservation.update") ); commandHistory.clear(); try { dlg.setIcon(getIcon("icon.warning")); dlg.start(); this.original = newReservation; setReservation(getModification().edit(newReservation) , null); } catch (RaplaException ex) { showException(ex,frame); } } void refresh(ModificationEvent evt) throws RaplaException { allocatableEdit.dataChanged(evt); } void editReservation(Reservation reservation, AppointmentBlock appointmentBlock) throws RaplaException { ModificationModule mod = getModification(); boolean bNew = false; if ( reservation.isReadOnly()) { mutableReservation = mod.edit(reservation); original = reservation; } else { try { original = getModification().getPersistant( reservation); } catch ( EntityNotFoundException ex) { bNew = true; original = null; } mutableReservation = reservation; } setSaved(!bNew); //printBlocks( appointment ); this.bNew = bNew; deleteButton.setEnabled(!bNew); Appointment appointment = appointmentBlock != null ? appointmentBlock.getAppointment() : null; Appointment mutableAppointment = null; for (Appointment app:mutableReservation.getAppointments()) { if ( appointment != null && app.equals(appointment)) { mutableAppointment = app; } } Date selectedDate = appointmentBlock != null ? new Date(appointmentBlock.getStart()) : null; setReservation(mutableReservation, mutableAppointment); appointmentEdit.getAppointmentController().setSelectedEditDate( selectedDate); setTitle(); boolean packFrame = false; frame.place( true, packFrame); frame.setVisible( true ); // Insert into open ReservationEditWindows, so that // we can't edit the same Reservation in different windows getPrivateReservationController().addReservationEdit(this); reservationInfo.requestFocus(); getLogger().debug("New Reservation-Window created"); } @Override public Reservation getReservation() { return mutableReservation; } public Reservation getOriginal() { return original; } @Override public Collection<Appointment> getSelectedAppointments() { Collection<Appointment> appointments = new ArrayList<Appointment>(); for ( Appointment value:appointmentEdit.getListEdit().getSelectedValues()) { appointments.add( value); } return appointments; } private void setTitle() { String title = getI18n().format((bNew) ? "new_reservation.format" : "edit_reservation.format" ,getName(mutableReservation)); frame.setTitle(title); } private void setReservation(Reservation newReservation, Appointment mutableAppointment) throws RaplaException { commandHistory.clear(); this.mutableReservation = newReservation; appointmentEdit.setReservation(mutableReservation, mutableAppointment); allocatableEdit.setReservation(mutableReservation, original); reservationInfo.setReservation(mutableReservation); List<AppointmentStatusFactory> statusFactories = new ArrayList<AppointmentStatusFactory>(); Collection<AppointmentStatusFactory> list= getContainer().lookupServicesFor(RaplaClientExtensionPoints.APPOINTMENT_STATUS); for (AppointmentStatusFactory entry:list) { statusFactories.add(entry); } JPanel status =appointmentEdit.getListEdit().getStatusBar(); status.removeAll(); for (AppointmentStatusFactory factory: statusFactories) { RaplaWidget statusWidget = factory.createStatus(getContext(), this); status.add( statusWidget.getComponent()); } // Should be done in initialization method of Appointmentstatus. The appointments are already selected then, so you can query the selected appointments thers. // if(appointment == null) // fireAppointmentSelected(Collections.singleton(mutableReservation.getAppointments()[0])); // else // fireAppointmentSelected(Collections.singleton(appointment)); } public void closeWindow() { appointmentEdit.dispose(); getPrivateReservationController().removeReservationEdit(this); frame.dispose(); getLogger().debug("Edit window closed."); } class Listener extends AbstractAction implements AppointmentListener,ChangeListener,VetoableChangeListener, ReservationInfoEdit.DetailListener { private static final long serialVersionUID = 1L; // Implementation of ReservationListener public void appointmentRemoved(Collection<Appointment> appointment) { setSaved(false); ReservationEditImpl.this.fireAppointmentRemoved(appointment); fireReservationChanged(new ChangeEvent(appointmentEdit)); } public void appointmentAdded(Collection<Appointment> appointment) { setSaved(false); ReservationEditImpl.this.fireAppointmentAdded(appointment); fireReservationChanged(new ChangeEvent(appointmentEdit)); } public void appointmentChanged(Collection<Appointment> appointment) { setSaved(false); ReservationEditImpl.this.fireAppointmentChanged(appointment); fireReservationChanged(new ChangeEvent(appointmentEdit)); } public void appointmentSelected(Collection<Appointment> appointment) { ReservationEditImpl.this.fireAppointmentSelected(appointment); } public void stateChanged(ChangeEvent evt) { if (evt.getSource() == reservationInfo) { getLogger().debug("ReservationInfo changed"); setSaved(false); setTitle(); } if (evt.getSource() == allocatableEdit) { getLogger().debug("AllocatableEdit changed"); setSaved(false); } fireReservationChanged(evt); } public void detailChanged() { boolean isMain = reservationInfo.isMainView(); if ( isMain != appointmentEdit.getComponent().isVisible() ) { appointmentEdit.getComponent().setVisible( isMain ); allocatableEdit.getComponent().setVisible( isMain ); if ( isMain ) { tableLayout.setRow(0, TableLayout.PREFERRED); tableLayout.setRow(1, TableLayout.PREFERRED); tableLayout.setRow(2, TableLayout.FILL); } else { tableLayout.setRow(0, TableLayout.FILL); tableLayout.setRow(1, 0); tableLayout.setRow(2, 0); } mainContent.validate(); } } public void actionPerformed(ActionEvent evt) { try { if (evt.getSource() == saveButton || evt.getSource() == saveButtonTop) { save(); } if (evt.getSource() == deleteButton) { delete(); } if (evt.getSource() == closeButton) { if (canClose()) closeWindow(); } } catch (RaplaException ex) { showException(ex, null); } } public void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException { if (!canClose()) throw new PropertyVetoException("Don't close",evt); closeWindow(); } } protected boolean canClose() { if (!isModifiedSinceLastChange()) return true; try { DialogUI dlg = DialogUI.create( getContext() ,mainContent ,true ,getString("confirm-close.title") ,getString("confirm-close.question") ,new String[] { getString("confirm-close.ok") ,getString("back") } ); dlg.setIcon(getIcon("icon.question")); dlg.setDefault(1); dlg.start(); return (dlg.getSelectedIndex() == 0) ; } catch (RaplaException e) { return true; } } /* (non-Javadoc) * @see org.rapla.gui.edit.reservation.IReservationEdit#save() */ @Override public void save() throws RaplaException { try { frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); bSaving = true; ReservationControllerImpl.ReservationSave saveCommand = getPrivateReservationController().new ReservationSave(mutableReservation, original, frame); if (getClientFacade().getCommandHistory().storeAndExecute(saveCommand)) { setSaved(true); } } catch (RaplaException ex) { showException(ex, frame); } finally { frame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); if (bSaved) closeWindow(); bSaving = false; } } /* (non-Javadoc) * @see org.rapla.gui.edit.reservation.IReservationEdit#delete() */ @Override public void delete() throws RaplaException { try { DialogUI dlg = getInfoFactory().createDeleteDialog(new Object[] {mutableReservation} ,frame); dlg.start(); if (dlg.getSelectedIndex() == 0) { bDeleting = true; Set<Reservation> reservationsToRemove = Collections.singleton( original); Set<Appointment> appointmentsToRemove = Collections.emptySet(); Map<Appointment, List<Date>> exceptionsToAdd = Collections.emptyMap(); CommandUndo<RaplaException> deleteCommand = getPrivateReservationController().new DeleteBlocksCommand(reservationsToRemove, appointmentsToRemove, exceptionsToAdd) { public String getCommandoName() { return getString("delete") + " " + getString("reservation"); } }; getClientFacade().getCommandHistory().storeAndExecute(deleteCommand); closeWindow(); } } finally { bDeleting = false; } } protected ChangeListener[] getReservationInfpListeners() { return changeListenerList.toArray(new ChangeListener[]{}); } protected void fireReservationChanged(ChangeEvent evt) { for (ChangeListener listener: getReservationInfpListeners()) { listener.stateChanged( evt); } } @Override public void addReservationChangeListener(ChangeListener listener) { changeListenerList.add(listener); } @Override public void removeReservationChangeListener(ChangeListener listener) { changeListenerList.remove( listener); } }
04900db4-rob
src/org/rapla/gui/internal/edit/reservation/ReservationEditImpl.java
Java
gpl3
24,548
/*--------------------------------------------------------------------------* | 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.edit.reservation; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; 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.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.swing.BoxLayout; import javax.swing.DefaultListModel; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.ListCellRenderer; import javax.swing.UIManager; import javax.swing.border.Border; import javax.swing.border.EmptyBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.rapla.components.layout.TableLayout; import org.rapla.components.util.DateTools; import org.rapla.components.util.undo.CommandHistory; import org.rapla.components.util.undo.CommandUndo; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.AppointmentBlock; import org.rapla.entities.domain.AppointmentStartComparator; import org.rapla.entities.domain.Period; import org.rapla.entities.domain.Repeating; import org.rapla.entities.domain.Reservation; import org.rapla.framework.Disposable; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.internal.edit.RaplaListEdit; import org.rapla.gui.toolkit.RaplaButton; import org.rapla.gui.toolkit.RaplaWidget; /** Default GUI for editing multiple appointments.*/ class AppointmentListEdit extends AbstractAppointmentEditor implements RaplaWidget ,Disposable { private AppointmentController appointmentController; private RaplaListEdit<Appointment> listEdit; private CommandHistory commandHistory; private boolean disableInternSelectionListener = false; protected Reservation mutableReservation; private Listener listener = new Listener(); DefaultListModel model = new DefaultListModel(); // use sorted model to start with sorting // respect dependencies ! on other components @SuppressWarnings("rawtypes") Comparator comp = new AppointmentStartComparator(); @SuppressWarnings("unchecked") SortedListModel sortedModel = new SortedListModel(model, SortedListModel.SortOrder.ASCENDING,comp ); RaplaButton freeButtonNext = new RaplaButton(); @SuppressWarnings("unchecked") AppointmentListEdit(RaplaContext sm, CommandHistory commandHistory) throws RaplaException { super(sm); this.commandHistory = commandHistory; appointmentController = new AppointmentController(sm, commandHistory); listEdit = new RaplaListEdit<Appointment>(getI18n(),appointmentController.getComponent(), listener); listEdit.getToolbar().add( freeButtonNext); freeButtonNext.setText(getString("appointment.search_free")); freeButtonNext.addActionListener( listener ); appointmentController.addChangeListener(listener); // activate this as a first step listEdit.getList().setModel(sortedModel); //listEdit.getList().setModel(model); listEdit.setColoredBackgroundEnabled(true); listEdit.setMoveButtonVisible(false); listEdit.getList().setCellRenderer(new AppointmentCellRenderer()); } public RaplaListEdit<Appointment> getListEdit() { return listEdit; } @SuppressWarnings("unchecked") private void addToModel(Appointment appointment) { model.addElement( appointment); } public JComponent getComponent() { return listEdit.getComponent(); } public void setReservation(Reservation mutableReservation, Appointment mutableAppointment) { this.mutableReservation = mutableReservation; Appointment[] appointments = mutableReservation.getAppointments(); model.clear(); for (Appointment app:appointments) { addToModel(app); } if ( mutableAppointment != null ) { selectAppointment(mutableAppointment, false); } else if ( appointments.length> 0 ){ selectAppointment(appointments[0], false); } } private void selectAppointment(Appointment appointment,boolean disableListeners) { if (disableListeners) { disableInternSelectionListener = true; } try { boolean shouldScroll = true; listEdit.getList().clearSelection(); listEdit.getList().setSelectedValue( appointment ,shouldScroll ); appointmentController.setAppointment( appointment ); } finally { if (disableListeners) { disableInternSelectionListener = false; } } } public void dispose() { appointmentController.dispose(); } class AppointmentCellRenderer implements ListCellRenderer { Border focusBorder = UIManager.getBorder("List.focusCellHighlightBorder"); Border emptyBorder = new EmptyBorder(1,1,1,1); Color selectionBackground = UIManager.getColor("List.selectionBackground"); Color background = UIManager.getColor("List.background"); AppointmentRow row = new AppointmentRow(); public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { row.setAppointment((Appointment) value,index); row.setBackground((isSelected) ? selectionBackground : background); row.setBorder((cellHasFocus) ? focusBorder : emptyBorder); return row; } } class AppointmentRow extends JPanel { private static final long serialVersionUID = 1L; JPanel content = new JPanel(); AppointmentIdentifier identifier = new AppointmentIdentifier(); AppointmentRow() { double fill = TableLayout.FILL; double pre = TableLayout.PREFERRED; this.setLayout(new TableLayout(new double[][] {{pre,5,fill,10,pre},{1,fill,1}})); this.add(identifier,"0,1,l,f"); this.add(content,"2,1,f,c"); this.setMaximumSize(new Dimension(500,40)); content.setOpaque(false); identifier.setOpaque(true); identifier.setBorder(null); } public void setAppointment(Appointment appointment,int index) { identifier.setText(getRaplaLocale().formatNumber(index + 1)); identifier.setIndex(index); content.setLayout(new BoxLayout(content,BoxLayout.Y_AXIS)); content.removeAll(); JLabel label1 = new JLabel(getAppointmentFormater().getSummary(appointment)); content.add( label1 ); if (appointment.getRepeating() != null) { label1.setIcon( getIcon("icon.repeating") ); Repeating r = appointment.getRepeating(); List<Period> periods = getPeriodModel().getPeriodsFor(appointment.getStart()); String repeatingString = getAppointmentFormater().getSummary(r,periods); content.add(new JLabel(repeatingString)); if ( r.hasExceptions() ) { content.add(new JLabel( getAppointmentFormater().getExceptionSummary( r ) ) ); } } else { label1.setIcon( getIcon("icon.single") ); } } } class Listener implements ActionListener, ChangeListener { public void actionPerformed(ActionEvent evt) { if ( evt.getSource() == freeButtonNext ) { appointmentController.nextFreeAppointment(); } if (evt.getActionCommand().equals("remove")) { @SuppressWarnings("deprecation") Object[] objects = listEdit.getList().getSelectedValues(); RemoveAppointments command = new RemoveAppointments( objects); commandHistory.storeAndExecute(command); } else if (evt.getActionCommand().equals("new")) { try { Appointment appointment = createAppointmentFromSelected(); NewAppointment command = new NewAppointment(appointment); commandHistory.storeAndExecute(command); } catch (RaplaException ex) { showException(ex, getMainComponent()); } } else if (evt.getActionCommand().equals("split")) { AppointmentSplit command = new AppointmentSplit(); commandHistory.storeAndExecute(command); } else if (evt.getActionCommand().equals("edit")) { Appointment newAppointment = (Appointment) listEdit.getList().getSelectedValue(); Appointment oldAppointment = appointmentController.getAppointment(); if (!disableInternSelectionListener) { if (oldAppointment!=null && !newAppointment.equals(oldAppointment) ) { AppointmentSelectionChange appointmentCommand = new AppointmentSelectionChange(oldAppointment, newAppointment); commandHistory.storeAndExecute(appointmentCommand); }else { appointmentController.setAppointment(newAppointment); } } } else if (evt.getActionCommand().equals("select")) { Collection<Appointment> appointments = new ArrayList<Appointment>(); @SuppressWarnings("deprecation") Object[] values = listEdit.getList().getSelectedValues(); for ( Object value:values) { appointments.add( (Appointment)value); } freeButtonNext.setEnabled( appointments.size() == 1); fireAppointmentSelected(appointments); } } @SuppressWarnings("unchecked") public void stateChanged(ChangeEvent evt) { Appointment appointment = appointmentController.getAppointment(); @SuppressWarnings("deprecation") Object[] values = listEdit.getList().getSelectedValues(); List<Object> selectedValues = Arrays.asList(values); int indexOf = model.indexOf(appointment); if ( indexOf >=0) { model.set(indexOf, appointment); } listEdit.updateSort( selectedValues); fireAppointmentChanged(Collections.singleton(appointment)); } } public AppointmentController getAppointmentController() { return appointmentController; } public void addAppointment(Appointment appointment) { NewAppointment newAppointment = new NewAppointment(appointment); commandHistory.storeAndExecute( newAppointment); } /** * This class collects any information of removed appointments in the edit view. * This is where undo/redo for removing an appointment at the fields on the top-left * of the edit view is realized. * @author Jens Fritz * */ public class RemoveAppointments implements CommandUndo<RuntimeException> { private final Map<Appointment,Allocatable[]> list; private int[] selectedAppointment; public RemoveAppointments(Object[] list) { this.list = new LinkedHashMap<Appointment,Allocatable[]>(); for ( Object obj:list) { Appointment appointment = (Appointment) obj; Allocatable[] restrictedAllocatables = mutableReservation.getRestrictedAllocatables(appointment); this.list.put ( appointment, restrictedAllocatables); } } public boolean execute() { selectedAppointment = listEdit.getList().getSelectedIndices(); Set<Appointment> appointmentList = list.keySet(); for (Appointment appointment:appointmentList) { mutableReservation.removeAppointment(appointment); } model.clear(); for (Appointment app:mutableReservation.getAppointments()) { addToModel(app); } fireAppointmentRemoved(appointmentList); listEdit.getList().requestFocus(); return true; } public boolean undo() { Set<Appointment> appointmentList = list.keySet(); for (Appointment appointment:appointmentList) { mutableReservation.addAppointment(appointment); Allocatable[] removedAllocatables = list.get( appointment); mutableReservation.setRestriction(appointment, removedAllocatables); } model.clear(); for (Appointment app:mutableReservation.getAppointments()) { addToModel(app); } fireAppointmentAdded(appointmentList); disableInternSelectionListener = true; try { listEdit.getList().setSelectedIndices(selectedAppointment); } finally { disableInternSelectionListener = false; } return true; } public String getCommandoName() { return getString("remove")+ " " + getString("appointment"); } } protected Appointment createAppointmentFromSelected() throws RaplaException { Appointment[] appointments = mutableReservation.getAppointments(); Appointment appointment; if (appointments.length == 0) { Date start = new Date(DateTools.cutDate(new Date()).getTime()+ getCalendarOptions().getWorktimeStartMinutes() * DateTools.MILLISECONDS_PER_MINUTE); Date end = new Date(start.getTime()+ DateTools.MILLISECONDS_PER_HOUR); appointment = getModification().newAppointment(start, end); } else { // copy the selected appointment as template // if no appointment is selected use the last final int selectedIndex = listEdit.getSelectedIndex(); final int index = selectedIndex > -1 ? selectedIndex : appointments.length - 1; final Appointment toClone = appointments[index]; // this allows each appointment as template appointment = getReservationController().copyAppointment(toClone); Repeating repeating = appointment.getRepeating(); if (repeating != null) { repeating.clearExceptions(); } } return appointment; } /** * This class collects any information of added appointments in the edit view. * This is where undo/redo for adding an appointment at the fields on the top-left * of the edit view is realized. * @author Jens Fritz * */ //Erstellt von Matthias Both public class NewAppointment implements CommandUndo<RuntimeException> { private Appointment newAppointment; public NewAppointment( Appointment appointment) { this.newAppointment = appointment; } public boolean execute() { mutableReservation.addAppointment(newAppointment); addToModel(newAppointment); selectAppointment(newAppointment, true); fireAppointmentAdded(Collections.singleton(newAppointment)); return true; } public boolean undo() { model.removeElement(newAppointment); mutableReservation.removeAppointment(newAppointment); fireAppointmentRemoved(Collections.singleton(newAppointment)); return true; } public String getCommandoName() { return getString("new_appointment"); } } /** * This class collects any information of an appointment that is split from a repeating type * into several single appointments in the edit view. * This is where undo/redo for splitting an appointment at the fields on the top-right * of the edit view is realized. * @author Jens Fritz * */ //Erstellt von Matthias Both public class AppointmentSplit implements CommandUndo<RuntimeException> { Appointment wholeAppointment; Allocatable[] allocatablesFor; List<Appointment> splitAppointments; public AppointmentSplit() { } public boolean execute() { try { // Generate time blocks from selected appointment List<AppointmentBlock> splits = new ArrayList<AppointmentBlock>(); Appointment appointment = appointmentController.getAppointment(); appointment.createBlocks(appointment.getStart(), DateTools.fillDate(appointment.getMaxEnd()), splits); allocatablesFor = mutableReservation.getAllocatablesFor(appointment); wholeAppointment = appointment; fireAppointmentRemoved(Collections.singleton(appointment)); splitAppointments = new ArrayList<Appointment>(); // Create single appointments for every time block for (AppointmentBlock block: splits) { Appointment newApp = getModification().newAppointment(new Date(block.getStart()), new Date(block.getEnd())); // Add appointment to list splitAppointments.add( newApp ); mutableReservation.addAppointment(newApp); } for (Allocatable alloc:allocatablesFor) { Appointment[] restrictions =mutableReservation.getRestriction(alloc); if ( restrictions.length > 0) { LinkedHashSet<Appointment> newRestrictions = new LinkedHashSet<Appointment>( Arrays.asList( restrictions)); newRestrictions.addAll(splitAppointments); mutableReservation.setRestriction(alloc, newRestrictions.toArray(Appointment.EMPTY_ARRAY)); } } // we need to remove the appointment after splitting not before, otherwise allocatable connections could be lost mutableReservation.removeAppointment( appointment); model.removeElement( appointment); for (Appointment newApp:splitAppointments) { addToModel(newApp); } fireAppointmentAdded(splitAppointments); if (splitAppointments.size() > 0) { Appointment app = splitAppointments.get(0); selectAppointment( app, true); } return true; } catch (RaplaException ex) { showException(ex, getComponent()); return false; } } public boolean undo() { // Switch the type of the appointment to old type mutableReservation.addAppointment(wholeAppointment); for (Allocatable alloc : allocatablesFor) { Appointment[] restrictions = mutableReservation.getRestriction(alloc); if (restrictions.length > 0) { LinkedHashSet<Appointment> newRestrictions = new LinkedHashSet<Appointment>(Arrays.asList(restrictions)); newRestrictions.removeAll(splitAppointments); newRestrictions.add(wholeAppointment); mutableReservation.setRestriction(alloc,newRestrictions.toArray(Appointment.EMPTY_ARRAY)); } } // same here we remove the split appointments after we add the old appointment so no allocatable connections gets lost for (Appointment newApp : splitAppointments) { mutableReservation.removeAppointment(newApp); model.removeElement(newApp); } addToModel(wholeAppointment); fireAppointmentAdded(Collections.singleton(wholeAppointment)); selectAppointment(wholeAppointment, true); return true; } public String getCommandoName() { return getString("appointment.convert"); } } /** * This class collects any information of which appointment is selected in the edit view. * This is where undo/redo for selecting an appointment at the fields on the top-left * of the edit view is realized. * @author Jens Fritz * */ //Erstellt von Dominick Krickl-Vorreiter public class AppointmentSelectionChange implements CommandUndo<RuntimeException> { private final Appointment oldAppointment; private final Appointment newAppointment; public AppointmentSelectionChange(Appointment oldAppointment, Appointment newAppointment) { this.oldAppointment = oldAppointment; this.newAppointment = newAppointment; } public boolean execute() { setAppointment(newAppointment); return oldAppointment != null; } public boolean undo() { setAppointment(oldAppointment); return true; } private void setAppointment(Appointment toAppointment) { appointmentController.setAppointment(toAppointment); selectAppointment(toAppointment, true); } public String getCommandoName() { return getString("select") + " " + getString("appointment"); } } }
04900db4-rob
src/org/rapla/gui/internal/edit/reservation/AppointmentListEdit.java
Java
gpl3
20,331
/*--------------------------------------------------------------------------* | 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.edit.reservation; import java.awt.Component; import javax.swing.BoxLayout; import javax.swing.JLabel; import javax.swing.JPanel; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.Reservation; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.RaplaGUIComponent; import org.rapla.gui.ReservationCheck; import org.rapla.gui.toolkit.DialogUI; public class DefaultReservationCheck extends RaplaGUIComponent implements ReservationCheck { public DefaultReservationCheck(RaplaContext context) { super(context); } public boolean check(Reservation reservation, Component sourceComponent) throws RaplaException { try { getClientFacade().checkReservation( reservation); Appointment[] appointments = reservation.getAppointments(); Appointment duplicatedAppointment = null; for (int i=0;i<appointments.length;i++) { for (int j=i + 1;j<appointments.length;j++) if (appointments[i].matches(appointments[j])) { duplicatedAppointment = appointments[i]; break; } } JPanel warningPanel = new JPanel(); warningPanel.setLayout( new BoxLayout( warningPanel, BoxLayout.Y_AXIS)); if (duplicatedAppointment != null) { JLabel warningLabel = new JLabel(); warningLabel.setForeground(java.awt.Color.red); warningLabel.setText (getI18n().format ( "warning.duplicated_appointments" ,getAppointmentFormater().getShortSummary(duplicatedAppointment) ) ); warningPanel.add( warningLabel); } if (reservation.getAllocatables().length == 0) { JLabel warningLabel = new JLabel(); warningLabel.setForeground(java.awt.Color.red); warningLabel.setText(getString("warning.no_allocatables_selected")); warningPanel.add( warningLabel); } if ( warningPanel.getComponentCount() > 0) { DialogUI dialog = DialogUI.create( getContext() ,sourceComponent ,true ,warningPanel ,new String[] { getString("continue") ,getString("back") } ); dialog.setTitle( getString("warning")); dialog.setIcon(getIcon("icon.warning")); dialog.setDefault(1); dialog.getButton(0).setIcon(getIcon("icon.save")); dialog.getButton(1).setIcon(getIcon("icon.cancel")); dialog.start(); if (dialog.getSelectedIndex() == 0) { return true; } else { return false; } } return true; } catch (RaplaException ex) { showWarning( ex.getMessage(), sourceComponent); return false; } } }
04900db4-rob
src/org/rapla/gui/internal/edit/reservation/DefaultReservationCheck.java
Java
gpl3
4,407
/*--------------------------------------------------------------------------* | 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.edit.reservation; import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Color; import java.awt.Component; import java.awt.Graphics; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.Locale; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.ButtonGroup; import javax.swing.DefaultListCellRenderer; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.ListCellRenderer; import javax.swing.ListSelectionModel; import javax.swing.SwingConstants; import javax.swing.UIManager; import javax.swing.border.Border; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import org.rapla.components.calendar.DateChangeEvent; import org.rapla.components.calendar.DateChangeListener; import org.rapla.components.calendar.RaplaCalendar; import org.rapla.components.calendar.RaplaNumber; import org.rapla.components.calendar.RaplaTime; import org.rapla.components.layout.TableLayout; import org.rapla.components.util.DateTools; import org.rapla.components.util.undo.CommandHistory; import org.rapla.components.util.undo.CommandUndo; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.Repeating; import org.rapla.entities.domain.RepeatingEnding; import org.rapla.entities.domain.RepeatingType; import org.rapla.entities.domain.Reservation; import org.rapla.entities.domain.ReservationHelper; import org.rapla.entities.domain.internal.AppointmentImpl; import org.rapla.facade.CalendarOptions; import org.rapla.framework.Disposable; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.framework.RaplaLocale; import org.rapla.gui.RaplaGUIComponent; import org.rapla.gui.internal.common.PeriodChooser; import org.rapla.gui.toolkit.DialogUI; import org.rapla.gui.toolkit.MonthChooser; import org.rapla.gui.toolkit.RaplaButton; import org.rapla.gui.toolkit.RaplaWidget; import org.rapla.gui.toolkit.WeekdayChooser; /** GUI for editing a single Appointment. */ public class AppointmentController extends RaplaGUIComponent implements Disposable ,RaplaWidget { JPanel panel = new JPanel(); SingleEditor singleEditor = new SingleEditor(); JPanel repeatingContainer = new JPanel(); RepeatingEditor repeatingEditor = new RepeatingEditor(); Appointment appointment = null; Repeating repeating; RepeatingType savedRepeatingType = null; ArrayList<ChangeListener> listenerList = new ArrayList<ChangeListener>(); JPanel repeatingType = new JPanel(); JRadioButton noRepeating = new JRadioButton(); JRadioButton weeklyRepeating = new JRadioButton(); JRadioButton dailyRepeating = new JRadioButton(); JRadioButton monthlyRepeating = new JRadioButton(); JRadioButton yearlyRepeating = new JRadioButton(); CardLayout repeatingCard = new CardLayout(); // Button for splitting appointments RaplaButton convertButton = new RaplaButton(); private CommandHistory commandHistory; Date selectedEditDate = null; public AppointmentController(RaplaContext sm, CommandHistory commandHistory) throws RaplaException { super(sm); this.commandHistory = commandHistory; panel.setLayout(new BorderLayout()); panel.add(repeatingType, BorderLayout.NORTH); repeatingType.setLayout(new BoxLayout(repeatingType, BoxLayout.X_AXIS)); repeatingType.add(noRepeating); repeatingType.add(weeklyRepeating); repeatingType.add(dailyRepeating); repeatingType.add(monthlyRepeating); repeatingType.add(yearlyRepeating); repeatingType.add(Box.createHorizontalStrut(40)); repeatingType.add(convertButton); ButtonGroup buttonGroup = new ButtonGroup(); buttonGroup.add(noRepeating); buttonGroup.add(weeklyRepeating); buttonGroup.add(dailyRepeating); buttonGroup.add(monthlyRepeating); buttonGroup.add(yearlyRepeating); panel.add(repeatingContainer, BorderLayout.CENTER); Border emptyLineBorder = new Border() { Insets insets = new Insets(1, 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(0, 0, c.getWidth(), 0); } public Insets getBorderInsets(Component c) { return insets; } public boolean isBorderOpaque() { return true; } }; Border outerBorder = (BorderFactory.createCompoundBorder( BorderFactory.createEmptyBorder(0, 5, 0, 5) // ,BorderFactory.createEmptyBorder() , emptyLineBorder)); repeatingContainer.setBorder(BorderFactory.createCompoundBorder( outerBorder, BorderFactory.createEmptyBorder(10, 5, 10, 5))); repeatingContainer.setLayout(repeatingCard); repeatingContainer.add(singleEditor.getComponent(), "0"); repeatingContainer.add(repeatingEditor.getComponent(), "1"); singleEditor.initialize(); repeatingEditor.initialize(); ActionListener listener = new ActionListener() { public void actionPerformed(ActionEvent evt) { switchRepeatings(); } }; noRepeating.addActionListener(listener); weeklyRepeating.addActionListener(listener); monthlyRepeating.addActionListener(listener); dailyRepeating.addActionListener(listener); yearlyRepeating.addActionListener(listener); noRepeating.setText(getString("no_repeating")); weeklyRepeating.setText(getString("weekly")); dailyRepeating.setText(getString("daily")); monthlyRepeating.setText(getString("monthly")); yearlyRepeating.setText(getString("yearly")); // Rapla 1.4: Initialize the split appointment button convertButton.setText(getString("appointment.convert")); } private void switchRepeatings() { UndoRepeatingTypeChange repeatingCommand = new UndoRepeatingTypeChange(savedRepeatingType, getCurrentRepeatingType()); commandHistory.storeAndExecute(repeatingCommand); } public void setAppointment(Appointment appointment) { this.appointment = appointment; this.repeating = appointment.getRepeating(); if (appointment.getRepeating() != null) { repeatingEditor.mapFromAppointment(); repeatingCard.show(repeatingContainer, "1"); if (repeating.isWeekly()) { weeklyRepeating.setSelected(true); } else if (repeating.isDaily()) { dailyRepeating.setSelected(true); } else if (repeating.isMonthly()) { monthlyRepeating.setSelected(true); } else if (repeating.isYearly()) { yearlyRepeating.setSelected(true); } } else { singleEditor.mapFromAppointment(); repeatingCard.show(repeatingContainer, "0"); noRepeating.setSelected(true); } savedRepeatingType = getCurrentRepeatingType(); } public Appointment getAppointment() { return appointment; } public void setSelectedEditDate(Date selectedEditDate) { this.selectedEditDate = selectedEditDate; } public Date getSelectedEditDate() { return selectedEditDate; } public void dispose() { singleEditor.dispose(); repeatingEditor.dispose(); } public JComponent getComponent() { return panel; } /** * registers new ChangeListener for this component. An ChangeEvent will be * fired to every registered ChangeListener when the appointment changes. * * @see javax.swing.event.ChangeListener * @see javax.swing.event.ChangeEvent */ public void addChangeListener(ChangeListener listener) { listenerList.add(listener); } /** removes a listener from this component. */ public void removeChangeListener(ChangeListener listener) { listenerList.remove(listener); } public ChangeListener[] getChangeListeners() { return listenerList.toArray(new ChangeListener[] {}); } protected void fireAppointmentChanged() { if (listenerList.size() == 0) return; ChangeEvent evt = new ChangeEvent(this); ChangeListener[] listeners = getChangeListeners(); for (int i = 0; i < listeners.length; i++) { listeners[i].stateChanged(evt); } getLogger().debug("appointment changed: " + appointment); } static double ROW_SIZE = 21; private void setToWholeDays(final boolean oneDayEvent) { boolean wasSet = appointment.isWholeDaysSet(); appointment.setWholeDays(oneDayEvent); if (wasSet && !oneDayEvent) { // BJO 00000070 CalendarOptions calenderOptions = getCalendarOptions(); int startMinutes = calenderOptions.getWorktimeStartMinutes(); int endMinutes = calenderOptions.getWorktimeEndMinutes(); Date start = new Date(appointment.getStart().getTime() + startMinutes * DateTools.MILLISECONDS_PER_MINUTE); Date end = new Date(appointment.getEnd().getTime() - DateTools.MILLISECONDS_PER_DAY + endMinutes * DateTools.MILLISECONDS_PER_MINUTE); // BJO 00000070 if ( end.before( start)) { end =DateTools.addDay(end); } appointment.move(start, end); } } class SingleEditor implements DateChangeListener, Disposable { JPanel content = new JPanel(); JLabel startLabel = new JLabel(); RaplaCalendar startDate; JLabel startTimeLabel = new JLabel(); RaplaTime startTime; JLabel endLabel = new JLabel(); RaplaCalendar endDate; JLabel endTimeLabel = new JLabel(); RaplaTime endTime; JCheckBox oneDayEventCheckBox = new JCheckBox(); private boolean listenerEnabled = true; public SingleEditor() { double pre = TableLayout.PREFERRED; double size[][] = { { pre, 5, pre, 10, pre, 5, pre, 5, pre }, // Columns { ROW_SIZE, 6, ROW_SIZE, 6, ROW_SIZE } }; // Rows TableLayout tableLayout = new TableLayout(size); content.setLayout(tableLayout); } public void initialize() { startDate = createRaplaCalendar(); endDate = createRaplaCalendar(); startTime = createRaplaTime(); endTime = createRaplaTime(); content.add(startLabel, "0,0,r,f"); startLabel.setText(getString("start_date")); startTimeLabel.setText(getString("time_at")); endTimeLabel.setText(getString("time_at")); content.add(startDate, "2,0,f,f"); content.add(startTimeLabel, "4,0,l,f"); content.add(startTime, "6,0,f,f"); content.add(endLabel, "0,2,r,f"); endLabel.setText(getString("end_date")); content.add(endDate, "2,2,f,f"); content.add(endTimeLabel, "4,2,r,f"); content.add(endTime, "6,2,f,f"); oneDayEventCheckBox.setText(getString("all-day")); content.add(oneDayEventCheckBox, "8,0"); oneDayEventCheckBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent itemevent) { boolean selected = itemevent.getStateChange() == ItemEvent.SELECTED; setToWholeDays(selected); processChange(itemevent.getSource()); } }); startDate.addDateChangeListener(this); startTime.addDateChangeListener(this); endDate.addDateChangeListener(this); endTime.addDateChangeListener(this); } public JComponent getComponent() { return content; } public void dispose() { } public void dateChanged(DateChangeEvent evt) { final Object source = evt.getSource(); processChange(source); } private void processChange(final Object source) { if (!listenerEnabled) return; try { listenerEnabled = false; RaplaLocale raplaLocale = getRaplaLocale(); Date appStart = appointment.getStart(); Date appEnd = appointment.getEnd(); long duration = appEnd.getTime() - appStart.getTime(); boolean wholeDaysSet = appointment.isWholeDaysSet(); boolean oneDayEventSelected = oneDayEventCheckBox.isSelected(); if (source == startDate || source == startTime) { Date date = startDate.getDate(); Date time = startTime.getTime(); Date newStart = raplaLocale.toDate(date, time); Date newEnd = new Date(newStart.getTime() + duration); if (newStart.equals(appStart) && newEnd.equals(appEnd)) return; UndoSingleEditorChange command = new UndoSingleEditorChange(appStart, appEnd,wholeDaysSet, newStart, newEnd,oneDayEventSelected); commandHistory.storeAndExecute(command); } if (source == endTime) { Date newEnd = raplaLocale.toDate(endDate.getDate(), endTime.getTime()); if (appStart.after(newEnd)) { newEnd = DateTools.addDay(newEnd); } if (newEnd.equals(appEnd)) return; UndoSingleEditorChange command = new UndoSingleEditorChange(null, appEnd,wholeDaysSet, null, newEnd, oneDayEventSelected); commandHistory.storeAndExecute(command); } if (source == endDate) { Date newEnd = raplaLocale.toDate(DateTools.addDays(endDate.getDate(), oneDayEventSelected ? 1 : 0), endTime.getTime()); Date newStart = null; if (appStart.after(newEnd) || (oneDayEventSelected && !appStart.before( newEnd))) { long mod = duration % DateTools.MILLISECONDS_PER_DAY; if ( mod != 0) { newStart = new Date(newEnd.getTime()- mod); } else { newStart = DateTools.addDays(newEnd,-1); } } UndoSingleEditorChange command = new UndoSingleEditorChange(appStart, appEnd,wholeDaysSet, newStart, newEnd,oneDayEventSelected); commandHistory.storeAndExecute(command); } if (source == oneDayEventCheckBox) { Date date = startDate.getDate(); Date time = startTime.getTime(); Date oldStart = raplaLocale.toDate(date, time); Date oldEnd = raplaLocale.toDate(endDate.getDate(), endTime.getTime()); UndoSingleEditorChange command = new UndoSingleEditorChange(oldStart, oldEnd,!oneDayEventSelected,appStart, appEnd,oneDayEventSelected); commandHistory.storeAndExecute(command); } } finally { listenerEnabled = true; } } private void mapFromAppointment() { listenerEnabled = false; try { final boolean wholeDaysSet = appointment.isWholeDaysSet(); Date start = appointment.getStart(); startDate.setDate(start); Date end = appointment.getEnd(); endDate.setDate(DateTools.addDays(end,wholeDaysSet ? -1 : 0)); endTime.setDurationStart( DateTools.isSameDay( start, end) ? start: null); startTime.setTime(start); endTime.setTime(end); oneDayEventCheckBox.setSelected(wholeDaysSet); startTimeLabel.setVisible(!wholeDaysSet); startTime.setVisible(!wholeDaysSet); endTime.setVisible(!wholeDaysSet); endTimeLabel.setVisible(!wholeDaysSet); } finally { listenerEnabled = true; } convertButton.setEnabled(false); } private void mapToAppointment() { RaplaLocale raplaLocale = getRaplaLocale(); Date start = raplaLocale.toDate(startDate.getDate(), startTime.getTime()); Date end = raplaLocale.toDate(endDate.getDate(), endTime.getTime()); if (oneDayEventCheckBox.isSelected()) { end = raplaLocale.toDate(DateTools.addDay(endDate.getDate()), endTime.getTime()); } appointment.move(start, end); fireAppointmentChanged(); } /** * This class collects any information of changes done in the fields when a single * appointment is selected. * This is where undo/redo for the fields within a single-appointment at right of the edit view * is realized. * @author Jens Fritz * */ //Erstellt von Dominik Krickl-Vorreiter public class UndoSingleEditorChange implements CommandUndo<RuntimeException> { Date oldStart; Date oldEnd; boolean oldoneDay; Date newStart; Date newEnd; boolean newoneDay; public UndoSingleEditorChange(Date oldstart, Date oldend, boolean oldoneDay, Date newstart, Date newend, boolean newoneDay) { this.oldStart = oldstart; this.oldEnd = oldend; this.oldoneDay = oldoneDay; this.newStart = newstart; this.newEnd = newend; this.newoneDay = newoneDay; } public boolean execute() { listenerEnabled = false; if (newStart != null && oldStart != null) { startTime.setTime(newStart); startDate.setDate(newStart); getLogger().debug("Starttime/-date adjusted"); } if (newEnd != null && oldEnd != null) { endTime.setTime(newEnd); endDate.setDate(DateTools.addDays(newEnd, newoneDay ? -1 : 0)); getLogger().debug("Endtime/-date adjusted"); } if (oldoneDay != newoneDay) { startTime.setVisible(!newoneDay); startTimeLabel.setVisible(!newoneDay); endTime.setVisible(!newoneDay); endTimeLabel.setVisible(!newoneDay); oneDayEventCheckBox.setSelected(newoneDay); getLogger().debug("Whole day adjusted"); } mapToAppointment(); getLogger().debug("SingleEditor adjusted"); listenerEnabled = true; return true; } public boolean undo() { listenerEnabled = false; if (oldStart != null && newStart != null) { startTime.setTime(oldStart); startDate.setDate(oldStart); getLogger().debug("Starttime/-date undo"); } if (oldEnd != null && newEnd != null) { endTime.setTime(oldEnd); endDate.setDate(oldEnd); getLogger().debug("Endtime/-date undo"); } if (oldoneDay != newoneDay) { startTime.setVisible(!oldoneDay); startTimeLabel.setVisible(!oldoneDay); endTime.setVisible(!oldoneDay); endTimeLabel.setVisible(!oldoneDay); oneDayEventCheckBox.setSelected(oldoneDay); getLogger().debug("Whole day undo"); } mapToAppointment(); getLogger().debug("SingleEditor undo"); listenerEnabled = true; return true; } public String getCommandoName() { return getString("change")+ " " + getString("appointment"); } } } class RepeatingEditor implements ActionListener, DateChangeListener, ChangeListener, Disposable { JPanel content = new JPanel(); JPanel intervalPanel = new JPanel(); JPanel weekdayInMonthPanel = new JPanel(); JPanel dayInMonthPanel = new JPanel(); RaplaNumber interval = new RaplaNumber(null, RaplaNumber.ONE, null, false); { addCopyPaste( interval.getNumberField()); } RaplaNumber weekdayInMonth = new RaplaNumber(null, RaplaNumber.ONE, new Integer(5), false); { addCopyPaste( weekdayInMonth.getNumberField()); } RaplaNumber dayInMonth = new RaplaNumber(null, RaplaNumber.ONE, new Integer(31), false); { addCopyPaste( dayInMonth.getNumberField()); } WeekdayChooser weekdayChooser = new WeekdayChooser(); JLabel dayLabel = new JLabel(); JLabel startTimeLabel = new JLabel(); RaplaTime startTime; JCheckBox oneDayEventCheckBox = new JCheckBox(); JLabel endTimeLabel = new JLabel(); JPanel endTimePanel = new JPanel(); RaplaTime endTime; public final int SAME_DAY = 0, NEXT_DAY = 1, X_DAYS = 2; JComboBox dayChooser; RaplaNumber days = new RaplaNumber(null, new Integer(2), null, false); { addCopyPaste( days.getNumberField()); } JLabel startDateLabel = new JLabel(); RaplaCalendar startDate; PeriodChooser startDatePeriod; JComboBox endingChooser; public final int REPEAT_UNTIL = 0, REPEAT_N_TIMES = 1, REPEAT_FOREVER = 2; RaplaCalendar endDate; JPanel numberPanel = new JPanel(); RaplaNumber number = new RaplaNumber(null, RaplaNumber.ONE, null, false); { addCopyPaste( number.getNumberField()); } JPanel endDatePeriodPanel = new JPanel(); PeriodChooser endDatePeriod; RaplaButton exceptionButton = new RaplaButton(); ExceptionEditor exceptionEditor; DialogUI exceptionDlg; MonthChooser monthChooser = new MonthChooser(); private boolean listenerEnabled = true; public RepeatingEditor() throws RaplaException { startDatePeriod = new PeriodChooser(getContext(), PeriodChooser.START_ONLY); endDatePeriod = new PeriodChooser(getContext(), PeriodChooser.END_ONLY); // Create a TableLayout for the frame double pre = TableLayout.PREFERRED; double fill = TableLayout.FILL; double size[][] = { { pre, 5, pre, 5, fill }, // Columns { ROW_SIZE, 18, ROW_SIZE, 5, ROW_SIZE, 15, ROW_SIZE, 6, ROW_SIZE, 0 } }; // Rows TableLayout tableLayout = new TableLayout(size); content.setLayout(tableLayout); } public Locale getLocale() { return getI18n().getLocale(); } public JComponent getComponent() { return content; } public void initialize() { // Interval / Weekday interval.setColumns(2); weekdayInMonth.setColumns(2); dayInMonth.setColumns(2); intervalPanel.setLayout(new BoxLayout(intervalPanel, BoxLayout.X_AXIS)); intervalPanel.add(new JLabel(getString("repeating.interval.pre") + " ")); intervalPanel.add(Box.createHorizontalStrut(3)); intervalPanel.add(interval); intervalPanel.add(Box.createHorizontalStrut(3)); intervalPanel.add(new JLabel(getString("repeating.interval.post"))); dayInMonthPanel.setLayout(new BoxLayout(dayInMonthPanel, BoxLayout.X_AXIS)); // dayInMonthPanel.add(new JLabel("Am")); dayInMonthPanel.add(Box.createHorizontalStrut(35)); dayInMonthPanel.add(dayInMonth); dayInMonthPanel.add(Box.createHorizontalStrut(3)); dayInMonthPanel.add(new JLabel(getString("repeating.interval.post"))); weekdayInMonthPanel.setLayout(new BoxLayout(weekdayInMonthPanel, BoxLayout.X_AXIS)); // weekdayInMonthPanel.add(new JLabel("Am")); weekdayInMonthPanel.add(Box.createHorizontalStrut(35)); weekdayInMonthPanel.add(weekdayInMonth); weekdayInMonthPanel.add(Box.createHorizontalStrut(3)); weekdayInMonthPanel.add(new JLabel( getString("repeating.interval.post"))); interval.addChangeListener(this); weekdayInMonth.addChangeListener(this); dayInMonth.addChangeListener(this); weekdayChooser.setLocale(getLocale()); weekdayChooser.addActionListener(this); monthChooser.setLocale(getLocale()); monthChooser.addActionListener(this); dayLabel.setText(getString("day") + " "); dayLabel.setVisible(false); // StartTime startTimeLabel.setText(getString("start_time")); startTime = createRaplaTime(); startTime.addDateChangeListener(this); oneDayEventCheckBox.setText(getString("all-day")); oneDayEventCheckBox.addActionListener(this); // EndTime duration endTimeLabel.setText(getString("end_time")); endTime = createRaplaTime(); endTime.addDateChangeListener(this); @SuppressWarnings("unchecked") JComboBox jComboBox = new JComboBox(new String[] { getString("appointment.same_day"), getString("appointment.next_day"), getString("appointment.day_x") }); dayChooser = jComboBox; dayChooser.addActionListener(this); days.setColumns(2); endTimePanel.setLayout(new TableLayout(new double[][] { { TableLayout.PREFERRED, 5, TableLayout.PREFERRED, TableLayout.FILL }, { ROW_SIZE } })); // endTimePanel.add(endTime,"0,0,l,f"); endTimePanel.add(dayChooser, "0,0"); endTimePanel.add(days, "2,0"); days.setVisible(false); days.addChangeListener(this); // start-date (with period-box) startDatePeriod.addActionListener(this); startDateLabel.setText(getString("repeating.start_date")); startDate = createRaplaCalendar(); startDate.addDateChangeListener(this); // end-date (with period-box)/n-times/forever endDatePeriod.addActionListener(this); endDate = createRaplaCalendar(); endDate.addDateChangeListener(this); @SuppressWarnings("unchecked") JComboBox jComboBox2 = new JComboBox(new RepeatingEnding[] { RepeatingEnding.END_DATE, RepeatingEnding.N_TIMES, RepeatingEnding.FOREVEVER }); endingChooser = jComboBox2; endingChooser.addActionListener(this); number.setColumns(3); number.setNumber(new Integer(1)); number.addChangeListener(this); numberPanel.setLayout(new BorderLayout()); numberPanel.add(number, BorderLayout.WEST); numberPanel.setVisible(false); intervalPanel.setVisible(false); weekdayInMonthPanel.setVisible(false); dayInMonthPanel.setVisible(false); // exception exceptionButton.setText(getString("appointment.exceptions") + " (0)"); exceptionButton.addActionListener(this); content.add(intervalPanel, "0,0,l,f"); content.add(weekdayInMonthPanel, "0,0,l,f"); content.add(dayInMonthPanel, "0,0,l,f"); content.add(weekdayChooser, "2,0,f,f"); content.add(monthChooser, "2,0,f,f"); content.add(dayLabel, "2,0,l,f"); content.add(startTimeLabel, "0,2,l,f"); content.add(startTime, "2,2,f,f"); content.add(oneDayEventCheckBox, "4,2"); content.add(exceptionButton, "4,0,r,t"); content.add(endTimeLabel, "0,4,l,f"); content.add(endTime, "2,4,f,f"); content.add(endTimePanel, "4,4,4,4,l,f"); content.add(startDateLabel, "0,6,l,f"); content.add(startDate, "2,6,l,f"); content.add(startDatePeriod, "4,6,f,f"); content.add(endingChooser, "0,8,l,f"); content.add(endDate, "2,8,l,f"); content.add(endDatePeriodPanel, "4,8,f,f"); // We must surround the endDatePeriod with a panel to // separate visiblity of periods from visibility of the panel endDatePeriodPanel.setLayout(new BorderLayout()); endDatePeriodPanel.add(endDatePeriod, BorderLayout.CENTER); content.add(numberPanel, "2,8,f,f"); setRenderer(endingChooser,new ListRenderer()); // Rapla 1.4: Initialize the split appointment button convertButton.addActionListener(this); // content.add(exceptionLabel,"0,10,l,c"); // content.add(exceptionPanel,"2,10,4,10,l,c"); } public void dispose() { endDatePeriod.removeActionListener(this); startDatePeriod.removeActionListener(this); } private Date getStart() { Date start = getRaplaLocale().toDate(startDate.getDate(), startTime.getTime()); /* * if (repeating.isWeekly() || repeating.isMonthly()) { Calendar * calendar = getRaplaLocale().createCalendar(); * calendar.setTime(start); calendar.set(Calendar.DAY_OF_WEEK, * weekdayChooser.getSelectedWeekday() ); if * (calendar.getTime().before(start)) { * calendar.add(Calendar.DAY_OF_WEEK,7); } start = * calendar.getTime(); } if (repeating.isYearly()) { Calendar * calendar = getRaplaLocale().createCalendar(); * calendar.setTime(start); calendar.set(Calendar.MONTH, * monthChooser.getSelectedMonth() ); * calendar.set(Calendar.DAY_OF_MONTH, * dayInMonth.getNumber().intValue() ); start = calendar.getTime(); * * } */ return start; } private Date getEnd() { Date end = getRaplaLocale().toDate(getStart(), endTime.getTime()); if (dayChooser.getSelectedIndex() == NEXT_DAY) end = DateTools.addDay(end); if (dayChooser.getSelectedIndex() == X_DAYS) end = DateTools.addDays(end, days.getNumber().intValue()); return end; } public void actionPerformed(ActionEvent evt) { if (evt.getSource() == exceptionButton) { try { showExceptionDlg(); } catch (RaplaException ex) { showException(ex, content); } return; } if (!listenerEnabled) return; try { listenerEnabled = false; // Rapla 1.4: Split appointment button has been clicked if (evt.getSource() == convertButton) { // Notify registered listeners ActionListener[] listeners = listenerList.toArray(new ActionListener[] {}); for (int i = 0; i < listeners.length; i++) { listeners[i].actionPerformed(new ActionEvent(AppointmentController.this,ActionEvent.ACTION_PERFORMED, "split")); } return; } else if (evt.getSource() == endingChooser) { // repeating has changed to UNTIL, the default endDate will // be set int index = endingChooser.getSelectedIndex(); if (index == REPEAT_UNTIL) { Date slotDate = getSelectedEditDate(); if (slotDate != null) endDate.setDate(slotDate); } } else if (evt.getSource() == weekdayChooser) { Calendar calendar = getRaplaLocale().createCalendar(); calendar.setTime(startDate.getDate()); calendar.set(Calendar.DAY_OF_WEEK, weekdayChooser.getSelectedWeekday()); startDate.setDate(calendar.getTime()); } else if (evt.getSource() == monthChooser) { Calendar calendar = getRaplaLocale().createCalendar(); calendar.setTime(startDate.getDate()); calendar.set(Calendar.MONTH, monthChooser.getSelectedMonth()); calendar.set(Calendar.DAY_OF_MONTH, dayInMonth.getNumber().intValue()); startDate.setDate(calendar.getTime()); } else if (evt.getSource() == dayChooser) { if (dayChooser.getSelectedIndex() == SAME_DAY) { if (getEnd().before(getStart())) { endTime.setTime(getStart()); getLogger().debug("endtime adjusted"); } } } else if (evt.getSource() == startDatePeriod && startDatePeriod.getPeriod() != null) { Calendar calendar = getRaplaLocale().createCalendar(); calendar.setTime(startDatePeriod.getPeriod().getStart()); if (repeating.isWeekly() || repeating.isMonthly()) { calendar.set(Calendar.DAY_OF_WEEK, weekdayChooser.getSelectedWeekday()); if (calendar.getTime().before( startDatePeriod.getPeriod().getStart())) { calendar.add(Calendar.DAY_OF_WEEK, 7); } } getLogger().debug("startdate adjusted to period"); startDate.setDate(calendar.getTime()); endDatePeriod.setSelectedPeriod(startDatePeriod.getPeriod()); } else if (evt.getSource() == endDatePeriod && endDatePeriod.getDate() != null) { endDate.setDate(DateTools.subDay(endDatePeriod.getDate())); getLogger().debug("enddate adjusted to period"); } doChanges(); } finally { listenerEnabled = true; } } public void stateChanged(ChangeEvent evt) { if (!listenerEnabled) return; try { listenerEnabled = false; if (evt.getSource() == weekdayInMonth && repeating.isMonthly()) { Number weekdayOfMonthValue = weekdayInMonth.getNumber(); if (weekdayOfMonthValue != null && repeating.isMonthly()) { Calendar cal = getRaplaLocale().createCalendar(); cal.setTime(appointment.getStart()); cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, weekdayOfMonthValue.intValue()); startDate.setDate(cal.getTime()); } } if (evt.getSource() == dayInMonth && repeating.isYearly()) { Number dayOfMonthValue = dayInMonth.getNumber(); if (dayOfMonthValue != null && repeating.isYearly()) { Calendar cal = getRaplaLocale().createCalendar(); cal.setTime(appointment.getStart()); cal.set(Calendar.DAY_OF_MONTH, dayOfMonthValue.intValue()); startDate.setDate(cal.getTime()); } } doChanges(); } finally { listenerEnabled = true; } } public void dateChanged(DateChangeEvent evt) { if (!listenerEnabled) return; try { listenerEnabled = false; long duration = appointment.getEnd().getTime()- appointment.getStart().getTime(); if (evt.getSource() == startTime) { Date newEnd = new Date(getStart().getTime() + duration); endTime.setTime(newEnd); getLogger().debug("endtime adjusted"); } if (evt.getSource() == endTime) { Date newEnd = getEnd(); if (getStart().after(newEnd)) { newEnd = DateTools.addDay(newEnd); endTime.setTime(newEnd); getLogger().debug("enddate adjusted"); } } doChanges(); } finally { listenerEnabled = true; } } private void mapToAppointment() { int index = endingChooser.getSelectedIndex(); Number intervalValue = interval.getNumber(); if (intervalValue != null) { repeating.setInterval(intervalValue.intValue()); } else { repeating.setInterval(1); } if (index == REPEAT_UNTIL) { if (DateTools.countDays(startDate.getDate(), endDate.getDate()) < 0) { endDate.setDate(startDate.getDate()); } repeating.setEnd(DateTools.addDay(endDate.getDate())); } else if (index == REPEAT_N_TIMES) { Number numberValue = number.getNumber(); if (number != null) { repeating.setNumber(numberValue.intValue()); } else { repeating.setNumber(1); } } else { // REPEAT_FOREVER repeating.setEnd(null); repeating.setNumber(-1); } appointment.move(getStart(), getEnd()); // We have todo the after the move to avoid reseting the dates final boolean oneDayEvent = oneDayEventCheckBox.isSelected(); setToWholeDays(oneDayEvent); } private void updateExceptionCount() { int count = repeating.getExceptions().length; if (count > 0) { exceptionButton.setForeground(Color.red); } else { exceptionButton.setForeground(UIManager.getColor("Label.foreground")); } String countValue = String.valueOf(count); if (count < 9) { countValue = " " + countValue + " "; } exceptionButton.setText(getString("appointment.exceptions") + " (" + countValue + ")"); } private void showEnding(int index) { if (index == REPEAT_UNTIL) { endDate.setVisible(true); endDatePeriodPanel.setVisible(isPeriodVisible()); numberPanel.setVisible(false); } if (index == REPEAT_N_TIMES) { endDate.setVisible(false); endDatePeriodPanel.setVisible(false); numberPanel.setVisible(true); } if (index == REPEAT_FOREVER) { endDate.setVisible(false); endDatePeriodPanel.setVisible(false); numberPanel.setVisible(false); } } private void mapFromAppointment() { // closing is not necessary as dialog is modal // if (exceptionDlg != null && exceptionDlg.isVisible()) // exceptionDlg.dispose(); repeating = appointment.getRepeating(); if (repeating == null) { return; } listenerEnabled = false; try { updateExceptionCount(); if (exceptionEditor != null) exceptionEditor.mapFromAppointment(); interval.setNumber(new Integer(repeating.getInterval())); Date start = appointment.getStart(); startDate.setDate(start); startDatePeriod.setDate(start); startTime.setTime(start); Date end = appointment.getEnd(); endTime.setTime(end); endTime.setDurationStart( DateTools.isSameDay( start, end) ? start: null); weekdayInMonthPanel.setVisible(repeating.isMonthly()); intervalPanel.setVisible(repeating.isDaily() || repeating.isWeekly()); dayInMonthPanel.setVisible(repeating.isYearly()); if (repeating.getEnd() != null) { endDate.setDate(DateTools.subDay(repeating.getEnd())); endDatePeriod.setDate(DateTools.cutDate(endDate.getDate())); number.setNumber(new Integer(repeating.getNumber())); if (!repeating.isFixedNumber()) { endingChooser.setSelectedIndex(REPEAT_UNTIL); showEnding(REPEAT_UNTIL); } else { endingChooser.setSelectedIndex(REPEAT_N_TIMES); showEnding(REPEAT_N_TIMES); } } else { endingChooser.setSelectedIndex(REPEAT_FOREVER); showEnding(REPEAT_FOREVER); } startDatePeriod.setVisible(isPeriodVisible() && (repeating.isDaily() || repeating.isWeekly())); endDatePeriod.setVisible(repeating.isDaily() || repeating.isWeekly()); if (repeating.isWeekly() || repeating.isMonthly()) { dayLabel.setVisible(false); weekdayChooser.setVisible(true); monthChooser.setVisible(false); Calendar calendar = getRaplaLocale().createCalendar(); calendar.setTime(start); weekdayChooser.selectWeekday(calendar.get(Calendar.DAY_OF_WEEK)); } if (repeating.isYearly()) { dayLabel.setVisible(false); weekdayChooser.setVisible(false); monthChooser.setVisible(true); Calendar cal = getRaplaLocale().createCalendar(); cal.setTime(start); monthChooser.selectMonth(cal.get(Calendar.MONTH)); int numb = cal.get(Calendar.DAY_OF_MONTH); dayInMonth.setNumber(new Integer(numb)); } if (repeating.isMonthly()) { Calendar cal = getRaplaLocale().createCalendar(); cal.setTime(start); int numb = cal.get(Calendar.DAY_OF_WEEK_IN_MONTH); weekdayInMonth.setNumber(new Integer(numb)); } if (repeating.isDaily()) { dayLabel.setVisible(true); weekdayChooser.setVisible(false); monthChooser.setVisible(false); } String typeString = repeating.getType().toString(); startDateLabel.setText(getString(typeString) + " " + getString("repeating.start_date")); int daysBetween = (int) DateTools.countDays( start, end); if (daysBetween == 0) { dayChooser.setSelectedIndex(SAME_DAY); days.setVisible(false); } else if (daysBetween == 1) { dayChooser.setSelectedIndex(NEXT_DAY); days.setVisible(false); } else { dayChooser.setSelectedIndex(X_DAYS); days.setNumber(new Integer(daysBetween)); days.setVisible(true); } final boolean wholeDaysSet = appointment.isWholeDaysSet(); startTime.setEnabled(!wholeDaysSet); endTime.setEnabled(!wholeDaysSet); dayChooser.setEnabled(!wholeDaysSet); days.setEnabled( !wholeDaysSet); oneDayEventCheckBox.setSelected(wholeDaysSet); } finally { listenerEnabled = true; } convertButton.setEnabled(repeating.getEnd() != null); getComponent().revalidate(); } private boolean isPeriodVisible() { try { return getQuery().getPeriodModel().getSize() > 0; } catch (RaplaException e) { return false; } } private void showExceptionDlg() throws RaplaException { exceptionEditor = new ExceptionEditor(); exceptionEditor.initialize(); exceptionEditor.mapFromAppointment(); exceptionEditor.getComponent().setBorder( BorderFactory.createEmptyBorder(5, 5, 5, 5)); exceptionDlg = DialogUI.create(getContext(), getComponent(), true, exceptionEditor.getComponent(), new String[] { getString("close") }); exceptionDlg.setTitle(getString("appointment.exceptions")); exceptionDlg.start(); updateExceptionCount(); } private void doChanges(){ Appointment oldState = ((AppointmentImpl) appointment).clone(); mapToAppointment(); Appointment newState = ((AppointmentImpl) appointment).clone(); UndoDataChange changeDataCommand = new UndoDataChange(oldState, newState); commandHistory.storeAndExecute(changeDataCommand); } } class ExceptionEditor implements ActionListener, ListSelectionListener { JPanel content = new JPanel(); RaplaCalendar exceptionDate; RaplaButton addButton = new RaplaButton(RaplaButton.SMALL); RaplaButton removeButton = new RaplaButton(RaplaButton.SMALL); JList specialExceptions = new JList(); public ExceptionEditor() { // Create a TableLayout for the frame double pre = TableLayout.PREFERRED; double min = TableLayout.MINIMUM; double fill = TableLayout.FILL; double yborder = 8; double size[][] = { { pre, pre, 0.1, 50, 100, 0.9 }, // Columns { yborder, min, min, fill } }; // Rows TableLayout tableLayout = new TableLayout(size); content.setLayout(tableLayout); } public JComponent getComponent() { return content; } public void initialize() { addButton.setText(getString("add")); addButton.setIcon(getIcon("icon.arrow_right")); removeButton.setText(getString("remove")); removeButton.setIcon(getIcon("icon.arrow_left")); exceptionDate = createRaplaCalendar(); /* * this.add(new JLabel(getString("appointment.exception.general") + * " "),"0,1"); this.add(new JScrollPane(generalExceptions * ,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS * ,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER) ,"1,1,1,3,t"); */ JLabel label = new JLabel(getString("appointment.exception.days") + " "); label.setHorizontalAlignment(SwingConstants.RIGHT); content.add(label, "3,1,4,1,r,t"); content.add(exceptionDate, "5,1,l,t"); content.add(addButton, "4,2,f,t"); content.add(removeButton, "4,3,f,t"); content.add(new JScrollPane(specialExceptions, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER), "5,2,5,3,t"); addButton.addActionListener(this); removeButton.addActionListener(this); specialExceptions.addListSelectionListener(this); removeButton.setEnabled(false); specialExceptions.setFixedCellWidth(200); specialExceptions.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); DefaultListCellRenderer cellRenderer = new DefaultListCellRenderer() { private static final long serialVersionUID = 1L; public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { if (value instanceof Date) value = getRaplaLocale().formatDateLong((Date) value); return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); } }; setRenderer(specialExceptions, cellRenderer); specialExceptions.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { if (evt.getClickCount() > 1) { removeException(); } } }); } @SuppressWarnings("unchecked") public void mapFromAppointment() { if (appointment.getRepeating() == null) specialExceptions.setListData(new Object[0]); else specialExceptions.setListData(appointment.getRepeating().getExceptions()); // exceptionDate.setDate( appointment.getStart()); Date exceptDate = getSelectedEditDate(); if (exceptDate == null) exceptionDate.setDate(appointment.getStart()); else exceptionDate.setDate(exceptDate); } public void actionPerformed(ActionEvent evt) { if (evt.getSource() == addButton) { addException(); } if (evt.getSource() == removeButton) { removeException(); } } private void addException() { Date date = exceptionDate.getDate(); if (appointment.getRepeating().isException(date.getTime())) return; UndoExceptionChange command = new UndoExceptionChange( addButton, date, null); commandHistory.storeAndExecute(command); } @SuppressWarnings("deprecation") private void removeException() { if (specialExceptions.getSelectedValues() == null) return; Object[] selectedExceptions = specialExceptions.getSelectedValues(); UndoExceptionChange command = new UndoExceptionChange( removeButton, null, selectedExceptions); commandHistory.storeAndExecute(command); } public void valueChanged(ListSelectionEvent e) { if (e.getSource() == specialExceptions) { removeButton.setEnabled(specialExceptions.getSelectedValue() != null); } } /** * This class collects any information of changes done to the exceptions * of an appointment, if a repeating-type is selected. * This is where undo/redo for the changes of the exceptions within a repeating-type-appointment * at the right of the edit view is realized. * @author Jens Fritz * */ //Erstellt von Dominik Krickl-Vorreiter public class UndoExceptionChange implements CommandUndo<RuntimeException> { RaplaButton pressedButton; Date exception; Object[] selectedExceptions; public UndoExceptionChange(RaplaButton pressedButton, Date exception, Object[] selectedExceptions) { this.pressedButton = pressedButton; this.exception = exception; this.selectedExceptions = selectedExceptions; } @SuppressWarnings("unchecked") public boolean execute() { Repeating repeating = appointment.getRepeating(); if (pressedButton == addButton) { repeating.addException(exception); specialExceptions.setListData(repeating.getExceptions()); fireAppointmentChanged(); } if (pressedButton == removeButton) { for (int i = 0; i < selectedExceptions.length; i++) { repeating.removeException((Date) selectedExceptions[i]); } specialExceptions.setListData(repeating.getExceptions()); fireAppointmentChanged(); } return true; } @SuppressWarnings("unchecked") public boolean undo() { Repeating repeating = appointment.getRepeating(); if (pressedButton == addButton) { repeating.removeException(exception); specialExceptions.setListData(repeating.getExceptions()); fireAppointmentChanged(); } if (pressedButton == removeButton) { for (int i = 0; i < selectedExceptions.length; i++) { repeating.addException( (Date) selectedExceptions[i]); } specialExceptions.setListData(repeating.getExceptions()); fireAppointmentChanged(); } return true; } public String getCommandoName() { return getString("change")+ " " + getString("appointment"); } } } private class ListRenderer extends DefaultListCellRenderer { private static final long serialVersionUID = 1L; public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { if (value != null) { setText(getString(value.toString())); } return this; } } public RepeatingType getCurrentRepeatingType() { if (noRepeating.isSelected()) { return null; } RepeatingType repeatingType; if (monthlyRepeating.isSelected()) { repeatingType = RepeatingType.MONTHLY; } else if (yearlyRepeating.isSelected()) { repeatingType = RepeatingType.YEARLY; } else if (dailyRepeating.isSelected()) { repeatingType = RepeatingType.DAILY; } else { repeatingType = RepeatingType.WEEKLY; } return repeatingType; } public Repeating getRepeating() { if (noRepeating.isSelected()) { return null; } return repeating; } /** * This class collects any information of changes done to the radiobuttons * with which the repeating-type is selected. * This is where undo/redo for the changes of the radiobuttons, with which the repeating-type of an appointment * can be set, at the right of the edit view is realized. * @author Jens Fritz * */ //Erstellt von Dominik Krickl-Vorreiter public class UndoRepeatingTypeChange implements CommandUndo<RuntimeException> { private final RepeatingType oldRepeatingType; private final RepeatingType newRepeatingType; public UndoRepeatingTypeChange(RepeatingType oldRepeatingType, RepeatingType newRepeatingType) { this.oldRepeatingType = oldRepeatingType; this.newRepeatingType = newRepeatingType; } public boolean execute() { setRepeatingType(newRepeatingType); return true; } public boolean undo() { setRepeatingType(oldRepeatingType); return true; } private void setRepeatingType(RepeatingType repeatingType) { if (repeatingType == null) { noRepeating.setSelected(true); repeatingCard.show(repeatingContainer, "0"); singleEditor.mapFromAppointment(); appointment.setRepeatingEnabled(false); } else { if (repeatingType == RepeatingType.WEEKLY) { weeklyRepeating.setSelected(true); } else if (repeatingType == RepeatingType.DAILY) { dailyRepeating.setSelected(true); } else if (repeatingType == RepeatingType.MONTHLY) { monthlyRepeating.setSelected(true); } else if (repeatingType == RepeatingType.YEARLY) { yearlyRepeating.setSelected(true); } ReservationHelper.makeRepeatingForPeriod(getPeriodModel(), appointment, repeatingType,1); repeatingEditor.mapFromAppointment(); repeatingCard.show(repeatingContainer, "1"); } savedRepeatingType = repeatingType; fireAppointmentChanged(); } public String getCommandoName() { return getString("change")+ " " + getString("repeating"); } } public void nextFreeAppointment() { Reservation reservation = appointment.getReservation(); Allocatable[] allocatables = reservation.getAllocatablesFor( appointment); try { CalendarOptions options = getCalendarOptions(); Date newStart = getQuery().getNextAllocatableDate(Arrays.asList(allocatables), appointment,options ); if ( newStart != null) { Appointment oldState = ((AppointmentImpl) appointment).clone(); appointment.move(newStart); Appointment newState = ((AppointmentImpl) appointment).clone(); UndoDataChange changeDataCommand = new UndoDataChange(oldState, newState); commandHistory.storeAndExecute(changeDataCommand); } else { showWarning("No free appointment found", getMainComponent()); } } catch (RaplaException ex) { showException( ex, getMainComponent()); } } public class UndoDataChange implements CommandUndo<RuntimeException> { private final Appointment oldState; private final Appointment newState; public UndoDataChange(Appointment oldState, Appointment newState) { this.oldState = oldState; this.newState = newState; } public boolean execute() { ((AppointmentImpl) appointment).copy(newState); if ( appointment.isRepeatingEnabled()) { repeatingEditor.mapFromAppointment(); } else { singleEditor.mapFromAppointment(); } fireAppointmentChanged(); return true; } public boolean undo() { ((AppointmentImpl) appointment).copy(oldState); if ( appointment.isRepeatingEnabled()) { repeatingEditor.mapFromAppointment(); } else { singleEditor.mapFromAppointment(); } fireAppointmentChanged(); return true; } public String getCommandoName() { return getString("change")+ " " + getString("appointment"); } } @SuppressWarnings("unchecked") private void setRenderer(JComboBox cb, ListCellRenderer listRenderer) { cb.setRenderer( listRenderer); } @SuppressWarnings("unchecked") private void setRenderer(JList cb, ListCellRenderer listRenderer) { cb.setCellRenderer( listRenderer); } }
04900db4-rob
src/org/rapla/gui/internal/edit/reservation/AppointmentController.java
Java
gpl3
50,431
/*--------------------------------------------------------------------------* | 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.edit.reservation; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Collections; import java.util.Set; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.border.Border; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.rapla.components.layout.TableLayout; import org.rapla.components.util.undo.CommandHistory; import org.rapla.components.util.undo.CommandUndo; 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.DynamicType; import org.rapla.entities.dynamictype.DynamicTypeAnnotations; import org.rapla.entities.dynamictype.internal.ClassificationImpl; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.EditField; import org.rapla.gui.RaplaGUIComponent; import org.rapla.gui.internal.common.NamedListCellRenderer; import org.rapla.gui.internal.edit.ClassificationEditUI; import org.rapla.gui.internal.edit.fields.SetGetField; import org.rapla.gui.toolkit.EmptyLineBorder; import org.rapla.gui.toolkit.RaplaButton; import org.rapla.gui.toolkit.RaplaListComboBox; import org.rapla.gui.toolkit.RaplaWidget; /** Gui for editing the {@link Classification} of a reservation. Same as {@link org.rapla.gui.internal.edit.ClassificationEditUI}. It will only layout the field with a {@link java.awt.FlowLayout}. */ public class ReservationInfoEdit extends RaplaGUIComponent implements RaplaWidget ,ActionListener { JPanel content = new JPanel(); MyClassificationEditUI editUI; private Classification classification; private Classification lastClassification = null; private Classifiable classifiable; private CommandHistory commandHistory; ArrayList<ChangeListener> listenerList = new ArrayList<ChangeListener>(); ArrayList<DetailListener> detailListenerList = new ArrayList<DetailListener>(); RaplaListComboBox typeSelector; RaplaButton tabSelector = new RaplaButton(); boolean isMainViewSelected = true; private boolean internalUpdate = false; public ReservationInfoEdit(RaplaContext sm, CommandHistory commandHistory) { super( sm); typeSelector = new RaplaListComboBox( sm ); this.commandHistory = commandHistory; editUI = new MyClassificationEditUI(sm); } public JComponent getComponent() { return content; } public void requestFocus() { editUI.requestFocus(); } private boolean hasSecondTab(Classification classification) { Attribute[] atts = classification.getAttributes(); for ( int i=0; i < atts.length; i++ ) { String view = atts[i].getAnnotation(AttributeAnnotations.KEY_EDIT_VIEW,AttributeAnnotations.VALUE_EDIT_VIEW_MAIN); if ( view.equals(AttributeAnnotations.VALUE_EDIT_VIEW_ADDITIONAL)) { return true; } } return false; } public void setReservation(Classifiable classifiable) throws RaplaException { content.removeAll(); this.classifiable = classifiable; classification = classifiable.getClassification(); lastClassification = classification; DynamicType[] types = getQuery().getDynamicTypes( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION); DynamicType dynamicType = classification.getType(); RaplaListComboBox jComboBox = new RaplaListComboBox( getContext() , types ); typeSelector = jComboBox; typeSelector.setEnabled( types.length > 1); typeSelector.setSelectedItem(dynamicType); setRenderer(); typeSelector.addActionListener( this ); content.setLayout( new BorderLayout()); JPanel header = new JPanel(); header.setLayout( null ); header.add( typeSelector ); Border border = new EmptyLineBorder(); header.setBorder( BorderFactory.createTitledBorder( border, getString("reservation_type") +":")); Dimension dim = typeSelector.getPreferredSize(); typeSelector.setBounds(135,0, dim.width,dim.height); tabSelector.setText(getString("additional-view")); tabSelector.addActionListener( this ); Dimension dim2 = tabSelector.getPreferredSize(); tabSelector.setBounds(145 + dim.width ,0,dim2.width,dim2.height); header.add( tabSelector ); header.setPreferredSize( new Dimension(600, Math.max(dim2.height, dim.height))); content.add( header,BorderLayout.NORTH); content.add( editUI.getComponent(),BorderLayout.CENTER); tabSelector.setVisible( hasSecondTab( classification ) || !isMainViewSelected); editUI.setObjects( Collections.singletonList(classification )); editUI.getComponent().validate(); updateHeight(); content.validate(); } @SuppressWarnings("unchecked") private void setRenderer() { typeSelector.setRenderer(new NamedListCellRenderer(getI18n().getLocale())); } /** registers new ChangeListener for this component. * An ChangeEvent will be fired to every registered ChangeListener * when the info changes. * @see javax.swing.event.ChangeListener * @see javax.swing.event.ChangeEvent */ public void addChangeListener(ChangeListener listener) { listenerList.add(listener); } /** removes a listener from this component.*/ public void removeChangeListener(ChangeListener listener) { listenerList.remove(listener); } public ChangeListener[] getChangeListeners() { return listenerList.toArray(new ChangeListener[]{}); } public void addDetailListener(DetailListener listener) { detailListenerList.add(listener); } /** removes a listener from this component.*/ public void removeDetailListener(DetailListener listener) { detailListenerList.remove(listener); } public DetailListener[] getDetailListeners() { return detailListenerList.toArray(new DetailListener[]{}); } protected void fireDetailChanged() { DetailListener[] listeners = getDetailListeners(); for (int i = 0;i<listeners.length; i++) { listeners[i].detailChanged(); } } public interface DetailListener { void detailChanged(); } protected void fireInfoChanged() { if (listenerList.size() == 0) return; ChangeEvent evt = new ChangeEvent(this); ChangeListener[] listeners = getChangeListeners(); for (int i = 0;i<listeners.length; i++) { listeners[i].stateChanged(evt); } } // The DynamicType has changed public void actionPerformed(ActionEvent event) { try { Object source = event.getSource(); if (source == typeSelector ) { if (internalUpdate) return; DynamicType oldDynamicType = lastClassification.getType(); DynamicType newDynamicType = (DynamicType) typeSelector.getSelectedItem(); Classification oldClassification = (Classification) ((ClassificationImpl) lastClassification).clone(); Classification newClassification = (Classification) ((ClassificationImpl) newDynamicType.newClassification(classification)).clone(); UndoReservationTypeChange command = new UndoReservationTypeChange(oldClassification, newClassification, oldDynamicType, newDynamicType); commandHistory.storeAndExecute(command); lastClassification = newClassification; } if (source == tabSelector ) { isMainViewSelected = !isMainViewSelected; fireDetailChanged(); editUI.layout(); tabSelector.setText( isMainViewSelected ? getString("additional-view") :getString("appointments") ); tabSelector.setIcon( isMainViewSelected ? null : getIcon("icon.list") ); } } catch (RaplaException ex) { showException(ex, content); } } private void updateHeight() { int newHeight = editUI.getHeight(); editUI.getComponent().setPreferredSize(new Dimension(600,newHeight)); } class MyClassificationEditUI extends ClassificationEditUI { int height = 0; public MyClassificationEditUI(RaplaContext sm) { super(sm); } public int getHeight() { return height; } protected void layout() { editPanel.removeAll(); editPanel.setLayout( null ); if ( !isMainViewSelected ) { super.layout(); return; } /* FlowLayout layout = new FlowLayout(); layout.setAlignment(FlowLayout.LEFT); layout.setHgap(10); layout.setVgap(2); editPanel.setLayout(layout); for (int i=0;i<fields.length;i++) { String tabview = getAttribute( i ).getAnnotation(AttributeAnnotations.KEY_EDIT_VIEW, AttributeAnnotations.VALUE_MAIN_VIEW); JPanel fieldPanel = new JPanel(); fieldPanel.setLayout( new BorderLayout()); fieldPanel.add(new JLabel(fields[i].getName() + ": "),BorderLayout.WEST); fieldPanel.add(fields[i].getComponent(),BorderLayout.CENTER); if ( tabview.equals("main-view") || !isMainViewSelected ) { editPanel.add(fieldPanel); } } */ TableLayout layout = new TableLayout(); layout.insertColumn(0, 5); layout.insertColumn(1,TableLayout.PREFERRED); layout.insertColumn(2,TableLayout.PREFERRED); layout.insertColumn(3, 10); layout.insertColumn(4,TableLayout.PREFERRED); layout.insertColumn(5,TableLayout.PREFERRED); layout.insertColumn(6,TableLayout.FULL); int col= 1; int row = 0; layout.insertRow( row, 8); row ++; layout.insertRow( row, TableLayout.PREFERRED); editPanel.setLayout(layout); height = 10; int maxCompHeightInRow = 0; for (int i=0;i<fields.size();i++) { EditField field = fields.get(i); String tabview = getAttribute( i ).getAnnotation(AttributeAnnotations.KEY_EDIT_VIEW, AttributeAnnotations.VALUE_EDIT_VIEW_MAIN); if ( !tabview.equals("main-view") ) { continue; } editPanel.add(new JLabel(getFieldName(field) + ": "),col + "," + row +",l,c"); col ++; editPanel.add(field.getComponent(), col + "," + row +",f,c"); int compHeight = (int)field.getComponent().getPreferredSize().getHeight(); compHeight = Math.max(25, compHeight); // first row maxCompHeightInRow = Math.max(maxCompHeightInRow ,compHeight); col ++; col ++; if ( col >= layout.getNumColumn()) { col = 1; if ( i < fields.size() -1) { row ++; layout.insertRow( row, 5); height +=5; row ++; layout.insertRow( row, TableLayout.PREFERRED); height += maxCompHeightInRow; maxCompHeightInRow = 0; } } } height += maxCompHeightInRow; } public void requestFocus() { if (fields.size()>0) fields.get(0).getComponent().requestFocus(); } public void stateChanged(ChangeEvent evt) { try { SetGetField<?> editField = (SetGetField<?>) evt.getSource(); String keyName = getKey(editField); Object oldValue = getAttValue(keyName); //this.classification.getValue(keyName); mapTo( editField ); Object newValue = getAttValue(keyName); UndoClassificationChange classificationChange = new UndoClassificationChange(oldValue, newValue, keyName); if (oldValue != newValue && (oldValue == null || newValue == null || !oldValue.equals(newValue))) { commandHistory.storeAndExecute(classificationChange); } } catch (RaplaException ex) { showException(ex, this.getComponent()); } } private Object getAttValue(String keyName) { Set<Object> uniqueAttValues = getUniqueAttValues(keyName); if ( uniqueAttValues.size() > 0) { return uniqueAttValues.iterator().next(); } return null; } /** * This class collects any information of changes done to all fields at the top of the edit view. * This is where undo/redo for all fields at the top of the edit view * is realized. * @author Jens Fritz * */ //Erstellt von Dominik Krickl-Vorreiter public class UndoClassificationChange implements CommandUndo<RaplaException> { private final Object oldValue; private final Object newValue; private final String keyName; public UndoClassificationChange(Object oldValue, Object newValue, String fieldName) { this.oldValue = oldValue; this.newValue = newValue; this.keyName = fieldName; } public boolean execute() throws RaplaException { return mapValue(newValue); } public boolean undo() throws RaplaException { return mapValue(oldValue); } protected boolean mapValue(Object valueToSet) throws RaplaException { Object attValue = getAttValue(keyName); if (attValue != valueToSet && (attValue == null || valueToSet == null || !attValue.equals(valueToSet))) { SetGetField<?> editField = (SetGetField<?>) getEditField(); if (editField == null) throw new RaplaException("Field with key " + keyName + " not found!"); setAttValue(keyName, valueToSet); mapFrom( editField); } fireInfoChanged(); return true; } protected EditField getEditField() { EditField editField = null; for (EditField field: editUI.fields) { if (getKey(field).equals(keyName)) { editField = field; break; } } return editField; } public String getCommandoName() { EditField editField = getEditField(); String fieldName; if ( editField != null) { fieldName = getFieldName(editField); } else { fieldName = getString("attribute"); } return getString("change") + " " + fieldName; } } } public boolean isMainView() { return isMainViewSelected; } /** * This class collects any information of changes done to the reservation type checkbox. * This is where undo/redo for the reservatoin type-selection at the top of the edit view * is realized * @author Jens Fritz * */ //Erstellt von Matthias Both public class UndoReservationTypeChange implements CommandUndo<RaplaException>{ private final Classification oldClassification; private final Classification newClassification; private final DynamicType oldDynamicType; private final DynamicType newDynamicType; public UndoReservationTypeChange(Classification oldClassification, Classification newClassification, DynamicType oldDynamicType, DynamicType newDynamicType) { this.oldDynamicType = oldDynamicType; this.newDynamicType = newDynamicType; this.oldClassification = oldClassification; this.newClassification = newClassification; } public boolean execute() throws RaplaException { classification = newClassification; setType(newDynamicType); return true; } public boolean undo() throws RaplaException { classification = oldClassification; setType(oldDynamicType); return true; } protected void setType(DynamicType typeToSet) throws RaplaException { if (!typeSelector.getSelectedItem().equals(typeToSet)) { internalUpdate = true; try { typeSelector.setSelectedItem(typeToSet); } finally { internalUpdate = false; } } classifiable.setClassification(classification); editUI.setObjects(Collections.singletonList(classification)); tabSelector.setVisible(hasSecondTab(classification) || !isMainViewSelected); content.validate(); updateHeight(); content.repaint(); fireInfoChanged(); } public String getCommandoName() { return getString("change") + " " + getString("dynamictype"); } } }
04900db4-rob
src/org/rapla/gui/internal/edit/reservation/ReservationInfoEdit.java
Java
gpl3
18,770
package org.rapla.gui.internal.edit.reservation; /* * SortedListModel.java * * Copyright 2006 Sun Microsystems, Inc. ALL RIGHTS RESERVED Use of * this software is authorized pursuant to the terms of the license * found at http://developers.sun.com/berkeley_license.html . * */ import java.text.Collator; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.swing.AbstractListModel; import javax.swing.ListModel; import javax.swing.event.ListDataEvent; import javax.swing.event.ListDataListener; /** * SortedListModel decorates an unsorted ListModel to provide * a sorted model. You can create a SortedListModel from models you * already have. Place the SortedListModel into a JList, for example, to provide * a sorted view of your underlying model. * * @author John O'Conner */ public class SortedListModel extends AbstractListModel { /** * */ private static final long serialVersionUID = 1L; /** * Create a SortedListModel from an existing model * using a default text comparator for the default Locale. Sort * in ascending order. * @param model the underlying, unsorted ListModel */ public SortedListModel(ListModel model) { this(model, SortOrder.ASCENDING, null); } /** * Create a SortedListModel from an existing model * using a specific comparator and sort order. Use * a default text comparator. * *@param model the unsorted list model *@param sortOrder that should be used */ public SortedListModel(ListModel model, SortOrder sortOrder) { this(model, sortOrder, null); } /** * Create a SortedListModel from an existing model. Sort the model * in the specified sort order using the given comparator. * *@param model *@param sortOrder *@param comp * */ public SortedListModel(ListModel model, SortOrder sortOrder, Comparator<Object> comp) { unsortedModel = model; unsortedModel.addListDataListener(new ListDataListener() { public void intervalAdded(ListDataEvent e) { unsortedIntervalAdded(e); } public void intervalRemoved(ListDataEvent e) { unsortedIntervalRemoved(e); } public void contentsChanged(ListDataEvent e) { unsortedContentsChanged(); } }); this.sortOrder = sortOrder; if (comp != null) { comparator = comp; } else { comparator = Collator.getInstance(); } // get base model info int size = model.getSize(); sortedModel = new ArrayList<SortedListEntry>(size); for (int x = 0; x < size; ++x) { SortedListEntry entry = new SortedListEntry(x); int insertionPoint = findInsertionPoint(entry); sortedModel.add(insertionPoint, entry); } } /** * Retrieve the sorted entry from the original model * @param index index of an entry in the sorted model * @return element in the original model to which our entry points */ public Object getElementAt(int index) throws IndexOutOfBoundsException { int modelIndex = toUnsortedModelIndex(index); Object element = unsortedModel.getElementAt(modelIndex); return element; } /** * Retrieve the size of the underlying model * @return size of the model */ public int getSize() { int size = sortedModel.size(); return size; } /** * Convert sorted model index to an unsorted model index. * *@param index an index in the sorted model *@return modelIndex an index in the unsorted model * */ public int toUnsortedModelIndex(int index) throws IndexOutOfBoundsException { int modelIndex = -1; SortedListEntry entry = sortedModel.get(index); modelIndex = entry.getIndex(); return modelIndex; } /** * Convert an array of sorted model indices to their unsorted model indices. Sort * the resulting set of indices. * *@param sortedSelectedIndices indices of selected elements in the sorted model * or sorted view *@return unsortedSelectedIndices selected indices in the unsorted model */ public int[] toUnsortedModelIndices(int[] sortedSelectedIndices) { int[] unsortedSelectedIndices = new int[sortedSelectedIndices.length]; int x = 0; for(int sortedIndex: sortedSelectedIndices) { unsortedSelectedIndices[x++] = toUnsortedModelIndex(sortedIndex); } // sort the array of indices before returning Arrays.sort(unsortedSelectedIndices); return unsortedSelectedIndices; } /** * Convert an unsorted model index to a sorted model index. * * @param unsortedIndex an element index in the unsorted model * @return sortedIndex an element index in the sorted model */ public int toSortedModelIndex(int unsortedIndex) { int sortedIndex = -1; int x = -1; for (SortedListEntry entry : sortedModel) { ++x; if (entry.getIndex() == unsortedIndex) { sortedIndex = x; break; } } return sortedIndex; } /** * Convert an array of unsorted model selection indices to * indices in the sorted model. Sort the model indices from * low to high to duplicate JList's getSelectedIndices method * * @param unsortedModelIndices * @return an array of selected indices in the sorted model */ public int[] toSortedModelIndices(int[] unsortedModelIndices) { int[] sortedModelIndices = new int[unsortedModelIndices.length]; int x = 0; for(int unsortedIndex : unsortedModelIndices) { sortedModelIndices[x++] = toSortedModelIndex(unsortedIndex); } Arrays.sort(sortedModelIndices); return sortedModelIndices; } private void resetModelData() { int index = 0; for (SortedListEntry entry : sortedModel) { entry.setIndex(index++); } } public void setComparator(Comparator<Object> comp) { if (comp == null) { sortOrder = SortOrder.UNORDERED; comparator = Collator.getInstance(); resetModelData(); } else { comparator = comp; Collections.sort(sortedModel); } fireContentsChanged(ListDataEvent.CONTENTS_CHANGED, 0, sortedModel.size()-1); } /** * Change the sort order of the model at runtime * @param sortOrder */ public void setSortOrder(SortOrder sortOrder) { if (this.sortOrder != sortOrder) { this.sortOrder = sortOrder; if (sortOrder == SortOrder.UNORDERED) { resetModelData(); } else { Collections.sort(sortedModel); } fireContentsChanged(ListDataEvent.CONTENTS_CHANGED, 0, sortedModel.size()-1); } } /** * Update the sorted model whenever new items * are added to the original/decorated model. * */ private void unsortedIntervalAdded(ListDataEvent e) { int begin = e.getIndex0(); int end = e.getIndex1(); int nElementsAdded = end-begin+1; /* Items in the decorated model have shifted in flight. * Increment our model pointers into the decorated model. * We must increment indices that intersect with the insertion * point in the decorated model. */ for (SortedListEntry entry: sortedModel) { int index = entry.getIndex(); // if our model points to a model index >= to where // new model entries are added, we must bump up their index if (index >= begin) { entry.setIndex(index+nElementsAdded); } } // now add the new items from the decorated model for (int x = begin; x <= end; ++x) { SortedListEntry newEntry = new SortedListEntry(x); int insertionPoint = findInsertionPoint(newEntry); sortedModel.add(insertionPoint, newEntry); fireIntervalAdded(ListDataEvent.INTERVAL_ADDED, insertionPoint, insertionPoint); } } /** * Update this model when items are removed from the original/decorated * model. Also, let our listeners know that we've removed items. */ private void unsortedIntervalRemoved(ListDataEvent e) { int begin = e.getIndex0(); int end = e.getIndex1(); int nElementsRemoved = end-begin+1; /* * Move from end to beginning of our sorted model, updating * element indices into the decorated model or removing * elements as necessary */ int sortedSize = sortedModel.size(); boolean[] bElementRemoved = new boolean[sortedSize]; for (int x = sortedSize-1; x >=0; --x) { SortedListEntry entry = sortedModel.get(x); int index = entry.getIndex(); if (index > end) { entry.setIndex(index - nElementsRemoved); } else if (index >= begin) { sortedModel.remove(x); bElementRemoved[x] = true; } } /* * Let listeners know that we've removed items. */ for(int x = bElementRemoved.length-1; x>=0; --x) { if (bElementRemoved[x]) { fireIntervalRemoved(ListDataEvent.INTERVAL_REMOVED, x, x); } } } /** * Resort the sorted model if there are changes in the original * unsorted model. Let any listeners know about changes. Since I don't * track specific changes, sort everywhere and redisplay all items. */ private void unsortedContentsChanged() { Collections.sort(sortedModel); fireContentsChanged(ListDataEvent.CONTENTS_CHANGED, 0, sortedModel.size()-1); } /** * Internal helper method to find the insertion point for a new * entry in the sorted model. */ private int findInsertionPoint(SortedListEntry entry) { int insertionPoint = sortedModel.size(); if (sortOrder != SortOrder.UNORDERED) { insertionPoint = Collections.binarySearch(sortedModel, entry); if (insertionPoint < 0) { insertionPoint = -(insertionPoint +1); } } return insertionPoint; } private List<SortedListEntry> sortedModel; private ListModel unsortedModel; private Comparator<Object> comparator; private SortOrder sortOrder; public enum SortOrder { UNORDERED, ASCENDING, DESCENDING; } class SortedListEntry implements Comparable<Object> { public SortedListEntry(int index) { this.index = index; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } public int compareTo(Object o) { // retrieve the element that this entry points to // in the original model Object thisElement = unsortedModel.getElementAt(index); SortedListEntry thatEntry = (SortedListEntry)o; // retrieve the element that thatEntry points to in the original // model Object thatElement = unsortedModel.getElementAt(thatEntry.getIndex()); if (comparator instanceof Collator) { thisElement = thisElement.toString(); thatElement = thatElement.toString(); } // compare the base model's elements using the provided comparator int comparison = comparator.compare(thisElement, thatElement); // convert to descending order as necessary if (sortOrder == SortOrder.DESCENDING) { comparison = -comparison; } return comparison; } private int index; } }
04900db4-rob
src/org/rapla/gui/internal/edit/reservation/SortedListModel.java
Java
gpl3
12,623
/*--------------------------------------------------------------------------* | 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.edit; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Insets; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Locale; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSplitPane; import javax.swing.border.Border; import javax.swing.border.TitledBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import org.rapla.client.ClientServiceContainer; import org.rapla.client.RaplaClientExtensionPoints; import org.rapla.entities.Named; import org.rapla.entities.NamedComparator; import org.rapla.entities.configuration.Preferences; import org.rapla.framework.PluginDescriptor; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.DefaultPluginOption; import org.rapla.gui.EditComponent; import org.rapla.gui.OptionPanel; import org.rapla.gui.PluginOptionPanel; import org.rapla.gui.RaplaGUIComponent; import org.rapla.gui.TreeFactory; import org.rapla.gui.toolkit.RaplaTree; public class PreferencesEditUI extends RaplaGUIComponent implements EditComponent<Preferences> ,ChangeListener { private JSplitPane content = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); protected TitledBorder selectionBorder; protected RaplaTree jPanelSelection = new RaplaTree(); protected JPanel jPanelContainer = new JPanel(); protected JPanel container = new JPanel(); JLabel messages = new JLabel(); JPanel defaultPanel = new JPanel(); OptionPanel lastOptionPanel; Preferences preferences; /** called during initialization to create the info component */ public PreferencesEditUI(RaplaContext context) { super( context); jPanelContainer.setLayout(new BorderLayout()); jPanelContainer.add(messages,BorderLayout.SOUTH); messages.setForeground( Color.red); Border emptyLineBorder = new Border() { Insets insets = new Insets(2,0,2,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(0,1, c.getWidth(), 1); g.drawLine(0,c.getHeight()-2, c.getWidth(), c.getHeight()-2); } public Insets getBorderInsets( Component c ) { return insets; } public boolean isBorderOpaque() { return true; } }; content.setBorder( emptyLineBorder); jPanelContainer.add(content,BorderLayout.CENTER); jPanelSelection.getTree().setCellRenderer(getTreeFactory().createRenderer()); jPanelSelection.setToolTipRenderer(getTreeFactory().createTreeToolTipRenderer()); container.setPreferredSize( new Dimension(700,550)); content.setLeftComponent(jPanelSelection); content.setRightComponent(container); content.setDividerLocation(260); Border emptyBorder=BorderFactory.createEmptyBorder(4,4,4,4); selectionBorder = BorderFactory.createTitledBorder(emptyBorder, getString("selection") + ":"); jPanelSelection.setBorder(selectionBorder); content.setResizeWeight(0.4); jPanelSelection.addChangeListener(this); } final private TreeFactory getTreeFactory() { return getService(TreeFactory.class); } protected OptionPanel[] getPluginOptions() throws RaplaException { Collection<PluginOptionPanel> panelList = getContainer().lookupServicesFor( RaplaClientExtensionPoints.PLUGIN_OPTION_PANEL_EXTENSION); List<OptionPanel> optionList = new ArrayList<OptionPanel>(); List<PluginDescriptor<ClientServiceContainer>> pluginList = getService( ClientServiceContainer.CLIENT_PLUGIN_LIST); for (final PluginDescriptor<ClientServiceContainer> plugin:pluginList) { OptionPanel optionPanel = find(panelList, plugin); if ( optionPanel == null ) { optionPanel = new DefaultPluginOption(getContext()) { @SuppressWarnings("unchecked") public Class<? extends PluginDescriptor<ClientServiceContainer>> getPluginClass() { return (Class<? extends PluginDescriptor<ClientServiceContainer>>) plugin.getClass(); } @Override public String getName(Locale locale) { String string = plugin.getClass().getSimpleName(); return string; } }; } optionList.add( optionPanel ); } sort( optionList); return optionList.toArray(new OptionPanel[] {}); } private OptionPanel find(Collection<PluginOptionPanel> panels, PluginDescriptor<?> plugin) { for (PluginOptionPanel panel: panels) { Class<? extends PluginDescriptor<?>> pluginClass = panel.getPluginClass(); if (plugin.getClass().equals( pluginClass)) { return panel; } } return null; } public void sort(List<OptionPanel> list) { Collections.sort( list, new NamedComparator<OptionPanel>(getRaplaLocale().getLocale())); } public OptionPanel[] getUserOptions() throws RaplaException { List<OptionPanel> optionList = new ArrayList<OptionPanel>(getContainer().lookupServicesFor( RaplaClientExtensionPoints.USER_OPTION_PANEL_EXTENSION )); sort( optionList); return optionList.toArray(new OptionPanel[] {}); } public OptionPanel[] getAdminOptions() throws RaplaException { List<OptionPanel> optionList = new ArrayList<OptionPanel>(getContainer().lookupServicesFor( RaplaClientExtensionPoints.SYSTEM_OPTION_PANEL_EXTENSION )); sort( optionList); return optionList.toArray(new OptionPanel[] {}); } protected JComponent createInfoComponent() { JPanel panel = new JPanel(); return panel; } private void setOptionPanel(OptionPanel optionPanel) throws Exception { String title = getString("nothing_selected"); JComponent comp = defaultPanel; if ( optionPanel != null) { title = optionPanel.getName( getRaplaLocale().getLocale()); comp = optionPanel.getComponent(); } TitledBorder titledBorder = new TitledBorder(BorderFactory.createEmptyBorder(4,4,4,4),title); container.removeAll(); container.setLayout(new BorderLayout()); container.setBorder(titledBorder); container.add( comp,BorderLayout.CENTER); container.revalidate(); container.repaint(); } public String getTitle() { return getString("options"); } /** maps all fields back to the current object.*/ public void mapToObjects() throws RaplaException { if ( lastOptionPanel != null) lastOptionPanel.commit(); } public void setObjects(List<Preferences> o) throws RaplaException { this.preferences = o.get(0); if ( preferences.getOwner() == null) { messages.setText(getString("restart_options")); } TreeFactory f = getTreeFactory(); DefaultMutableTreeNode root = new DefaultMutableTreeNode(""); if ( preferences.getOwner() != null) { Named[] element = getUserOptions(); for (int i=0; i< element.length; i++) { root.add( f.newNamedNode( element[i])); } } else { { Named[] element = getAdminOptions(); DefaultMutableTreeNode adminRoot = new DefaultMutableTreeNode("admin-options"); for (int i=0; i< element.length; i++) { adminRoot.add( f.newNamedNode( element[i])); } root.add( adminRoot ); } { Named[] element = getPluginOptions(); DefaultMutableTreeNode pluginRoot = new DefaultMutableTreeNode("plugins"); for (int i=0; i< element.length; i++) { pluginRoot.add( f.newNamedNode( element[i])); } root.add( pluginRoot ); } } DefaultTreeModel treeModel = new DefaultTreeModel(root); jPanelSelection.exchangeTreeModel(treeModel); } public List<Preferences> getObjects() { return Collections.singletonList(preferences); } public void stateChanged(ChangeEvent evt) { try { if ( lastOptionPanel != null) lastOptionPanel.commit(); OptionPanel optionPanel = null; if ( getSelectedElement() instanceof OptionPanel ) { optionPanel = (OptionPanel) getSelectedElement(); if ( optionPanel != null) { optionPanel.setPreferences( preferences ); optionPanel.show(); } } lastOptionPanel = optionPanel; setOptionPanel( lastOptionPanel ); } catch (Exception ex) { showException(ex,getComponent()); } } public Object getSelectedElement() { return jPanelSelection.getSelectedElement(); } public JComponent getComponent() { return jPanelContainer; } }
04900db4-rob
src/org/rapla/gui/internal/edit/PreferencesEditUI.java
Java
gpl3
10,652
package org.rapla.gui.internal.edit; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import org.rapla.components.util.undo.CommandUndo; import org.rapla.entities.Category; import org.rapla.entities.Entity; import org.rapla.entities.RaplaType; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; public class DeleteUndo<T extends Entity<T>> extends RaplaComponent implements CommandUndo<RaplaException> { // FIXME Delete of categories in multiple levels can cause the lower levels not to be deleted if it contains categories higher in rank but same hierarchy that are also deleted // FIXME Needs a check last changed private List<T> entities; Map<Category,Category> removedCategories = new LinkedHashMap<Category, Category>(); public DeleteUndo(RaplaContext context,Collection<T> entities) { super(context); this.entities = new ArrayList<T>(); for ( T entity: entities) { // Hack for 1.6 compiler compatibility if ( ((Object)entity.getRaplaType()) == Category.TYPE) { this.entities.add(entity); } else { this.entities.add(entity.clone()); } } } public boolean execute() throws RaplaException { Collection<Category> toStore = new ArrayList<Category>(); List<T> toRemove = new ArrayList<T>(); for ( T entity: entities) { // Hack for 1.6 compiler compatibility if ( ((Object)entity.getRaplaType()) == Category.TYPE) { Entity casted = entity; // to avoid compiler error Category category = (Category) casted; Category parent = category.getParent(); Category parentClone = null; if ( toStore.contains( parent)) { for ( Category cat: toStore) { if ( cat.equals(parent)) { parentClone = parent; } } } else { parentClone = getModification().edit( parent ); toStore.add( parentClone); } if ( parentClone != null) { removedCategories.put( category, parent); parentClone.removeCategory( parentClone.findCategory( category)); } } else { toRemove.add( entity); } } Entity<?>[] arrayStore = toStore.toArray( Category.ENTITY_ARRAY); @SuppressWarnings("unchecked") Entity<T>[] arrayRemove = toRemove.toArray(new Entity[]{}); getModification().storeAndRemove(arrayStore,arrayRemove); return true; } public boolean undo() throws RaplaException { List<Entity<T>> toStore = new ArrayList<Entity<T>>(); for ( T entity: entities) { Entity<T> mutableEntity = entity.clone(); toStore.add( mutableEntity); } Collection<Category> categoriesToStore2 = new LinkedHashSet<Category>(); for ( Category category: removedCategories.keySet()) { Category parent = removedCategories.get( category); Category parentClone = null; if ( categoriesToStore2.contains( parent)) { for ( Category cat: categoriesToStore2) { if ( cat.equals(parent)) { parentClone = parent; } } } else { parentClone = getModification().edit( parent ); Entity castedParent1 = parentClone; @SuppressWarnings({ "cast", "unchecked" }) Entity<T> castedParent = (Entity<T>) castedParent1; toStore.add( castedParent); categoriesToStore2.add( parentClone); } if ( parentClone != null) { parentClone.addCategory( category); } } // Todo generate undo for category store @SuppressWarnings("unchecked") Entity<T>[] array = toStore.toArray(new Entity[]{}); getModification().storeObjects( array); return true; } public String getCommandoName() { Iterator<T> iterator = entities.iterator(); StringBuffer buf = new StringBuffer(); buf.append(getString("delete") ); if ( iterator.hasNext()) { RaplaType raplaType = iterator.next().getRaplaType(); buf.append( " " + getString(raplaType.getLocalName())); } return buf.toString(); } }
04900db4-rob
src/org/rapla/gui/internal/edit/DeleteUndo.java
Java
gpl3
4,444
/*--------------------------------------------------------------------------* | 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.gui.internal.edit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Collections; import java.util.List; import javax.swing.JComboBox; import javax.swing.JComponent; 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.components.util.Assert; import org.rapla.components.util.Tools; import org.rapla.entities.IllegalAnnotationException; import org.rapla.entities.MultiLanguageName; import org.rapla.entities.UniqueKeyException; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.AttributeAnnotations; import org.rapla.entities.dynamictype.AttributeType; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.DynamicTypeAnnotations; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.EditComponent; import org.rapla.gui.RaplaGUIComponent; import org.rapla.gui.internal.edit.fields.MultiLanguageField; import org.rapla.gui.internal.edit.fields.TextField; import org.rapla.gui.toolkit.DialogUI; /**************************************************************** * This is the controller-class for the DynamicType-Edit-Panel * ****************************************************************/ class DynamicTypeEditUI extends RaplaGUIComponent implements EditComponent<DynamicType> { public static String WARNING_SHOWED = DynamicTypeEditUI.class.getName() + "/Warning"; DynamicType dynamicType; JPanel editPanel = new JPanel(); JPanel annotationPanel = new JPanel(); JLabel nameLabel = new JLabel(); MultiLanguageField name; JLabel elementKeyLabel = new JLabel(); TextField elementKey; AttributeEdit attributeEdit; JLabel annotationLabel = new JLabel(); JLabel annotationDescription = new JLabel(); JTextField annotationText = new JTextField(); JTextField annotationTreeText = new JTextField(); JComboBox colorChooser; JLabel locationLabel = new JLabel("location"); JComboBox locationChooser; JLabel conflictLabel = new JLabel("conflict creation"); JComboBox conflictChooser; boolean isResourceType; boolean isEventType; public DynamicTypeEditUI(RaplaContext context) throws RaplaException { super(context); { @SuppressWarnings("unchecked") JComboBox jComboBox = new JComboBox(new String[] {getString("color.automated"),getString("color.manual"),getString("color.no")}); colorChooser = jComboBox; } { @SuppressWarnings("unchecked") JComboBox jComboBox = new JComboBox(new String[] {"yes","no"}); locationChooser = jComboBox; } { @SuppressWarnings("unchecked") JComboBox jComboBox = new JComboBox(new String[] {DynamicTypeAnnotations.VALUE_CONFLICTS_ALWAYS,DynamicTypeAnnotations.VALUE_CONFLICTS_NONE,DynamicTypeAnnotations.VALUE_CONFLICTS_WITH_OTHER_TYPES}); conflictChooser = jComboBox; } name = new MultiLanguageField(context,"name"); elementKey = new TextField(context,"elementKey"); attributeEdit = new AttributeEdit(context); nameLabel.setText(getString("dynamictype.name") + ":"); elementKeyLabel.setText(getString("elementkey") + ":"); attributeEdit.setEditKeys( true ); annotationPanel.setVisible( true); double PRE = TableLayout.PREFERRED; double[][] sizes = new double[][] { {5,PRE,5,TableLayout.FILL,5} ,{PRE,5,PRE,5,PRE,5,PRE,5,TableLayout.FILL,5,PRE} }; TableLayout tableLayout = new TableLayout(sizes); editPanel.setLayout(tableLayout); editPanel.add(nameLabel,"1,2"); editPanel.add(name.getComponent(),"3,2"); editPanel.add(elementKeyLabel,"1,4"); editPanel.add(elementKey.getComponent(),"3,4"); editPanel.add(attributeEdit.getComponent(),"1,6,3,6"); // #FIXM Should be replaced by generic solution tableLayout.insertRow(7,5); tableLayout.insertRow(8,PRE); editPanel.add(annotationPanel,"1,8,3,8"); annotationPanel.setLayout(new TableLayout(new double[][] { {PRE,5,TableLayout.FILL} ,{PRE,5,PRE,5,PRE, 5, PRE,5, PRE,5,PRE} })); addCopyPaste( annotationText); addCopyPaste(annotationTreeText); annotationPanel.add(annotationLabel,"0,0"); annotationPanel.add(annotationText ,"2,0"); annotationPanel.add(annotationDescription,"2,2"); annotationPanel.add(annotationTreeText ,"2,4"); annotationPanel.add(new JLabel(getString("color")),"0,6"); annotationPanel.add(colorChooser,"2,6"); annotationPanel.add(locationLabel,"0,8"); annotationPanel.add(locationChooser,"2,8"); annotationPanel.add(conflictLabel,"0,10"); annotationPanel.add(conflictChooser,"2,10"); annotationLabel.setText(getString("dynamictype.annotation.nameformat") + ":"); annotationDescription.setText(getString("dynamictype.annotation.nameformat.description")); float newSize = (float) (annotationDescription.getFont().getSize() * 0.8); annotationDescription.setFont(annotationDescription.getFont().deriveFont( newSize)); attributeEdit.addChangeListener( new ChangeListener() { public void stateChanged( ChangeEvent e ) { updateAnnotations(); } }); colorChooser.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { if ( dynamicType.getAttribute("color") != null || colorChooser.getSelectedIndex() != 1) { return; } DialogUI ui = DialogUI.create(getContext(), getMainComponent(), true, getString("color.manual"), getString("attribute_color_dialog"), new String[]{getString("yes"),getString("no")}); ui.start(); if (ui.getSelectedIndex() == 0) { Attribute colorAttribute = getModification().newAttribute(AttributeType.STRING); colorAttribute.setKey( "color"); colorAttribute.getName().setName(getLocale().getLanguage(), getString("color")); colorAttribute.setAnnotation(AttributeAnnotations.KEY_EDIT_VIEW, AttributeAnnotations.VALUE_EDIT_VIEW_NO_VIEW); dynamicType.addAttribute( colorAttribute); attributeEdit.setDynamicType(dynamicType); } else { colorChooser.setSelectedIndex(2); } } catch (RaplaException ex) { showException(ex, getMainComponent()); } } }); /* annotationText.addFocusListener( new FocusAdapter() { public void focusLost( FocusEvent e ) { try { setAnnotations(); } catch ( RaplaException ex ) { showException( ex, getComponent()); } } }); */ } public JComponent getComponent() { return editPanel; } public void mapToObjects() throws RaplaException { MultiLanguageName newName = name.getValue(); dynamicType.getName().setTo( newName); dynamicType.setKey(elementKey.getValue()); attributeEdit.confirmEdits(); validate(); setAnnotations(); } private void setAnnotations() throws RaplaException { try { dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_NAME_FORMAT, annotationText.getText().trim()); String planningText = annotationTreeText.getText().trim(); dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_NAME_FORMAT_PLANNING, planningText.length() > 0 ? planningText : null); } catch (IllegalAnnotationException ex) { throw ex; } String color= null; switch (colorChooser.getSelectedIndex()) { case 0:color = DynamicTypeAnnotations.VALUE_COLORS_AUTOMATED;break; case 1:color = DynamicTypeAnnotations.VALUE_COLORS_COLOR_ATTRIBUTE;break; case 2:color = DynamicTypeAnnotations.VALUE_COLORS_DISABLED;break; } dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_COLORS, color); if ( isResourceType) { String location = null; switch (locationChooser.getSelectedIndex()) { case 0:location = "true";break; case 1:location = "false";break; } if ( location == null || location.equals( "false")) { dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_LOCATION, null); } else { dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_LOCATION, location); } } if ( isEventType) { String conflicts = null; switch (conflictChooser.getSelectedIndex()) { case 0:conflicts = DynamicTypeAnnotations.VALUE_CONFLICTS_ALWAYS;break; case 1:conflicts = DynamicTypeAnnotations.VALUE_CONFLICTS_NONE;break; case 2:conflicts = DynamicTypeAnnotations.VALUE_CONFLICTS_WITH_OTHER_TYPES;break; } if ( conflicts == null || conflicts.equals( DynamicTypeAnnotations.VALUE_CONFLICTS_ALWAYS)) { dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_CONFLICTS, null); } else { dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_CONFLICTS, conflicts); } } } public List<DynamicType> getObjects() { List<DynamicType> types = Collections.singletonList(dynamicType); return types; } public void setObjects(List<DynamicType> o) { dynamicType = o.get(0); mapFromObjects(); } public void mapFromObjects() { name.setValue( dynamicType.getName()); elementKey.setValue( dynamicType.getKey()); attributeEdit.setDynamicType(dynamicType); String classificationType = dynamicType.getAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE); isEventType = classificationType != null && classificationType.equals( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION); isResourceType = classificationType != null && classificationType.equals( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE); conflictLabel.setVisible( isEventType); conflictChooser.setVisible( isEventType); locationLabel.setVisible( isResourceType); locationChooser.setVisible( isResourceType); updateAnnotations(); } private void updateAnnotations() { annotationText.setText( dynamicType.getAnnotation( DynamicTypeAnnotations.KEY_NAME_FORMAT ) ); annotationTreeText.setText( dynamicType.getAnnotation( DynamicTypeAnnotations.KEY_NAME_FORMAT_PLANNING,"" ) ); { String annotation = dynamicType.getAnnotation( DynamicTypeAnnotations.KEY_COLORS); if (annotation == null) { annotation = dynamicType.getAttribute("color") != null ? DynamicTypeAnnotations.VALUE_COLORS_COLOR_ATTRIBUTE: DynamicTypeAnnotations.VALUE_COLORS_AUTOMATED; } if ( annotation.equals(DynamicTypeAnnotations.VALUE_COLORS_AUTOMATED)) { colorChooser.setSelectedIndex(0); } else if ( annotation.equals( DynamicTypeAnnotations.VALUE_COLORS_COLOR_ATTRIBUTE)) { colorChooser.setSelectedIndex(1); } else if ( annotation.equals( DynamicTypeAnnotations.VALUE_COLORS_DISABLED)) { colorChooser.setSelectedIndex(2); } } if ( isEventType) { String annotation = dynamicType.getAnnotation( DynamicTypeAnnotations.KEY_CONFLICTS); if (annotation == null) { annotation = DynamicTypeAnnotations.VALUE_CONFLICTS_ALWAYS; } if ( annotation.equals( DynamicTypeAnnotations.VALUE_CONFLICTS_ALWAYS)) { conflictChooser.setSelectedIndex(0); } else if ( annotation.equals(DynamicTypeAnnotations.VALUE_CONFLICTS_NONE)) { conflictChooser.setSelectedIndex(1); } else if ( annotation.equals( DynamicTypeAnnotations.VALUE_CONFLICTS_WITH_OTHER_TYPES)) { conflictChooser.setSelectedIndex(2); } } if ( isResourceType) { String annotation = dynamicType.getAnnotation( DynamicTypeAnnotations.KEY_LOCATION); if (annotation == null) { annotation = "false"; } if ( annotation.equals( "true")) { locationChooser.setSelectedIndex(0); } else { locationChooser.setSelectedIndex(1); } } } private void validate() throws RaplaException { Assert.notNull(dynamicType); if ( getName( dynamicType ).length() == 0) throw new RaplaException(getString("error.no_name")); if (dynamicType.getKey().equals("")) { throw new RaplaException(getI18n().format("error.no_key","")); } checkKey(dynamicType.getKey()); Attribute[] attributes = dynamicType.getAttributes(); for (int i=0;i<attributes.length;i++) { String key = attributes[i].getKey(); if (key == null || key.trim().equals("")) throw new RaplaException(getI18n().format("error.no_key","(" + i + ")")); checkKey(key); for (int j=i+1;j<attributes.length;j++) { if ((key.equals(attributes[j].getKey()))) { throw new UniqueKeyException(getI18n().format("error.not_unique",key)); } } } } private void checkKey(String key) throws RaplaException { if (key.length() ==0) throw new RaplaException(getString("error.no_key")); if (!Tools.isKey(key) || key.length()>50) { Object[] param = new Object[3]; param[0] = key; param[1] = "'-', '_'"; param[2] = "'_'"; throw new RaplaException(getI18n().format("error.invalid_key", param)); } } }
04900db4-rob
src/org/rapla/gui/internal/edit/DynamicTypeEditUI.java
Java
gpl3
15,409
package org.rapla.gui.internal.edit.fields; public class EditFieldLayout { private boolean block; private boolean variableSized; public boolean isBlock() { return block; } public void setBlock(boolean block) { this.block = block; } public boolean isVariableSized() { return variableSized; } public void setVariableSized(boolean variableSized) { this.variableSized = variableSized; } }
04900db4-rob
src/org/rapla/gui/internal/edit/fields/EditFieldLayout.java
Java
gpl3
469
/*--------------------------------------------------------------------------* | 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.edit.fields; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.JScrollPane; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Reservation; import org.rapla.entities.dynamictype.Classifiable; import org.rapla.entities.dynamictype.Classification; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.DynamicTypeAnnotations; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.internal.common.NamedListCellRenderer; import org.rapla.gui.internal.edit.ClassificationEditUI; import org.rapla.gui.toolkit.RaplaListComboBox; /**************************************************************** * This is the base-class for all Classification-Panels * ****************************************************************/ public class ClassificationField<T extends Classifiable> extends AbstractEditField implements EditFieldWithLayout, ActionListener { JPanel content = new JPanel(); RaplaListComboBox typeSelector; ClassificationEditUI editUI; DynamicType oldDynamicType; List<Classification> oldClassifications; // enhancement to array final String multipleValues = TextField.getOutputForMultipleValues(); public ClassificationField(RaplaContext context) { super(context); editUI = new ClassificationEditUI(context); setFieldName("type"); content.setBorder(BorderFactory.createEmptyBorder(3, 2, 3, 2)); } @Override public EditFieldLayout getLayout() { EditFieldLayout layout = new EditFieldLayout(); layout.setBlock( true); layout.setVariableSized( true); return layout; } public void mapTo(List<T> list) throws RaplaException { List<Classification> classifications = editUI.getObjects(); for (int i = 0; i < list.size(); i++) { Classification classification = classifications.get( i ); Classifiable x = list.get(i); x.setClassification(classification); } editUI.mapToObjects(); } public void setTypeChooserVisible( boolean visible) { if ( typeSelector != null) { typeSelector.setVisible( visible); } } @SuppressWarnings("unchecked") public void mapFrom(List<T> list) throws RaplaException { content.removeAll(); List<Classifiable> classifiables = new ArrayList<Classifiable>(); // read out Classifications from Classifiable List<Classification> classifications = new ArrayList<Classification>(); for (Classifiable classifiable:list) { classifiables.add( classifiable); Classification classification = classifiable.getClassification(); classifications.add(classification); } // commit Classifications to ClassificationEditUI editUI.setObjects(classifications); oldClassifications = classifications; // checks unity from RaplaTypes of all Classifiables Set<RaplaType> raplaTypes = new HashSet<RaplaType>(); for (Classifiable c : classifiables) { raplaTypes.add(((RaplaObject) c).getRaplaType()); } RaplaType raplaType; // if there is an unitary type then set typ if (raplaTypes.size() == 1) { raplaType = raplaTypes.iterator().next(); } else { return; } String classificationType = null; if (Reservation.TYPE.equals(raplaType)) { classificationType = DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION; } else if (Allocatable.TYPE.equals(raplaType)) { boolean arePersons = true; // checks if Classifiables are person for (Classifiable c : classifiables) { if (!((Allocatable) c).isPerson()) { arePersons = false; } } if (arePersons) { classificationType = DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON; } else { classificationType = DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE; } } DynamicType[] types = getQuery().getDynamicTypes(classificationType); // determine DynamicTypes of Classifications Set<DynamicType> dynamicTypes = new HashSet<DynamicType>(); for (Classification c : classifications) { dynamicTypes.add(c.getType()); } DynamicType dynamicType; // checks if there is a common DynamicType? if (dynamicTypes.size() == 1) // set dynamicTyp dynamicType = dynamicTypes.iterator().next(); else dynamicType = null; oldDynamicType = dynamicType; RaplaListComboBox jComboBox = new RaplaListComboBox(getContext(),types); typeSelector = jComboBox; typeSelector.setEnabled( types.length > 1); if (dynamicType != null) // set common dynamicType of the Classifications in ComboBox typeSelector.setSelectedItem(dynamicType); else { // ... otherwise set place holder for the several values typeSelector.addItem(multipleValues); typeSelector.setSelectedItem(multipleValues); } typeSelector.setRenderer(new NamedListCellRenderer(getI18n().getLocale())); typeSelector.addActionListener(this); content.setLayout(new BorderLayout()); JPanel container = new JPanel(); container.setLayout(new BorderLayout()); container.add(typeSelector, BorderLayout.WEST); content.add(container, BorderLayout.NORTH); JComponent editComponent = editUI.getComponent(); JScrollPane scrollPane = new JScrollPane(editComponent,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); scrollPane.setViewportView(editComponent); scrollPane.setBorder(BorderFactory.createEtchedBorder()); scrollPane.setMinimumSize(new Dimension(300, 100)); scrollPane.setPreferredSize(new Dimension(500, 340)); scrollPane.getVerticalScrollBar().setUnitIncrement( 10); content.add(scrollPane, BorderLayout.CENTER); } // The DynamicType has changed public void actionPerformed(ActionEvent event) { try { Object source = event.getSource(); if (source == typeSelector) { // checks if a DynamicType has been selected in ComboBox if (typeSelector.getSelectedItem() instanceof DynamicType) { // delete place holder for the several values typeSelector.removeItem(multipleValues); DynamicType dynamicType = (DynamicType) typeSelector .getSelectedItem(); // checks if no new DynmicType has been selected if (dynamicType.equals(oldDynamicType)) // yes: set last Classifications again editUI.setObjects(oldClassifications); else { // no: set new Classifications List<Classification> newClassifications = new ArrayList<Classification>(); List<Classification> classifications = editUI.getObjects(); for (int i = 0; i < classifications.size(); i++) { Classification classification = classifications.get(i); // checks if Classification hast already the new // selected DynamicType if (dynamicType.equals(classification .getType())) { // yes: adopt Classification newClassifications.add( classification ); } else { // no: create new Classification newClassifications.add( dynamicType.newClassification(classification)); } } // set new Classifications in ClassificationEditUI editUI.setObjects(newClassifications); } } } } catch (RaplaException ex) { showException(ex, content); } } public JComponent getComponent() { return content; } }
04900db4-rob
src/org/rapla/gui/internal/edit/fields/ClassificationField.java
Java
gpl3
8,583
/*--------------------------------------------------------------------------* | 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.edit.fields; import java.awt.Component; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import javax.swing.BoxLayout; import javax.swing.ButtonGroup; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRadioButton; import org.rapla.framework.RaplaContext; public class BooleanField extends AbstractEditField implements ActionListener, FocusListener, MultiEditField, SetGetField<Boolean> { JPanel panel = new JPanel(); JRadioButton field1 = new JRadioButton(); JRadioButton field2 = new JRadioButton(); ButtonGroup group = new ButtonGroup(); boolean multipleValues; // indicator, shows if multiple different values are // shown in this field JLabel multipleValuesLabel = new JLabel(); public BooleanField(RaplaContext context,String fieldName) { this(context); setFieldName( fieldName ); } public BooleanField(RaplaContext context) { super( context); field1.setOpaque( false ); field2.setOpaque( false ); panel.setOpaque( false ); panel.setLayout( new BoxLayout(panel,BoxLayout.X_AXIS) ); panel.add( field1 ); panel.add( field2 ); panel.add(multipleValuesLabel); group.add( field1 ); group.add( field2 ); field2.setSelected( true ); field1.addActionListener(this); field2.addActionListener(this); field1.setText(getString("yes")); field2.setText(getString("no")); field1.addFocusListener(this); } public Boolean getValue() { return field1.isSelected() ? Boolean.TRUE : Boolean.FALSE; } public void setValue(Boolean object) { boolean selected = object!= null ? (object).booleanValue() :false; field1.setSelected(selected); field2.setSelected(!selected); } public void actionPerformed(ActionEvent evt) { // once an action is executed, the field shows a common value multipleValues = false; multipleValuesLabel.setText(""); fireContentChanged(); } public JComponent getComponent() { return panel; } public void focusGained(FocusEvent evt) { Component focusedComponent = evt.getComponent(); Component parent = focusedComponent.getParent(); if(parent instanceof JPanel) { ((JPanel)parent).scrollRectToVisible(focusedComponent.getBounds(null)); } } public void focusLost(FocusEvent evt) { } public void setFieldForMultipleValues() { // if multiple different values should be shown, no RadioButton is // activated (instead a place holder) group.clearSelection(); multipleValues = true; multipleValuesLabel.setText(TextField.getOutputForMultipleValues()); multipleValuesLabel.setFont(multipleValuesLabel.getFont().deriveFont(Font.ITALIC)); } public boolean hasMultipleValues() { return multipleValues; } }
04900db4-rob
src/org/rapla/gui/internal/edit/fields/BooleanField.java
Java
gpl3
4,000
/*--------------------------------------------------------------------------* | 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.edit.fields; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Font; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.util.Date; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import org.rapla.components.calendar.DateChangeEvent; import org.rapla.components.calendar.DateChangeListener; import org.rapla.components.calendar.RaplaCalendar; import org.rapla.framework.RaplaContext; public class DateField extends AbstractEditField implements DateChangeListener, FocusListener, SetGetField<Date> ,MultiEditField{ RaplaCalendar field; JPanel panel; boolean multipleValues = false; // Indikator, ob mehrere verschiedene Werte ueber dieses Feld angezeigt werden JLabel multipleValuesLabel = new JLabel(); public DateField(RaplaContext context,String fieldName) { this( context); setFieldName(fieldName); } public DateField(RaplaContext context) { super( context); panel = new JPanel(); field = createRaplaCalendar(); panel.setLayout(new BorderLayout()); panel.add(field,BorderLayout.WEST); panel.add( multipleValuesLabel, BorderLayout.CENTER); panel.setOpaque( false ); field.setNullValuePossible( true); field.addDateChangeListener(this); field.addFocusListener(this); } public Date getValue() { return field.getDate(); } public void setValue(Date date) { // //check if standard-value exists and is a Date-Object // if(object instanceof Date) // date = (Date) object; // //if it's not a Date-Object, set the current Date as Standart // else // date = new Date(); field.setDate(date); } public RaplaCalendar getCalendar() { return field; } public void dateChanged(DateChangeEvent evt) { // Eingabe wurde getaetigt: einheitlicher Werte wurde gesetzt => Flag aendern, da kein Platzhalter mehr angezeigt wird if(multipleValues){ multipleValues = false; } fireContentChanged(); } public JComponent getComponent() { return panel; } public void focusGained(FocusEvent evt) { Component focusedComponent = evt.getComponent(); Component parent = focusedComponent.getParent(); if(parent instanceof JPanel) { ((JPanel)parent).scrollRectToVisible(focusedComponent.getBounds(null)); } } public void focusLost(FocusEvent evt) { } // Implementierung fuer Interface MultiEditField public boolean hasMultipleValues() { return multipleValues; } // Implementierung fuer Interface MultiEditField public void setFieldForMultipleValues() { multipleValues = true; multipleValuesLabel.setText(TextField.getOutputForMultipleValues()); multipleValuesLabel.setFont(multipleValuesLabel.getFont().deriveFont(Font.ITALIC)); field.setDate( null); } }
04900db4-rob
src/org/rapla/gui/internal/edit/fields/DateField.java
Java
gpl3
3,917
/*--------------------------------------------------------------------------* | 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.edit.fields; import java.util.Arrays; import java.util.Set; import java.util.TreeSet; import org.rapla.entities.NamedComparator; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.dynamictype.ClassificationFilter; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; public class AllocatableListField extends ListField<Allocatable> { DynamicType dynamicTypeConstraint; public AllocatableListField(RaplaContext context, DynamicType dynamicTypeConstraint) throws RaplaException{ super( context, true); this.dynamicTypeConstraint = dynamicTypeConstraint; ClassificationFilter filter = dynamicTypeConstraint.newClassificationFilter(); ClassificationFilter[] filters = new ClassificationFilter[] {filter}; Allocatable[] allocatables = getQuery().getAllocatables(filters); Set<Allocatable> list = new TreeSet<Allocatable>(new NamedComparator<Allocatable>(getLocale())); list.addAll( Arrays.asList( allocatables)); setVector(list); } }
04900db4-rob
src/org/rapla/gui/internal/edit/fields/AllocatableListField.java
Java
gpl3
2,074
/*--------------------------------------------------------------------------* | 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.edit.fields; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import javax.swing.BorderFactory; import javax.swing.DefaultListCellRenderer; import javax.swing.DefaultListModel; import javax.swing.JComponent; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Permission; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.internal.edit.RaplaListEdit; import org.rapla.gui.toolkit.EmptyLineBorder; /** * @author Christopher Kohlhaas */ public class PermissionListField extends AbstractEditField implements EditFieldWithLayout { JList permissionList = new JList(); JPanel jPanel = new JPanel(); PermissionField permissionField; private RaplaListEdit<Permission> listEdit; Listener listener = new Listener(); Allocatable firstAllocatable; DefaultListModel model = new DefaultListModel(); Permission selectedPermission = null; int selectedIndex = 0; List<Permission> notAllList = new ArrayList<Permission>(); public PermissionListField(RaplaContext context, String fieldName) throws RaplaException { super(context); permissionField = new PermissionField(context); super.setFieldName(fieldName); jPanel.setLayout(new BorderLayout()); listEdit = new RaplaListEdit<Permission>(getI18n(), permissionField.getComponent(), listener); jPanel.add(listEdit.getComponent(), BorderLayout.CENTER); jPanel.setBorder(BorderFactory.createTitledBorder(new EmptyLineBorder(), getString("permissions"))); permissionField.addChangeListener(listener); } public JComponent getComponent() { return jPanel; } public EditFieldLayout getLayout() { EditFieldLayout layout = new EditFieldLayout(); return layout; } public void mapTo(List<Allocatable> list) { for (Allocatable allocatable :list) { for (Permission perm : allocatable.getPermissions()) { if (!model.contains( perm) ) { allocatable.removePermission(perm); } } @SuppressWarnings({ "unchecked", "cast" }) Enumeration<Permission> it = (Enumeration<Permission>) model.elements(); while (it.hasMoreElements()) { Permission perm= it.nextElement(); if ( !hasPermission(allocatable, perm) && !isNotForAll( perm)) { allocatable.addPermission( perm); } } } } private boolean hasPermission(Allocatable allocatable, Permission permission) { for (Permission perm: allocatable.getPermissions()) { if (perm.equals( permission)) { return true; } } return false; } @SuppressWarnings("unchecked") public void mapFrom(List<Allocatable> list) { model.clear(); firstAllocatable = list.size() > 0 ? list.get(0) : null; Set<Permission> permissions = new LinkedHashSet<Permission>(); for (Allocatable allocatable :list) { List<Permission> permissionList = Arrays.asList(allocatable.getPermissions()); permissions.addAll(permissionList); } Set<Permission> set = new LinkedHashSet<Permission>(); for (Permission perm : permissions) { model.addElement(perm); for (Allocatable allocatable:list) { List<Permission> asList = Arrays.asList(allocatable.getPermissions()); if (!asList.contains(perm)) { set.add( perm); } } } notAllList.clear(); for (Permission perm : set) { notAllList.add(perm); } listEdit.setListDimension(new Dimension(210, 90)); listEdit.setMoveButtonVisible(false); listEdit.getList().setModel(model); listEdit.getList().setCellRenderer(new DefaultListCellRenderer() { private static final long serialVersionUID = 1L; public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { Permission p = (Permission) value; if (p.getUser() != null) { value = getString("user") + " " + p.getUser().getUsername(); } else if (p.getGroup() != null) { value = getString("group") + " " + p.getGroup().getName(getI18n().getLocale()); } else { value = getString("all_users"); } value = (index + 1) + ") " + value; Component component = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); Font f; if (isNotForAll( p)) { f =component.getFont().deriveFont(Font.ITALIC); } else { f =component.getFont().deriveFont(Font.BOLD); } component.setFont(f); return component; } }); } // Check if permission is in notAllList. We need to check references as the equals method could also match another permission private boolean isNotForAll( Permission p) { for (Permission perm: notAllList) { if ( perm == p) { return true; } } return false; } private void removePermission() { for (Permission permission:listEdit.getSelectedValues()) { model.removeElement(permission); } listEdit.getList().requestFocus(); } @SuppressWarnings("unchecked") private void createPermission() { if ( firstAllocatable == null) { return; } Permission permission = firstAllocatable.newPermission(); model.addElement(permission); } class Listener implements ActionListener, ChangeListener { public void actionPerformed(ActionEvent evt) { if (evt.getActionCommand().equals("remove")) { removePermission(); } else if (evt.getActionCommand().equals("new")) { createPermission(); } else if (evt.getActionCommand().equals("edit")) { // buffer selected Permission selectedPermission = (Permission) listEdit.getList().getSelectedValue(); selectedIndex = listEdit.getList().getSelectedIndex(); // commit common Permissions (like the selected one) for // processing permissionField.setValue(selectedPermission); } } @SuppressWarnings("unchecked") public void stateChanged(ChangeEvent evt) { // set processed selected Permission in the list model.set(selectedIndex, selectedPermission); // remove permission from notAllList we need to check references as the equals method could also match another permission Iterator<Permission> it = notAllList.iterator(); while (it.hasNext()) { Permission next = it.next(); if ( next == selectedPermission ) { it.remove(); } } } } }
04900db4-rob
src/org/rapla/gui/internal/edit/fields/PermissionListField.java
Java
gpl3
7,736
/*--------------------------------------------------------------------------* | 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.edit.fields; import javax.swing.tree.TreeModel; import org.rapla.entities.Category; import org.rapla.framework.RaplaContext; public class CategorySelectField extends AbstractSelectField<Category> { Category rootCategory; public CategorySelectField(RaplaContext context,Category rootCategory){ this( context, rootCategory, null); } public CategorySelectField(RaplaContext context,Category rootCategory, Category defaultCategory) { super( context, defaultCategory); this.rootCategory = rootCategory; } @Override protected String getNodeName(Category selectedCategory) { return selectedCategory.getPath(rootCategory,getI18n().getLocale()); } @Override public TreeModel createModel() { return getTreeFactory().createModel(rootCategory); } public Category getRootCategory() { return rootCategory; } public void setRootCategory(Category rootCategory) { this.rootCategory = rootCategory; } }
04900db4-rob
src/org/rapla/gui/internal/edit/fields/CategorySelectField.java
Java
gpl3
1,979
package org.rapla.gui.internal.edit.fields; public interface EditFieldWithLayout { EditFieldLayout getLayout(); }
04900db4-rob
src/org/rapla/gui/internal/edit/fields/EditFieldWithLayout.java
Java
gpl3
120
package org.rapla.gui.internal.edit.fields; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Arrays; import java.util.Collection; import java.util.Enumeration; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import javax.swing.DefaultListCellRenderer; import javax.swing.DefaultListModel; import javax.swing.JComponent; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JToolBar; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.rapla.entities.Category; import org.rapla.entities.User; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.toolkit.RaplaButton; public class GroupListField extends AbstractEditField implements ChangeListener, ActionListener, EditFieldWithLayout { DefaultListModel model = new DefaultListModel(); JPanel panel = new JPanel(); JToolBar toolbar = new JToolBar(); CategorySelectField newCategory; RaplaButton removeButton = new RaplaButton(RaplaButton.SMALL); RaplaButton newButton = new RaplaButton(RaplaButton.SMALL); JList list = new JList(); Set<Category> notAllList = new HashSet<Category>(); /** * @param context * @throws RaplaException */ public GroupListField(RaplaContext context) throws RaplaException { super(context); final Category rootCategory = getQuery().getUserGroupsCategory(); if ( rootCategory == null ) return; newCategory = new CategorySelectField(context, rootCategory ); newCategory.setUseNull( false); toolbar.add( newButton ); toolbar.add( removeButton ); toolbar.setFloatable( false ); panel.setLayout( new BorderLayout() ); panel.add( toolbar, BorderLayout.NORTH ); final JScrollPane jScrollPane = new JScrollPane(list, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); jScrollPane.setPreferredSize( new Dimension( 300, 150 ) ); panel.add( jScrollPane, BorderLayout.CENTER ); newButton.setText( getString( "group" ) + " " + getString( "add" ) ); removeButton.setText( getString( "group" ) + " " + getString( "remove" ) ); newButton.setIcon( getIcon( "icon.new" ) ); removeButton.setIcon( getIcon( "icon.remove" ) ); newCategory.addChangeListener( this ); newButton.addActionListener( this ); removeButton.addActionListener( this ); DefaultListCellRenderer cellRenderer = new DefaultListCellRenderer() { private static final long serialVersionUID = 1L; public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { Category category = (Category) value; if ( value != null ) { value = category.getPath( rootCategory , getI18n().getLocale()); } Component component = super.getListCellRendererComponent(list,value,index,isSelected,cellHasFocus); if (notAllList.contains( category)) { Font f =component.getFont().deriveFont(Font.ITALIC); component.setFont(f); } return component; } }; setRenderer(cellRenderer); } @SuppressWarnings("unchecked") private void setRenderer(DefaultListCellRenderer cellRenderer) { list.setCellRenderer(cellRenderer ); } public JComponent getComponent() { return panel; } @Override public EditFieldLayout getLayout() { EditFieldLayout layout = new EditFieldLayout(); layout.setBlock( true); layout.setVariableSized( false); return layout; } public void mapFrom(List<User> users) { Set<Category> categories = new LinkedHashSet<Category>(); // determination of the common categories/user groups for (User user:users) { categories.addAll(Arrays.asList(user.getGroups())); } Set<Category> notAll = new LinkedHashSet<Category>(); for ( Category group: categories) { for (User user:users) { if (!user.belongsTo( group)) { notAll.add(group); } } } mapFromList(categories,notAll); } public void mapToList(Collection<Category> groups) { groups.clear(); @SuppressWarnings({ "unchecked", "cast" }) Enumeration<Category> it = (Enumeration<Category>) model.elements(); while (it.hasMoreElements()) { Category cat= it.nextElement(); groups.add( cat); } } public void mapFromList(Collection<Category> groups) { mapFromList(groups, new HashSet<Category>()); } @SuppressWarnings("unchecked") private void mapFromList(Collection<Category> groups,Set<Category> notToAll) { model.clear(); this.notAllList = notToAll; for ( Category cat:groups) { model.addElement( cat ); } list.setModel(model); } public void mapTo(List<User> users) { for (User user:users) { for (Category cat : user.getGroups()) { if (!model.contains( cat) && !notAllList.contains( cat)) { user.removeGroup( cat); } } @SuppressWarnings({ "unchecked", "cast" }) Enumeration<Category> it = (Enumeration<Category>) model.elements(); while (it.hasMoreElements()) { Category cat= it.nextElement(); if ( !user.belongsTo( cat) && !notAllList.contains( cat)) { user.addGroup( cat); } } } } public void actionPerformed(ActionEvent evt) { if ( evt.getSource() == newButton) { try { newCategory.setValue( null ); newCategory.showDialog(newButton); } catch (RaplaException ex) { showException(ex,newButton); } } if ( evt.getSource() == removeButton) { @SuppressWarnings("deprecation") Object[] selectedValues = list.getSelectedValues(); for ( Object value: selectedValues) { Category group = (Category) value; if (group != null) { model.removeElement( group ); notAllList.remove( group); fireContentChanged(); } } } } @SuppressWarnings("unchecked") public void stateChanged(ChangeEvent evt) { Collection<Category> newGroup = newCategory.getValues(); for ( Category group:newGroup) { notAllList.remove( group); if ( ! model.contains( group ) ) { model.addElement( group ); } } fireContentChanged(); list.repaint(); } }
04900db4-rob
src/org/rapla/gui/internal/edit/fields/GroupListField.java
Java
gpl3
7,395
/*--------------------------------------------------------------------------* | 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.edit.fields; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Collection; import javax.swing.AbstractCellEditor; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.event.CellEditorListener; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.table.DefaultTableModel; import org.rapla.entities.MultiLanguageName; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.toolkit.DialogUI; import org.rapla.gui.toolkit.RaplaButton; public class MultiLanguageField extends AbstractEditField implements ChangeListener, ActionListener,CellEditorListener, SetGetField<MultiLanguageName> { JPanel panel = new JPanel(); TextField textField; RaplaButton button = new RaplaButton(RaplaButton.SMALL); MultiLanguageName name = new MultiLanguageName(); MultiLanguageEditorDialog editorDialog; String[] availableLanguages; public MultiLanguageField(RaplaContext context, String fieldName) { this(context); setFieldName(fieldName); } public MultiLanguageField(RaplaContext context) { super( context); textField = new TextField(context, "name"); availableLanguages = getRaplaLocale().getAvailableLanguages(); panel.setLayout( new BorderLayout() ); panel.add( textField.getComponent(), BorderLayout.CENTER ); panel.add( button, BorderLayout.EAST ); button.addActionListener( this ); button.setIcon( getIcon("icon.language-select") ); textField.addChangeListener( this ); } public void requestFocus() { textField.getComponent().requestFocus(); } public void selectAll() { textField.selectAll(); } public void stateChanged(ChangeEvent e) { if (name != null) { name.setName(getI18n().getLang(),textField.getValue()); fireContentChanged(); } } public void actionPerformed(ActionEvent evt) { editorDialog = new MultiLanguageEditorDialog( button ); editorDialog.addCellEditorListener( this ); editorDialog.setEditorValue( name ); try { editorDialog.show(); } catch (RaplaException ex) { showException( ex, getComponent()); } } public void editingStopped(ChangeEvent e) { setValue((MultiLanguageName) editorDialog.getEditorValue()); fireContentChanged(); } public void editingCanceled(ChangeEvent e) { } public MultiLanguageName getValue() { return this.name; } public void setValue(MultiLanguageName object) { this.name = object; textField.setValue(name.getName(getI18n().getLang())); } public JComponent getComponent() { return panel; } class MultiLanguageEditorDialog extends AbstractCellEditor { private static final long serialVersionUID = 1L; JTable table = new JTable(); JLabel label = new JLabel(); JPanel comp = new JPanel(); MultiLanguageName editorValue; Component owner; MultiLanguageEditorDialog(JComponent owner) { this.owner = owner; table.setPreferredScrollableViewportSize(new Dimension(300, 200)); comp.setLayout(new BorderLayout()); comp.add(label,BorderLayout.NORTH); comp.add(new JScrollPane(table),BorderLayout.CENTER); } public void setEditorValue(Object value) { this.editorValue = (MultiLanguageName)value; table.setModel(new TranslationTableModel(editorValue)); table.getColumnModel().getColumn(0).setPreferredWidth(30); table.getColumnModel().getColumn(1).setPreferredWidth(200); label.setText(getI18n().format("translation.format", editorValue)); } public Object getEditorValue() { return editorValue; } public Object getCellEditorValue() { return getEditorValue(); } public void show() throws RaplaException { DialogUI dlg = DialogUI.create(getContext(),owner,true,comp,new String[] { getString("ok"),getString("cancel")}); dlg.setTitle(getString("translation")); // Workaround for Bug ID 4480264 on developer.java.sun.com if (table.getRowCount() > 0 ) { table.editCellAt(0, 0); table.editCellAt(0, 1); } dlg.start(); if (dlg.getSelectedIndex() == 0) { for (int i=0;i<availableLanguages.length;i++) { String value = (String)table.getValueAt(i,1); if (value != null) editorValue.setName(availableLanguages[i],value); } if (table.isEditing()) { if (table.getEditingColumn() == 1) { JTextField textField = (JTextField) table.getEditorComponent(); addCopyPaste( textField); int row = table.getEditingRow(); String value = textField.getText(); editorValue.setName(availableLanguages[row],value); } } fireEditingStopped(); } else { fireEditingCanceled(); } } } class TranslationTableModel extends DefaultTableModel { private static final long serialVersionUID = 1L; public TranslationTableModel(MultiLanguageName name) { super(); addColumn(getString("language")); addColumn(getString("translation")); Collection<String> trans = name.getAvailableLanguages(); for (int i=0;i<availableLanguages.length;i++) { String lang = availableLanguages[i]; String[] row = new String[2]; row[0] = lang; row[1] = trans.contains(lang) ? name.getName(lang): ""; addRow(row); } } public boolean isCellEditable(int row, int col) { //Note that the data/cell address is constant, //no matter where the cell appears onscreen. if (col < 1) { return false; } else { return true; } } } }
04900db4-rob
src/org/rapla/gui/internal/edit/fields/MultiLanguageField.java
Java
gpl3
7,612
/*--------------------------------------------------------------------------* | 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.edit.fields; import java.awt.BorderLayout; import java.awt.Dimension; 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.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import javax.swing.AbstractAction; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTree; import javax.swing.SwingUtilities; import javax.swing.plaf.basic.BasicTreeUI; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeSelectionModel; 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; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.TreeFactory; import org.rapla.gui.toolkit.DialogUI; import org.rapla.gui.toolkit.RaplaButton; import org.rapla.gui.toolkit.RaplaTree.TreeIterator; public abstract class AbstractSelectField<T> extends AbstractEditField implements MultiEditField, SetGetField<T>, SetGetCollectionField<T> { private RaplaButton selectButton = new RaplaButton(RaplaButton.SMALL); JPanel panel = new JPanel(); JLabel selectText = new JLabel(); private Collection<T> selectedValues = new ArrayList<T>(); T defaultValue; private boolean useDefault = true; private boolean useNull = true; boolean multipleValues = false; boolean multipleSelectionPossible = false; public RaplaButton getButton() { return selectButton; } public AbstractSelectField(RaplaContext context){ this( context, null); } public AbstractSelectField(RaplaContext context, T defaultValue) { super( context); useDefault = defaultValue != null; selectButton.setAction(new SelectionAction()); selectButton.setHorizontalAlignment(RaplaButton.LEFT); selectButton.setText(getString("select")); selectButton.setIcon(getIcon("icon.tree")); panel.setLayout( new BoxLayout(panel, BoxLayout.X_AXIS)); panel.add( selectButton); panel.add( Box.createHorizontalStrut(10)); panel.add( selectText); this.defaultValue = defaultValue; } public boolean isUseNull() { return useNull; } public void setUseNull(boolean useNull) { this.useNull = useNull; } public boolean isMultipleSelectionPossible() { return multipleSelectionPossible; } public void setMultipleSelectionPossible(boolean multipleSelectionPossible) { this.multipleSelectionPossible = multipleSelectionPossible; } public class SelectionAction extends AbstractAction { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent evt) { try { showDialog(selectButton); } catch (RaplaException ex) { showException(ex,selectButton); } } } public T getValue() { Collection<T> values = getValues(); if ( values.size() == 0) { return null; } else { T first = values.iterator().next(); return first; } } public Collection<T> getValues() { return selectedValues; } public void setValue(T object) { List<T> list; if ( object == null) { list = Collections.emptyList(); } else { list = Collections.singletonList(object); } setValues(list); } final protected TreeFactory getTreeFactory() { return getService(TreeFactory.class); } public void setValues(Collection<T> values) { selectedValues = new ArrayList<T>(); if ( values !=null) { selectedValues.addAll(values); } String text; if (selectedValues.size() > 0) { text=""; T selectedCategory = selectedValues.iterator().next(); { text +=getNodeName(selectedCategory); } if ( selectedValues.size() > 1) { text+= ", ..."; } } else { text = getString("nothing_selected"); } selectText.setText(text); } protected abstract String getNodeName(T selectedCategory); public class MultiSelectionTreeUI extends BasicTreeUI { @Override protected boolean isToggleSelectionEvent( MouseEvent event ) { return SwingUtilities.isLeftMouseButton( event ); } } @SuppressWarnings("serial") public void showDialog(JComponent parent) throws RaplaException { final DialogUI dialog; final JTree tree; if ( multipleSelectionPossible) { tree = new JTree() { public void setSelectionPath(TreePath path) { StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); StackTraceElement caller = stackTrace[2]; String className = caller.getClassName(); String methodName = caller.getMethodName(); if ( className.contains("BasicTreeUI") && (methodName.contains("keyTyped") || methodName.contains("page"))) { setLeadSelectionPath( path); return; } setSelectionPath(path); } public void setSelectionInterval(int index0, int index1) { if ( index0 >= 0) { TreePath path = getPathForRow(index0); setLeadSelectionPath( path); } } }; TreeSelectionModel model = new DefaultTreeSelectionModel(); tree.setUI( new MultiSelectionTreeUI() ); model.setSelectionMode( TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION ); tree.setSelectionModel(model ); } else { tree = new JTree(); tree.getSelectionModel().setSelectionMode( TreeSelectionModel.SINGLE_TREE_SELECTION ); } tree.setCellRenderer(getTreeFactory().createRenderer()); //tree.setVisibleRowCount(15); tree.setRootVisible( false ); tree.setShowsRootHandles(true); TreeModel model = createModel(); tree.setModel(model); selectCategory(tree,selectedValues); JPanel panel = new JPanel(); panel.setLayout( new BorderLayout()); JScrollPane scrollPane = new JScrollPane(tree); scrollPane.setMinimumSize(new Dimension(300, 200)); scrollPane.setPreferredSize(new Dimension(400, 260)); panel.add(scrollPane, BorderLayout.PAGE_START); if (useDefault) { JButton defaultButton = new JButton(getString("defaultselection")); panel.add( defaultButton, BorderLayout.CENTER); defaultButton.setPreferredSize(new Dimension(100, 20)); defaultButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent arg0) { selectCategory( tree, Collections.singletonList(defaultValue)); } }); } if (useNull) { JButton emptyButton = new JButton(getString("nothing_selected")); panel.add( emptyButton, BorderLayout.PAGE_END); emptyButton.setPreferredSize(new Dimension(100, 20)); emptyButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent arg0) { List<T> emptyList = Collections.emptyList(); selectCategory(tree, emptyList ); } }); } dialog = DialogUI.create(getContext() ,parent ,true ,panel ,new String[] { getString("apply"),getString("cancel")}); 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) { DefaultMutableTreeNode node = (DefaultMutableTreeNode)selPath.getLastPathComponent(); if (node.isLeaf()) { dialog.getButton(0).doClick(); } } } }); dialog.setTitle(getString("select")); dialog.setInitFocus( tree); dialog.start(); if (dialog.getSelectedIndex() == 0) { TreePath[] paths = tree.getSelectionPaths(); Collection<T> newValues = new ArrayList<T>(); if ( paths != null) { for (TreePath path:paths) { Object valueObject = ((DefaultMutableTreeNode)path.getLastPathComponent()).getUserObject(); T value = getValue(valueObject); if ( value != null) { newValues.add(value); } } } if ( !newValues.equals(selectedValues)) { setValues( newValues ); fireContentChanged(); } } } protected T getValue(Object valueObject) { @SuppressWarnings("unchecked") T casted = (T) valueObject; return casted; } public abstract TreeModel createModel() throws RaplaException; private void selectCategory(JTree tree, Collection<T> categories) { select(tree, categories); //RecursiveNode.selectUserObjects(tree,path.toArray()); } public void select(JTree jTree,Collection<?> selectedObjects) { Collection<TreeNode> selectedNodes = new ArrayList<TreeNode>(); Iterator<TreeNode> it = new TreeIterator((TreeNode)jTree.getModel().getRoot()); while (it.hasNext()) { TreeNode node = it.next(); if (node != null && selectedObjects.contains( getObject(node) )) selectedNodes.add(node); } it = selectedNodes.iterator(); TreePath[] path = new TreePath[selectedNodes.size()]; int i=0; while (it.hasNext()) { path[i] = getPath(it.next()); jTree.expandPath(path[i]); i++; } jTree.getSelectionModel().clearSelection(); jTree.setSelectionPaths(path); } 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; } } private TreePath getPath(TreeNode node) { if (node.getParent() == null) return new TreePath(node); else return getPath(node.getParent()).pathByAddingChild(node); } public JComponent getComponent() { return panel; } // implementation for interface MultiEditField public boolean hasMultipleValues() { return multipleValues; } // implementation for interface MultiEditField public void setFieldForMultipleValues() { multipleValues = true; // sets place holder for different values selectText.setText(TextField.getOutputForMultipleValues()); } }
04900db4-rob
src/org/rapla/gui/internal/edit/fields/AbstractSelectField.java
Java
gpl3
13,144
/*--------------------------------------------------------------------------* | 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.edit.fields; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Font; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.rapla.components.calendar.RaplaNumber; import org.rapla.framework.RaplaContext; public class LongField extends AbstractEditField implements ChangeListener, FocusListener, MultiEditField, SetGetField<Long>{ JPanel panel = new JPanel(); RaplaNumber field; boolean multipleValues = false; // indicator, shows if multiple different // values are shown in this field JLabel multipleValuesLabel = new JLabel(); public LongField(RaplaContext context, String fieldName) { this(context, (Long)null); setFieldName(fieldName); } public LongField(RaplaContext context) { this(context, (Long)null); } public LongField(RaplaContext context, Long minimum) { super(context); panel.setLayout(new BorderLayout()); panel.setOpaque(false); field = new RaplaNumber(minimum, minimum, null, minimum == null); addCopyPaste(field.getNumberField()); field.setColumns(8); field.addChangeListener(this); panel.add(field, BorderLayout.WEST); panel.add(multipleValuesLabel, BorderLayout.CENTER); field.addFocusListener(this); } public Long getValue() { if (field.getNumber() != null) return new Long(field.getNumber().longValue()); else return null; } public Integer getIntValue() { if (field.getNumber() != null) return new Integer(field.getNumber().intValue()); else return null; } public void setValue(Long object) { if (object != null) { field.setNumber( object); } else { field.setNumber(null); } } public void setValue(Integer object) { if (object != null) { field.setNumber( object); } else { field.setNumber(null); } } public void stateChanged(ChangeEvent evt) { // if entry was executed: a common value has been set -> change flag, no // place holder has to be shown anymore if (multipleValues) { multipleValues = false; multipleValuesLabel.setText(""); } fireContentChanged(); } public JComponent getComponent() { return panel; } public void focusGained(FocusEvent evt) { Component focusedComponent = evt.getComponent(); Component parent = focusedComponent.getParent(); if (parent instanceof JPanel) { ((JPanel) parent).scrollRectToVisible(focusedComponent .getBounds(null)); } } public void focusLost(FocusEvent evt) { } // implementation for interface MultiEditField public boolean hasMultipleValues() { return multipleValues; } // implementation for interface MultiEditField public void setFieldForMultipleValues() { multipleValues = true; // place holder for multiple different values: multipleValuesLabel.setText(TextField.getOutputForMultipleValues()); multipleValuesLabel.setFont(multipleValuesLabel.getFont().deriveFont(Font.ITALIC)); } }
04900db4-rob
src/org/rapla/gui/internal/edit/fields/LongField.java
Java
gpl3
4,028
package org.rapla.gui.internal.edit.fields; import java.util.Collection; public interface SetGetCollectionField<T> { void setValues(Collection<T> values); Collection<T> getValues(); }
04900db4-rob
src/org/rapla/gui/internal/edit/fields/SetGetCollectionField.java
Java
gpl3
194
/*--------------------------------------------------------------------------* | 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.edit.fields; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import javax.swing.BorderFactory; import javax.swing.DefaultComboBoxModel; import javax.swing.DefaultListCellRenderer; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.rapla.components.layout.TableLayout; import org.rapla.entities.Category; import org.rapla.entities.User; import org.rapla.entities.domain.Permission; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; public class PermissionField extends AbstractEditField implements ChangeListener, ActionListener { SetGetField<Category> groupSelect; ListField<User> userSelect; JPanel panel = new JPanel(); JPanel reservationPanel; Permission permission; JComboBox startSelection = new JComboBox(); JComboBox endSelection = new JComboBox(); DateField startDate; DateField endDate; LongField minAdvance; LongField maxAdvance; ListField<Integer> accessField; @SuppressWarnings("unchecked") public PermissionField(RaplaContext context) throws RaplaException { super( context); panel.setBorder(BorderFactory.createEmptyBorder(5,8,5,8)); double pre =TableLayout.PREFERRED; double fill =TableLayout.FILL; panel.setLayout( new TableLayout( new double[][] {{fill, 5}, // Columns {pre,5,pre,5,pre}} // Rows )); JPanel userPanel = new JPanel(); panel.add( userPanel , "0,0,f,f" ); userPanel.setLayout( new TableLayout( new double[][] {{pre, 10, fill, 5}, // Columns {pre,5,pre,5,pre}} // Rows )); userSelect = new UserListField( context ); userPanel.add( new JLabel(getString("user") + ":"), "0,0,l,f" ); userPanel.add( userSelect.getComponent(),"2,0,l,f" ); Category rootCategory = getQuery().getUserGroupsCategory(); if ( rootCategory != null) { AbstractEditField groupSelect; if (rootCategory.getDepth() > 2) { CategorySelectField field= new CategorySelectField(getContext(), rootCategory); this.groupSelect = field; groupSelect = field; } else { CategoryListField field = new CategoryListField(getContext(), rootCategory); this.groupSelect = field; groupSelect = field; } userPanel.add( new JLabel(getString("group") + ":"), "0,2,l,f" ); userPanel.add( groupSelect.getComponent(),"2,2,l,f" ); groupSelect.addChangeListener( this ); } reservationPanel = new JPanel(); panel.add( reservationPanel , "0,2,f,f" ); reservationPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(), getString("allocatable_in_timeframe") + ":" )); reservationPanel.setLayout( new TableLayout( new double[][] {{pre,3, pre, 5, pre, 5}, // Columns {pre, 5, pre}} // Rows )); reservationPanel.add( new JLabel( getString("start_date") + ":" ) , "0,0,l,f" ); reservationPanel.add( startSelection , "2,0,l,f" ); startSelection.setModel( createSelectionModel() ); startSelection.setSelectedIndex( 0 ); startDate = new DateField(context); reservationPanel.add( startDate.getComponent() , "4,0,l,f" ); minAdvance = new LongField(context,new Long(0) ); reservationPanel.add( minAdvance.getComponent() , "4,0,l,f" ); reservationPanel.add( new JLabel( getString("end_date") + ":" ), "0,2,l,f" ); reservationPanel.add( endSelection , "2,2,l,f" ); endSelection.setModel( createSelectionModel() ); endSelection.setSelectedIndex( 0 ); endDate = new DateField(context); reservationPanel.add( endDate.getComponent() , "4,2,l,f" ); maxAdvance = new LongField(context, new Long(1) ); reservationPanel.add( maxAdvance.getComponent() , "4,2,l,f" ); userPanel.add( new JLabel(getString("permission.access") + ":"), "0,4,f,f" ); Collection<Integer> vector = new ArrayList<Integer>(); for (Integer accessLevel:Permission.ACCESS_LEVEL_NAMEMAP.keySet()) { vector.add( accessLevel ) ; } accessField = new ListField<Integer>(context, vector ); accessField.setRenderer( new DefaultListCellRenderer() { private static final long serialVersionUID = 1L; public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { if (value != null) { String key = Permission.ACCESS_LEVEL_NAMEMAP.get( ((Integer) value).intValue() ); value = getI18n().getString("permission." + key ); } return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus ); }} ); userPanel.add( accessField.getComponent(), "2,4,f,f" ); toggleVisibility(); userSelect.addChangeListener( this ); startSelection.addActionListener(this); minAdvance.addChangeListener(this); startDate.addChangeListener(this); endSelection.addActionListener(this); maxAdvance.addChangeListener(this); endDate.addChangeListener(this); accessField.addChangeListener(this); panel.revalidate(); } public JComponent getComponent() { return panel; } @SuppressWarnings("unchecked") private DefaultComboBoxModel createSelectionModel() { DefaultComboBoxModel model = new DefaultComboBoxModel(); model.addElement(getString( "open" ) ); model.addElement(getString( "fixed_date") ); model.addElement(getString( "x_days_advance") ); return model; } private void toggleVisibility() { int level = accessField.getValue().intValue(); reservationPanel.setVisible( level >= Permission.ALLOCATE && level < Permission.ADMIN); int i = startSelection.getSelectedIndex(); startDate.getComponent().setVisible( i == 1 ); minAdvance.getComponent().setVisible( i == 2 ); int j = endSelection.getSelectedIndex(); endDate.getComponent().setVisible( j == 1 ); maxAdvance.getComponent().setVisible( j == 2 ); } boolean listenersDisabled = false; public void setValue(Permission value) { try { listenersDisabled = true; permission = value; int startIndex = 0; if ( permission.getStart() != null ) startIndex = 1; if ( permission.getMinAdvance() != null ) startIndex = 2; startSelection.setSelectedIndex( startIndex ); int endIndex = 0; if ( permission.getEnd() != null ) endIndex = 1; if ( permission.getMaxAdvance() != null ) endIndex = 2; endSelection.setSelectedIndex( endIndex ); startDate.setValue( permission.getStart()); minAdvance.setValue( permission.getMinAdvance()); endDate.setValue(permission.getEnd() ); maxAdvance.setValue(permission.getMaxAdvance()); if ( groupSelect != null ) { groupSelect.setValue( permission.getGroup()); } userSelect.setValue(permission.getUser() ); accessField.setValue( permission.getAccessLevel() ); toggleVisibility(); } finally { listenersDisabled = false; } } public void actionPerformed(ActionEvent evt) { if ( listenersDisabled ) return; if (evt.getSource() == startSelection) { int i = startSelection.getSelectedIndex(); if ( i == 0 ) { permission.setStart( null ); permission.setMinAdvance( null ); } if ( i == 1 ) { Date today = getQuery().today(); permission.setStart( today ); startDate.setValue( today); } if ( i == 2 ) { permission.setMinAdvance( new Integer(0) ); minAdvance.setValue( new Integer(0 )); } } if (evt.getSource() == endSelection) { int i = endSelection.getSelectedIndex(); if ( i == 0 ) { permission.setEnd( null ); permission.setMaxAdvance( null ); } if ( i == 1 ) { Date today = getQuery().today(); permission.setEnd( today ); endDate.setValue( today); } if ( i == 2 ) { permission.setMaxAdvance( new Integer( 30 ) ); maxAdvance.setValue( new Integer(30)); } } toggleVisibility(); fireContentChanged(); } public Permission getValue() { return permission; } public void stateChanged(ChangeEvent evt) { if ( listenersDisabled ) return; Permission perm = permission; if (evt.getSource() == groupSelect) { perm.setGroup(groupSelect.getValue() ); userSelect.setValue(perm.getUser()) ; } else if (evt.getSource() == userSelect) { perm.setUser( userSelect.getValue()); if ( groupSelect != null ) groupSelect.setValue(perm.getGroup()); } else if (evt.getSource() == startDate) { perm.setStart(startDate.getValue() ); } else if (evt.getSource() == minAdvance) { perm.setMinAdvance( minAdvance.getIntValue()); } else if (evt.getSource() == endDate) { perm.setEnd(endDate.getValue()); } else if (evt.getSource() == maxAdvance) { perm.setMaxAdvance(maxAdvance.getIntValue() ); } else if (evt.getSource() == accessField ) { perm.setAccessLevel( accessField.getValue() ); toggleVisibility(); } fireContentChanged(); } class UserListField extends ListField<User> { public UserListField(RaplaContext sm) throws RaplaException{ super(sm,true); setVector(Arrays.asList(getQuery().getUsers() )); } } }
04900db4-rob
src/org/rapla/gui/internal/edit/fields/PermissionField.java
Java
gpl3
11,867
/*--------------------------------------------------------------------------* | 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.edit.fields; import java.util.Vector; import org.rapla.entities.Category; import org.rapla.framework.RaplaContext; public class CategoryListField extends ListField<Category> { Category rootCategory; public CategoryListField(RaplaContext context,Category rootCategory) { super(context, true); this.rootCategory = rootCategory; Category[] obj = rootCategory.getCategories(); Vector<Category> list = new Vector<Category>(); for (int i=0;i<obj.length;i++) list.add(obj[i]); setVector(list); } }
04900db4-rob
src/org/rapla/gui/internal/edit/fields/CategoryListField.java
Java
gpl3
1,538
/*--------------------------------------------------------------------------* | 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.edit.fields; import java.awt.BorderLayout; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Vector; import javax.swing.DefaultComboBoxModel; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.ListCellRenderer; import org.rapla.framework.RaplaContext; import org.rapla.gui.toolkit.RaplaListComboBox; public class ListField<T> extends AbstractEditField implements ActionListener,FocusListener, MultiEditField, SetGetField<T>, SetGetCollectionField<T> { JPanel panel; JComboBox field; protected String nothingSelected; Vector<Object> list; boolean multipleValues = false; // indicator, shows if multiple different // values are shown in this field final String multipleValuesOutput = TextField.getOutputForMultipleValues(); boolean includeNothingSelected; public ListField(RaplaContext context, Collection<T> v) { this(context, false); setVector(v); } public ListField(RaplaContext sm, boolean includeNothingSelected) { super(sm); this.includeNothingSelected = includeNothingSelected; setFieldName(fieldName); panel = new JPanel(); panel.setOpaque(false); field = new RaplaListComboBox(sm); field.addActionListener(this); panel.setLayout(new BorderLayout()); panel.add(field, BorderLayout.WEST); nothingSelected = getString("nothing_selected"); field.addFocusListener(this); } @SuppressWarnings("unchecked") public void setVector(Collection<T> v) { this.list = new Vector<Object>(v); if ( includeNothingSelected) { list.insertElementAt(nothingSelected, 0); } DefaultComboBoxModel aModel = new DefaultComboBoxModel(list); field.setModel(aModel); } @SuppressWarnings("unchecked") public void setRenderer(ListCellRenderer renderer) { field.setRenderer(renderer); } public Collection<T> getValues() { Object value = field.getSelectedItem(); if (list.contains(nothingSelected) && nothingSelected.equals(value)) { return Collections.emptyList(); } else { @SuppressWarnings("unchecked") T casted = (T) value; return Collections.singletonList( casted); } } public T getValue() { Collection<T> values = getValues(); if ( values.size() == 0) { return null; } else { T first = values.iterator().next(); return first; } } public void setValue(T object) { List<T> list; if ( object == null) { list = Collections.emptyList(); } else { list = Collections.singletonList(object); } setValues(list); } public void setValues(Collection<T> value) { if (list.contains(nothingSelected) && (value == null || value.size() == 0) ) { field.setSelectedItem(nothingSelected); } else { if ( value != null && value.size() > 0) { T first = value.iterator().next(); field.setSelectedItem(first); } else { field.setSelectedItem(null); } } } public JComponent getComponent() { return panel; } public void actionPerformed(ActionEvent evt) { // checks if a new common value has been set if (multipleValues && field.getSelectedItem() != multipleValuesOutput) { // delete place holder for multiple different values multipleValues = false; field.removeItem(multipleValuesOutput); } fireContentChanged(); } public void focusGained(FocusEvent evt) { Component focusedComponent = evt.getComponent(); Component parent = focusedComponent.getParent(); if (parent instanceof JPanel) { ((JPanel) parent).scrollRectToVisible(focusedComponent .getBounds(null)); } } public void focusLost(FocusEvent evt) { } // implementation of interface MultiEditField public boolean hasMultipleValues() { return multipleValues; } // implementation of interface MultiEditField @SuppressWarnings("unchecked") public void setFieldForMultipleValues() { multipleValues = true; // place holder for multiple different values field.addItem(multipleValuesOutput); field.setSelectedItem(multipleValuesOutput); } }
04900db4-rob
src/org/rapla/gui/internal/edit/fields/ListField.java
Java
gpl3
5,352
/*--------------------------------------------------------------------------* | 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.edit.fields; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeModel; import javax.swing.tree.TreeNode; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.dynamictype.ClassificationFilter; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; public class AllocatableSelectField extends AbstractSelectField<Allocatable> { DynamicType dynamicTypeConstraint; public AllocatableSelectField(RaplaContext context, DynamicType dynamicTypeConstraint){ super( context); this.dynamicTypeConstraint = dynamicTypeConstraint; } @Override protected Allocatable getValue(Object valueObject) { if ( valueObject instanceof Allocatable) { return (Allocatable) valueObject; } else { return null; } } @Override protected String getNodeName(Allocatable selectedAllocatable) { return selectedAllocatable.getName(getI18n().getLocale()); } @Override public TreeModel createModel() throws RaplaException { Allocatable[] allocatables; if (dynamicTypeConstraint !=null) { ClassificationFilter filter = dynamicTypeConstraint.newClassificationFilter(); ClassificationFilter[] filters = new ClassificationFilter[] {filter}; allocatables = getQuery().getAllocatables(filters); } else { allocatables = getQuery().getAllocatables(); } TreeModel treeModel = getTreeFactory().createClassifiableModel(allocatables); if (dynamicTypeConstraint !=null) { TreeNode child = ((TreeNode)treeModel.getRoot()).getChildAt(0); treeModel = new DefaultTreeModel( child ); } return treeModel; } }
04900db4-rob
src/org/rapla/gui/internal/edit/fields/AllocatableSelectField.java
Java
gpl3
2,715
/*--------------------------------------------------------------------------* | 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.edit.fields; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JColorChooser; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.text.JTextComponent; import org.rapla.framework.RaplaContext; import org.rapla.gui.toolkit.AWTColorUtil; public class TextField extends AbstractEditField implements ActionListener,FocusListener,KeyListener, MultiEditField, SetGetField<String> { JTextComponent field; JComponent colorPanel; JScrollPane scrollPane; JButton colorChooserBtn ; JPanel color; Object oldValue; Color currentColor; boolean multipleValues = false; // indicator, shows if multiple different // values are shown in this field public final static int DEFAULT_LENGTH = 30; public TextField(RaplaContext context) { this( context,"", 1, TextField.DEFAULT_LENGTH); } public TextField(RaplaContext context,String fieldName) { this( context,fieldName, 1, TextField.DEFAULT_LENGTH); } public TextField(RaplaContext sm,String fieldName, int rows, int columns) { super( sm); setFieldName( fieldName ); if ( rows > 1 ) { JTextArea area = new JTextArea(); field = area; scrollPane = new JScrollPane( field, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); area.setColumns( columns); area.setRows( rows ); area.setLineWrap( true); } else { field = new JTextField( columns); } addCopyPaste( field); field.addFocusListener(this); field.addKeyListener(this); if (fieldName.equals("color")) { colorPanel = new JPanel(); color = new JPanel(); color.setPreferredSize(new Dimension(20,20)); color.setBorder( BorderFactory.createEtchedBorder()); colorPanel.setLayout(new BorderLayout()); colorPanel.add( field, BorderLayout.CENTER); colorPanel.add( color, BorderLayout.WEST); colorChooserBtn = new JButton(); if ( field instanceof JTextField) { ((JTextField) field).setColumns( 7); } else { ((JTextArea) field).setColumns( 7); } colorPanel.add( colorChooserBtn, BorderLayout.EAST); colorChooserBtn.setText( getString("change") ); colorChooserBtn.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { currentColor = JColorChooser.showDialog( colorPanel, "Choose Background Color", currentColor); color.setBackground( currentColor ); if ( currentColor != null) { field.setText( AWTColorUtil.getHexForColor( currentColor )); } fireContentChanged(); } }); } setValue(""); } public String getValue() { return field.getText().trim(); } public void setValue(String string) { if (string == null) string = ""; field.setText(string); oldValue = string; if ( colorPanel != null) { try { currentColor = AWTColorUtil.getColorForHex( string); } catch (NumberFormatException ex) { currentColor = null; } color.setBackground( currentColor ); } } public JComponent getComponent() { if ( colorPanel!= null) { return colorPanel; } if ( scrollPane != null ) { return scrollPane; } else { return field; } } public void selectAll() { field.selectAll(); } public void actionPerformed(ActionEvent evt) { if (field.getText().equals(oldValue)) return; oldValue = field.getText(); fireContentChanged(); } public void focusLost(FocusEvent evt) { if (field.getText().equals(oldValue)) return; // checks if entry was executed if (field.getText().equals("") && multipleValues) // no set place holder for multiple values setFieldForMultipleValues(); else // yes: reset flag, because there is just one common entry multipleValues = false; oldValue = field.getText(); fireContentChanged(); } public void focusGained(FocusEvent evt) { Component focusedComponent = evt.getComponent(); Component parent = focusedComponent.getParent(); if(parent instanceof JPanel) { ((JPanel)parent).scrollRectToVisible(focusedComponent.getBounds(null)); } // if the place holder shown for different values, the place holder // should be deleted if (multipleValues) { setValue(""); // set font PLAIN (place holder is shown italic) field.setFont(field.getFont().deriveFont(Font.PLAIN)); } } public void keyPressed(KeyEvent evt) {} public void keyTyped(KeyEvent evt) {} public void keyReleased(KeyEvent evt) { if (field.getText().equals(oldValue)) return; // reset flag, because there is just one common entry if (multipleValues) { multipleValues = false; } oldValue = field.getText(); fireContentChanged(); } public void setFieldForMultipleValues() { // set a place holder for multiple different values (italic) field.setFont(field.getFont().deriveFont(Font.ITALIC)); field.setText(TextField.getOutputForMultipleValues()); multipleValues = true; } public boolean hasMultipleValues() { return multipleValues; } static public String getOutputForMultipleValues() { // place holder for mulitple different values return "<multiple Values>"; } }
04900db4-rob
src/org/rapla/gui/internal/edit/fields/TextField.java
Java
gpl3
7,398
/*--------------------------------------------------------------------------* | 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.edit.fields; import org.rapla.gui.EditField; public interface SetGetField<T> extends EditField { T getValue(); void setValue(T value); }
04900db4-rob
src/org/rapla/gui/internal/edit/fields/SetGetField.java
Java
gpl3
1,118
/*--------------------------------------------------------------------------* | 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.edit.fields; import java.util.ArrayList; import javax.swing.JComponent; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.rapla.framework.RaplaContext; import org.rapla.gui.EditField; import org.rapla.gui.RaplaGUIComponent; /** 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 abstract class AbstractEditField extends RaplaGUIComponent implements EditField { String fieldName; ArrayList<ChangeListener> listenerList = new ArrayList<ChangeListener>(); public AbstractEditField(RaplaContext context) { super(context); } public void addChangeListener(ChangeListener listener) { listenerList.add(listener); } public void removeChangeListener(ChangeListener listener) { listenerList.remove(listener); } public ChangeListener[] getChangeListeners() { return listenerList.toArray(new ChangeListener[]{}); } protected void fireContentChanged() { if (listenerList.size() == 0) return; ChangeEvent evt = new ChangeEvent(this); ChangeListener[] listeners = getChangeListeners(); for (int i = 0;i<listeners.length; i++) { listeners[i].stateChanged(evt); } } abstract public JComponent getComponent(); public void setFieldName(String fieldName) { this.fieldName = fieldName; } public String getFieldName() { return this.fieldName; } }
04900db4-rob
src/org/rapla/gui/internal/edit/fields/AbstractEditField.java
Java
gpl3
2,610
package org.rapla.gui.internal.edit.fields; //Interface for one EditField; it is designed for showing multiple values at the same time public interface MultiEditField { // shows the field a place holder for different values or a common value for all objects? public boolean hasMultipleValues(); // sets on a field a place holder for different values public void setFieldForMultipleValues(); }
04900db4-rob
src/org/rapla/gui/internal/edit/fields/MultiEditField.java
Java
gpl3
397
<body> Edit-dialogs for all rapla entities. </body>
04900db4-rob
src/org/rapla/gui/internal/edit/package.html
HTML
gpl3
55
/*--------------------------------------------------------------------------* | 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.edit; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.rapla.components.layout.TableLayout; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.EditComponent; import org.rapla.gui.EditField; import org.rapla.gui.RaplaGUIComponent; import org.rapla.gui.internal.edit.fields.EditFieldLayout; import org.rapla.gui.internal.edit.fields.EditFieldWithLayout; /** */ public abstract class AbstractEditUI<T> extends RaplaGUIComponent implements EditComponent<T> ,ChangeListener { protected JPanel editPanel = new JPanel(); protected List<T> objectList; protected List<EditField> fields = Collections.emptyList(); public AbstractEditUI(RaplaContext context) { super(context); } final protected void setFields(Collection<? extends EditField> fields) { for (EditField field:fields) { field.removeChangeListener(this); } this.fields = new ArrayList<EditField>(fields); for (EditField field:fields) { field.addChangeListener(this); } editPanel.removeAll(); layout(); editPanel.revalidate(); } protected void layout() { TableLayout tableLayout = new TableLayout(); editPanel.setLayout(tableLayout); tableLayout.insertColumn(0,5); tableLayout.insertColumn(1,TableLayout.PREFERRED); tableLayout.insertColumn(2,5); tableLayout.insertColumn(3,TableLayout.FILL); tableLayout.insertColumn(4,5); int variableSizedBlocks = 0; for (EditField field:fields) { EditFieldLayout layout = getLayout(field); if (layout.isVariableSized()) { variableSizedBlocks ++; } } int row = 0; for (EditField field:fields) { tableLayout.insertRow(row,5); row ++; EditFieldLayout layout = getLayout(field); if (layout.isVariableSized()) { @SuppressWarnings("cast") double size = 0.99 / ((double) variableSizedBlocks); tableLayout.insertRow(row,size); } else{ tableLayout.insertRow(row,TableLayout.PREFERRED); } if (layout.isBlock()) { editPanel.add("1," + row + ",3," + row+",l", field.getComponent()); } else { editPanel.add("1," + row +",l,c", new JLabel(getFieldName(field) + ":")); editPanel.add("3," + row +",l,c", field.getComponent()); } row ++; } if (variableSizedBlocks == 0) { tableLayout.insertRow(row,TableLayout.FILL); editPanel.add("0," + row + ",4," + row ,new JLabel("")); } } private EditFieldLayout getLayout(EditField field) { if ( field instanceof EditFieldWithLayout) { return ((EditFieldWithLayout) field).getLayout(); } else { return new EditFieldLayout(); } } final public String getFieldName(EditField field) { String fieldName = field.getFieldName(); if ( fieldName == null) { return ""; } return fieldName; } public void setObjects(List<T> o) throws RaplaException { this.objectList = o; mapFromObjects(); } abstract protected void mapFromObjects() throws RaplaException; public List<T> getObjects() { return objectList; } public boolean isBlock() { return false; } public JComponent getComponent() { return editPanel; } public void stateChanged(ChangeEvent evt) { } }
04900db4-rob
src/org/rapla/gui/internal/edit/AbstractEditUI.java
Java
gpl3
4,966
/*--------------------------------------------------------------------------* | 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.edit; import java.awt.BorderLayout; import java.awt.Component; import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import javax.swing.AbstractAction; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.JPanel; import org.rapla.components.util.undo.CommandHistory; import org.rapla.entities.Category; import org.rapla.entities.Entity; import org.rapla.entities.IllegalAnnotationException; import org.rapla.entities.configuration.Preferences; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.facade.ModificationEvent; import org.rapla.facade.ModificationListener; import org.rapla.framework.Disposable; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.EditComponent; import org.rapla.gui.EditController; import org.rapla.gui.RaplaGUIComponent; import org.rapla.gui.toolkit.DialogUI; import org.rapla.gui.toolkit.DisposingTool; public class EditDialog<T extends Entity> extends RaplaGUIComponent implements ModificationListener,Disposable { DialogUI dlg; boolean bSaving = false; EditComponent<T> ui; boolean modal; private Collection<T> originals; public EditDialog(RaplaContext sm,EditComponent<T> ui,boolean modal){ super( sm); this.ui = ui; this.modal = modal; } public EditDialog(RaplaContext sm,EditComponent<T> ui) { this(sm,ui,true); } final private EditControllerImpl getPrivateEditDialog() { return (EditControllerImpl) getService(EditController.class); } public int start(Collection<T> editObjects,String title,Component owner) throws RaplaException { // sets for every object in this array an edit item in the logfile originals= new ArrayList<T>(); Map<T, T> persistant = getModification().getPersistant( editObjects); for (T entity : editObjects) { getLogger().debug("Editing Object: " + entity); @SuppressWarnings("unchecked") Entity<T> mementable = persistant.get( entity); if ( mementable != null) { if ( originals == null) { throw new RaplaException("You cannot edit persistant and new entities in one operation"); } originals.add( mementable.clone() ); } else { if ( originals != null && !originals.isEmpty()) { throw new RaplaException("You cannot edit persistant and new entities in one operation"); } originals = null; } } List<T> toEdit = new ArrayList<T>(editObjects); ui.setObjects(toEdit); JComponent editComponent = ui.getComponent(); JPanel panel = new JPanel(); panel.setLayout( new BorderLayout()); panel.add( editComponent, BorderLayout.CENTER); editComponent.setBorder(BorderFactory.createEmptyBorder(3,3,3,3)); dlg = DialogUI.create(getContext(),owner,modal,panel,new String[] { getString("save") ,getString("cancel") }); dlg.setAbortAction(new AbortAction()); dlg.getButton(0).setAction(new SaveAction()); dlg.getButton(1).setAction(new AbortAction()); dlg.getButton(0).setIcon(getIcon("icon.save")); dlg.getButton(1).setIcon(getIcon("icon.cancel")); dlg.setTitle(getI18n().format("edit.format",title)); getUpdateModule().addModificationListener(this); dlg.addWindowListener(new DisposingTool(this)); dlg.start(); if (modal) { return dlg.getSelectedIndex(); } else { getPrivateEditDialog().addEditDialog( this ); // to avoid java compiler error EditComponent test = ui; if ( test instanceof CategoryEditUI) { ((CategoryEditUI)test).processCreateNew(); } return -1; } } protected boolean shouldCancelOnModification(ModificationEvent evt) { List<T> objects = ui.getObjects(); for (T o:objects ) { // TODO include timestamps in preferencepatches if ( o instanceof Preferences && ((Preferences)o).getOwner() != null) { continue; } if (evt.hasChanged(o)) { return true; } } return false; } public void dataChanged(ModificationEvent evt) throws RaplaException { if (bSaving || dlg == null || !dlg.isVisible() || ui == null) return; if (shouldCancelOnModification(evt)) { getLogger().warn("Object has been changed outside."); DialogUI warning = DialogUI.create(getContext() ,ui.getComponent() ,true ,getString("warning") ,getI18n().format("warning.update",ui.getObjects()) ); warning.start(); getPrivateEditDialog().removeEditDialog( this ); dlg.close(); } } class SaveAction extends AbstractAction { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent evt) { try { ui.mapToObjects(); bSaving = true; // object which is processed by EditComponent List<T> saveObjects = ui.getObjects(); Collection<T> entities = new ArrayList<T>(); entities.addAll(saveObjects); boolean canUndo = true; for ( T obj: saveObjects) { if ( obj instanceof Preferences || obj instanceof DynamicType || obj instanceof Category) { canUndo = false; } } if ( canUndo) { @SuppressWarnings({ "unchecked", "rawtypes" }) SaveUndo<T> saveCommand = new SaveUndo(getContext(), entities, originals); CommandHistory commandHistory = getModification().getCommandHistory(); commandHistory.storeAndExecute(saveCommand); } else { getModification().storeObjects( saveObjects.toArray( new Entity[] {})); } getPrivateEditDialog().removeEditDialog(EditDialog.this); dlg.close(); } catch (IllegalAnnotationException ex) { showWarning(ex.getMessage(), dlg); } catch (RaplaException ex) { showException(ex, dlg); } } } class AbortAction extends AbstractAction { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent evt) { getPrivateEditDialog().removeEditDialog( EditDialog.this ); dlg.close(); } } public void dispose() { getUpdateModule().removeModificationListener(this); } }
04900db4-rob
src/org/rapla/gui/internal/edit/EditDialog.java
Java
gpl3
8,462
/*--------------------------------------------------------------------------* | 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.edit; import java.awt.Component; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.rapla.entities.Category; import org.rapla.entities.Entity; import org.rapla.entities.RaplaType; import org.rapla.entities.User; import org.rapla.entities.configuration.Preferences; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Reservation; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.DynamicTypeAnnotations; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.EditComponent; import org.rapla.gui.EditController; import org.rapla.gui.RaplaGUIComponent; /** This class handles the edit-ui for all entities (except reservations). */ public class EditControllerImpl extends RaplaGUIComponent implements EditController { Collection<EditDialog<?>> editWindowList = new ArrayList<EditDialog<?>>(); public EditControllerImpl(RaplaContext sm){ super(sm); } void addEditDialog(EditDialog<?> editWindow) { editWindowList.add(editWindow); } void removeEditDialog(EditDialog<?> editWindow) { editWindowList.remove(editWindow); } public <T extends Entity> EditComponent<T> createUI(T obj) throws RaplaException { return createUI( obj,false); } /* * (non-Javadoc) * * @see org.rapla.gui.edit.IEditController#createUI(org.rapla.entities. * RaplaPersistant) */ @SuppressWarnings("unchecked") public <T extends Entity> EditComponent<T> createUI(T obj, boolean createNew) throws RaplaException { RaplaType type = obj.getRaplaType(); EditComponent<?> ui = null; if (Allocatable.TYPE.equals(type)) { boolean internal = isInternalType( (Allocatable)obj); ui = new AllocatableEditUI(getContext(), internal); } else if (DynamicType.TYPE.equals(type)) { ui = new DynamicTypeEditUI(getContext()); } else if (User.TYPE.equals(type)) { ui = new UserEditUI(getContext()); } else if (Category.TYPE.equals(type)) { ui = new CategoryEditUI(getContext(), createNew); } else if (Preferences.TYPE.equals(type)) { ui = new PreferencesEditUI(getContext()); } else if (Reservation.TYPE.equals(type)) { ui = new ReservationEditUI(getContext()); } if (ui == null) { throw new RuntimeException("Can't edit objects of type " + type.toString()); } return (EditComponent<T>)ui; } private boolean isInternalType(Allocatable alloc) { DynamicType type = alloc.getClassification().getType(); String annotation = type.getAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE); return annotation != null && annotation.equals( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RAPLATYPE); } // enhancement of the method to deal with arrays protected String guessTitle(Object obj) { RaplaType raplaType = getRaplaType(obj); String title = ""; if(raplaType != null) { title = getString(raplaType.getLocalName()); } return title; } // method for determining the consistent RaplaType from different objects protected RaplaType getRaplaType(Object obj){ Set<RaplaType> types = new HashSet<RaplaType>(); // if the committed object is no array -> wrap object into array if (!obj.getClass().isArray()) { obj = new Object[] { obj }; } // iterate all committed objects and store RaplayType of the objects in a Set // identic typs aren't stored double because of Set for (Object o : (Object[]) obj) { if (o instanceof Entity) { RaplaType type = ((Entity<?>) o).getRaplaType(); types.add(type); } } // check if there is a explicit type, then return this type; otherwise return null if (types.size() == 1) return types.iterator().next(); else return null; } public <T extends Entity> void edit(T obj, Component owner) throws RaplaException { edit(obj, guessTitle(obj), owner); } public <T extends Entity> void editNew(T obj, Component owner) throws RaplaException { edit(obj, guessTitle(obj), owner, true); } public <T extends Entity> void edit(T[] obj, Component owner) throws RaplaException { edit(obj, guessTitle(obj), owner); } /* * (non-Javadoc) * * @see org.rapla.gui.edit.IEditController#edit(org.rapla.entities.Entity, * java.lang.String, java.awt.Component) */ public <T extends Entity> void edit(T obj, String title, Component owner) throws RaplaException { edit(obj, title, owner, false); } protected <T extends Entity> void edit(T obj, String title, Component owner,boolean createNew ) throws RaplaException { // Hack for 1.6 compiler compatibility @SuppressWarnings("cast") Entity<?> testObj = (Entity<?>) obj; if ( testObj instanceof Reservation) { getReservationController().edit( (Reservation) testObj ); return; } // Lookup if the reservation is already beeing edited EditDialog<?> c = null; Iterator<EditDialog<?>> it = editWindowList.iterator(); while (it.hasNext()) { c = it.next(); List<?> editObj = c.ui.getObjects(); if (editObj != null && editObj.size() == 1 ) { Object first = editObj.get(0); if (first instanceof Entity && ((Entity<?>) first).isIdentical(obj)) { break; } } c = null; } if (c != null) { c.dlg.requestFocus(); c.dlg.toFront(); } else { editAndOpenDialog( Collections.singletonList( obj),title, owner, createNew); } } // method analog to edit(Entity obj, String title, Component owner) // however for using with arrays public <T extends Entity> void edit(T[] obj, String title, Component owner) throws RaplaException { // checks if all entities are from the same type; otherwise return if(getRaplaType(obj) == null) return; // if selektion contains only one object start usual Edit dialog if(obj.length == 1){ edit(obj[0], title, owner); } else { editAndOpenDialog(Arrays.asList(obj), title, owner, false); } } protected <T extends Entity> void editAndOpenDialog(List<T> list, String title, Component owner, boolean createNew) throws RaplaException { // gets for all objects in array a modifiable version and add it to a set to avoid duplication Collection<T> toEdit = getModification().edit( list); if (toEdit.size() > 0) { EditComponent<T> ui = createUI(toEdit.iterator().next(), createNew); EditDialog<T> gui = new EditDialog<T>(getContext(), ui, false); gui.start(toEdit, title, owner); } } }
04900db4-rob
src/org/rapla/gui/internal/edit/EditControllerImpl.java
Java
gpl3
7,638
package org.rapla.gui.internal.edit; import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTree; import javax.swing.UIManager; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.TreeModelEvent; import javax.swing.event.TreeModelListener; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreeModel; import javax.swing.tree.TreePath; import org.rapla.components.layout.TableLayout; import org.rapla.components.xmlbundle.I18nBundle; import org.rapla.gui.toolkit.RaplaWidget; final class RaplaTreeEdit implements RaplaWidget { int oldIndex = -1; JPanel mainPanel = new JPanel(); JLabel nothingSelectedLabel = new JLabel(); JScrollPane scrollPane; Color selectionBackground = UIManager.getColor("List.selectionBackground"); Color background = UIManager.getColor("List.background"); JPanel jointPanel = new JPanel() { private static final long serialVersionUID = 1L; int xa[] = new int[4]; int ya[] = new int[4]; public void paint(Graphics g) { super.paint(g); TreePath selectedPath = tree.getPathForRow( getSelectedIndex() ); Rectangle rect = tree.getPathBounds( selectedPath ); Dimension dim = getSize(); if (rect != null) { int y = rect.y -scrollPane.getViewport().getViewPosition().y; int y1= Math.min(dim.height,Math.max(0, y) + scrollPane.getLocation().y); int y2= Math.min(dim.height,Math.max(0,y + rect.height) + scrollPane.getLocation().y); xa[0]=0; ya[0]=y1; xa[1]=dim.width; ya[1]=0; xa[2]=dim.width; ya[2]=dim.height; xa[3]=0; ya[3]=y2; g.setColor(selectionBackground); g.fillPolygon(xa,ya,4); g.setColor(background); g.drawLine(xa[0],ya[0],xa[1],ya[1]); g.drawLine(xa[3],ya[3],xa[2],ya[2]); } } }; JPanel content = new JPanel(); JPanel detailContainer = new JPanel(); JPanel editPanel = new JPanel(); JTree tree = new JTree() { private static final long serialVersionUID = 1L; public void setModel(TreeModel model) { if ( this.treeModel!= null) { treeModel.removeTreeModelListener( listener); } super.setModel( model ); model.addTreeModelListener(listener); } }; CardLayout cardLayout = new CardLayout(); private Listener listener = new Listener(); private ActionListener callback; I18nBundle i18n; public RaplaTreeEdit(I18nBundle i18n,JComponent detailContent,ActionListener callback) { this.i18n = i18n; this.callback = callback; mainPanel.setLayout(new TableLayout(new double[][] { {TableLayout.PREFERRED,TableLayout.PREFERRED,TableLayout.FILL} ,{TableLayout.FILL} })); jointPanel.setPreferredSize(new Dimension(20,50)); mainPanel.add(content,"0,0"); mainPanel.add(jointPanel,"1,0"); mainPanel.add(editPanel,"2,0"); editPanel.setLayout(cardLayout); editPanel.add(nothingSelectedLabel, "0"); editPanel.add(detailContainer, "1"); content.setLayout(new BorderLayout()); scrollPane = new JScrollPane(tree ,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS ,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); scrollPane.setPreferredSize(new Dimension(310,80)); content.add(scrollPane, BorderLayout.CENTER); detailContainer.setLayout(new BorderLayout()); editPanel.setBorder(BorderFactory.createRaisedBevelBorder()); detailContainer.add(detailContent, BorderLayout.CENTER); scrollPane.getViewport().addChangeListener(listener); tree.addMouseListener(listener); tree.addTreeSelectionListener(listener); modelUpdate(); nothingSelectedLabel.setHorizontalAlignment(JLabel.CENTER); nothingSelectedLabel.setText(i18n.getString("nothing_selected")); } public JComponent getComponent() { return mainPanel; } public JTree getTree() { return tree; } public void setListDimension(Dimension d) { scrollPane.setPreferredSize(d); } public int getSelectedIndex() { return tree.getMinSelectionRow(); } public void select(int index) { tree.setSelectionRow(index); if (index >=0) { TreePath selectedPath = tree.getPathForRow(index); tree.makeVisible( selectedPath ); } } private void modelUpdate() { jointPanel.repaint(); } public Object getSelectedValue() { TreePath treePath = tree.getSelectionPath(); if (treePath == null) return null; return ((DefaultMutableTreeNode)treePath.getLastPathComponent()).getUserObject(); } private void editSelectedEntry() { Object selected = getSelectedValue(); if (selected == null) { cardLayout.first(editPanel); return; } else { cardLayout.last(editPanel); callback.actionPerformed(new ActionEvent(this ,ActionEvent.ACTION_PERFORMED ,"edit" ) ); } } class Listener extends MouseAdapter implements TreeSelectionListener,ChangeListener, TreeModelListener { public void valueChanged(TreeSelectionEvent evt) { int index = getSelectedIndex(); if (index != oldIndex) { oldIndex = index; editSelectedEntry(); modelUpdate(); } } public void stateChanged(ChangeEvent evt) { if (evt.getSource() == scrollPane.getViewport()) { jointPanel.repaint(); } } public void treeNodesChanged(TreeModelEvent e) { modelUpdate(); } public void treeNodesInserted(TreeModelEvent e) { } public void treeNodesRemoved(TreeModelEvent e) { } public void treeStructureChanged(TreeModelEvent e) { } } }
04900db4-rob
src/org/rapla/gui/internal/edit/RaplaTreeEdit.java
Java
gpl3
7,140
package org.rapla.gui.internal.edit; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Map; import org.rapla.components.util.undo.CommandUndo; import org.rapla.entities.Entity; import org.rapla.entities.EntityNotFoundException; import org.rapla.entities.Named; import org.rapla.entities.RaplaType; import org.rapla.entities.User; import org.rapla.entities.dynamictype.Classifiable; import org.rapla.entities.internal.ModifiableTimestamp; import org.rapla.entities.storage.EntityReferencer.ReferenceInfo; import org.rapla.entities.storage.internal.SimpleEntity; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; public class SaveUndo<T extends Entity> extends RaplaComponent implements CommandUndo<RaplaException> { protected final List<T> newEntities; protected final List<T> oldEntities; protected final String commandoName; protected boolean firstTimeCall = true; public SaveUndo(RaplaContext context,Collection<T> newEntity,Collection<T> originalEntity) { this( context, newEntity, originalEntity, null); } public SaveUndo(RaplaContext context,Collection<T> newEntity,Collection<T> originalEntity, String commandoName) { super(context); this.commandoName = commandoName; this.newEntities = new ArrayList<T>(); for ( T entity: newEntity) { @SuppressWarnings("unchecked") T clone = (T) entity.clone(); this.newEntities.add(clone); } if (originalEntity !=null) { if ( originalEntity.size() != newEntity.size() ) { throw new IllegalArgumentException("Original and new list need the same size"); } this.oldEntities = new ArrayList<T>(); for ( T entity: originalEntity) { @SuppressWarnings("unchecked") T clone = (T) entity.clone(); this.oldEntities.add( clone); } } else { this.oldEntities = null; } } public boolean execute() throws RaplaException { final boolean isNew = oldEntities == null; List<T> toStore = new ArrayList<T>(); Map<T,T> newEntitiesPersistant = null; if ( !firstTimeCall || !isNew) { newEntitiesPersistant= getModification().getPersistant(newEntities); } if ( firstTimeCall) { firstTimeCall = false; } else { checklastChanged(newEntities, newEntitiesPersistant); } for ( T entity: newEntities) { @SuppressWarnings("unchecked") T mutableEntity = (T) entity.clone(); if (!isNew) { @SuppressWarnings("null") Entity persistant = (Entity) newEntitiesPersistant.get( entity); checkConsistency( mutableEntity ); setNewTimestamp( mutableEntity, persistant); } toStore.add( mutableEntity); } @SuppressWarnings("unchecked") Entity<T>[] array = toStore.toArray(new Entity[]{}); getModification().storeObjects( array); return true; } protected void checklastChanged(List<T> entities, Map<T,T> persistantVersions) throws RaplaException, EntityNotFoundException { getUpdateModule().refresh(); for ( T entity:entities) { if ( entity instanceof ModifiableTimestamp) { T persistant = persistantVersions.get( entity); if ( persistant != null) { User lastChangedBy = ((ModifiableTimestamp) persistant).getLastChangedBy(); if (lastChangedBy != null && !getUser().equals(lastChangedBy)) { String name = entity instanceof Named ? ((Named) entity).getName( getLocale()) : entity.toString(); throw new RaplaException(getI18n().format("error.new_version", name)); } } else { // if there exists an older version if ( oldEntities != null) { String name = entity instanceof Named ? ((Named) entity).getName( getLocale()) : entity.toString(); throw new RaplaException(getI18n().format("error.new_version", name)); } // otherwise we ignore it } } } } public boolean undo() throws RaplaException { boolean isNew = oldEntities == null; if (isNew) { Map<T,T> newEntitiesPersistant = getModification().getPersistant(newEntities); checklastChanged(newEntities, newEntitiesPersistant); Entity[] array = newEntities.toArray(new Entity[]{}); getModification().removeObjects(array); } else { List<T> toStore = new ArrayList<T>(); Map<T,T> oldEntitiesPersistant = getModification().getPersistant(oldEntities); checklastChanged(oldEntities, oldEntitiesPersistant); for ( T entity: oldEntities) { @SuppressWarnings("unchecked") T mutableEntity = (T) entity.clone(); T persistantVersion = oldEntitiesPersistant.get( entity); checkConsistency( mutableEntity); setNewTimestamp( mutableEntity, persistantVersion); toStore.add( mutableEntity); } @SuppressWarnings("unchecked") Entity<T>[] array = toStore.toArray(new Entity[]{}); getModification().storeObjects( array); } return true; } private void checkConsistency(Entity entity) throws EntityNotFoundException { // this will also be checked by the server but we try to avoid if ( entity instanceof SimpleEntity) { for ( ReferenceInfo info: ((SimpleEntity) entity).getReferenceInfo()) { getClientFacade().getOperator().resolve( info.getId(), info.getType()); } } if ( entity instanceof Classifiable) { Date lastChanged = ((Classifiable) entity).getClassification().getType().getLastChanged(); if ( lastChanged != null) { } } } private void setNewTimestamp( Entity dest, Entity persistant) { if ( persistant instanceof ModifiableTimestamp) { Date version = ((ModifiableTimestamp)persistant).getLastChanged(); ((ModifiableTimestamp)dest).setLastChanged(version); } } public String getCommandoName() { if ( commandoName != null) { return commandoName; } boolean isNew = oldEntities == null; Iterator<T> iterator = newEntities.iterator(); StringBuffer buf = new StringBuffer(); buf.append(isNew ? getString("new"): getString("edit") ); if ( iterator.hasNext()) { RaplaType raplaType = iterator.next().getRaplaType(); buf.append(" " + getString(raplaType.getLocalName())); } return buf.toString(); } }
04900db4-rob
src/org/rapla/gui/internal/edit/SaveUndo.java
Java
gpl3
6,422
/*--------------------------------------------------------------------------* | 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.edit; import java.awt.Component; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.List; import javax.swing.AbstractAction; import javax.swing.BorderFactory; import javax.swing.DefaultComboBoxModel; import javax.swing.DefaultListCellRenderer; import javax.swing.DefaultListModel; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.rapla.components.calendar.DateChangeEvent; import org.rapla.components.calendar.DateChangeListener; import org.rapla.components.calendar.RaplaCalendar; import org.rapla.components.calendar.RaplaNumber; import org.rapla.components.layout.TableLayout; import org.rapla.entities.Annotatable; import org.rapla.entities.Category; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.AttributeAnnotations; import org.rapla.entities.dynamictype.AttributeType; import org.rapla.entities.dynamictype.ConstraintIds; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.DynamicTypeAnnotations; import org.rapla.framework.Container; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.AnnotationEditExtension; import org.rapla.gui.RaplaGUIComponent; import org.rapla.gui.internal.edit.annotation.AnnotationEditUI; import org.rapla.gui.internal.edit.fields.AbstractEditField; import org.rapla.gui.internal.edit.fields.BooleanField; import org.rapla.gui.internal.edit.fields.CategorySelectField; import org.rapla.gui.internal.edit.fields.ListField; import org.rapla.gui.internal.edit.fields.MultiLanguageField; import org.rapla.gui.internal.edit.fields.TextField; import org.rapla.gui.toolkit.DialogUI; import org.rapla.gui.toolkit.EmptyLineBorder; import org.rapla.gui.toolkit.RaplaButton; import org.rapla.gui.toolkit.RaplaWidget; public class AttributeEdit extends RaplaGUIComponent implements RaplaWidget { RaplaListEdit<Attribute> listEdit; DynamicType dt; DefaultConstraints constraintPanel; ArrayList<ChangeListener> listenerList = new ArrayList<ChangeListener>(); Listener listener = new Listener(); DefaultListModel model = new DefaultListModel(); boolean editKeys; public AttributeEdit(RaplaContext context) throws RaplaException { super( context); constraintPanel = new DefaultConstraints(context); listEdit = new RaplaListEdit<Attribute>( getI18n(), constraintPanel.getComponent(), listener ); listEdit.setListDimension( new Dimension( 200,220 ) ); constraintPanel.addChangeListener( listener ); listEdit.getComponent().setBorder( BorderFactory.createTitledBorder( new EmptyLineBorder(),getString("attributes")) ); setRender(); constraintPanel.setEditKeys( false ); } @SuppressWarnings("unchecked") private void setRender() { listEdit.getList().setCellRenderer(new DefaultListCellRenderer() { private static final long serialVersionUID = 1L; public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { Attribute a = (Attribute) value; value = a.getName(getRaplaLocale().getLocale()); if (editKeys) { value = "{" + a.getKey() + "} " + value; } value = (index + 1) +") " + value; return super.getListCellRendererComponent(list,value,index,isSelected,cellHasFocus); } }); } public RaplaWidget getConstraintPanel() { return constraintPanel; } public void selectAttribute( Attribute attribute) { boolean shouldScroll = true; listEdit.getList().setSelectedValue( attribute, shouldScroll); } class Listener implements ActionListener,ChangeListener { public void actionPerformed(ActionEvent evt) { int index = getSelectedIndex(); try { if (evt.getActionCommand().equals("remove")) { removeAttribute(); } else if (evt.getActionCommand().equals("new")) { createAttribute(); } else if (evt.getActionCommand().equals("edit")) { Attribute attribute = (Attribute) listEdit.getList().getSelectedValue(); constraintPanel.mapFrom( attribute ); } else if (evt.getActionCommand().equals("moveUp")) { dt.exchangeAttributes(index, index -1); updateModel(null); } else if (evt.getActionCommand().equals("moveDown")) { dt.exchangeAttributes(index, index + 1); updateModel(null); } } catch (RaplaException ex) { showException(ex, getComponent()); } } public void stateChanged(ChangeEvent e) { try { confirmEdits(); fireContentChanged(); } catch (RaplaException ex) { showException(ex, getComponent()); } } } public JComponent getComponent() { return listEdit.getComponent(); } public int getSelectedIndex() { return listEdit.getList().getSelectedIndex(); } public void setDynamicType(DynamicType dt) { this.dt = dt; updateModel(null); } @SuppressWarnings("unchecked") private void updateModel(Attribute newSelectedItem) { Attribute selectedItem = newSelectedItem != null ? newSelectedItem : listEdit.getSelectedValue(); model.clear(); Attribute[] attributes = dt.getAttributes(); for (int i = 0; i < attributes.length; i++ ) { model.addElement( attributes[i] ); } listEdit.getList().setModel(model); if ( listEdit.getSelectedValue() != selectedItem ) listEdit.getList().setSelectedValue(selectedItem, true ); } @SuppressWarnings("unchecked") public void confirmEdits() throws RaplaException { if ( getSelectedIndex() < 0 ) return; Attribute attribute = listEdit.getSelectedValue(); constraintPanel.mapTo (attribute ); model.set( model.indexOf( attribute ), attribute ); } public void setEditKeys(boolean editKeys) { constraintPanel.setEditKeys(editKeys); this.editKeys = editKeys; } private String createNewKey() { Attribute[] atts = dt.getAttributes(); int max = 1; for (int i=0;i<atts.length;i++) { String key = atts[i].getKey(); if (key.length()>1 && key.charAt(0) =='a' && Character.isDigit(key.charAt(1)) ) { try { int value = Integer.valueOf(key.substring(1)).intValue(); if (value >= max) max = value + 1; } catch (NumberFormatException ex) { } } } return "a" + (max); } void removeAttribute() { List<Attribute> toRemove = new ArrayList<Attribute>(); for ( int index:listEdit.getList().getSelectedIndices()) { Attribute att = dt.getAttributes() [index]; toRemove.add( att); } for (Attribute att:toRemove) { dt.removeAttribute(att); } updateModel(null); } void createAttribute() throws RaplaException { confirmEdits(); AttributeType type = AttributeType.STRING; Attribute att = getModification().newAttribute(type); String language = getRaplaLocale().getLocale().getLanguage(); att.getName().setName(language, getString("attribute")); att.setKey(createNewKey()); dt.addAttribute(att); updateModel( att); // int index = dt.getAttributes().length -1; // listEdit.getList().setSelectedIndex( index ); constraintPanel.name.selectAll(); constraintPanel.name.requestFocus(); } public void addChangeListener(ChangeListener listener) { listenerList.add(listener); } public void removeChangeListener(ChangeListener listener) { listenerList.remove(listener); } public ChangeListener[] getChangeListeners() { return listenerList.toArray(new ChangeListener[]{}); } protected void fireContentChanged() { if (listenerList.size() == 0) return; ChangeEvent evt = new ChangeEvent(this); ChangeListener[] listeners = getChangeListeners(); for (int i = 0;i<listeners.length; i++) { listeners[i].stateChanged(evt); } } } class DefaultConstraints extends AbstractEditField implements ActionListener ,ChangeListener { JPanel panel = new JPanel(); JLabel nameLabel = new JLabel(); JLabel keyLabel = new JLabel(); JLabel typeLabel = new JLabel(); JLabel categoryLabel = new JLabel(); JLabel dynamicTypeLabel = new JLabel(); JLabel defaultLabel = new JLabel(); JLabel multiSelectLabel = new JLabel(); JLabel tabLabel = new JLabel(); AttributeType types[] = { AttributeType.BOOLEAN ,AttributeType.STRING ,AttributeType.INT ,AttributeType.CATEGORY ,AttributeType.ALLOCATABLE ,AttributeType.DATE }; String tabs[] = { AttributeAnnotations.VALUE_EDIT_VIEW_MAIN ,AttributeAnnotations.VALUE_EDIT_VIEW_ADDITIONAL ,AttributeAnnotations.VALUE_EDIT_VIEW_NO_VIEW }; boolean mapping = false; MultiLanguageField name ; TextField key; JComboBox classSelect = new JComboBox(); ListField<DynamicType> dynamicTypeSelect; CategorySelectField categorySelect; CategorySelectField defaultSelectCategory; TextField defaultSelectText; BooleanField defaultSelectBoolean; BooleanField multiSelect; RaplaNumber defaultSelectNumber = new RaplaNumber(new Long(0),null,null, false); RaplaCalendar defaultSelectDate ; RaplaButton annotationButton = new RaplaButton(RaplaButton.DEFAULT); JComboBox tabSelect = new JComboBox(); DialogUI dialog; boolean emailPossible = false; Category rootCategory; AnnotationEditUI annotationEdit; Collection<AnnotationEditExtension> annotationExtensions; Attribute attribute; DefaultConstraints(RaplaContext context) throws RaplaException{ super( context ); annotationExtensions = context.lookup(Container.class).lookupServicesFor(AnnotationEditExtension.ATTRIBUTE_ANNOTATION_EDIT); annotationEdit = new AnnotationEditUI(context, annotationExtensions); key = new TextField(context); name = new MultiLanguageField(context); Collection<DynamicType> typeList = new ArrayList<DynamicType>(Arrays.asList(getQuery().getDynamicTypes(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE))); typeList.addAll(Arrays.asList(getQuery().getDynamicTypes(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON))); dynamicTypeSelect = new ListField<DynamicType>(context,true ); dynamicTypeSelect.setVector( typeList ); rootCategory = getQuery().getSuperCategory(); categorySelect = new CategorySelectField(context,rootCategory); categorySelect.setUseNull(false); defaultSelectCategory = new CategorySelectField(context,rootCategory); defaultSelectText = new TextField(context); addCopyPaste( defaultSelectNumber.getNumberField()); //addCopyPaste( expectedRows.getNumberField()); //addCopyPaste( expectedColumns.getNumberField()); defaultSelectBoolean = new BooleanField(context); defaultSelectDate = createRaplaCalendar(); defaultSelectDate.setNullValuePossible( true); defaultSelectDate.setDate( null); multiSelect = new BooleanField(context); double fill = TableLayout.FILL; double pre = TableLayout.PREFERRED; panel.setLayout( new TableLayout( new double[][] {{5, pre, 5, fill }, // Columns {5, pre ,5, pre, 5, pre, 5, pre, 5, pre, 5, pre, 5,pre, 5, pre, 5}} // Rows )); panel.add("1,1,l,f", nameLabel); panel.add("3,1,f,f", name.getComponent() ); panel.add("1,3,l,f", keyLabel); panel.add("3,3,f,f", key.getComponent() ); panel.add("1,5,l,f", typeLabel); panel.add("3,5,l,f", classSelect); // constraints panel.add("1,7,l,t", categoryLabel); panel.add("3,7,l,t", categorySelect.getComponent()); panel.add("1,7,l,t", dynamicTypeLabel); panel.add("3,7,l,t", dynamicTypeSelect.getComponent()); panel.add("1,9,l,t", defaultLabel); panel.add("3,9,l,t", defaultSelectCategory.getComponent()); panel.add("3,9,l,t", defaultSelectText.getComponent()); panel.add("3,9,l,t", defaultSelectBoolean.getComponent()); panel.add("3,9,l,t", defaultSelectDate); panel.add("3,9,l,t", defaultSelectNumber); panel.add("1,11,l,t", multiSelectLabel); panel.add("3,11,l,t", multiSelect.getComponent()); panel.add("1,13,l,t", tabLabel); panel.add("3,13,l,t", tabSelect); panel.add("1,15,l,t", new JLabel("erweitert")); panel.add("3,15,l,t", annotationButton); annotationButton.setText(getString("edit")); annotationButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { showAnnotationDialog(); } catch (RaplaException ex) { showException(ex, getComponent()); } } }); setModel(); nameLabel.setText(getString("name") + ":"); keyLabel.setText(getString("key") +" *"+ ":"); typeLabel.setText(getString("type") + ":"); categoryLabel.setText(getString("root") + ":"); dynamicTypeLabel.setText(getString("root") + ":"); tabLabel.setText(getString("edit-view") + ":"); multiSelectLabel.setText("Multiselect:"); defaultLabel.setText(getString("default") +":"); categorySelect.addChangeListener ( this ); categorySelect.addChangeListener( new ChangeListener() { public void stateChanged(ChangeEvent e) { final Category rootCategory = categorySelect.getValue(); defaultSelectCategory.setRootCategory( rootCategory ); defaultSelectCategory.setValue( null); defaultSelectCategory.getComponent().setEnabled( rootCategory != null); } } ); name.addChangeListener ( this ); key.addChangeListener ( this ); classSelect.addActionListener ( this ); tabSelect.addActionListener( this); defaultSelectCategory.addChangeListener( this ); defaultSelectText.addChangeListener( this ); defaultSelectBoolean.addChangeListener( this ); defaultSelectNumber.addChangeListener( this ); defaultSelectDate.addDateChangeListener( new DateChangeListener() { public void dateChanged(DateChangeEvent evt) { stateChanged(null); } }); } @SuppressWarnings("unchecked") private void setModel() { DefaultComboBoxModel model = new DefaultComboBoxModel(); for ( int i = 0; i < types.length; i++ ) { model.addElement(getString("type." + types[i])); } classSelect.setModel( model ); model = new DefaultComboBoxModel(); for ( int i = 0; i < tabs.length; i++ ) { model.addElement(getString(tabs[i])); } tabSelect.setModel( model ); } public void setEditKeys(boolean editKeys) { keyLabel.setVisible( editKeys ); key.getComponent().setVisible( editKeys ); } public JComponent getComponent() { return panel; } private void clearValues() { categorySelect.setValue(null); defaultSelectCategory.setValue( null); defaultSelectText.setValue(""); defaultSelectBoolean.setValue( null); defaultSelectNumber.setNumber(null); defaultSelectDate.setDate(null); multiSelect.setValue( Boolean.FALSE); } public void mapFrom(Attribute attribute) throws RaplaException { clearValues(); try { mapping = true; this.attribute = attribute; clearValues(); String classificationType = attribute.getDynamicType().getAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE); emailPossible = classificationType != null && (classificationType.equals( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON) || classificationType.equals( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE)); name.setValue( attribute.getName()); key.setValue( attribute.getKey()); final AttributeType attributeType = attribute.getType(); classSelect.setSelectedItem(getString("type." + attributeType)); if (attributeType.equals(AttributeType.CATEGORY)) { final Category rootCategory = (Category)attribute.getConstraint(ConstraintIds.KEY_ROOT_CATEGORY); categorySelect.setValue( rootCategory ); defaultSelectCategory.setRootCategory( rootCategory); defaultSelectCategory.setValue( (Category)attribute.convertValue(attribute.defaultValue())); defaultSelectCategory.getComponent().setEnabled( rootCategory != null); } else if (attributeType.equals(AttributeType.ALLOCATABLE)) { final DynamicType rootCategory = (DynamicType)attribute.getConstraint(ConstraintIds.KEY_DYNAMIC_TYPE); dynamicTypeSelect.setValue( rootCategory ); } else if (attributeType.equals(AttributeType.STRING)) { defaultSelectText.setValue( (String)attribute.defaultValue()); } else if (attributeType.equals(AttributeType.BOOLEAN)) { defaultSelectBoolean.setValue( (Boolean)attribute.defaultValue()); } else if (attributeType.equals(AttributeType.INT)) { defaultSelectNumber.setNumber( (Number)attribute.defaultValue()); } else if (attributeType.equals(AttributeType.DATE)) { defaultSelectDate.setDate( (Date)attribute.defaultValue()); } if (attributeType.equals(AttributeType.CATEGORY) || attributeType.equals(AttributeType.ALLOCATABLE)) { Boolean multiSelectValue = (Boolean) attribute.getConstraint(ConstraintIds.KEY_MULTI_SELECT) ; multiSelect.setValue( multiSelectValue != null ? multiSelectValue: Boolean.FALSE ); } String selectedTab = attribute.getAnnotation(AttributeAnnotations.KEY_EDIT_VIEW, AttributeAnnotations.VALUE_EDIT_VIEW_MAIN); tabSelect.setSelectedItem(getString(selectedTab)); update(); } finally { mapping = false; } } public void mapTo(Attribute attribute) throws RaplaException { attribute.getName().setTo( name.getValue()); attribute.setKey( key.getValue()); AttributeType type = types[classSelect.getSelectedIndex()]; attribute.setType( type ); if ( type.equals(AttributeType.CATEGORY)) { Object defaultValue = defaultSelectCategory.getValue(); Object rootCategory = categorySelect.getValue(); if ( rootCategory == null) { rootCategory = this.rootCategory; defaultValue = null; } attribute.setConstraint(ConstraintIds.KEY_ROOT_CATEGORY, rootCategory ); attribute.setDefaultValue( defaultValue); } else { attribute.setConstraint(ConstraintIds.KEY_ROOT_CATEGORY, null); } if ( type.equals(AttributeType.ALLOCATABLE)) { Object rootType = dynamicTypeSelect.getValue(); // if ( rootType == null) // { // rootType = this.rootCategory; // } attribute.setConstraint(ConstraintIds.KEY_DYNAMIC_TYPE, rootType ); attribute.setDefaultValue( null); } else { attribute.setConstraint(ConstraintIds.KEY_DYNAMIC_TYPE, null); } if ( type.equals(AttributeType.ALLOCATABLE) || type.equals(AttributeType.CATEGORY)) { Boolean value = multiSelect.getValue(); attribute.setConstraint(ConstraintIds.KEY_MULTI_SELECT, value); } else { attribute.setConstraint(ConstraintIds.KEY_MULTI_SELECT, null); } if ( type.equals(AttributeType.BOOLEAN)) { final Object defaultValue = defaultSelectBoolean.getValue(); attribute.setDefaultValue( defaultValue); } if ( type.equals(AttributeType.INT)) { final Object defaultValue = defaultSelectNumber.getNumber(); attribute.setDefaultValue( defaultValue); } if ( type.equals(AttributeType.DATE)) { final Object defaultValue = defaultSelectDate.getDate(); attribute.setDefaultValue( defaultValue); } List<Annotatable> asList = Arrays.asList((Annotatable)attribute); annotationEdit.mapTo(asList); String selectedTab = tabs[tabSelect.getSelectedIndex()]; if ( selectedTab != null && !selectedTab.equals(AttributeAnnotations.VALUE_EDIT_VIEW_MAIN)) { attribute.setAnnotation(AttributeAnnotations.KEY_EDIT_VIEW, selectedTab); } else { attribute.setAnnotation(AttributeAnnotations.KEY_EDIT_VIEW, null); } } private void update() throws RaplaException { AttributeType type = types[classSelect.getSelectedIndex()]; List<Annotatable> asList = Arrays.asList((Annotatable)attribute); annotationEdit.setObjects( asList); final boolean categoryVisible = type.equals(AttributeType.CATEGORY); final boolean allocatableVisible = type.equals(AttributeType.ALLOCATABLE); final boolean textVisible = type.equals(AttributeType.STRING); final boolean booleanVisible = type.equals(AttributeType.BOOLEAN); final boolean numberVisible = type.equals(AttributeType.INT); final boolean dateVisible = type.equals(AttributeType.DATE); categoryLabel.setVisible( categoryVisible ); categorySelect.getComponent().setVisible( categoryVisible ); dynamicTypeLabel.setVisible( allocatableVisible); dynamicTypeSelect.getComponent().setVisible( allocatableVisible); defaultLabel.setVisible( !allocatableVisible); defaultSelectCategory.getComponent().setVisible( categoryVisible); defaultSelectText.getComponent().setVisible( textVisible); defaultSelectBoolean.getComponent().setVisible( booleanVisible); defaultSelectNumber.setVisible( numberVisible); defaultSelectDate.setVisible( dateVisible); multiSelectLabel.setVisible( categoryVisible || allocatableVisible); multiSelect.getComponent().setVisible( categoryVisible || allocatableVisible); } private void showAnnotationDialog() throws RaplaException { RaplaContext context = getContext(); boolean modal = false; if (dialog != null) { dialog.close(); } dialog = DialogUI.create(context ,getComponent() ,modal ,annotationEdit.getComponent() ,new String[] { getString("close")}); dialog.getButton(0).setAction( new AbstractAction() { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { fireContentChanged(); dialog.close(); } }); dialog.setTitle(getString("select")); dialog.start(); } public void actionPerformed(ActionEvent evt) { if (mapping) return; if ( evt.getSource() == classSelect) { clearValues(); AttributeType newType = types[classSelect.getSelectedIndex()]; if (newType.equals(AttributeType.CATEGORY)) { categorySelect.setValue( rootCategory ); } } fireContentChanged(); try { update(); } catch (RaplaException ex) { showException(ex, getComponent()); } } public void stateChanged(ChangeEvent e) { if (mapping) return; fireContentChanged(); } }
04900db4-rob
src/org/rapla/gui/internal/edit/AttributeEdit.java
Java
gpl3
26,676
/*--------------------------------------------------------------------------* | 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.edit; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.rapla.components.util.Assert; import org.rapla.entities.Category; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.AttributeAnnotations; import org.rapla.entities.dynamictype.AttributeType; import org.rapla.entities.dynamictype.Classification; import org.rapla.entities.dynamictype.ConstraintIds; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.EditField; import org.rapla.gui.internal.edit.fields.AllocatableSelectField; import org.rapla.gui.internal.edit.fields.BooleanField; import org.rapla.gui.internal.edit.fields.CategoryListField; import org.rapla.gui.internal.edit.fields.CategorySelectField; import org.rapla.gui.internal.edit.fields.DateField; import org.rapla.gui.internal.edit.fields.LongField; import org.rapla.gui.internal.edit.fields.MultiEditField; import org.rapla.gui.internal.edit.fields.SetGetCollectionField; import org.rapla.gui.internal.edit.fields.SetGetField; import org.rapla.gui.internal.edit.fields.TextField; public class ClassificationEditUI extends AbstractEditUI<Classification> { public ClassificationEditUI(RaplaContext sm) { super(sm); } // enhanced to an array, for administration of multiple classifications private String getAttName(String key) { // collection of all attribute-names for the deposited classifications Set<String> attNames = new HashSet<String>(); for (Classification c : objectList) { attNames.add(getName(c.getAttribute(key))); } // checks if there is a common attribute-name if (attNames.size() == 1) { // delivers this name return attNames.iterator().next(); } else { return "-"; } } protected Attribute getAttribute(int i) { // collection of all attributes for the deposited classifications for a // certain field Set<Attribute> attributes = new HashSet<Attribute>(); for (Classification c : objectList) { String key = getKey( fields.get(i)); Attribute attribute = c.getAttribute(key); attributes.add(attribute); } // check if there is a common attribute if (attributes.size() == 1) { // delivers this attribute return attributes.iterator().next(); } else { return null; } } protected void setAttValue(String key, Object value) { // sets the attribute value for all deposited classifications for (Classification c : objectList) { Attribute attribute = c.getAttribute(key); if ( value instanceof Collection<?>) { Collection<?> collection = (Collection<?>)value; Boolean multiSelect = (Boolean)attribute.getConstraint(ConstraintIds.KEY_MULTI_SELECT); if ( multiSelect != null && multiSelect==true) { c.setValues(attribute, collection); } else if ( collection.size() > 0) { c.setValue(attribute, collection.iterator().next()); } else { c.setValue(attribute, null); } } else { c.setValue(attribute, value); } } } public Set<Object> getUniqueAttValues(String key) { // collection of all attribute values for a certain attribute Set<Object> values = new LinkedHashSet<Object>(); for (Classification c : objectList) { Attribute attribute = c.getAttribute(key); Object value; Boolean multiSelect = (Boolean) attribute.getConstraint(ConstraintIds.KEY_MULTI_SELECT); if ( multiSelect != null && multiSelect == true) { value = c.getValues(attribute); } else { value = c.getValue(attribute); } values.add(value); } return values; } private SetGetField<?> createField(Attribute attribute) { AttributeType type = attribute.getType(); String label = getAttName(attribute.getKey()); SetGetField<?> field = null; RaplaContext context = getContext(); if (type.equals(AttributeType.STRING)) { Integer rows = new Integer(attribute.getAnnotation( AttributeAnnotations.KEY_EXPECTED_ROWS, "1")); Integer columns = new Integer(attribute.getAnnotation( AttributeAnnotations.KEY_EXPECTED_COLUMNS,String.valueOf(TextField.DEFAULT_LENGTH))); field = new TextField(context, label, rows.intValue(),columns.intValue()); } else if (type.equals(AttributeType.INT)) { field = new LongField(context, label); } else if (type.equals(AttributeType.DATE)) { field = new DateField(context, label); } else if (type.equals(AttributeType.BOOLEAN)) { field = new BooleanField(context, label); } else if (type.equals(AttributeType.ALLOCATABLE)) { DynamicType dynamicTypeConstraint = (DynamicType)attribute.getConstraint( ConstraintIds.KEY_DYNAMIC_TYPE); Boolean multipleSelectionPossible = (Boolean) attribute.getConstraint(ConstraintIds.KEY_MULTI_SELECT); // if (dynamicTypeConstraint == null || multipleSelectionPossible) { AllocatableSelectField allocField = new AllocatableSelectField(context, dynamicTypeConstraint); allocField.setFieldName(label); allocField.setMultipleSelectionPossible( multipleSelectionPossible != null ? multipleSelectionPossible : false); field = allocField; // }else { // AllocatableListField allocField = new AllocatableListField(context, key, dynamicTypeConstraint); // field = allocField; // } } else if (type.equals(AttributeType.CATEGORY)) { Category defaultCategory = (Category) attribute.defaultValue(); Category rootCategory = (Category) attribute.getConstraint(ConstraintIds.KEY_ROOT_CATEGORY); boolean multipleSelectionPossible = attribute.getAnnotation(ConstraintIds.KEY_MULTI_SELECT, "false").equals("true"); if (rootCategory.getDepth() > 2 || multipleSelectionPossible) { CategorySelectField catField = new CategorySelectField(context, rootCategory, defaultCategory); catField.setMultipleSelectionPossible( multipleSelectionPossible); catField.setFieldName( label ); field = catField; } else { CategoryListField catField = new CategoryListField(context, rootCategory); catField.setFieldName( label ); field = catField; } } Assert.notNull(field, "Unknown AttributeType"); return field; } Map<EditField,String> fieldKeyMap = new HashMap<EditField,String>(); public void setObjects(List<Classification> classificationList) throws RaplaException { this.objectList = classificationList; // determining of the DynmicTypes from the classifications Set<DynamicType> types = new HashSet<DynamicType>(); for (Classification c : objectList) { types.add(c.getType()); } // checks if there is a common DynmicType if (types.size() == 1) { fieldKeyMap.clear(); // read out attributes for this DynmicType Attribute[] attributes = types.iterator().next().getAttributes(); // create fields for attributes List<SetGetField<?>> fields= new ArrayList<SetGetField<?>>(); for (Attribute attribute:attributes) { SetGetField<?> field = createField(attribute); //field.setUser(classificationList); fields.add( field); fieldKeyMap.put( field, attribute.getKey()); } // show fields setFields(fields); } mapFromObjects(); } public void mapTo(SetGetField<?> field) { // checks if the EditField shows a common value if (field instanceof MultiEditField && ((MultiEditField) field).hasMultipleValues()) return; // read out attribute value if the field shows a common value String attKey = getKey(field); if ( field instanceof SetGetCollectionField) { Collection<?> values = ((SetGetCollectionField<?>) field).getValues(); setAttValue(attKey, values); } else { setAttValue(attKey, field.getValue()); } } protected String getKey(EditField field) { String key = fieldKeyMap.get( field); return key; } public <T> void mapFrom(SetGetField<T> field ) { // read out attribute values Set<Object> values = getUniqueAttValues(getKey(field)); // checks if there is a common value, otherwise a place holder has // to be shown for this field if ( values.size() > 1 && field instanceof MultiEditField) { // shows place holder ((MultiEditField) field).setFieldForMultipleValues(); } else if ( values.size() == 1) { // set common value Object first = values.iterator().next(); if ( first instanceof Collection) { @SuppressWarnings("unchecked") Collection<T> list = (Collection<T>)first; if ( field instanceof SetGetCollectionField) { @SuppressWarnings("unchecked") SetGetCollectionField<T> setGetCollectionField = (SetGetCollectionField<T>)field; setGetCollectionField.setValues(list); } else if ( list.size() > 0) { field.setValue( list.iterator().next()); } else { field.setValue( null); } } else { @SuppressWarnings("unchecked") T casted = (T)first; field.setValue( casted); } } else { field.setValue(null); } } public void mapToObjects() throws RaplaException { for (EditField field: fields) { SetGetField<?> f = (SetGetField<?>) field; mapTo( f); } } protected void mapFromObjects() throws RaplaException { for (EditField field: fields) { SetGetField<?> f = (SetGetField<?>) field; mapFrom( f); } } }
04900db4-rob
src/org/rapla/gui/internal/edit/ClassificationEditUI.java
Java
gpl3
11,198
/*--------------------------------------------------------------------------* | 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.edit; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.ResourceAnnotations; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.EditField; import org.rapla.gui.internal.edit.fields.BooleanField; import org.rapla.gui.internal.edit.fields.ClassificationField; import org.rapla.gui.internal.edit.fields.PermissionListField; /**************************************************************** * This is the controller-class for the Resource-Edit-Panel * ****************************************************************/ class AllocatableEditUI extends AbstractEditUI<Allocatable> { ClassificationField<Allocatable> classificationField; PermissionListField permissionField; BooleanField holdBackConflictsField; boolean internal =false; public AllocatableEditUI(RaplaContext contest, boolean internal) throws RaplaException { super(contest); this.internal = internal; ArrayList<EditField> fields = new ArrayList<EditField>(); classificationField = new ClassificationField<Allocatable>(contest); fields.add(classificationField ); permissionField = new PermissionListField(contest,getString("permissions")); fields.add( permissionField ); if ( !internal) { holdBackConflictsField = new BooleanField(contest,getString("holdbackconflicts")); fields.add(holdBackConflictsField ); } setFields(fields); } public void mapToObjects() throws RaplaException { classificationField.mapTo( objectList); permissionField.mapTo( objectList); if ( getName(objectList).length() == 0) throw new RaplaException(getString("error.no_name")); if ( !internal) { Boolean value = holdBackConflictsField.getValue(); if ( value != null) { for ( Allocatable alloc:objectList) { alloc.setAnnotation(ResourceAnnotations.KEY_CONFLICT_CREATION, value ? ResourceAnnotations.VALUE_CONFLICT_CREATION_IGNORE : null); } } } } protected void mapFromObjects() throws RaplaException { classificationField.mapFrom( objectList); permissionField.mapFrom( objectList); Set<Boolean> values = new HashSet<Boolean>(); for ( Allocatable alloc:objectList) { String annotation = alloc.getAnnotation( ResourceAnnotations.KEY_CONFLICT_CREATION); boolean holdBackConflicts = annotation != null && annotation.equals( ResourceAnnotations.VALUE_CONFLICT_CREATION_IGNORE); values.add(holdBackConflicts); } if ( !internal) { if ( values.size() == 1) { Boolean singleValue = values.iterator().next(); holdBackConflictsField.setValue( singleValue); } if ( values.size() > 1) { holdBackConflictsField.setFieldForMultipleValues(); } } classificationField.setTypeChooserVisible( !internal); } }
04900db4-rob
src/org/rapla/gui/internal/edit/AllocatableEditUI.java
Java
gpl3
4,219
/*--------------------------------------------------------------------------* | Copyright (C) 2013 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; import java.awt.Component; import java.awt.Point; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.TreeMap; import javax.swing.Action; import javax.swing.JMenuItem; import javax.swing.MenuElement; import org.rapla.client.RaplaClientExtensionPoints; import org.rapla.components.util.DateTools; import org.rapla.components.util.TimeInterval; import org.rapla.entities.Category; import org.rapla.entities.Entity; 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.Period; import org.rapla.entities.domain.Reservation; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.DynamicTypeAnnotations; import org.rapla.facade.CalendarModel; import org.rapla.facade.CalendarSelectionModel; import org.rapla.facade.internal.CalendarModelImpl; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.MenuContext; import org.rapla.gui.MenuFactory; import org.rapla.gui.ObjectMenuFactory; import org.rapla.gui.RaplaGUIComponent; import org.rapla.gui.internal.action.DynamicTypeAction; import org.rapla.gui.internal.action.RaplaObjectAction; import org.rapla.gui.internal.action.user.PasswordChangeAction; import org.rapla.gui.internal.action.user.UserAction; import org.rapla.gui.toolkit.IdentifiableMenuEntry; import org.rapla.gui.toolkit.MenuInterface; import org.rapla.gui.toolkit.RaplaMenuItem; import org.rapla.gui.toolkit.RaplaSeparator; public class MenuFactoryImpl extends RaplaGUIComponent implements MenuFactory { public void addReservationWizards( MenuInterface menu, MenuContext context, String afterId ) throws RaplaException { if (canCreateReservation()) { addNewMenus(menu, afterId); } } /** * @param model * @param startDate * @return */ protected Date getEndDate( CalendarModel model,Date startDate) { Collection<TimeInterval> markedIntervals = model.getMarkedIntervals(); Date endDate = null; if ( markedIntervals.size() > 0) { TimeInterval first = markedIntervals.iterator().next(); endDate = first.getEnd(); } if ( endDate != null) { return endDate; } return new Date(startDate.getTime() + DateTools.MILLISECONDS_PER_HOUR); } protected Date getStartDate(CalendarModel model) { Collection<TimeInterval> markedIntervals = model.getMarkedIntervals(); Date startDate = null; if ( markedIntervals.size() > 0) { TimeInterval first = markedIntervals.iterator().next(); startDate = first.getStart(); } if ( startDate != null) { return startDate; } Date selectedDate = model.getSelectedDate(); if ( selectedDate == null) { selectedDate = getQuery().today(); } Date time = new Date (DateTools.MILLISECONDS_PER_MINUTE * getCalendarOptions().getWorktimeStartMinutes()); startDate = getRaplaLocale().toDate(selectedDate,time); return startDate; } private void addNewMenus(MenuInterface menu, String afterId) throws RaplaException { boolean canAllocateSelected = canAllocateSelected(); if ( canAllocateSelected ) { Collection<IdentifiableMenuEntry> wizards = getContainer().lookupServicesFor( RaplaClientExtensionPoints.RESERVATION_WIZARD_EXTENSION); Map<String,IdentifiableMenuEntry> sortedMap = new TreeMap<String, IdentifiableMenuEntry>(); for (IdentifiableMenuEntry entry:wizards) { sortedMap.put(entry.getId(), entry); } for ( IdentifiableMenuEntry wizard: sortedMap.values()) { MenuElement menuElement = wizard.getMenuElement(); if ( menuElement != null) { menu.insertAfterId(menuElement.getComponent(), afterId); } } } // else // { // JMenuItem cantAllocate = new JMenuItem(getString("permission.denied")); // cantAllocate.setEnabled( false); // menu.insertAfterId(cantAllocate, afterId); // } } protected boolean canAllocateSelected() throws RaplaException { User user = getUser(); Date today = getQuery().today(); boolean canAllocate = false; CalendarSelectionModel model = getService(CalendarSelectionModel.class); Collection<Allocatable> selectedAllocatables = model.getMarkedAllocatables(); Date start = getStartDate( model); Date end = getEndDate( model, start); for ( Allocatable alloc: selectedAllocatables) { if (alloc.canAllocate( user, start, end, today)) canAllocate = true; } boolean canAllocateSelected = canAllocate || (selectedAllocatables.size() == 0 && canUserAllocateSomething( getUser())); return canAllocateSelected; } public MenuFactoryImpl(RaplaContext sm) { super(sm); } public MenuInterface addNew( MenuInterface menu, MenuContext context,String afterId) throws RaplaException { return addNew(menu, context, afterId, false); } public MenuInterface addNew( MenuInterface menu, MenuContext context,String afterId, boolean addNewReservationMenu ) throws RaplaException { // Do nothing if the user can't allocate anything User user = getUser(); if (!canUserAllocateSomething( user) ) { return menu; } Component parent = context.getComponent(); Object focusedObject = context.getFocusedObject(); Point p = context.getPoint(); if ( addNewReservationMenu) { addReservationWizards(menu, context, afterId); } boolean allocatableType = false; boolean reservationType = false; if ( focusedObject instanceof DynamicType) { DynamicType type = (DynamicType) focusedObject; String classificationType = type.getAnnotation( DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE ); allocatableType = classificationType.equals( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON ) || classificationType.equals( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE ); reservationType = classificationType.equals( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION ); } boolean allocatableNodeContext = allocatableType || focusedObject instanceof Allocatable || focusedObject == CalendarModelImpl.ALLOCATABLES_ROOT; if ( isRegisterer() || isAdmin()) { if ( allocatableNodeContext) { menu.addSeparator(); addAllocatableMenuNew( menu, parent,p, focusedObject); } } if ( isAdmin() ) { boolean reservationNodeContext = reservationType || (focusedObject!= null && focusedObject.equals( getString("reservation_type" ))); boolean userNodeContext = focusedObject instanceof User || (focusedObject != null && focusedObject.equals( getString("users"))); boolean periodNodeContext = focusedObject instanceof Period || (focusedObject != null && focusedObject.equals( getString("periods"))); boolean categoryNodeContext = focusedObject instanceof Category || (focusedObject != null && focusedObject.equals( getString("categories"))); if (userNodeContext || allocatableNodeContext || reservationNodeContext || periodNodeContext || categoryNodeContext ) { if ( allocatableNodeContext || addNewReservationMenu) { menu.addSeparator(); } } if ( userNodeContext) { addUserMenuNew( menu , parent, p); } if (allocatableNodeContext) { addTypeMenuNew(menu, DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE,parent, p); addTypeMenuNew(menu, DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON,parent, p); } if ( periodNodeContext) { addPeriodMenuNew( menu , parent, p ); } if ( categoryNodeContext ) { addCategoryMenuNew( menu , parent, p, focusedObject ); } if ( reservationNodeContext) { addTypeMenuNew(menu, DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION,parent, p); } /* */ } return menu; } public MenuInterface addObjectMenu( MenuInterface menu, MenuContext context) throws RaplaException { return addObjectMenu( menu, context, "EDIT_BEGIN"); } public MenuInterface addObjectMenu( MenuInterface menu, MenuContext context, String afterId ) throws RaplaException { Component parent = context.getComponent(); Object focusedObject = context.getFocusedObject(); Point p = context.getPoint(); Collection<Entity<?>> list = new LinkedHashSet<Entity<?>>(); if ( focusedObject != null && (focusedObject instanceof Entity)) { Entity<?> obj = (Entity<?>) focusedObject; list.add( obj ); addAction(menu, parent, p, afterId).setView(obj); } for ( Object obj: context.getSelectedObjects()) { if ( obj instanceof Entity) { list.add( (Entity<?>) obj); } } { List<Entity<?>> deletableObjects = getDeletableObjects(list); if ( deletableObjects.size() > 0) { addAction(menu,parent,p, afterId).setDeleteSelection(deletableObjects); Collection<Entity<?>> editObjects = getObjectsWithSameType( deletableObjects ); if ( deletableObjects.size() == 1 ) { Entity<?> first = editObjects.iterator().next(); addAction(menu, parent, p, afterId).setEdit(first); } else if (isMultiEditSupported(deletableObjects)) { addAction(menu, parent, p, afterId).setEditSelection(editObjects); } } } List<Entity<?>> editableObjects = getEditableObjects(list); if ( editableObjects.size() == 1 ) { RaplaObject next = editableObjects.iterator().next(); if ( next.getRaplaType() == User.TYPE) { addUserMenuEdit( menu , parent, p, (User) next , afterId); } } Iterator<ObjectMenuFactory> it = getContainer().lookupServicesFor( RaplaClientExtensionPoints.OBJECT_MENU_EXTENSION).iterator(); while (it.hasNext()) { ObjectMenuFactory objectMenuFact = it.next(); RaplaObject obj = focusedObject instanceof RaplaObject ? (RaplaObject) focusedObject : null; RaplaMenuItem[] items = objectMenuFact.create( context, obj); for ( int i =0;i<items.length;i++) { RaplaMenuItem item = items[i]; menu.insertAfterId( item, afterId); } } return menu; } private boolean isMultiEditSupported(List<Entity<?>> editableObjects) { if ( editableObjects.size() > 0 ) { RaplaType raplaType = editableObjects.iterator().next().getRaplaType(); if ( raplaType == Allocatable.TYPE || raplaType == User.TYPE || raplaType == Reservation.TYPE) { return true; } } return false; } private void addAllocatableMenuNew(MenuInterface menu,Component parent,Point p,Object focusedObj) throws RaplaException { RaplaObjectAction newResource = addAction(menu,parent,p).setNew( Allocatable.TYPE ); if (focusedObj != CalendarModelImpl.ALLOCATABLES_ROOT) { if (focusedObj instanceof DynamicType) { if (((DynamicType) focusedObj).getAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE).equals(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON)) { newResource.setPerson(true); } newResource.changeObject( (DynamicType)focusedObj ); } if (focusedObj instanceof Allocatable) { if (((Allocatable) focusedObj).isPerson()) { newResource.setPerson(true); } newResource.changeObject( (Allocatable)focusedObj ); } DynamicType[] types = newResource.guessTypes(); if (types.length == 1) //user has clicked on a resource/person type { DynamicType type = types[0]; newResource.putValue(Action.NAME,type.getName( getLocale() )); return; } } else { //user has clicked on top "resources" folder : //add an entry to create a new resource and another to create a new person DynamicType[] resourceType= getQuery().getDynamicTypes(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE ); if ( resourceType.length == 1) { newResource.putValue(Action.NAME,resourceType[0].getName( getLocale() )); } else { newResource.putValue(Action.NAME,getString("resource")); } RaplaObjectAction newPerson = addAction(menu,parent,p).setNew( Allocatable.TYPE ); newPerson.setPerson( true ); DynamicType[] personType= getQuery().getDynamicTypes(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON ); if ( personType.length == 1) { newPerson.putValue(Action.NAME,personType[0].getName( getLocale())); } else { newPerson.putValue(Action.NAME,getString("person")); } } } private void addTypeMenuNew(MenuInterface menu,String classificationType,Component parent,Point p) { DynamicTypeAction newReservationType = newDynamicTypeAction(parent,p); menu.add(new JMenuItem(newReservationType)); newReservationType.setNewClassificationType(classificationType); newReservationType.putValue(Action.NAME,getString(classificationType + "_type")); } private void addUserMenuEdit(MenuInterface menu,Component parent,Point p,User obj,String afterId) { menu.insertAfterId( new RaplaSeparator("sep1"), afterId); menu.insertAfterId( new RaplaSeparator("sep2"), afterId); PasswordChangeAction passwordChangeAction = new PasswordChangeAction(getContext(),parent); passwordChangeAction.changeObject( obj ); menu.insertAfterId( new JMenuItem( passwordChangeAction ), "sep2"); UserAction switchUserAction = newUserAction(parent,p); switchUserAction.setSwitchToUser(); switchUserAction.changeObject( obj ); menu.insertAfterId( new JMenuItem( switchUserAction ), "sep2"); } private void addUserMenuNew(MenuInterface menu,Component parent,Point p) { UserAction newUserAction = newUserAction(parent,p); newUserAction.setNew(); menu.add( new JMenuItem( newUserAction )); } private void addCategoryMenuNew(MenuInterface menu, Component parent, Point p, Object obj) { RaplaObjectAction newAction = addAction(menu,parent,p).setNew( Category.TYPE ); if ( obj instanceof Category) { newAction.changeObject((Category)obj); } else if ( obj != null && obj.equals( getString("categories"))) { newAction.changeObject(getQuery().getSuperCategory()); } newAction.putValue(Action.NAME,getString("category")); } private void addPeriodMenuNew(MenuInterface menu, Component parent, Point p) { Action newAction = addAction(menu,parent,p).setNew( Period.TYPE ); newAction.putValue(Action.NAME,getString("period")); } private RaplaObjectAction addAction(MenuInterface menu, Component parent,Point p) { RaplaObjectAction action = newObjectAction(parent,p); menu.add(new JMenuItem(action)); return action; } private RaplaObjectAction addAction(MenuInterface menu, Component parent,Point p,String id) { RaplaObjectAction action = newObjectAction(parent,p); menu.insertAfterId( new JMenuItem(action), id); return action; } private RaplaObjectAction newObjectAction(Component parent,Point point) { RaplaObjectAction action = new RaplaObjectAction(getContext(),parent, point); return action; } private DynamicTypeAction newDynamicTypeAction(Component parent,Point point) { DynamicTypeAction action = new DynamicTypeAction(getContext(),parent,point); return action; } private UserAction newUserAction(Component parent,Point point) { UserAction action = new UserAction(getContext(),parent,point); return action; } // This will exclude DynamicTypes and non editable Objects from the list private List<Entity<?>> getEditableObjects(Collection<?> list) { Iterator<?> it = list.iterator(); ArrayList<Entity<?>> editableObjects = new ArrayList<Entity<?>>(); while (it.hasNext()) { Object o = it.next(); if (canModify(o) ) editableObjects.add((Entity<?>)o); } return editableObjects; } private List<Entity<?>> getDeletableObjects(Collection<?> list) { Iterator<?> it = list.iterator(); Category superCategory = getQuery().getSuperCategory(); ArrayList<Entity<?>> deletableObjects = new ArrayList<Entity<?>>(); while (it.hasNext()) { Object o = it.next(); if (canModify(o) && !o.equals( superCategory) ) deletableObjects.add((Entity<?>)o); } return deletableObjects; } // method for filtering a selection(Parameter: list) of similar RaplaObjekte // (from type raplaType) // criteria: RaplaType: isPerson-Flag private <T extends RaplaObject> List<T> getObjectsWithSameType(Collection<T> list, RaplaType raplaType, boolean isPerson) { ArrayList<T> objects = new ArrayList<T>(); for (RaplaObject o : list) { // element will be added if it is from the stated RaplaType... if (raplaType != null && (o.getRaplaType() == raplaType)) { // ...furthermore the flag isPerson at allocatables has to // be conform, because person and other resources aren't // able to process at the same time if (raplaType!=Allocatable.TYPE || ((Allocatable) o).isPerson() == isPerson) { @SuppressWarnings("unchecked") T casted = (T)o; objects.add(casted); } } } return objects; } private <T extends RaplaObject> Collection<T> getObjectsWithSameType(Collection<T> list) { Iterator<T> iterator = list.iterator(); if ( !iterator.hasNext()) { return list; } RaplaObject obj = iterator.next(); RaplaType raplaType = obj.getRaplaType(); boolean isPerson = raplaType == Allocatable.TYPE && ((Allocatable) obj).isPerson(); return getObjectsWithSameType(list, raplaType, isPerson); } }
04900db4-rob
src/org/rapla/gui/internal/MenuFactoryImpl.java
Java
gpl3
20,372
/*--------------------------------------------------------------------------* | 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.Color; import org.rapla.components.calendar.DateRenderer; import org.rapla.components.calendar.WeekendHighlightRenderer; import org.rapla.entities.domain.Period; import org.rapla.facade.PeriodModel; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; public class RaplaDateRenderer extends RaplaComponent implements DateRenderer { protected WeekendHighlightRenderer renderer = new WeekendHighlightRenderer(); protected Color periodColor = new Color(0xc5,0xda,0xdd); protected PeriodModel periodModel; public RaplaDateRenderer(RaplaContext sm) { super(sm); periodModel = getPeriodModel(); } public RenderingInfo getRenderingInfo(int dayOfWeek,int day,int month, int year) { Period period = periodModel.getPeriodFor(getRaplaLocale().toRaplaDate(year,month,day)); if (period != null) { Color backgroundColor = periodColor; Color foregroundColor = Color.BLACK; String tooltipText = "<html>" + getString("period") + ":<br>" + period.getName(getI18n().getLocale()) + "</html>"; return new RenderingInfo(backgroundColor, foregroundColor, tooltipText); } return renderer.getRenderingInfo(dayOfWeek,day,month,year); } }
04900db4-rob
src/org/rapla/gui/internal/RaplaDateRenderer.java
Java
gpl3
2,272
/*--------------------------------------------------------------------------* | 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.common; import java.awt.Component; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.util.Date; import java.util.List; import org.rapla.facade.CalendarModel; import org.rapla.facade.CalendarSelectionModel; import org.rapla.framework.RaplaContext; import org.rapla.gui.RaplaAction; import org.rapla.gui.toolkit.DisposingTool; import org.rapla.gui.toolkit.RaplaFrame; public class CalendarAction extends RaplaAction { CalendarSelectionModel model; List<?> objects; Component parent; Date start; public CalendarAction(RaplaContext sm,Component parent,CalendarModel selectionModel) { super( sm); this.model = (CalendarSelectionModel)selectionModel.clone(); this.parent = parent; putValue(NAME,getString("calendar")); putValue(SMALL_ICON,getIcon("icon.calendar")); } public void changeObjects(List<?> objects) { this.objects = objects; } public void setStart(Date start) { this.start = start; } public void actionPerformed(ActionEvent evt) { try { RaplaFrame frame = new RaplaFrame(getContext()); Dimension dimension = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); frame.setSize(new Dimension( Math.min(dimension.width,800) ,Math.min(dimension.height-10,630) ) ); if (start != null) model.setSelectedDate(start); if (objects != null && objects.size() > 0) model.setSelectedObjects( objects ); if ( model.getViewId( ).equals("table")) { model.setViewId("week"); } model.setOption( CalendarModel.ONLY_MY_EVENTS, "false"); model.setAllocatableFilter( null); model.setReservationFilter( null); frame.setTitle("Rapla " + getString("calendar")); MultiCalendarView cal = new MultiCalendarView(getContext(),model, false ); frame.setContentPane(cal.getComponent()); frame.addWindowListener(new DisposingTool(cal)); boolean packFrame = false; frame.place( true, packFrame ); frame.setVisible(true); cal.getSelectedCalendar().scrollToStart(); } catch (Exception ex) { showException(ex, parent); } } }
04900db4-rob
src/org/rapla/gui/internal/common/CalendarAction.java
Java
gpl3
3,453
/*--------------------------------------------------------------------------* | 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.common; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.AppointmentStartComparator; import org.rapla.entities.domain.Reservation; 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; public class RaplaClipboard extends RaplaGUIComponent implements ModificationListener { private Appointment appointment; private Collection<Reservation> reservations = Collections.emptyList(); private boolean wholeReservation; private Allocatable[] restrictedAllocatables; private Collection<Allocatable> contextAllocatables = Collections.emptyList(); public RaplaClipboard( RaplaContext sm ) { super( sm ); getUpdateModule().addModificationListener( this ); } public void dataChanged( ModificationEvent evt ) throws RaplaException { if ( appointment == null ) return; if ( evt.isRemoved( appointment) || evt.isRemoved( appointment.getReservation())) { clearAppointment(); } } private void clearAppointment() { this.appointment = null; this.wholeReservation = false; this.restrictedAllocatables = null; this.reservations = Collections.emptyList(); this.contextAllocatables = Collections.emptyList(); } public void setAppointment( Appointment appointment, boolean wholeReservation, Reservation destReservation, Allocatable[] restrictedAllocatables,Collection<Allocatable> contextAllocatables ) { this.appointment = appointment; this.wholeReservation = wholeReservation; this.reservations = Collections.singleton(destReservation); this.restrictedAllocatables = restrictedAllocatables; this.contextAllocatables = contextAllocatables; } public void setReservation(Collection<Reservation> copyReservation, Collection<Allocatable> contextAllocatables) { ArrayList<Appointment> appointmentList = new ArrayList<Appointment>(); for (Reservation r:copyReservation) { appointmentList.addAll( Arrays.asList( r.getAppointments())); } Collections.sort( appointmentList, new AppointmentStartComparator()); appointment = appointmentList.get(0); wholeReservation = true; restrictedAllocatables = Allocatable.ALLOCATABLE_ARRAY; reservations = copyReservation; this.contextAllocatables = contextAllocatables; } public boolean isWholeReservation() { return wholeReservation; } public Appointment getAppointment() { return appointment; } public Allocatable[] getRestrictedAllocatables() { return restrictedAllocatables; } public Reservation getReservation() { if ( reservations == null || reservations.size() == 0) { return null; } return reservations.iterator().next(); } public Collection<Reservation> getReservations() { return reservations; } public Collection<Allocatable> getConextAllocatables() { return contextAllocatables; } public void setContextAllocatables(Collection<Allocatable> contextAllocatables) { this.contextAllocatables = contextAllocatables; } } /* class AllocationData implements Transferable { public static final DataFlavor allocationFlavor = new DataFlavor(java.util.Map.class, "Rapla Allocation"); private static DataFlavor[] flavors = new DataFlavor[] {allocationFlavor}; Map data; AllocationData(Map data) { this.data = data; } public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException { if (isDataFlavorSupported(flavor)) return data; else throw new UnsupportedFlavorException(flavor); } public DataFlavor[] getTransferDataFlavors() { return flavors; } public boolean isDataFlavorSupported(DataFlavor flavor) { return flavor.equals(allocationFlavor); } }*/
04900db4-rob
src/org/rapla/gui/internal/common/RaplaClipboard.java
Java
gpl3
5,129
package org.rapla.gui.internal.common; import org.rapla.framework.TypedComponentRole; import org.rapla.gui.toolkit.RaplaMenu; import org.rapla.gui.toolkit.RaplaMenubar; public interface InternMenus { public static final TypedComponentRole<RaplaMenubar> MENU_BAR = new TypedComponentRole<RaplaMenubar>("org.rapla.gui.MenuBar"); public static final TypedComponentRole<RaplaMenu> FILE_MENU_ROLE = new TypedComponentRole<RaplaMenu>("org.rapla.gui.SystemMenu"); public static final TypedComponentRole<RaplaMenu> EXTRA_MENU_ROLE = new TypedComponentRole<RaplaMenu>("org.rapla.gui.ExtraMenu"); public static final TypedComponentRole<RaplaMenu> VIEW_MENU_ROLE =new TypedComponentRole<RaplaMenu>("org.rapla.gui.ViewMenu"); public static final TypedComponentRole<RaplaMenu> EXPORT_MENU_ROLE = new TypedComponentRole<RaplaMenu>("org.rapla.gui.ExportMenu"); public static final TypedComponentRole<RaplaMenu> ADMIN_MENU_ROLE =new TypedComponentRole<RaplaMenu>("org.rapla.gui.AdminMenu"); public static final TypedComponentRole<RaplaMenu> EDIT_MENU_ROLE = new TypedComponentRole<RaplaMenu>("org.rapla.gui.EditMenu"); public static final TypedComponentRole<RaplaMenu> IMPORT_MENU_ROLE =new TypedComponentRole<RaplaMenu>("org.rapla.gui.ImportMenu"); public static final TypedComponentRole<RaplaMenu> NEW_MENU_ROLE =new TypedComponentRole<RaplaMenu>("org.rapla.gui.NewMenu"); public static final TypedComponentRole<RaplaMenu> CALENDAR_SETTINGS = new TypedComponentRole<RaplaMenu>("org.rapla.gui.CalendarSettings"); }
04900db4-rob
src/org/rapla/gui/internal/common/InternMenus.java
Java
gpl3
1,549
/*--------------------------------------------------------------------------* | 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.internal.common; import java.awt.BorderLayout; import java.awt.Color; 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.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.swing.BorderFactory; import javax.swing.ButtonGroup; import javax.swing.DefaultListCellRenderer; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.rapla.client.RaplaClientExtensionPoints; import org.rapla.components.calendar.RaplaArrowButton; import org.rapla.components.layout.TableLayout; import org.rapla.components.util.TimeInterval; import org.rapla.entities.RaplaObject; import org.rapla.entities.dynamictype.ClassificationFilter; import org.rapla.facade.CalendarSelectionModel; import org.rapla.facade.ModificationEvent; import org.rapla.framework.Disposable; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.RaplaGUIComponent; import org.rapla.gui.SwingCalendarView; import org.rapla.gui.SwingViewFactory; import org.rapla.gui.VisibleTimeInterval; import org.rapla.gui.internal.CalendarEditor; import org.rapla.gui.internal.FilterEditButton; import org.rapla.gui.internal.edit.ClassifiableFilterEdit; import org.rapla.gui.toolkit.IdentifiableMenuEntry; import org.rapla.gui.toolkit.RaplaMenu; import org.rapla.gui.toolkit.RaplaMenuItem; import org.rapla.gui.toolkit.RaplaWidget; public class MultiCalendarView extends RaplaGUIComponent implements RaplaWidget, Disposable, ChangeListener { private final JPanel page = new JPanel(); private final JPanel header = new JPanel(); Map<String,RaplaMenuItem> viewMenuItems = new HashMap<String,RaplaMenuItem>(); JComboBox viewChooser; List<ChangeListener> listeners = new ArrayList<ChangeListener>(); // Default view, when no plugin defined String ERROR_NO_VIEW_DEFINED = "No views enabled. Please add a plugin in the menu admin/settings/plugins"; private SwingCalendarView defaultView = new SwingCalendarView() { JLabel noViewDefined = new JLabel(ERROR_NO_VIEW_DEFINED); JPanel test =new JPanel(); { test.add( noViewDefined); } public JComponent getDateSelection() { return null; } public void scrollToStart() { } public JComponent getComponent() { return test; } public void update( ) throws RaplaException { } }; private SwingCalendarView currentView = defaultView; String currentViewId; private final CalendarSelectionModel model; final Collection<SwingViewFactory> factoryList; /** renderer for weekdays in month-view */ boolean editable = true; boolean listenersEnabled = true; FilterEditButton filter; CalendarEditor calendarEditor; public MultiCalendarView(RaplaContext context,CalendarSelectionModel model, CalendarEditor calendarEditor) throws RaplaException { this( context, model, true); this.calendarEditor = calendarEditor; } public MultiCalendarView(RaplaContext context,CalendarSelectionModel model, boolean editable) throws RaplaException { super( context); this.editable = editable; factoryList = getContainer().lookupServicesFor(RaplaClientExtensionPoints.CALENDAR_VIEW_EXTENSION); this.model = model; String[] ids = getIds(); { SwingViewFactory factory = findFactory( model.getViewId()); if ( factory == null) { if ( ids.length != 0 ) { String firstId = ids[0]; model.setViewId( firstId ); factory = findFactory( firstId ); } } } RaplaMenu view = getService( InternMenus.VIEW_MENU_ROLE); if ( !view.hasId( "views") ) { addMenu( model, ids, view ); } addTypeChooser( ids ); header.setLayout(new BorderLayout()); header.add( viewChooser, BorderLayout.CENTER); filter =new FilterEditButton(context,model, this, false); final JPanel filterContainer = new JPanel(); filterContainer.setLayout( new BorderLayout()); filterContainer.add(filter.getButton(), BorderLayout.WEST); header.add( filterContainer, BorderLayout.SOUTH); page.setBackground( Color.white ); page.setLayout(new TableLayout( new double[][]{ {TableLayout.PREFERRED, TableLayout.FILL} ,{TableLayout.PREFERRED, TableLayout.FILL}})); update(null); } public void dispose() { } @SuppressWarnings("unchecked") private void addTypeChooser( String[] ids ) { JComboBox jComboBox = new JComboBox( ids); viewChooser = jComboBox; viewChooser.setVisible( viewChooser.getModel().getSize() > 0); viewChooser.setMaximumRowCount(ids.length); viewChooser.setSelectedItem( getModel().getViewId() ); viewChooser.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent evt) { if ( !listenersEnabled ) return; String viewId = (String) ((JComboBox)evt.getSource()).getSelectedItem(); try { selectView( viewId ); } catch (RaplaException ex) { showException(ex, page); } } } ); viewChooser.setRenderer( new DefaultListCellRenderer() { private static final long serialVersionUID = 1L; public Component getListCellRendererComponent(JList arg0, Object selectedItem, int index, boolean arg3, boolean arg4) { super.getListCellRendererComponent( arg0, selectedItem, index, arg3, arg4); if ( selectedItem == null) { setIcon( null ); } else { SwingViewFactory factory = findFactory( (String)selectedItem); setText( factory.getName() ); setIcon( factory.getIcon()); } return this; } }); } public void addValueChangeListener(ChangeListener changeListener) { listeners .add( changeListener); } public void removeValueChangeListener(ChangeListener changeListener) { listeners .remove( changeListener); } public RaplaArrowButton getFilterButton() { return filter.getButton(); } public void stateChanged(ChangeEvent e) { try { ClassifiableFilterEdit filterUI = filter.getFilterUI(); if ( filterUI != null) { final ClassificationFilter[] filters = filterUI.getFilters(); model.setReservationFilter( filters ); update(null); } } catch (Exception ex) { showException(ex, getComponent()); } } private void addMenu( CalendarSelectionModel model, String[] ids, RaplaMenu view ) { RaplaMenu viewMenu = new RaplaMenu("views"); viewMenu.setText(getString("show_as")); view.insertBeforeId( viewMenu, "show_tips"); ButtonGroup group = new ButtonGroup(); for (int i=0;i<ids.length;i++) { String id = ids[i]; RaplaMenuItem viewItem = new RaplaMenuItem( id); if ( id.equals( model.getViewId())) { viewItem.setIcon( getIcon("icon.radio")); } else { viewItem.setIcon( getIcon("icon.empty")); } group.add( viewItem ); SwingViewFactory factory = findFactory( id ); viewItem.setText( factory.getName() ); viewMenu.add( viewItem ); viewItem.setSelected( id.equals( getModel().getViewId())); viewMenuItems.put( id, viewItem ); viewItem.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent evt) { if ( !listenersEnabled ) return; String viewId = ((IdentifiableMenuEntry)evt.getSource()).getId(); try { selectView( viewId ); } catch (RaplaException ex) { showException(ex, page); } } }); } } private SwingViewFactory findFactory(String id) { for (Iterator<SwingViewFactory> it = factoryList.iterator();it.hasNext();) { SwingViewFactory factory = it.next(); if ( factory.getViewId().equals( id ) ) { return factory; } } return null; } private void selectView(String viewId) throws RaplaException { listenersEnabled = false; try { getModel().setViewId( viewId ); update(null); getSelectedCalendar().scrollToStart(); if ( viewMenuItems.size() > 0) { for ( Iterator<RaplaMenuItem> it = viewMenuItems.values().iterator();it.hasNext();) { RaplaMenuItem item = it.next(); item.setIcon( getIcon("icon.empty")); } RaplaMenuItem item = viewMenuItems.get( viewId ); item.setIcon( getIcon("icon.radio")); } for(ChangeListener listener:listeners) { listener.stateChanged( new ChangeEvent( this)); } viewChooser.setSelectedItem( viewId ); } finally { listenersEnabled = true; } } private String[] getIds() { List<SwingViewFactory> sortedList = new ArrayList<SwingViewFactory>(factoryList); Collections.sort( sortedList, new Comparator<SwingViewFactory>() { public int compare( SwingViewFactory arg0, SwingViewFactory arg1 ) { SwingViewFactory f1 = arg0; SwingViewFactory f2 = arg1; return f1.getMenuSortKey().compareTo( f2.getMenuSortKey() ); } }); List<String> list = new ArrayList<String>(); for (Iterator<SwingViewFactory> it = sortedList.iterator();it.hasNext();) { SwingViewFactory factory = it.next(); list.add(factory.getViewId()); } return list.toArray( RaplaObject.EMPTY_STRING_ARRAY); } public CalendarSelectionModel getModel() { return model; } public void update(ModificationEvent evt) throws RaplaException { try { // don't show filter button in template mode filter.getButton().setVisible( getModification().getTemplateName() == null); listenersEnabled = false; String viewId = model.getViewId(); SwingViewFactory factory = findFactory( viewId ); if ( factory == null ) { getLogger().error("View with id " + viewId + " not found. Selecting first view."); if( factoryList.size() == 0) { getLogger().error(ERROR_NO_VIEW_DEFINED); viewId =null; } else { factory = factoryList.iterator().next(); viewId = factory.getViewId(); } } if ( factory != null) { viewChooser.setSelectedItem( viewId ); } else { viewId = "ERROR_VIEW"; } if ( currentViewId == null || !currentViewId.equals( viewId) ) { if ( factory != null) { currentView = factory.createSwingView( getContext(), model, editable); currentViewId = viewId; } else { currentView = defaultView; currentViewId = "ERROR_VIEW"; } page.removeAll(); page.add( header, "0,0,f,f"); JComponent dateSelection = currentView.getDateSelection(); if ( dateSelection != null) page.add( dateSelection, "1,0,f,f" ); JComponent component = currentView.getComponent(); page.add( component, "0,1,1,1,f,f" ); component.setBorder( BorderFactory.createEtchedBorder()); page.setVisible(false); page.invalidate(); page.setVisible( true); } else { boolean update = true; if ( currentView instanceof VisibleTimeInterval) { TimeInterval visibleTimeInterval = ((VisibleTimeInterval) currentView).getVisibleTimeInterval(); if ( evt != null && !evt.isModified() && visibleTimeInterval != null) { TimeInterval invalidateInterval = evt.getInvalidateInterval(); if ( invalidateInterval != null && !invalidateInterval.overlaps( visibleTimeInterval)) { update = false; } } } if ( update ) { currentView.update( ); } } if ( calendarEditor != null) { calendarEditor.updateOwnReservationsSelected(); } } finally { listenersEnabled = true; } } public SwingCalendarView getSelectedCalendar() { return currentView; } public JComponent getComponent() { return page; } }
04900db4-rob
src/org/rapla/gui/internal/common/MultiCalendarView.java
Java
gpl3
14,977
/*--------------------------------------------------------------------------* | 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.common; import java.awt.Component; import java.util.Calendar; import java.util.Date; import javax.swing.DefaultComboBoxModel; import javax.swing.DefaultListCellRenderer; import javax.swing.JComboBox; import javax.swing.JList; import org.rapla.components.util.DateTools; import org.rapla.components.xmlbundle.I18nBundle; import org.rapla.entities.domain.Period; import org.rapla.facade.ClientFacade; import org.rapla.facade.PeriodModel; import org.rapla.facade.RaplaComponent; import org.rapla.framework.Disposable; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; public class PeriodChooser extends JComboBox implements Disposable { private static final long serialVersionUID = 1L; Date selectedDate = null; Period selectedPeriod = null; public static int START_ONLY = 1; public static int START_AND_END = 0; public static int END_ONLY = -1; int visiblePeriods; I18nBundle i18n; PeriodModel periodModel; private boolean listenersEnabled = true; private boolean isWeekOfPeriodVisible = true; public PeriodChooser( RaplaContext context) throws RaplaException { this(context,START_AND_END); } public PeriodChooser(RaplaContext context,int visiblePeriods) throws RaplaException { // super(RaplaButton.SMALL); this.visiblePeriods = visiblePeriods; i18n = context.lookup(RaplaComponent.RAPLA_RESOURCES); setPeriodModel( context.lookup(ClientFacade.class) .getPeriodModel()); } @SuppressWarnings("unchecked") public void setPeriodModel(PeriodModel model) { this.periodModel = model; if ( periodModel != null ) { try { listenersEnabled = false; DefaultComboBoxModel aModel = new DefaultComboBoxModel(model.getAllPeriods()); this.setModel(aModel); } finally { listenersEnabled = true; } } setRenderer(new PeriodListCellRenderer()); update(); } public void dispose() { listenersEnabled = false; } private String formatPeriod(Period period) { if ( !isWeekOfPeriodVisible) { return period.getName(); } int lastWeek = period.getWeeks(); int week = weekOf(period,selectedDate); if (week != 1 && week >= lastWeek) { return i18n.format( "period.format.end" ,period.getName() ); } else { return i18n.format( "period.format.week" ,String.valueOf(weekOf(period,selectedDate)) ,period.getName() ); } } public static int weekOf(Period period, Date date) { Date start = period.getStart(); Calendar cal = Calendar.getInstance(DateTools.getTimeZone()); if (!period.contains(date) || start == null) return -1; long duration = date.getTime() - start.getTime(); long weeks = duration / (DateTools.MILLISECONDS_PER_WEEK); // setTimeInMillis has protected access in JDK 1.3.1 cal.setTime(new Date(date.getTime() - weeks * DateTools.MILLISECONDS_PER_WEEK)); int week_of_year = cal.get(Calendar.WEEK_OF_YEAR); cal.setTime(start); return ((int)weeks) + 1 + (((week_of_year) != cal.get(Calendar.WEEK_OF_YEAR))? 1 :0); } private String formatPeriodList(Period period) { if (visiblePeriods == START_ONLY) { return i18n.format( "period.format.start" ,period.getName() ); } else if (visiblePeriods == END_ONLY) { return i18n.format( "period.format.end" ,period.getName() ); } else { return period.getName(); } } public void setDate(Date date, Date endDate) { try { listenersEnabled = false; if (date != selectedDate) // Compute period only on date change { selectedPeriod = getPeriod(date, endDate); } if ( selectedPeriod != null ) { selectedDate = date; setSelectedItem(selectedPeriod); } else { selectedDate = date; setSelectedItem(null); } repaint(); revalidate(); } finally { listenersEnabled = true; } } public void setDate(Date date) { setDate(date, null); } private String getSelectionText() { Period period = selectedPeriod; if ( period != null ) { return formatPeriod(period); } else { return i18n.getString("period.not_set"); } } public void setSelectedPeriod(Period period) { selectedPeriod = period; // EXCO listenersEnabled = false; setSelectedItem(period); listenersEnabled = true; if (visiblePeriods == END_ONLY) { selectedDate = period.getEnd(); } else { selectedDate = period.getStart(); } } public Period getPeriod() { return selectedPeriod; // getPeriod(selectedDate); } private Period getPeriod(Date date, Date endDate) { if (periodModel == null ) return null; if ( visiblePeriods == END_ONLY) { return periodModel.getNearestPeriodForEndDate(date); } else { return periodModel.getNearestPeriodForStartDate(date, endDate); } } public Date getDate() { return selectedDate; } private void update() { setVisible(periodModel != null && periodModel.getSize() > 0); setDate(getDate()); } protected void fireActionEvent() { if ( !listenersEnabled ) { return ; } Period period = (Period) getSelectedItem(); selectedPeriod = period; // EXCO if (period != null) { if (visiblePeriods == END_ONLY) { selectedDate = period.getEnd(); } else { selectedDate = period.getStart(); } } super.fireActionEvent(); } class PeriodListCellRenderer extends DefaultListCellRenderer { private static final long serialVersionUID = 1L; public Component getListCellRendererComponent( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { if (index == -1) { value = getSelectionText(); } else { Period period = (Period) value; value = formatPeriodList(period); } return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); } } public boolean isWeekOfPeriodVisible() { return isWeekOfPeriodVisible; } public void setWeekOfPeriodVisible( boolean isWeekOfPeriodVisible ) { this.isWeekOfPeriodVisible = isWeekOfPeriodVisible; } }
04900db4-rob
src/org/rapla/gui/internal/common/PeriodChooser.java
Java
gpl3
8,837
/*--------------------------------------------------------------------------* | 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.common; import java.awt.Component; import java.text.MessageFormat; import java.util.Locale; import javax.swing.DefaultListCellRenderer; import javax.swing.JList; import org.rapla.entities.Named; public class NamedListCellRenderer extends DefaultListCellRenderer { private static final long serialVersionUID = 1L; Locale locale; MessageFormat format = null; public NamedListCellRenderer(Locale locale) { this.locale = locale; } public NamedListCellRenderer(Locale locale,String formatString) { this(locale); this.format = new MessageFormat(formatString); } public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { if (value instanceof Named) value = ((Named) value).getName(locale); if (format != null) value = format.format(new Object[] {value}); return super.getListCellRendererComponent(list,value,index,isSelected,cellHasFocus); } }
04900db4-rob
src/org/rapla/gui/internal/common/NamedListCellRenderer.java
Java
gpl3
2,195
/*--------------------------------------------------------------------------* | 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 ); } }
04900db4-rob
src/org/rapla/gui/internal/view/UserInfoUI.java
Java
gpl3
3,214
/*--------------------------------------------------------------------------* | 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); } } }
04900db4-rob
src/org/rapla/gui/internal/view/TreeFactoryImpl.java
Java
gpl3
39,739
/*--------------------------------------------------------------------------* | 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; } } }
04900db4-rob
src/org/rapla/gui/internal/view/HTMLInfo.java
Java
gpl3
7,581
/*--------------------------------------------------------------------------* | 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); } }
04900db4-rob
src/org/rapla/gui/internal/view/AppointmentInfoUI.java
Java
gpl3
2,304
/*--------------------------------------------------------------------------* | 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); }
04900db4-rob
src/org/rapla/gui/internal/view/LinkController.java
Java
gpl3
1,120
/*--------------------------------------------------------------------------* | 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()); } } } } }
04900db4-rob
src/org/rapla/gui/internal/view/ViewTable.java
Java
gpl3
6,162
/*--------------------------------------------------------------------------* | 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"); } }
04900db4-rob
src/org/rapla/gui/internal/view/DeleteInfoUI.java
Java
gpl3
1,813
/*--------------------------------------------------------------------------* | 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)); } }
04900db4-rob
src/org/rapla/gui/internal/view/LicenseUI.java
Java
gpl3
3,519
/*--------------------------------------------------------------------------* | 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(); } }
04900db4-rob
src/org/rapla/gui/internal/view/AllocatableInfoUI.java
Java
gpl3
4,763
/*--------------------------------------------------------------------------* | 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()); } }
04900db4-rob
src/org/rapla/gui/internal/view/CategoryInfoUI.java
Java
gpl3
1,399
/*--------------------------------------------------------------------------* | 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); } } }
04900db4-rob
src/org/rapla/gui/internal/view/LicenseInfoUI.java
Java
gpl3
3,692
/*--------------------------------------------------------------------------* | 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); } }
04900db4-rob
src/org/rapla/gui/internal/view/PeriodInfoUI.java
Java
gpl3
2,316
/*--------------------------------------------------------------------------* | 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"); } }
04900db4-rob
src/org/rapla/gui/internal/view/DependencyInfoUI.java
Java
gpl3
2,229
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.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"); } }
04900db4-rob
src/org/rapla/gui/internal/view/ReservationInfoUI.java
Java
gpl3
7,402
/*--------------------------------------------------------------------------* | 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; } }
04900db4-rob
src/org/rapla/gui/internal/view/InfoFactoryImpl.java
Java
gpl3
8,634
/*--------------------------------------------------------------------------* | 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()); } }
04900db4-rob
src/org/rapla/gui/internal/view/ClassificationInfoUI.java
Java
gpl3
4,766
/*--------------------------------------------------------------------------* | 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; } } }
04900db4-rob
src/org/rapla/gui/internal/view/DynamicTypeInfoUI.java
Java
gpl3
2,713
/*--------------------------------------------------------------------------* | 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; } }
04900db4-rob
src/org/rapla/gui/internal/ConflictSelection.java
Java
gpl3
9,820
/*--------------------------------------------------------------------------* | 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(); } }
04900db4-rob
src/org/rapla/gui/internal/MainFrame.java
Java
gpl3
9,144
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; } }
04900db4-rob
src/org/rapla/gui/internal/FilterEditButton.java
Java
gpl3
3,331
/*--------------------------------------------------------------------------* | 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(); }
04900db4-rob
src/org/rapla/gui/SwingViewFactory.java
Java
gpl3
1,686
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; }
04900db4-rob
src/org/rapla/gui/AppointmentStatusFactory.java
Java
gpl3
310
/*--------------------------------------------------------------------------* | 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); } } } } } }
04900db4-rob
src/org/rapla/gui/RaplaGUIComponent.java
Java
gpl3
17,327
/*--------------------------------------------------------------------------* | 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; } }
04900db4-rob
src/org/rapla/gui/MenuContext.java
Java
gpl3
2,169
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; }
04900db4-rob
src/org/rapla/gui/PublishExtensionFactory.java
Java
gpl3
342
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(); }
04900db4-rob
src/org/rapla/gui/ReservationEdit.java
Java
gpl3
1,000
/*--------------------------------------------------------------------------* | 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); }
04900db4-rob
src/org/rapla/gui/AppointmentListener.java
Java
gpl3
1,395
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; }
04900db4-rob
src/org/rapla/gui/ReservationController.java
Java
gpl3
2,833
/*--------------------------------------------------------------------------* | 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(); }
04900db4-rob
src/org/rapla/gui/SwingCalendarView.java
Java
gpl3
1,521
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; }
04900db4-rob
src/org/rapla/gui/InfoFactory.java
Java
gpl3
767
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(); }
04900db4-rob
src/org/rapla/gui/TreeFactory.java
Java
gpl3
1,183
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; }
04900db4-rob
src/org/rapla/gui/AnnotationEditExtension.java
Java
gpl3
820
/*--------------------------------------------------------------------------* | 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()); } }
04900db4-rob
src/org/rapla/gui/DefaultPluginOption.java
Java
gpl3
4,803
/*--------------------------------------------------------------------------* | 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; } }
04900db4-rob
src/org/rapla/gui/toolkit/RaplaMenu.java
Java
gpl3
2,886
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); } }
04900db4-rob
src/org/rapla/gui/toolkit/AWTColorUtil.java
Java
gpl3
1,139
/*--------------------------------------------------------------------------* | 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(); }
04900db4-rob
src/org/rapla/gui/toolkit/FrameControllerListener.java
Java
gpl3
1,105
/*--------------------------------------------------------------------------* | 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); } } }
04900db4-rob
src/org/rapla/gui/toolkit/FrameControllerList.java
Java
gpl3
8,379
/*--------------------------------------------------------------------------* | 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; } }
04900db4-rob
src/org/rapla/gui/toolkit/ErrorDialogException.java
Java
gpl3
1,578
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; } } }
04900db4-rob
src/org/rapla/gui/toolkit/MenuScroller.java
Java
gpl3
18,987
/*--------------------------------------------------------------------------* | 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() ); } } }
04900db4-rob
src/org/rapla/gui/toolkit/RaplaMenubar.java
Java
gpl3
2,804
/*--------------------------------------------------------------------------* | 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(); }
04900db4-rob
src/org/rapla/gui/toolkit/RaplaWidget.java
Java
gpl3
1,145
/*--------------------------------------------------------------------------* | 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; } }
04900db4-rob
src/org/rapla/gui/toolkit/RaplaColors.java
Java
gpl3
4,828
/*--------------------------------------------------------------------------* | 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; } }
04900db4-rob
src/org/rapla/gui/toolkit/PopupEvent.java
Java
gpl3
1,482
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(); }
04900db4-rob
src/org/rapla/gui/toolkit/IdentifiableMenuEntry.java
Java
gpl3
252
/*--------------------------------------------------------------------------* | 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); } } }
04900db4-rob
src/org/rapla/gui/toolkit/HTMLView.java
Java
gpl3
3,686
/*--------------------------------------------------------------------------* | 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); } }
04900db4-rob
src/org/rapla/gui/toolkit/DialogUI.java
Java
gpl3
13,222
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.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(); } }
04900db4-rob
src/org/rapla/gui/toolkit/RaplaFrame.java
Java
gpl3
4,562
/*--------------------------------------------------------------------------* | 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(); } }
04900db4-rob
src/org/rapla/gui/toolkit/MonthChooser.java
Java
gpl3
2,139
/*--------------------------------------------------------------------------* | 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()); } }
04900db4-rob
src/org/rapla/gui/toolkit/WeekdayChooser.java
Java
gpl3
2,188
/*--------------------------------------------------------------------------* | 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()); } } }
04900db4-rob
src/org/rapla/gui/toolkit/ErrorDialog.java
Java
gpl3
7,820
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); }
04900db4-rob
src/org/rapla/gui/toolkit/MenuInterface.java
Java
gpl3
567
/*--------------------------------------------------------------------------* | 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; } }
04900db4-rob
src/org/rapla/gui/toolkit/RaplaSeparator.java
Java
gpl3
1,951