code
stringlengths
3
1.18M
language
stringclasses
1 value
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendar; import java.awt.Component; import java.awt.MouseInfo; import java.awt.Point; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import java.util.ArrayList; import javax.swing.InputVerifier; import javax.swing.JComponent; import javax.swing.JTextField; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import javax.swing.text.PlainDocument; /** The base class for TextFields that supports entering values in blocks. Most notifiably the DateField and the TimeField. <br> You can use the left/right arrow keys to switch the blocks. Use of the top/down arrow keys will increase/decrease the values in the selected block (page_up/page_down for major changes). You can specify maximum length for each block. If a block reaches this maximum value the focus will switch to the next block. @see DateField @see TimeField */ public abstract class AbstractBlockField extends JTextField { private static final long serialVersionUID = 1L; int m_markedBlock = 0; char m_lastChar = 0; boolean m_keyPressed = false; protected String m_oldText; ArrayList<ChangeListener> m_listenerList = new ArrayList<ChangeListener>(); public AbstractBlockField() { Listener listener = new Listener(); addMouseListener(listener); addActionListener(listener); addFocusListener(listener); addKeyListener(listener); addMouseWheelListener( listener ); setInputVerifier(new InputVerifier() { public boolean verify(JComponent comp) { boolean valid = blocksValid(); if ( valid ) { fireValueChanged(); } return valid; } }); } class Listener implements MouseListener,KeyListener,FocusListener,ActionListener, MouseWheelListener { public void mouseReleased(MouseEvent evt) { } public void mousePressed(MouseEvent evt) { if ( !isMouseOverComponent()) { blocksValid(); fireValueChanged(); } if ( evt.getButton() != MouseEvent.BUTTON1) { return; } // We have to mark the block on mouse pressed and mouse clicked. // Windows needs mouse clicked while Linux needs mouse pressed. markCurrentBlock(); } public void mouseEntered(MouseEvent me) { } public void mouseExited(MouseEvent me) { blocksValid(); fireValueChanged(); } public void mouseClicked(MouseEvent evt) { if ( evt.getButton() != MouseEvent.BUTTON1) { return; } // We have to mark the block on mouse pressed and mouse clicked. markCurrentBlock(); if (evt.getClickCount()>1) { selectAll(); return; } if (blocksValid()) { fireValueChanged(); } } // Implementation of ActionListener public void actionPerformed(ActionEvent e) { blocksValid(); fireValueChanged(); } public void focusGained(FocusEvent evt) { if (blocksValid()) { //setBlock(0); } } public void focusLost(FocusEvent evt) { //select(-1,-1); blocksValid(); fireValueChanged(); } public void keyPressed(KeyEvent evt) { m_keyPressed = true; m_lastChar=evt.getKeyChar(); if (!blocksValid()) return; if (isSeparator(evt.getKeyChar())) { evt.consume(); return; } switch (evt.getKeyCode()) { case KeyEvent.VK_LEFT: case KeyEvent.VK_KP_LEFT: if (blockCount() >1) { setBlock(-1); evt.consume(); } return; case KeyEvent.VK_KP_RIGHT: case KeyEvent.VK_RIGHT: if (blockCount() >1) { setBlock(1); evt.consume(); } return; case KeyEvent.VK_HOME: setBlock(-1000); evt.consume(); return; case KeyEvent.VK_END: setBlock(1000); evt.consume(); return; case KeyEvent.VK_KP_UP: case KeyEvent.VK_UP: changeSelectedBlock(1); evt.consume(); return; case KeyEvent.VK_KP_DOWN: case KeyEvent.VK_DOWN: changeSelectedBlock(-1); evt.consume(); return; case KeyEvent.VK_PAGE_UP: changeSelectedBlock(10); evt.consume(); return; case KeyEvent.VK_PAGE_DOWN: changeSelectedBlock(-10); evt.consume(); return; } } public void keyReleased(KeyEvent evt) { m_lastChar=evt.getKeyChar(); // Only change the block if the keyReleased // event follows a keyPressed. // If you type very quickly you could // get two strunged keyReleased events if (m_keyPressed == true) m_keyPressed = false; else return; if (!blocksValid()) return; if (isSeparator(m_lastChar) ) { if ( isSeparator( getText().charAt(getCaretPosition()))) nextBlock(); evt.consume(); } else if (isValidChar(m_lastChar)) { advance(); evt.consume(); if (blocksValid() && !isMouseOverComponent()) { // fireValueChanged(); } } } private boolean isMouseOverComponent() { Component comp = AbstractBlockField.this; Point compLoc = comp.getLocationOnScreen(); Point mouseLoc = MouseInfo.getPointerInfo().getLocation(); boolean result = (mouseLoc.x >= compLoc.x && mouseLoc.x <= compLoc.x + comp.getWidth() && mouseLoc.y >= compLoc.y && mouseLoc.y <= compLoc.y + comp.getHeight()); return result; } public void keyTyped(KeyEvent evt) { } public void mouseWheelMoved(MouseWheelEvent e) { if (!hasFocus()) { return; } if (!blocksValid() || e == null) return; int count = e.getWheelRotation(); changeSelectedBlock(-1 * count/(Math.abs(count))); } } private void markCurrentBlock() { if (!blocksValid()) { return; } int blockstart[] = new int[blockCount()]; int block = calcBlocks(blockstart); markBlock(blockstart,block); } public void addChangeListener(ChangeListener listener) { m_listenerList.add(listener); } /** removes a listener from this component.*/ public void removeChangeListener(ChangeListener listener) { m_listenerList.remove(listener); } public ChangeListener[] getChangeListeners() { return m_listenerList.toArray(new ChangeListener[]{}); } /** A ChangeEvent will be fired to every registered ActionListener * when the value has changed. */ protected void fireValueChanged() { if (m_listenerList.size() == 0) return; // Only fire, when text has changed. if (m_oldText != null && m_oldText.equals(getText())) return; m_oldText = getText(); ChangeEvent evt = new ChangeEvent(this); ChangeListener[] listeners = getChangeListeners(); for (int i = 0; i<listeners.length; i ++) { listeners[i].stateChanged(evt); } } // switch to next block private void nextBlock() { int[] blockstart = new int[blockCount()]; int block = calcBlocks(blockstart); markBlock(blockstart,Math.min(block + 1,blockCount() -1)); } // switch to next block if blockend is reached and private void advance() { if (blockCount()<2) return; int blockstart[] = new int[blockCount()]; int block = calcBlocks(blockstart); if (block >= blockCount() -1) return; int selectedLen = (block ==0) ? blockstart[1] : (blockstart[block + 1] - blockstart[block] - 1); if (selectedLen == maxBlockLength(block)) { markBlock(blockstart,Math.min(block + 1,blockCount() -1)); } } /** changes the value of the selected Block. Adds the count value. */ private void changeSelectedBlock(int count) { int blockstart[] = new int[blockCount()]; int block = calcBlocks(blockstart); int start = (block == 0) ? 0 : blockstart[block] + 1; int end = (block == blockCount() -1) ? getText().length() : blockstart[block+1]; String selected = getText().substring(start,end); markBlock(blockstart,block); changeSelectedBlock(blockstart,block,selected,count); } private void setBlock(int count) { if (blockCount()<1) return; int blockstart[] = new int[blockCount()]; int block = calcBlocks(blockstart); if (count !=0) markBlock(blockstart,Math.min(Math.max(0,block + count),blockCount()-1)); else markBlock(blockstart,m_markedBlock); } /** Select the specified block. */ final protected void markBlock(int[] blockstart,int block) { m_markedBlock = block; if (m_markedBlock == 0) mark(blockstart[0], (blockCount()>1) ? blockstart[1] : getText().length()); else if (m_markedBlock==blockCount()-1) mark(blockstart[m_markedBlock] + 1,getText().length()); else mark(blockstart[m_markedBlock] + 1,blockstart[m_markedBlock+1]); } private boolean isPrevSeparator(int i,char[] source,String currentText,int offs) { return (i>0 && isSeparator(source[i-1]) || (offs > 0 && isSeparator(currentText.charAt(offs-1)))); } private boolean isNextSeparator(String currentText,int offs) { return (offs < currentText.length()-1 && isSeparator(currentText.charAt(offs))); } class DateDocument extends PlainDocument { private static final long serialVersionUID = 1L; public void insertString(int offs, String str, AttributeSet a) throws BadLocationException { String currentText = getText(0, getLength()); char[] source = str.toCharArray(); char[] result = new char[source.length]; int j = 0; boolean bShouldBeep = false; for (int i = 0; i < source.length; i++) { boolean bValid = true; if (!isValidChar(source[i])) { bValid = false; } else { //if (offs < currentText.length()-1) //System.out.println("offset-char: " + currentText.charAt(offs)); // if (isSeparator(source[i])) if (isNextSeparator(currentText,offs) || isPrevSeparator(i,source,currentText,offs) || (i==0 && offs==0) || (i==source.length && offs==currentText.length()) ) { // beep(); continue; } } if (bValid) result[j++] = source[i]; else bShouldBeep = true; } if (bShouldBeep) beep(); super.insertString(offs, new String(result, 0, j), a); } public void remove(int offs, int len) throws BadLocationException { if (m_lastChar == 0 || (!isSeparator(m_lastChar) && (isValidChar(m_lastChar) || !Character.isLetter(m_lastChar)) ) ) super.remove(offs, len); } } final protected Document createDefaultModel() { return new DateDocument(); } /** Calculate the blocks. The new blockstarts will be stored in the int array. @return the block that contains the caret. */ protected int calcBlocks(int[] blockstart) { String text = getText(); int dot = getCaretPosition(); int block = 0; blockstart[0] = 0; char[] separators = getSeparators(); for (int i=1;i<blockstart.length;i++) { int min = text.length(); for (int j=0;j<separators.length;j++) { int pos = text.indexOf(separators[j], blockstart[i-1] + 1); if (pos>=0 && pos < min) min = pos; } blockstart[i] = min; if (dot>blockstart[i]) block = i; } return block; } /** Select the text from dot to mark. */ protected void mark(int dot,int mark) { setCaretPosition(mark); moveCaretPosition(dot); } /** this method will be called when an non-valid character is entered. */ protected void beep() { Toolkit.getDefaultToolkit().beep(); } /** returns true if the text can be split into blocks. */ abstract public boolean blocksValid(); /** The number of blocks for this Component. */ abstract protected int blockCount(); /** This method will be called, when the user has pressed the up/down * arrows on a selected block. * @param count Posible values are 1,-1,10,-10. */ abstract protected void changeSelectedBlock(int[] blocks,int block,String selected,int count); /** returns the maximum length of the specified block. */ abstract protected int maxBlockLength(int block); /** returns true if the character should be accepted by the component. */ abstract protected boolean isValidChar(char c); /** returns true if the character is a block-separator. All block-separators must be valid characters. @see #isValidChar */ abstract protected boolean isSeparator(char c); /** @return all seperators.*/ abstract protected char[] getSeparators(); }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendar; import java.text.DateFormat; import java.text.FieldPosition; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; /** The TimeField only accepts characters that are part of DateFormat.getTimeInstance(DateFormat.SHORT,locale). * The input blocks are [hour,minute,am_pm] or [hour_of_day,minute] * depending on the selected locale. You can use the keyboard to * navigate between the blocks or to increment/decrement the blocks. * @see AbstractBlockField */ final public class TimeField extends AbstractBlockField { private static final long serialVersionUID = 1L; private DateFormat m_outputFormat; private DateFormat m_parsingFormat; private Calendar m_calendar; private int m_rank[] = null; private char[] m_separators; private boolean m_useAM_PM = false; private boolean americanAM_PM_character = false; public TimeField() { this(Locale.getDefault()); } public TimeField(Locale locale) { this(locale, TimeZone.getDefault()); } public TimeField(Locale locale,TimeZone timeZone) { super(); m_calendar = Calendar.getInstance(timeZone, locale); super.setLocale(locale); setFormat(); setTime(new Date()); } public void setLocale(Locale locale) { super.setLocale(locale); if (locale != null && getTimeZone() != null) setFormat(); } private void setFormat() { m_parsingFormat = DateFormat.getTimeInstance(DateFormat.SHORT, getLocale()); m_parsingFormat.setTimeZone(getTimeZone()); Date oldDate = m_calendar.getTime(); m_calendar.set(Calendar.HOUR_OF_DAY,0); m_calendar.set(Calendar.MINUTE,0); String formatStr = m_parsingFormat.format(m_calendar.getTime()); FieldPosition minutePos = new FieldPosition(DateFormat.MINUTE_FIELD); m_parsingFormat.format(m_calendar.getTime(), new StringBuffer(),minutePos); FieldPosition hourPos = new FieldPosition(DateFormat.HOUR0_FIELD); StringBuffer hourBuf = new StringBuffer(); m_parsingFormat.format(m_calendar.getTime(), hourBuf,hourPos); FieldPosition hourPos1 = new FieldPosition(DateFormat.HOUR1_FIELD); StringBuffer hourBuf1 = new StringBuffer(); m_parsingFormat.format(m_calendar.getTime(), hourBuf1,hourPos1); FieldPosition amPmPos = new FieldPosition(DateFormat.AM_PM_FIELD); m_parsingFormat.format(m_calendar.getTime(), new StringBuffer(),amPmPos); String zeroDigit = m_parsingFormat.getNumberFormat().format(0); int zeroPos = hourBuf.toString().indexOf(zeroDigit,hourPos.getBeginIndex()); // 0:30 or 12:30 boolean zeroBased = (zeroPos == 0); String testFormat = m_parsingFormat.format( m_calendar.getTime() ).toLowerCase(); int mp = minutePos.getBeginIndex(); int ap = amPmPos.getBeginIndex(); int hp = Math.max( hourPos.getBeginIndex(), hourPos1.getBeginIndex() ); int pos[] = null; // Use am/pm if (amPmPos.getEndIndex()>0) { m_useAM_PM = true; americanAM_PM_character = m_useAM_PM && (testFormat.indexOf( "am" )>=0 || testFormat.indexOf( "pm" )>=0); // System.out.println(formatStr + " hour:"+hp+" minute:"+mp+" ampm:"+ap); if (hp<0 || mp<0 || ap<0 || formatStr == null) { throw new IllegalArgumentException("Can't parse the time-format for this locale: " + formatStr); } // quick and diry sorting if (mp<hp && hp<ap) { pos = new int[] {mp,hp,ap}; m_rank = new int[] {Calendar.MINUTE, Calendar.HOUR, Calendar.AM_PM}; } else if (mp<ap && ap<hp) { pos = new int[] {mp,ap,hp}; m_rank = new int[] {Calendar.MINUTE, Calendar.AM_PM, Calendar.HOUR}; } else if (hp<mp && mp<ap) { pos = new int[] {hp,mp,ap}; m_rank = new int[] {Calendar.HOUR, Calendar.MINUTE, Calendar.AM_PM}; } else if (hp<ap && ap<mp) { pos = new int[] {hp,ap,mp}; m_rank = new int[] {Calendar.HOUR, Calendar.AM_PM, Calendar.MINUTE}; } else if (ap<mp && mp<hp) { pos = new int[] {ap,mp,hp}; m_rank = new int[] {Calendar.AM_PM, Calendar.MINUTE, Calendar.HOUR}; } else if (ap<hp && hp<mp) { pos = new int[] {ap,hp,mp}; m_rank = new int[] {Calendar.AM_PM, Calendar.HOUR, Calendar.MINUTE}; } else { throw new IllegalStateException("Ordering am=" +ap + " h=" +hp + " m="+mp +" not supported"); } char firstSeparator = formatStr.charAt(pos[1]-1); char secondSeparator = formatStr.charAt(pos[2]-1); if (Character.isDigit(firstSeparator) || Character.isDigit(secondSeparator)) throw new IllegalArgumentException("Can't parse the time-format for this locale: " + formatStr); m_separators = new char[] {firstSeparator,secondSeparator}; StringBuffer buf = new StringBuffer(); for (int i=0;i<m_rank.length;i++) { if (m_rank[i] == Calendar.HOUR) { if (zeroBased) buf.append("KK"); else buf.append("hh"); } else if (m_rank[i] == Calendar.MINUTE) { buf.append("mm"); } else if (m_rank[i] == Calendar.AM_PM) { buf.append("a"); } if (i==0 && americanAM_PM_character) { buf.append(firstSeparator); } else if (i==1) { buf.append(secondSeparator); } } m_outputFormat= new SimpleDateFormat(buf.toString(), getLocale()); m_outputFormat.setTimeZone(getTimeZone()); setColumns(7); // Don't use am/pm } else { m_useAM_PM = false; // System.out.println(formatStr + " hour:"+hp+" minute:" + mp); if (hp<0 || mp<0) { throw new IllegalArgumentException("Can't parse the time-format for this locale"); } // quick and diry sorting if (mp<hp) { pos = new int[] {mp,hp}; m_rank = new int[] {Calendar.MINUTE, Calendar.HOUR_OF_DAY}; } else { pos = new int[] {hp,mp}; m_rank = new int[] {Calendar.HOUR_OF_DAY, Calendar.MINUTE}; } char firstSeparator = formatStr.charAt(pos[1]-1); if (Character.isDigit(firstSeparator)) throw new IllegalArgumentException("Can't parse the time-format for this locale"); m_separators = new char[] {firstSeparator}; StringBuffer buf = new StringBuffer(); for (int i=0;i<m_rank.length;i++) { if (m_rank[i] == Calendar.HOUR_OF_DAY) { if (zeroBased) buf.append("HH"); else buf.append("kk"); } else if (m_rank[i] == Calendar.MINUTE) { buf.append("mm"); } else if (m_rank[i] == Calendar.AM_PM) { buf.append("a"); } if (i==0) { buf.append(firstSeparator); } } m_outputFormat= new SimpleDateFormat(buf.toString(), getLocale()); m_outputFormat.setTimeZone(getTimeZone()); setColumns(5); } m_calendar.setTime(oldDate); } public TimeZone getTimeZone() { if (m_calendar != null) return m_calendar.getTimeZone(); return null; } /** returns the parsingFormat of the selected locale. This is same as the default time-format of the selected locale.*/ public DateFormat getParsingFormat() { return m_parsingFormat; } /** returns the output format of the date-field. The outputFormat always uses the full block size: 01:02 instead of 1:02 */ public DateFormat getOutputFormat() { return m_outputFormat; } private void update(TimeZone timeZone, Locale locale) { Date date = getTime(); m_calendar = Calendar.getInstance(timeZone, locale); setFormat(); setText(m_outputFormat.format(date)); } public void setTimeZone(TimeZone timeZone) { update(timeZone, getLocale()); } public Date getTime() { return m_calendar.getTime(); } public void setTime(Date value) { m_calendar.setTime(value); setText(m_outputFormat.format(value)); } protected char[] getSeparators() { return m_separators; } protected boolean isSeparator(char c) { for (int i=0;i<m_separators.length;i++) if (m_separators[i] == c) return true; return false; } protected void changeSelectedBlock(int[] blocks,int block,String selected,int count) { int type = m_rank[block]; if (m_rank.length<block) return; if (type == Calendar.AM_PM) { m_calendar.roll(Calendar.HOUR_OF_DAY,12); } else if (type == Calendar.MINUTE) { m_calendar.add(type,count); } else { if (Math.abs(count) == 10) m_calendar.add(type,count/Math.abs(count) * 12); else m_calendar.add(type,count/Math.abs(count)); } setTime(m_calendar.getTime()); calcBlocks(blocks); markBlock(blocks,block); } public boolean blocksValid() { try { m_calendar.setTime(m_parsingFormat.parse(getText())); return true; } catch (ParseException e) { return false; } } static int[] BLOCKLENGTH1 = new int[] {2,2,2}; static int[] BLOCKLENGTH2 = new int[] {2,2}; protected int blockCount() { return m_useAM_PM ? BLOCKLENGTH1.length : BLOCKLENGTH2.length; } protected int maxBlockLength(int block) { return m_useAM_PM ? BLOCKLENGTH1[block] : BLOCKLENGTH2[block]; } protected boolean isValidChar(char c) { return (Character.isDigit(c) || isSeparator(c) || ((m_useAM_PM) && ((americanAM_PM_character && (c == 'a' || c=='A' || c=='p' || c=='P' || c=='m' || c=='M')) || (!americanAM_PM_character && Character.isLetter( c )) ) )); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendar; import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Dimension; import java.awt.Font; import java.awt.Point; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.Timer; import java.util.TimerTask; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.event.PopupMenuEvent; import javax.swing.event.PopupMenuListener; /** This is an alternative ComboBox implementation. The main differences are: <ul> <li>No pluggable look and feel</li> <li>drop-down button and editor in a separate component (each can get focus)</li> <li>the popup-component can be an arbitrary JComponent.</li> </ul> */ public abstract class RaplaComboBox extends JPanel { private static final long serialVersionUID = 1L; private JPopupMenu m_popup; private boolean m_popupVisible = false; private boolean m_isDropDown = true; protected RaplaArrowButton m_popupButton; protected JLabel jLabel; protected JComponent m_editorComponent; // If you click on the popupButton while the PopupWindow is shown, // the Window will be closed, because you clicked outside the Popup // (not because you clicked that special button). // The flag popupVisible is unset. // After that the same click will trigger the actionPerfomed method // on our button. And the window would popup again. // Solution: We track down that one mouseclick that closes the popup // with the following flags: private boolean m_closing = false; private boolean m_pressed = false; private Listener m_listener = new Listener(); public RaplaComboBox(JComponent editorComponent) { this(true,editorComponent); } RaplaComboBox(boolean isDropDown,JComponent editorComponent) { m_editorComponent = editorComponent; m_isDropDown = isDropDown; jLabel = new JLabel(); setLayout(new BorderLayout()); add(jLabel,BorderLayout.WEST); add(m_editorComponent,BorderLayout.CENTER); if (m_isDropDown) { installPopupButton(); add(m_popupButton,BorderLayout.EAST); m_popupButton.addActionListener(m_listener); m_popupButton.addMouseListener(m_listener); m_popupVisible = false; } } public JLabel getLabel() { return jLabel; } class Listener implements ActionListener,MouseListener,PopupMenuListener { // Implementation of ActionListener public void actionPerformed(ActionEvent e) { // Ignore action, when Popup is closing log("Action Performed"); if (m_pressed && m_closing) { m_closing = false; return; } if ( !m_popupVisible && !m_closing) { log("Open"); showPopup(); } else { m_popupVisible = false; closePopup(); } // end of else } private void log(@SuppressWarnings("unused") String string) { // System.out.println(System.currentTimeMillis() / 1000 + "m_visible:" + m_popupVisible + " closing: " + m_closing + " [" + string + "]"); } // Implementation of MouseListener public void mousePressed(MouseEvent evt) { m_pressed = true; m_closing = false; log("Pressed"); } public void mouseClicked(MouseEvent evt) { m_closing = false; } public void mouseReleased(MouseEvent evt) { m_pressed = false; m_closing = false; log("Released"); } public void mouseEntered(MouseEvent me) { } public void mouseExited(MouseEvent me) { } // Implementation of PopupListener public void popupMenuWillBecomeVisible(PopupMenuEvent e) { m_popupVisible = true; } public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { m_popupVisible = false; m_closing = true; m_popupButton.requestFocus(); m_popupButton.setChar('v'); log("Invisible"); final boolean oldState = m_popupButton.isEnabled(); m_popupButton.setEnabled( false); final Timer timer = new Timer(true); TimerTask task = new TimerTask() { public void run() { m_popupButton.setEnabled( oldState); } }; timer.schedule(task, 100); } public void popupMenuCanceled(PopupMenuEvent e) { m_popupVisible = false; m_closing = true; m_popupButton.requestFocus(); log("Cancel"); } } private void installPopupButton() { // Maybe we could use the combobox drop-down button here. m_popupButton = new RaplaArrowButton('v'); } public void setFont(Font font) { super.setFont(font); // Method called during constructor? if (font == null) return; if (m_editorComponent != null) m_editorComponent.setFont(font); if (m_popupButton != null && m_isDropDown) { int size = (int) getPreferredSize().getHeight(); m_popupButton.setSize(size,size); } } public void setEnabled( boolean enabled ) { super.setEnabled( enabled ); if ( m_editorComponent != null ) { m_editorComponent.setEnabled( enabled ); } if ( m_popupButton != null ) { m_popupButton.setEnabled ( enabled ); } } protected void showPopup() { if (m_popup == null) createPopup(); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Dimension menuSize = m_popup.getPreferredSize(); Dimension buttonSize = m_popupButton.getSize(); Point location = m_popupButton.getLocationOnScreen(); int diffx= buttonSize.width - menuSize.width; if (location.x + diffx<0) diffx = - location.x; int diffy= buttonSize.height; if (location.y + diffy + menuSize.height > screenSize.height) diffy = screenSize.height - menuSize.height - location.y; m_popup.show(m_popupButton,diffx,diffy); m_popup.requestFocus(); m_popupButton.setChar('^'); } protected void closePopup() { if (m_popup != null && m_popup.isVisible()) { // #Workaround for JMenuPopup-Bug in JDK 1.4 // intended behaviour: m_popup.setVisible(false); javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { // Show JMenuItem and fire a mouse-click cardLayout.last(m_popup); menuItem.menuSelectionChanged(true); menuItem.dispatchEvent(new MouseEvent(m_popup ,MouseEvent.MOUSE_RELEASED ,System.currentTimeMillis() ,0 ,0 ,0 ,1 ,false)); // show original popup again cardLayout.first(m_popup); m_popupButton.requestFocus(); } }); } m_popupVisible = false; } private JMenuItem menuItem; private CardLayout cardLayout; class MyPopup extends JPopupMenu { private static final long serialVersionUID = 1L; MyPopup() { super(); } public void menuSelectionChanged(boolean isIncluded) { closePopup(); } } private void createPopup() { m_popup = new JPopupMenu(); /* try { PopupMenu.class.getMethod("isPopupTrigger",new Object[]{}); } catch (Exception ex) { m_popup.setLightWeightPopupEnabled(true); }*/ m_popup.setBorder(null); cardLayout = new CardLayout(); m_popup.setLayout(cardLayout); m_popup.setInvoker(this); m_popup.add(getPopupComponent(),"0"); menuItem = new JMenuItem(""); m_popup.add(menuItem,"1"); m_popup.setBorderPainted(true); m_popup.addPopupMenuListener(m_listener); } /** the component that should apear in the popup menu */ protected abstract JComponent getPopupComponent(); }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendar; import java.awt.Polygon; /* The following classes are only responsible to paint the Arrows for the NavButton. */ class ArrowPolygon extends Polygon { private static final long serialVersionUID = 1L; public ArrowPolygon(char type,int width) { this(type,width,true); } public ArrowPolygon(char type,int width,boolean border) { int polyWidth = ((width - 7) / 8); polyWidth = (polyWidth + 1) * 8; int dif = border ? (width - polyWidth) /2 : 0; int half = polyWidth / 2 + dif; int insets = (polyWidth == 8) ? 0 : polyWidth / 4; int start = insets + dif; int full = polyWidth - insets + dif; int size = (polyWidth == 8) ? polyWidth / 4 : polyWidth / 8; if ( type == '>') { addPoint(half - size,start); addPoint(half + size,half); addPoint(half - size,full); } // end of if () if ( type == '<') { addPoint(half + size,start); addPoint(half - size,half); addPoint(half + size,full); } // end of if () if ( type == '^') { addPoint(start,half + size); addPoint(half,half - size); addPoint(full,half + size); } // end of if () if ( type == 'v') { addPoint(start,half - size); addPoint(half,half + size); addPoint(full,half - size); } // end of if () if ( type == '-') { addPoint(start + 1,half - 1); addPoint(full - 3,half - 1); } // end of if () if ( type == '+') { addPoint(start + 1,half - 1); addPoint(full - 3,half - 1); addPoint(half -1,half - 1); addPoint(half- 1, half - (size + 1)); addPoint(half -1,half + ( size -1)); addPoint(half -1,half - 1); } // end of if () } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendar; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.TimeZone; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.MenuElement; import javax.swing.MenuSelectionManager; import javax.swing.border.Border; import javax.swing.border.EmptyBorder; import javax.swing.border.LineBorder; /** The graphical date-selection field with month and year incerement/decrement buttons. * @author Christopher Kohlhaas */ public class CalendarMenu extends JPanel implements MenuElement { private static final long serialVersionUID = 1L; static Color BACKGROUND_COLOR = Color.white; static Border FOCUSBORDER = new LineBorder(DaySelection.FOCUSCOLOR,1); static Border EMPTYBORDER = new EmptyBorder(1,1,1,1); BorderLayout borderLayout1 = new BorderLayout(); JPanel topSelection = new JPanel(); Border border1 = BorderFactory.createEtchedBorder(); BorderLayout borderLayout2 = new BorderLayout(); JPanel monthSelection = new JPanel(); NavButton jPrevMonth = new NavButton('<'); JLabel labelMonth = new JLabel(); NavButton jNextMonth = new NavButton('>'); JPanel yearSelection = new JPanel(); NavButton jPrevYear = new NavButton('<'); JLabel labelYear = new JLabel(); NavButton jNextYear = new NavButton('>'); protected DaySelection daySelection; JLabel labelCurrentDay = new JLabel(); JButton focusButton = new JButton() { private static final long serialVersionUID = 1L; public void paint(Graphics g) { Dimension size = getSize(); g.setColor(getBackground()); g.fillRect(0,0,size.width,size.height); } }; DateModel m_model; DateModel m_focusModel; String[] m_monthNames; boolean m_focusable = true; public CalendarMenu(DateModel newModel) { m_model = newModel; m_monthNames = createMonthNames(); m_focusModel = new DateModel(newModel.getLocale(),newModel.getTimeZone()); daySelection = new DaySelection(newModel,m_focusModel); initGUI(); Listener listener = new Listener(); jPrevMonth.addActionListener(listener); jPrevMonth.setBorder( null ); jNextMonth.addActionListener(listener); jNextMonth.setBorder( null ); jPrevYear.addActionListener(listener); jPrevYear.setBorder( null ); jNextYear.addActionListener(listener); jNextYear.setBorder( null ); jPrevMonth.setFocusable( false ); jNextMonth.setFocusable( false ); jPrevYear.setFocusable( false ); jNextYear.setFocusable( false ); this.addMouseListener(listener); jPrevMonth.addMouseListener(listener); jNextMonth.addMouseListener(listener); jPrevYear.addMouseListener(listener); jNextYear.addMouseListener(listener); labelCurrentDay.addMouseListener(listener); daySelection.addMouseListener(listener); labelCurrentDay.addMouseListener(listener); m_model.addDateChangeListener(listener); m_focusModel.addDateChangeListener(listener); focusButton.addKeyListener(listener); focusButton.addFocusListener(listener); calculateSizes(); m_focusModel.setDate(m_model.getDate()); } class Listener implements ActionListener,MouseListener,FocusListener,DateChangeListener,KeyListener { public void actionPerformed(ActionEvent evt) { if ( evt.getSource() == jNextMonth) { m_focusModel.addMonth(1); } // end of if () if ( evt.getSource() == jPrevMonth) { m_focusModel.addMonth(-1); } // end of if () if ( evt.getSource() == jNextYear) { m_focusModel.addYear(1); } // end of if () if ( evt.getSource() == jPrevYear) { m_focusModel.addYear(-1); } // end of if () } // Implementation of DateChangeListener public void dateChanged(DateChangeEvent evt) { if (evt.getSource() == m_model) { m_focusModel.setDate(evt.getDate()); } else { updateFields(); } } // Implementation of MouseListener public void mousePressed(MouseEvent me) { if (me.getSource() == labelCurrentDay) { // Set the current day as sellected day m_model.setDate(new Date()); } else { if (m_focusable && !focusButton.hasFocus()) focusButton.requestFocus(); } } public void mouseClicked(MouseEvent me) { } public void mouseReleased(MouseEvent me) { } public void mouseEntered(MouseEvent me) { } public void mouseExited(MouseEvent me) { } // Implementation of KeyListener public void keyPressed(KeyEvent e) { processCalendarKey(e); } public void keyReleased(KeyEvent e) { } public void keyTyped(KeyEvent e) { } // Implementation of FocusListener public void focusGained(FocusEvent e) { if (e.getSource() == focusButton) setBorder(FOCUSBORDER); else transferFocus(); } public void focusLost(FocusEvent e) { if (e.getSource() == focusButton) setBorder(EMPTYBORDER); } } private void updateFields() { labelCurrentDay.setText(m_focusModel.getCurrentDateString()); labelMonth.setText(m_monthNames[m_focusModel.getMonth() -1]); labelYear.setText(m_focusModel.getYearString()); } public DateModel getModel() { return m_model; } public boolean hasFocus() { return focusButton.hasFocus(); } public boolean isFocusable() { return m_focusable; } public void setFocusable(boolean m_focusable) { this.m_focusable = m_focusable; } // #TODO Property change listener for TimeZone public void setTimeZone(TimeZone timeZone) { m_focusModel.setTimeZone(timeZone); } public void setFont(Font font) { super.setFont(font); // Method called during constructor? if (labelMonth == null || font == null) return; labelMonth.setFont(font); labelYear.setFont(font); daySelection.setFont(font); labelCurrentDay.setFont(font); calculateSizes(); invalidate(); } public void requestFocus() { if (m_focusable) focusButton.requestFocus(); } public DaySelection getDaySelection() { return daySelection; } private void calculateSizes() { // calculate max size of month names int maxWidth =0; FontMetrics fm = getFontMetrics(labelMonth.getFont()); for (int i=0;i< m_monthNames.length;i++) { int len = fm.stringWidth(m_monthNames[i]); if (len>maxWidth) maxWidth = len; } labelMonth.setPreferredSize(new Dimension(maxWidth,fm.getHeight())); int h = fm.getHeight(); jPrevMonth.setSize(h,h); jNextMonth.setSize(h,h); jPrevYear.setSize(h,h); jNextYear.setSize(h,h); // Workaraund for focus-bug in JDK 1.3.1 Border dummyBorder = new EmptyBorder(fm.getHeight(),0,0,0); focusButton.setBorder(dummyBorder); } private void initGUI() { setBorder(EMPTYBORDER); topSelection.setLayout(borderLayout2); topSelection.setBorder(border1); daySelection.setBackground(BACKGROUND_COLOR); FlowLayout flowLayout = new FlowLayout(FlowLayout.LEFT,0,0); monthSelection.setLayout(flowLayout); monthSelection.add(focusButton); monthSelection.add(jPrevMonth); monthSelection.add(labelMonth); monthSelection.add(jNextMonth); yearSelection.setLayout(flowLayout); yearSelection.add(jPrevYear); yearSelection.add(labelYear); yearSelection.add(jNextYear); topSelection.add(monthSelection,BorderLayout.WEST); topSelection.add(yearSelection,BorderLayout.EAST); setLayout(borderLayout1); add(topSelection,BorderLayout.NORTH); add(daySelection,BorderLayout.CENTER); add(labelCurrentDay,BorderLayout.SOUTH); } private String[] createMonthNames( ) { Calendar calendar = Calendar.getInstance(m_model.getLocale()); calendar.setLenient(true); Collection<String> monthNames = new ArrayList<String>(); SimpleDateFormat format = new SimpleDateFormat("MMM",m_model.getLocale()); int firstMonth = 0; int month = 0; while (true) { calendar.set(Calendar.DATE,1); calendar.set(Calendar.MONTH,month); if (month == 0) firstMonth = calendar.get(Calendar.MONTH); else if (calendar.get(Calendar.MONTH) == firstMonth) break; monthNames.add(format.format(calendar.getTime())); month ++; } return monthNames.toArray(new String[0]); } private void processCalendarKey(KeyEvent e) { switch (e.getKeyCode()) { case (KeyEvent.VK_KP_UP): case (KeyEvent.VK_UP): m_focusModel.addDay(-7); break; case (KeyEvent.VK_KP_DOWN): case (KeyEvent.VK_DOWN): m_focusModel.addDay(7); break; case (KeyEvent.VK_KP_LEFT): case (KeyEvent.VK_LEFT): m_focusModel.addDay(-1); break; case (KeyEvent.VK_KP_RIGHT): case (KeyEvent.VK_RIGHT): m_focusModel.addDay(1); break; case (KeyEvent.VK_PAGE_DOWN): m_focusModel.addMonth(1); break; case (KeyEvent.VK_PAGE_UP): m_focusModel.addMonth(-1); break; case (KeyEvent.VK_ENTER): m_model.setDate(m_focusModel.getDate()); break; case (KeyEvent.VK_SPACE): m_model.setDate(m_focusModel.getDate()); break; } } // Start of MenuElement implementation public Component getComponent() { return this; } public MenuElement[] getSubElements() { return new MenuElement[0]; } public void menuSelectionChanged(boolean isIncluded) { } public void processKeyEvent(KeyEvent event, MenuElement[] path, MenuSelectionManager manager) { if (event.getID() == KeyEvent.KEY_PRESSED) processCalendarKey(event); switch (event.getKeyCode()) { case (KeyEvent.VK_ENTER): case (KeyEvent.VK_ESCAPE): manager.clearSelectedPath(); } event.consume(); } public void processMouseEvent(MouseEvent event, MenuElement[] path, MenuSelectionManager manager) { } // End of MenuElement implementation }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendar; import java.awt.Color; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Insets; import java.awt.event.MouseEvent; import java.text.DateFormat; import java.text.FieldPosition; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import org.rapla.components.calendar.DateRenderer.RenderingInfo; /** The DateField only accepts characters that are part of * DateFormat.getDateInstance(DateFormat.SHORT,locale). The * inputblocks are [date,month,year]. The order of the input-blocks is * determined by the locale. You can use the keyboard to navigate * between the blocks or to increment/decrement the blocks. * @see AbstractBlockField */ final public class DateField extends AbstractBlockField { private static final long serialVersionUID = 1L; private DateFormat m_outputFormat; private DateFormat m_parsingFormat; private Calendar m_calendar; private int m_rank[] = null; private char[] m_separators; private SimpleDateFormat m_weekdayFormat; private boolean m_weekdaysVisible = true; private DateRenderer m_dateRenderer; /** stores the y-coordinate of the weekdays display field*/ private int m_weekdaysX; private boolean nullValuePossible; private boolean nullValue; RenderingInfo renderingInfo; public boolean isNullValue() { return nullValue; } public void setNullValue(boolean nullValue) { this.nullValue = nullValue; } public boolean isNullValuePossible() { return nullValuePossible; } public void setNullValuePossible(boolean nullValuePossible) { this.nullValuePossible = nullValuePossible; } public DateField() { this(Locale.getDefault(),TimeZone.getDefault()); } public DateField(Locale locale,TimeZone timeZone) { super(); m_calendar = Calendar.getInstance(timeZone, locale); super.setLocale(locale); setFormat(); setDate(new Date()); } /** you can choose, if weekdays should be displayed in the right corner of the DateField. Default is true. */ public void setWeekdaysVisible(boolean m_weekdaysVisible) { this.m_weekdaysVisible = m_weekdaysVisible; } /** sets the DateRenderer for the calendar */ public void setDateRenderer(DateRenderer dateRenderer) { m_dateRenderer = dateRenderer; } private void setFormat() { m_parsingFormat = DateFormat.getDateInstance(DateFormat.SHORT, getLocale()); m_weekdayFormat = new SimpleDateFormat("EE", getLocale()); TimeZone timeZone = getTimeZone(); m_parsingFormat.setTimeZone(timeZone); m_weekdayFormat.setTimeZone(timeZone); String formatStr = m_parsingFormat.format(m_calendar.getTime()); FieldPosition datePos = new FieldPosition(DateFormat.DATE_FIELD); FieldPosition monthPos = new FieldPosition(DateFormat.MONTH_FIELD); FieldPosition yearPos = new FieldPosition(DateFormat.YEAR_FIELD); m_parsingFormat.format(m_calendar.getTime(), new StringBuffer(),datePos); m_parsingFormat.format(m_calendar.getTime(), new StringBuffer(),monthPos); m_parsingFormat.format(m_calendar.getTime(), new StringBuffer(),yearPos); int mp = monthPos.getBeginIndex(); int dp = datePos.getBeginIndex(); int yp = yearPos.getBeginIndex(); int pos[] = null; // System.out.println(formatStr + " day:"+dp+" month:"+mp+" year:"+yp); if (mp<0 || dp<0 || yp<0) { throw new IllegalArgumentException("Can't parse the date-format for this locale"); } // quick and diry sorting if (dp<mp && mp<yp) { pos = new int[] {dp,mp,yp}; m_rank = new int[] {Calendar.DATE, Calendar.MONTH, Calendar.YEAR}; } else if (dp<yp && yp<mp) { pos = new int[] {dp,yp,mp}; m_rank = new int[] {Calendar.DATE, Calendar.YEAR, Calendar.MONTH}; } else if (mp<dp && dp<yp) { pos = new int[] {mp,dp,yp}; m_rank = new int[] {Calendar.MONTH, Calendar.DATE, Calendar.YEAR}; } else if (mp<yp && yp<dp) { pos = new int[] {mp,yp,dp}; m_rank = new int[] {Calendar.MONTH, Calendar.YEAR, Calendar.DATE}; } else if (yp<dp && dp<mp) { pos = new int[] {yp,dp,mp}; m_rank = new int[] {Calendar.YEAR, Calendar.DATE, Calendar.MONTH}; } else if (yp<mp && mp<dp) { pos = new int[] {yp,mp,dp}; m_rank = new int[] {Calendar.YEAR, Calendar.MONTH, Calendar.DATE}; } else { throw new IllegalStateException("Ordering y=" +yp + " d=" +dp + " m="+mp +" not supported"); } char firstSeparator = formatStr.charAt(pos[1]-1); char secondSeparator = formatStr.charAt(pos[2]-1); // System.out.println("first-sep:"+firstSeparator+" sec-sep:"+secondSeparator); if (Character.isDigit(firstSeparator) || Character.isDigit(secondSeparator)) throw new IllegalArgumentException("Can't parse the date-format for this locale"); m_separators = new char[] {firstSeparator,secondSeparator}; StringBuffer buf = new StringBuffer(); for (int i=0;i<m_rank.length;i++) { if (m_rank[i] == Calendar.YEAR) { buf.append("yyyy"); } else if (m_rank[i] == Calendar.MONTH) { buf.append("MM"); } else if (m_rank[i] == Calendar.DATE) { buf.append("dd"); } if (i==0) { buf.append(firstSeparator); } else if (i==1) { buf.append(secondSeparator); } } setColumns(buf.length() -1 + (m_weekdaysVisible ? 1:0 )); m_outputFormat= new SimpleDateFormat(buf.toString(),getLocale()); m_outputFormat.setTimeZone(timeZone); } public TimeZone getTimeZone() { if (m_calendar != null) return m_calendar.getTimeZone(); return null; } public Date getDate() { if ( nullValue && nullValuePossible) { return null; } Date date = m_calendar.getTime(); return date; } public void setDate(Date value) { if ( value == null) { if ( !nullValuePossible) { return; } } nullValue = value == null; if ( !nullValue) { m_calendar.setTime(value); if (m_dateRenderer != null) { renderingInfo = m_dateRenderer.getRenderingInfo( m_calendar.get(Calendar.DAY_OF_WEEK) ,m_calendar.get(Calendar.DATE) ,m_calendar.get(Calendar.MONTH) + 1 ,m_calendar.get(Calendar.YEAR) ); String text = renderingInfo.getTooltipText(); setToolTipText(text); } String formatedDate = m_outputFormat.format(value); setText(formatedDate); } else { setText(""); } } protected char[] getSeparators() { return m_separators; } protected boolean isSeparator(char c) { for (int i=0;i<m_separators.length;i++) if (m_separators[i] == c) return true; return false; } /** returns the parsingFormat of the selected locale. This is same as the default date-format of the selected locale.*/ public DateFormat getParsingFormat() { return m_parsingFormat; } /** returns the output format of the date-field. The OutputFormat always uses the full block size: 01.01.2000 instead of 1.1.2000 */ public DateFormat getOutputFormat() { return m_outputFormat; } protected void changeSelectedBlock(int[] blocks,int block,String selected,int count) { int type = m_rank[block]; if (m_rank.length<block) return; if (type == Calendar.MONTH) if (Math.abs(count) == 10) m_calendar.add(type,count/Math.abs(count) * 3); else m_calendar.add(type,count/Math.abs(count)); else if (type == Calendar.DATE) if (Math.abs(count) == 10) m_calendar.add(type,count/Math.abs(count) * 7); else m_calendar.add(type,count/Math.abs(count)); else m_calendar.add(type,count); setDate(m_calendar.getTime()); calcBlocks(blocks); markBlock(blocks,block); } public String getToolTipText(MouseEvent event) { if (m_weekdaysVisible && event.getX() >= m_weekdaysX) return super.getToolTipText(event); return null; } public boolean blocksValid() { String dateTxt = null; try { dateTxt = getText(); if ( isNullValuePossible() && dateTxt.length() == 0) { nullValue = true; return true; } m_calendar.setTime(m_parsingFormat.parse(dateTxt)); nullValue = false; return true; } catch (ParseException e) { return false; } } static int[] BLOCKLENGTH = new int[] {2,2,5}; protected int blockCount() { return BLOCKLENGTH.length; } protected void mark(int dot,int mark) { super.mark(dot,mark); if (!m_weekdaysVisible) repaint(); } protected int maxBlockLength(int block) { return BLOCKLENGTH[block]; } protected boolean isValidChar(char c) { return (Character.isDigit(c) || isSeparator(c) ); } /** This method is necessary to shorten the names down to 2 characters. Some date-formats ignore the setting. */ private String small(String string) { return string.substring(0,Math.min(string.length(),2)); } public void paint(Graphics g) { super.paint(g); if (!m_weekdaysVisible) return; Insets insets = getInsets(); final String format = nullValue ? "" :m_weekdayFormat.format(m_calendar.getTime()); String s = small(format); FontMetrics fm = g.getFontMetrics(); int width = fm.stringWidth(s); int x = getWidth()-width-insets.right-3; m_weekdaysX = x; int y = insets.top + (getHeight() - (insets.bottom + insets.top))/2 + fm.getAscent()/3; g.setColor(Color.gray); if (renderingInfo != null) { Color color = renderingInfo.getBackgroundColor(); if (color != null) { g.setColor(color); g.fillRect(x-1, insets.top, width + 3 , getHeight() - insets.bottom - insets.top - 1); } color = renderingInfo.getForegroundColor(); if (color != null) { g.setColor(color); } else { g.setColor(Color.GRAY); } } g.drawString(s,x,y); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.rapla.components.util.DateTools; import org.rapla.entities.domain.Allocatable; import org.rapla.plugin.abstractcalendar.AbstractRaplaBlock; /** Tries to put reservations that allocate the same Ressources in the same column.*/ public class GroupStartTimesStrategy extends AbstractGroupStrategy { List<Allocatable> allocatables; List<Integer> startTimes = new ArrayList<Integer>(); { for ( int i=0;i<=23;i++) { startTimes.add(i*60); } } @Override protected Map<Block, Integer> getBlockMap(CalendarView wv, List<Block> blocks) { if (allocatables != null) { Map<Block,Integer> map = new LinkedHashMap<Block, Integer>(); for (Block block:blocks) { AbstractRaplaBlock b = (AbstractRaplaBlock)block; for (Allocatable a:b.getReservation().getAllocatablesFor(b.getAppointment())) { int index = allocatables.indexOf( a ); if ( index >= 0 ) { map.put( block, index ); } } } return map; } else { return super.getBlockMap(wv, blocks); } } @Override protected List<List<Block>> getSortedSlots(List<Block> list) { TreeMap<Integer,List<Block>> groups = new TreeMap<Integer,List<Block>>(); for (Iterator<Block> it = list.iterator();it.hasNext();) { Block block = it.next(); long startTime = block.getStart().getTime(); int minuteOfDay = DateTools.getMinuteOfDay(startTime); int rowNumber = -1 ; for ( Integer start: startTimes) { if ( start <= minuteOfDay) { rowNumber++; } else { break; } } if ( rowNumber <0) { rowNumber = 0; } List<Block> col = groups.get( rowNumber ); if (col == null) { col = new ArrayList<Block>(); groups.put( rowNumber, col ); } col.add(block); } List<List<Block>> slots = new ArrayList<List<Block>>(); for (int row =0 ;row<startTimes.size();row++) { List<Block> oneRow = groups.get( row ); if ( oneRow == null) { oneRow = new ArrayList<Block>(); } else { Collections.sort( oneRow, blockComparator); } slots.add(oneRow); } return slots; } @Override protected Collection<List<Block>> group(List<Block> blockList) { List<List<Block>> singleGroup = new ArrayList<List<Block>>(); singleGroup.add(blockList); return singleGroup; } public List<Allocatable> getAllocatables() { return allocatables; } public void setAllocatables(List<Allocatable> allocatables) { this.allocatables = allocatables; } public List<Integer> getStartTimes() { return startTimes; } public void setStartTimes(List<Integer> startTimes) { this.startTimes = startTimes; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview.html; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import org.rapla.components.calendarview.AbstractCalendar; import org.rapla.components.calendarview.Block; import org.rapla.components.calendarview.BlockComparator; import org.rapla.components.calendarview.CalendarView; public abstract class AbstractHTMLView extends AbstractCalendar implements CalendarView { public static String COLOR_NO_RESOURCE = "#BBEEBB"; String m_html; abstract public Collection<Block> getBlocks(); void checkBlock( Block bl ) { Date endDate = getEndDate(); if ( !bl.getStart().before(endDate)) { throw new IllegalStateException("Start-date " +bl.getStart() + " must be before calendar end at " +endDate); } } public String getHtml() { return m_html; } protected class HTMLSmallDaySlot extends ArrayList<Block> { private static final long serialVersionUID = 1L; private String date; private Date startTime; public HTMLSmallDaySlot(String date) { super(2); this.date = date; } public void putBlock(Block block) { add( block ); } public void sort() { Collections.sort( this, BlockComparator.COMPARATOR); } public void paint(StringBuffer out) { out.append("<div valign=\"top\" align=\"right\">"); out.append( date ); out.append("</div>\n"); for ( int i=0;i<size();i++) { Block block = get(i); out.append("<div valign=\"top\" class=\"month_block\""); if ( block instanceof HTMLBlock ) { out.append(" style=\"background-color:" + ((HTMLBlock)block).getBackgroundColor() + ";\""); } out.append(">"); out.append(block.toString()); out.append("</div>\n"); } } public void setStart(Date date) { startTime = date; } public Date getStart() { return startTime; } } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview.html; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Iterator; import org.rapla.components.calendarview.Block; import org.rapla.components.calendarview.Builder; import org.rapla.components.util.DateTools; public class HTMLMonthView extends AbstractHTMLView { public final static int ROWS = 6; //without the header row public final static int COLUMNS = 7; HTMLSmallDaySlot[] slots; public Collection<Block> getBlocks() { ArrayList<Block> list = new ArrayList<Block>(); for (int i=0;i<slots.length;i++) { list.addAll(slots[i]); } return Collections.unmodifiableCollection( list ); } protected boolean isEmpty(int column) { for ( int i=column;i < slots.length;i+=7 ) { if (!slots[i].isEmpty() ) { return false; } } return true; } public void rebuild() { // we need to clone the calendar, because we modify the calendar object int the getExclude() method Calendar counter = (Calendar) blockCalendar.clone(); // calculate the blocks Iterator<Builder> it= builders.iterator(); final Date startDate = getStartDate(); while (it.hasNext()) { Builder b= it.next(); b.prepareBuild(startDate,getEndDate()); } slots = new HTMLSmallDaySlot[ daysInMonth ]; for (int i=0;i<slots.length;i++) { slots[i] = new HTMLSmallDaySlot(String.valueOf( i + 1)); } it= builders.iterator(); while (it.hasNext()) { Builder b= it.next(); if (b.isEnabled()) { b.build(this); } } int lastRow = 0; HTMLSmallDaySlot[][] table = new HTMLSmallDaySlot[ROWS][COLUMNS]; counter.setTime(startDate); int firstDayOfWeek = getFirstWeekday(); if ( counter.get(Calendar.DAY_OF_WEEK) != firstDayOfWeek) { counter.set(Calendar.DAY_OF_WEEK, firstDayOfWeek); if ( counter.getTime().after( startDate)) { counter.add(Calendar.DATE, -7); } } Date time = counter.getTime(); int offset = (int) DateTools.countDays(counter.getTime(),startDate); // add headers counter.setTime(startDate); for (int i=0; i<daysInMonth; i++) { int column = (offset + i) % 7; int row = (counter.get(Calendar.DATE) + 6 - column ) / 7; table[row][column] = slots[i]; lastRow = row; slots[i].sort(); counter.add(Calendar.DATE,1); } StringBuffer result = new StringBuffer(); // Rapla 1.4: Show month and year in monthview SimpleDateFormat monthYearFormat = new SimpleDateFormat("MMMMM yyyy", locale); result.append("<h2 class=\"title\">" + monthYearFormat.format(startDate) + "</h2>\n"); result.append("<table class=\"month_table\">\n"); result.append("<tr>\n"); counter.setTime( time ); for (int i=0;i<COLUMNS;i++) { if (isExcluded(i)) { counter.add(Calendar.DATE, 1); continue; } int weekday = counter.get(Calendar.DAY_OF_WEEK); if ( counter.getTime().equals( startDate)) { offset = i; } result.append("<td class=\"month_header\" width=\"14%\">"); result.append("<nobr>"); String name = getWeekdayName(weekday); result.append(name); result.append("</nobr>"); result.append("</td>"); counter.add(Calendar.DATE, 1); } result.append("\n</tr>"); for (int row=0; row<=lastRow; row++) { boolean excludeRow = true; // calculate if we can exclude the row for (int column = 0; column<COLUMNS; column ++) { if ( table[row][column] != null && !isExcluded( column )) { excludeRow = false; } } if ( excludeRow ) continue; result.append("<tr>\n"); for (int column = 0; column<COLUMNS; column ++) { if ( isExcluded( column )) { continue; } HTMLSmallDaySlot slot = table[row][column]; if ( slot == null ) { result.append("<td class=\"month_cell\" height=\"40\"></td>\n"); } else { result.append("<td class=\"month_cell\" valign=\"top\" height=\"40\">\n"); slot.paint( result ); result.append("</td>\n"); } } result.append("</tr>\n"); } result.append("</table>"); m_html = result.toString(); } public void addBlock(Block block,int col,int slot) { checkBlock( block ); blockCalendar.setTime(block.getStart()); int day = blockCalendar.get(Calendar.DATE); slots[day-1].putBlock( block ); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview.html; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.SortedSet; import java.util.TreeSet; import org.rapla.components.calendarview.AbstractCalendar; import org.rapla.components.calendarview.Block; import org.rapla.components.calendarview.Builder; public class HTMLWeekView extends AbstractHTMLView { private int endMinutes; private int minMinute; private int maxMinute; private int startMinutes; int m_rowsPerHour = 2; HTMLDaySlot[] multSlots ; ArrayList<Block> blocks = new ArrayList<Block>(); //ArrayList<Integer> blockStart = new ArrayList<Integer>(); //ArrayList<Integer> blockSize = new ArrayList<Integer>(); String weeknumber; /** The granularity of the selection rows. * <ul> * <li>1: 1 rows per hour = 1 Hour</li> * <li>2: 2 rows per hour = 1/2 Hour</li> * <li>3: 3 rows per hour = 20 Minutes</li> * <li>4: 4 rows per hour = 15 Minutes</li> * <li>6: 6 rows per hour = 10 Minutes</li> * <li>12: 12 rows per hour = 5 Minutes</li> * </ul> * Default is 2. */ public void setRowsPerHour(int rows) { m_rowsPerHour = rows; } public int getRowsPerHour() { return m_rowsPerHour; } public void setWorktime(int startHour, int endHour) { this.startMinutes = startHour * 60; this.endMinutes = endHour * 60; } public void setWorktimeMinutes(int startMinutes, int endMinutes) { this.startMinutes = startMinutes; this.endMinutes = endMinutes; } public void setToDate(Date weekDate) { calcMinMaxDates( weekDate ); } public Collection<Block> getBlocks() { return blocks; } /** must be called after the slots are filled*/ protected boolean isEmpty( int column) { return multSlots[column].isEmpty(); } protected int getColumnCount() { return getDaysInView(); } public void rebuild() { int columns = getColumnCount(); blocks.clear(); multSlots = new HTMLDaySlot[columns]; String[] headerNames = new String[columns]; for (int i=0;i<columns;i++) { String headerName = createColumnHeader(i); headerNames[i] = headerName; } // calculate the blocks int start = startMinutes; int end = endMinutes; minuteBlock.clear(); Iterator<Builder> it= builders.iterator(); while (it.hasNext()) { Builder b= it.next(); b.prepareBuild(getStartDate(),getEndDate()); start = Math.min(b.getMinMinutes(),start); end = Math.max(b.getMaxMinutes(),end); if (start<0) throw new IllegalStateException("builder.getMin() is smaller than 0"); if (end>24*60) throw new IllegalStateException("builder.getMax() is greater than 24"); } minMinute = start ; maxMinute = end ; for (int i=0;i<multSlots.length;i++) { multSlots[i] = new HTMLDaySlot(2); } it= builders.iterator(); while (it.hasNext()) { Builder b= it.next(); if (b.isEnabled()) { b.build(this); } } StringBuffer result = new StringBuffer(); result.append("<table class=\"week_table\">\n"); result.append("<tbody>"); result.append("<tr>\n"); result.append("<th class=\"week_number\">"+weeknumber+"</th>"); for (int i=0;i<multSlots.length;i++) { if ( isExcluded ( i ) ) continue; result.append("<td class=\"week_header\" colspan=\""+ (Math.max(1,multSlots[i].size()) * 2 + 1) + "\">"); result.append("<nobr>"); result.append(headerNames[i]); result.append("</nobr>"); result.append("</td>"); } result.append("\n</tr>"); result.append("<tr></tr>"); boolean useAM_PM = org.rapla.components.calendarview.AbstractCalendar.isAmPmFormat( locale ); int firstEventMarkerId = 7; boolean firstEventMarkerSet = false; for (int minuteOfDay = minMinute;minuteOfDay<maxMinute;minuteOfDay++) { boolean isLine = (minuteOfDay ) % (60 / m_rowsPerHour) == 0; if ( isLine || minuteOfDay == minMinute) { minuteBlock.add( minuteOfDay); } } for (Integer minuteOfDay:minuteBlock) { if ( minuteBlock.last().equals( minuteOfDay)) { break; } //System.out.println("Start row " + row / m_rowsPerHour + ":" + row % m_rowsPerHour +" " + timeString ); result.append("<tr>\n"); boolean fullHour = (minuteOfDay) % 60 == 0; boolean isLine = (minuteOfDay ) % (60 / m_rowsPerHour) == 0; if ( fullHour || minuteOfDay == minMinute) { int rowspan = calcRowspan(minuteOfDay, ((minuteOfDay / 60) + 1) * 60); String timeString = formatTime(minuteOfDay, useAM_PM); result.append("<th class=\"week_times\" rowspan=\""+ rowspan +"\"><nobr>"); result.append(timeString); result.append("</nobr>"); result.append(" &#160;</th>\n"); } for (int day=0;day<columns;day++) { if (isExcluded(day)) continue; if (multSlots[day].size() == 0) { // Rapla 1.4: Make line for full hours darker than others if (fullHour ) { result.append("<td class=\"week_smallseparatorcell_black\">&nbsp;</td>"); result.append("<td class=\"week_emptycell_black\">&nbsp;</td>\n"); } else if (isLine) { result.append("<td class=\"week_smallseparatorcell\">&nbsp;</td>"); result.append("<td class=\"week_emptycell\">&nbsp;</td>\n"); } else { result.append("<td class=\"week_smallseparatornolinecell\">&nbsp;</td>"); result.append("<td class=\"week_emptynolinecell\">&nbsp;</td>\n"); } } else if ( firstEventMarkerSet) { firstEventMarkerId = day; } for (int slotnr = 0; slotnr < multSlots[day].size(); slotnr++) { // Rapla 1.4: Make line for full hours darker than others if (fullHour) { result.append("<td class=\"week_smallseparatorcell_black\">&nbsp;</td>"); } else if (isLine) { result.append("<td class=\"week_smallseparatorcell\">&nbsp;</td>"); } else { result.append("<td class=\"week_smallseparatornolinecell\"></td>"); } Slot slot = multSlots[day].getSlotAt(slotnr); Block block = slot.getBlock(minuteOfDay); if ( block != null) { blockCalendar.setTime( block.getEnd()); int endMinute = Math.min(maxMinute,blockCalendar.get(Calendar.HOUR_OF_DAY) * 60 + blockCalendar.get(Calendar.MINUTE)); int rowspan = calcRowspan(minuteOfDay, endMinute); result.append("<td valign=\"top\" class=\"week_block\""); result.append(" rowspan=\"" + rowspan + "\"" ); if (block instanceof HTMLBlock) result.append(" style=\"background-color:" + ((HTMLBlock) block).getBackgroundColor() + "\""); result.append(">"); printBlock(result, firstEventMarkerId, block); result.append("</td>"); slot.setLastEnd( endMinute); } else { // skip ? if (slot.getLastEnd() > minuteOfDay) { // Do nothing } else { // Rapla 1.4: Make line for full hours darker than others if (fullHour )//|| (!slot.isEmpty(row-1) && (row-minRow) > 0)) { result.append("<td class=\"week_emptycell_black\">&nbsp;</td>\n"); } else if (isLine) { result.append("<td class=\"week_emptycell\">&nbsp;</td>\n"); } else { result.append("<td class=\"week_emptynolinecell\"></td>\n"); } } } } // Rapla 1.4: Make line for full hours darker than others if (fullHour) { result.append("<td class=\"week_separatorcell_black\">&nbsp;</td>"); } else if ( isLine) { result.append("<td class=\"week_separatorcell\">&nbsp;</td>"); } else { result.append("<td class=\"week_separatornolinecell\"></td>\n"); } } result.append("\n</tr>\n"); } result.append("</tbody>"); result.append("</table>\n"); m_html = result.toString(); } private int calcRowspan(int start, int end) { if ( start == end) { return 0; } SortedSet<Integer> tailSet = minuteBlock.tailSet( start); int col = 0; for (Integer minute:tailSet) { if ( minute< end) { col++; } else { break; } } return col; } public String getWeeknumber() { return weeknumber; } public void setWeeknumber(String weeknumber) { this.weeknumber = weeknumber; } protected void printBlock(StringBuffer result, @SuppressWarnings("unused") int firstEventMarkerId, Block block) { String string = block.toString(); result.append(string); } protected String createColumnHeader(int i) { blockCalendar.setTime(getStartDate()); blockCalendar.add(Calendar.DATE, i); String headerName = AbstractCalendar.formatDayOfWeekDateMonth (blockCalendar.getTime() ,locale ,timeZone ); return headerName; } SortedSet<Integer> minuteBlock = new TreeSet<Integer>(); public void addBlock(Block block,int column,int slot) { checkBlock ( block ); HTMLDaySlot multiSlot =multSlots[column]; blockCalendar.setTime( block.getStart()); int startMinute = Math.max(minMinute,( blockCalendar.get(Calendar.HOUR_OF_DAY)* 60 + blockCalendar.get(Calendar.MINUTE) )); blockCalendar.setTime(block.getEnd()); int endMinute = (Math.min(maxMinute, blockCalendar.get(Calendar.HOUR_OF_DAY)* 60 + blockCalendar.get(Calendar.MINUTE) )); blocks.add(block); // startBlock.add( startMinute); // endBlock.add( endMinute); minuteBlock.add( startMinute); minuteBlock.add( endMinute); multiSlot.putBlock( block, slot, startMinute); } private String formatTime(int minuteOfDay,boolean useAM_PM) { blockCalendar.set(Calendar.MINUTE, minuteOfDay%60); int hour = minuteOfDay/60; blockCalendar.set(Calendar.HOUR_OF_DAY, hour); SimpleDateFormat format = new SimpleDateFormat(useAM_PM ? "h:mm" : "H:mm", locale); format.setTimeZone(blockCalendar.getTimeZone()); if (useAM_PM && hour == 12 && minuteOfDay%60 == 0) { return format.format(blockCalendar.getTime()) + " PM"; } else { return format.format(blockCalendar.getTime()); } } protected class HTMLDaySlot extends ArrayList<Slot> { private static final long serialVersionUID = 1L; private boolean empty = true; public HTMLDaySlot(int size) { super(size); } public void putBlock(Block block,int slotnr, int startMinute) { while (slotnr >= size()) { addSlot(); } getSlotAt(slotnr).putBlock( block, startMinute); empty = false; } public int addSlot() { Slot slot = new Slot(); add(slot); return size(); } public Slot getSlotAt(int index) { return get(index); } public boolean isEmpty() { return empty; } } protected class Slot { // int[] EMPTY = new int[]{-2}; // int[] SKIP = new int[]{-1}; int lastEnd = 0; HashMap<Integer, Block> map = new HashMap<Integer, Block>(); public Slot() { } public void putBlock( Block block, int startMinute) { map.put( startMinute, block); } Block getBlock(Integer startMinute) { return map.get( startMinute); } public int getLastEnd() { return lastEnd; } public void setLastEnd(int lastEnd) { this.lastEnd = lastEnd; } } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview.html; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.rapla.components.calendarview.AbstractCalendar; import org.rapla.components.calendarview.Block; import org.rapla.components.calendarview.Builder; import org.rapla.components.util.DateTools; public class HTMLCompactWeekView extends AbstractHTMLView { public final static int ROWS = 6; //without the header row /** shared calendar instance. Only used for temporary stored values. */ HTMLSmallDaySlot[] slots = {}; String[] slotNames = {}; private ArrayList<List<Block>> rows = new ArrayList<List<Block>>(); Map<Block, Integer> columnMap = new HashMap<Block, Integer>(); private double leftColumnSize = 0.1; String weeknumber = ""; public String getWeeknumber() { return weeknumber; } public void setWeeknumber(String weeknumber) { this.weeknumber = weeknumber; } public void setLeftColumnSize(double leftColumnSize) { this.leftColumnSize = leftColumnSize; } public void setSlots( String[] slotNames ) { this.slotNames = slotNames; } public Collection<Block> getBlocks() { ArrayList<Block> list = new ArrayList<Block>(); for (int i=0;i<slots.length;i++) { list.addAll(slots[i]); } return Collections.unmodifiableCollection( list ); } /** must be called after the slots are filled*/ protected boolean isEmpty( int column) { HTMLSmallDaySlot slot = slots[column]; return slot.isEmpty(); } public void rebuild() { List<String> headerNames; int columns = getColumnCount(); headerNames = getHeaderNames(); columnMap.clear(); rows.clear(); for ( int i=0; i<slotNames.length; i++ ) { addRow(); } // calculate the blocks Iterator<Builder> it= builders.iterator(); while (it.hasNext()) { Builder b= it.next(); b.prepareBuild(getStartDate(),getEndDate()); } // build Blocks it= builders.iterator(); while (it.hasNext()) { Builder b= it.next(); if (b.isEnabled()) { b.build(this); } } Calendar calendar = createCalendar(); calendar.setTime(getStartDate()); calendar.set( Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek()); // resource header // add headers StringBuffer result = new StringBuffer(); result.append("<table class=\"month_table\">\n"); result.append("<tr>\n"); result.append("<td class=\"week_number\" width=\"" + Math.round(getLeftColumnSize() * 100) + "%\">"); result.append(weeknumber); result.append("</td>"); String percentage = "" + Math.round(columns); int rowsize = rows.size(); slots = new HTMLSmallDaySlot[rowsize * columns]; for (int row=0;row<rowsize;row++) { for (int column=0;column < columns; column++) { List<Block> blocks = rows.get( row ); int fieldNumber = row * columns + column; slots[fieldNumber] = createField( blocks, column ); } } for (int i=0;i<columns;i++) { if (isExcluded(i)) { continue; } result.append("<td class=\"month_header\" width=\""+percentage + "%\">"); result.append("<nobr>"); result.append(headerNames.get(i)); result.append("</nobr>"); result.append("</td>"); } result.append("\n</tr>"); for (int row=0;row<rowsize;row++) { result.append("<tr>\n"); result.append("<td class=\"month_cell\" valign=\"top\" height=\"40\">\n"); if ( slotNames.length > row ) { result.append( slotNames[ row ] ); } result.append("</td>\n"); for (int column=0;column < columns; column++) { int fieldNumber = row * columns + column; if ( !isExcluded( column ) ) { result.append("<td class=\"month_cell\" valign=\"top\" height=\"40\">\n"); slots[fieldNumber].paint( result ); result.append("</td>\n"); } } result.append("</tr>\n"); } result.append("</table>"); m_html = result.toString(); } protected List<String> getHeaderNames() { List<String> headerNames = new ArrayList<String>(); blockCalendar.setTime(getStartDate()); int columnCount = getColumnCount(); for (int i=0;i<columnCount;i++) { headerNames.add (AbstractCalendar.formatDayOfWeekDateMonth (blockCalendar.getTime() ,locale ,timeZone )); blockCalendar.add(Calendar.DATE, 1); } return headerNames; } public double getLeftColumnSize() { return leftColumnSize ; } protected int getColumnCount() { return getDaysInView(); } private HTMLSmallDaySlot createField(List<Block> blocks, int column) { HTMLSmallDaySlot c = new HTMLSmallDaySlot(""); c.setStart(DateTools.addDays( getStartDate(), column)); if ( blocks != null) { Iterator<Block> it = blocks.iterator(); while (it.hasNext()){ HTMLBlock block = (HTMLBlock)it.next(); if (columnMap.get( block) == column) { c.putBlock( block ); } } } c.sort(); return c; } public void addBlock(Block block, int column,int slot) { checkBlock( block ); while ( rows.size() <= slot ) { addRow(); } List<Block> blocks = rows.get( slot ); blocks.add( block ); columnMap.put(block, column); } private void addRow() { rows.add( rows.size(), new ArrayList<Block>()); } }
Java
package org.rapla.components.calendarview.html; import org.rapla.components.calendarview.Block; public interface HTMLBlock extends Block { String getBackgroundColor(); String toString(); }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview; import java.util.List; public interface BuildStrategy { public void build(CalendarView wv,List<Block> blocks); }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.rapla.components.util.DateTools; /** Arranges blocks into groups, and tries to place one group into one slot. The subclass must overide the group method to perform the grouping on a given list of blocks. */ public abstract class AbstractGroupStrategy implements BuildStrategy { boolean m_sortSlotsBySize; public static long MILLISECONDS_PER_DAY = 24 * 3600 * 1000; private boolean m_fixedSlots; private boolean m_conflictResolving; protected Comparator<Block> blockComparator = new BlockComparator(); protected Comparator<List<Block>> slotComparator = new Comparator<List<Block>>() { public int compare(List<Block> s1,List<Block> s2) { if (s1.size() == 0 || s2.size() ==0) { if (s1.size() == s2.size()) return 0; else return s1.size() < s2.size() ? -1 : 1; } Block b1 = s1.get(0); Block b2 = s2.get(0); return b1.getStart().compareTo(b2.getStart()); } }; public void build(CalendarView wv, List<Block> blocks) { LinkedHashMap<Integer,List<Block>> days = new LinkedHashMap<Integer,List<Block>>(); Map<Block, Integer> blockMap = getBlockMap(wv, blocks); for (Block b:blockMap.keySet()) { Integer index = blockMap.get(b); List<Block> list = days.get(index); if (list == null) { list = new ArrayList<Block>(); days.put(index, list); } list.add(b); } for (Integer day: days.keySet()) { List<Block> list = days.get(day); Collections.sort(list, blockComparator); if (list == null) continue; insertDay( wv, day,list ); } } protected Map<Block,Integer> getBlockMap(CalendarView wv, List<Block> blocks) { Map<Block,Integer> map = new LinkedHashMap<Block, Integer>(); Date startDate = wv.getStartDate(); for (Block block:blocks) { int days = (int)DateTools.countDays(startDate, block.getStart()); map.put(block, days); } return map; } protected void insertDay(CalendarView wv, int column,List<Block> blockList) { Iterator<List<Block>> it = getSortedSlots(blockList).iterator(); int slotCount= 0; while (it.hasNext()) { List<Block> slot = it.next(); if (slot == null) { continue; } for (int i=0;i<slot.size();i++) { wv.addBlock(slot.get(i),column,slotCount); } slotCount ++; } } /** You can split the blockList into different groups. * This method returns a collection of lists. * Each list represents a group * of blocks. * @return a collection of List-objects * @see List * @see Collection */ abstract protected Collection<List<Block>> group(List<Block> blockList); public boolean isSortSlotsBySize() { return m_sortSlotsBySize; } public void setSortSlotsBySize(boolean enable) { m_sortSlotsBySize = enable; } /** takes a block list and returns a sorted slotList */ protected List<List<Block>> getSortedSlots(List<Block> blockList) { Collection<List<Block>> group = group(blockList); List<List<Block>> slots = new ArrayList<List<Block>>(group); if ( isResolveConflictsEnabled()) { resolveConflicts(slots); } if ( !isFixedSlotsEnabled() ) { mergeSlots(slots); } if (isSortSlotsBySize()) Collections.sort(slots, slotComparator); return slots; } protected boolean isCollision(Block b1, Block b2) { final long start1 = b1.getStart().getTime(); long minimumLength = DateTools.MILLISECONDS_PER_MINUTE * 5; final long end1 = Math.max(start1+ minimumLength,b1.getEnd().getTime()); final long start2 = b2.getStart().getTime(); final long end2 = Math.max(start2 + minimumLength,b2.getEnd().getTime()); boolean result = start1 < end2 && start2 <end1 ; return result; } private void resolveConflicts(List<List<Block>> groups) { int pos = 0; while (pos < groups.size()) { List<Block> group = groups.get(pos++ ); List<Block> newSlot = null; int i = 0; while (i< group.size()) { Block element1 = group.get( i++ ); int j = i; while (j< group.size()) { Block element2 = group.get( j ++); if ( isCollision( element1, element2 ) ) { group.remove( element2 ); j --; if (newSlot == null) { newSlot = new ArrayList<Block>(); groups.add(pos, newSlot); } newSlot.add( element2); } } } } } /** the lists must be sorted */ private boolean canMerge(List<Block> slot1,List<Block> slot2) { int size1 = slot1.size(); int size2 = slot2.size(); int i = 0; int j = 0; while (i<size1 && j < size2) { Block b1 = slot1.get(i); Block b2 = slot2.get(j); if (isCollision( b1, b2)) return false; if ( b1.getStart().before( b2.getStart() )) i ++; else j ++; } return true; } /** merge two slots */ private void mergeSlots(List<List<Block>> slots) { // We use a (sub-optimal) greedy algorithm for merging slots int pos = 0; while (pos < slots.size()) { List<Block> slot1 = slots.get(pos ++); for (int i= pos; i<slots.size(); i++) { List<Block> slot2 = slots.get(i); if (canMerge(slot1, slot2)) { slot1.addAll(slot2); Collections.sort(slot1, blockComparator); slots.remove(slot2); pos --; break; } } } } public void setFixedSlotsEnabled( boolean enable) { m_fixedSlots = enable; } public boolean isFixedSlotsEnabled() { return m_fixedSlots; } /** enables or disables conflict resolving. If turned on and 2 blocks ocupy the same slot, * a new slot will be inserted dynamicly * @param enable */ public void setResolveConflictsEnabled( boolean enable) { m_conflictResolving = enable; } public boolean isResolveConflictsEnabled() { return m_conflictResolving; } public Comparator<Block> getBlockComparator() { return blockComparator; } public void setBlockComparator(Comparator<Block> blockComparator) { this.blockComparator = blockComparator; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview.swing; import java.awt.Component; import java.awt.Point; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.Date; import javax.swing.SwingUtilities; /** SelectionHandler handles the selection events and the Slot * Context Menu (right click). * This is internally used by the weekview to communicate with its slots. */ public class SelectionHandler extends MouseAdapter { Date start; Date end; boolean bPopupClicked = false; boolean bSelecting = false; public int selectionStart = -1; public int selectionEnd = -1; private int oldIndex = -1; private int oldSlotNr = -1; private int startSlot = -1; private int endSlot = -1; private int draggingSlot = -1; private int draggingIndex = -1; AbstractSwingCalendar m_wv; public enum SelectionStrategy { FLOW,BLOCK; } SelectionStrategy selectionStrategy = SelectionStrategy.FLOW; public SelectionHandler(AbstractSwingCalendar wv) { m_wv = wv; } public void mouseClicked(MouseEvent evt) { if (evt.isPopupTrigger()) { bPopupClicked = true; slotPopup(evt); } else { /* We don't check click here if (SwingUtilities.isLeftMouseButton(evt)) move(evt); */ } } public void mousePressed(MouseEvent evt) { if (evt.isPopupTrigger()) { bPopupClicked = true; move(evt, true); slotPopup(evt); } else { if (SwingUtilities.isLeftMouseButton(evt)) move(evt,false); } } public void mouseReleased(MouseEvent evt) { if (evt.isPopupTrigger()) { bPopupClicked = true; move(evt, true); slotPopup(evt); } if (SwingUtilities.isLeftMouseButton(evt) && !bPopupClicked) move(evt, false); bPopupClicked = false; bSelecting = false; } public void mouseDragged(MouseEvent evt) { if (SwingUtilities.isLeftMouseButton(evt) && !bPopupClicked) move(evt, false); } public void mouseMoved(MouseEvent evt) { } public void setSelectionStrategy(SelectionStrategy strategy) { selectionStrategy = strategy; } public void clearSelection() { for (int i=0;i<m_wv.getDayCount();i++) { if (m_wv.getSlot(i) != null) { m_wv.getSlot(i).unselectAll(); } } selectionStart = -1; selectionEnd = -1; oldIndex = -1; oldSlotNr = -1; startSlot = -1; endSlot = -1; draggingSlot = -1; draggingIndex = -1; } public void slotPopup(MouseEvent evt) { Point p = new Point(evt.getX(),evt.getY()); DaySlot slot= (DaySlot)evt.getSource(); if (start == null || end == null) { int index = slot.calcRow( evt.getY() ); start = m_wv.createDate(slot, index, true); end = m_wv.createDate(slot, index, false); clearSelection(); slot.select(index,index); } m_wv.fireSelectionPopup((Component)slot,p,start,end,m_wv.getSlotNr( slot )); } public void move(MouseEvent evt, boolean contextPopup) { if (!m_wv.isEditable()) return; DaySlot source = (DaySlot) evt.getSource(); int slotNr; { Point location = source.getLocation(); slotNr = m_wv.calcSlotNr( location.x + evt.getX() ,location.y + evt.getY() ); } if (slotNr == -1) return; int selectedIndex = source.calcRow(evt.getY()); if ( contextPopup && inCurrentSelection(slotNr,selectedIndex)) { return; } if (!bSelecting) { clearSelection(); bSelecting = true; selectionStart = selectedIndex; selectionEnd = selectedIndex; draggingSlot =slotNr; draggingIndex = selectedIndex; startSlot = slotNr; endSlot = slotNr; } else { if (slotNr == draggingSlot) { startSlot = endSlot = slotNr; if ( selectedIndex > draggingIndex ) { selectionStart = draggingIndex; selectionEnd = selectedIndex; } else if (selectedIndex < draggingIndex ){ selectionStart = selectedIndex; selectionEnd = draggingIndex; } } else if (slotNr > draggingSlot) { startSlot = draggingSlot; selectionStart = draggingIndex; endSlot = slotNr; selectionEnd = selectedIndex; } else if (slotNr < draggingSlot) { startSlot = slotNr; selectionStart = selectedIndex; endSlot = draggingSlot; selectionEnd = draggingIndex; } if (selectedIndex == oldIndex && slotNr == oldSlotNr) { return; } int rowsPerDay = m_wv.getRowsPerDay(); if (selectedIndex >= rowsPerDay-1) { selectedIndex = rowsPerDay-1; } } oldSlotNr = slotNr; oldIndex = selectedIndex; switch ( selectionStrategy) { case BLOCK: setSelectionBlock();break; case FLOW: setSelectionFlow();break; } { Point location = m_wv.getSlot(slotNr).getLocation(); m_wv.scrollTo( location.x + evt.getX() ,location.y + evt.getY() ); } } private boolean inCurrentSelection(int slotNr, int selectedIndex) { if ( slotNr < startSlot || slotNr > endSlot) { return false; } if (slotNr == startSlot && selectedIndex < selectionStart) { return false; } if (slotNr == endSlot && selectedIndex > selectionEnd) { return false; } return true; } protected void setSelectionFlow() { int startRow = selectionStart; int endRow = m_wv.getRowsPerDay() -1; for (int i=0;i<startSlot;i++) { DaySlot daySlot = m_wv.getSlot(i); if (daySlot != null) { daySlot.unselectAll(); } } int dayCount = m_wv.getDayCount(); for (int i=startSlot;i<=endSlot;i++) { if (i > startSlot) { startRow = 0; } if (i == endSlot) { endRow = selectionEnd; } DaySlot slot = m_wv.getSlot(i); if (slot != null) { slot.select(startRow,endRow); } } startRow = selectionStart ; endRow = selectionEnd ; for (int i=endSlot+1;i<dayCount;i++) { DaySlot slot = m_wv.getSlot(i); if (slot != null) { slot.unselectAll(); } } start = m_wv.createDate(m_wv.getSlot(startSlot),startRow, true); end = m_wv.createDate(m_wv.getSlot(endSlot),endRow, false); m_wv.fireSelectionChanged(start,end); } protected void setSelectionBlock() { int startRow = selectionStart; int endRow = selectionEnd; Point endSlotLocation = m_wv.getSlot(endSlot).getLocation(); Point startSlotLocation = m_wv.getSlot(startSlot).getLocation(); int min_y = Math.min(startSlotLocation.y, endSlotLocation.y); int min_x = Math.min(startSlotLocation.x, endSlotLocation.x); int max_y = Math.max(startSlotLocation.y, endSlotLocation.y); int max_x = Math.max(startSlotLocation.x, endSlotLocation.x); int dayCount = m_wv.getDayCount(); for (int i=0;i<dayCount;i++) { DaySlot slot = m_wv.getSlot(i); if (slot != null) { Point location = slot.getLocation(); if ( location.x >= min_x && location.x <= max_x && location.y >= min_y && location.y <= max_y) { slot.select(startRow,endRow); } else { slot.unselectAll(); } } } start = m_wv.createDate(m_wv.getSlot(startSlot),startRow, true); end = m_wv.createDate(m_wv.getSlot(endSlot),endRow, false); m_wv.fireSelectionChanged(start,end); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview.swing; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Rectangle; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Locale; import javax.swing.JComponent; import org.rapla.components.calendarview.AbstractCalendar; /** A vertical scale displaying the hours of day. Uses am/pm notation * in the appropriate locale. */ public class TimeScale extends JComponent { private static final long serialVersionUID = 1L; private int pixelPerHour = 60; private int mintime; private int maxtime; private boolean useAM_PM = false; private Font fontLarge= new Font("SansSerif", Font.PLAIN, 14); private Font fontSmall= new Font("SansSerif", Font.PLAIN, 9); private FontMetrics fm1 = getFontMetrics(fontLarge); private FontMetrics fm2 = getFontMetrics(fontSmall); String[] hours; private int SCALE_WIDTH = 35; private boolean smallSize = false; private int repeat = 1; private String days[] ; public TimeScale() { useAM_PM = AbstractCalendar.isAmPmFormat(Locale.getDefault()); createHours(Locale.getDefault()); } public void setLocale(Locale locale) { if (locale == null) return; useAM_PM = AbstractCalendar.isAmPmFormat(locale); createHours(locale); } /** mintime und maxtime definieren das zeitintevall in vollen stunden. die skalen-einteilung wird um vgap pixel nach unten verschoben (um ggf. zu justieren). */ public void setTimeIntervall(int minHour, int maxHour, int pixelPerHour) { removeAll(); this.mintime = minHour; this.maxtime = maxHour; this.pixelPerHour = pixelPerHour; //setBackground(Color.yellow); //super(JSeparator.VERTICAL); setLayout(null); setPreferredSize(new Dimension( SCALE_WIDTH, (maxHour-minHour + 1) * pixelPerHour * repeat)); } private void createHours(Locale locale) { hours = new String[24]; Calendar cal = Calendar.getInstance(locale); SimpleDateFormat format = new SimpleDateFormat(useAM_PM ? "h" : "H",locale); for (int i=0;i<24;i++) { cal.set(Calendar.HOUR_OF_DAY,i); hours[i] = format.format(cal.getTime()); } } public void setSmallSize(boolean smallSize) { this.smallSize = smallSize; } public void setRepeat(int repeat, String[] days) { this.repeat = repeat; this.days = days; } public void paint(Graphics g) { super.paint(g); int indent[]; int heightHour = (int) fm1.getLineMetrics("12",g).getHeight() ; int heightEnding = (int) fm2.getLineMetrics("12",g).getHeight() ; int current_y ; // Compute indentations FontMetrics fm; String[] indent_string = new String[3] ; if ( days != null ) { indent_string[0] = "M"; indent_string[1] = "M2"; indent_string[2] = "M22"; } else { indent_string[0] = ""; indent_string[1] = "2"; indent_string[2] = "22"; } if ( smallSize ) { fm = fm2; } else { fm = fm1; } indent = new int[3]; for(int i=0; i<3; i++) { indent[i] = fm.stringWidth(indent_string[i]) ; } Rectangle rect = g.getClipBounds(); //System.out.println(mintime + " - " + maxtime); int height = (maxtime - mintime) * pixelPerHour + 1 ; if ( days != null ) { g.drawLine(indent[0]+1,0,indent[0]+1,repeat*height); } for (int r=0; r<repeat; r++) { current_y = height * r; g.drawLine(0,current_y-1,SCALE_WIDTH ,current_y-1); int pad = 0; if ( days != null ) { pad = (maxtime - mintime - days[r].length())/2 ; if ( pad < 0 ) { pad = 0; } } for (int i=mintime; i<maxtime; i++) { int y = current_y + (i - mintime) * pixelPerHour; int hour; String ending; String prefix; if (useAM_PM) { hour = (i == 0) ? 12 : ((i-1)%12 + 1); ending = (i<=11) ? "AM" : "PM"; } else { hour = i; ending = "00"; } if ( days != null && i - mintime < days[r].length() + pad && i - mintime >= pad ) { prefix = days[r].substring(i-mintime-pad,i-mintime+1-pad); } else { prefix = null; } if (y >= rect.y && y <= (rect.y + rect.height)) { g.drawLine(i == mintime ? 0:indent[0]+1,y,SCALE_WIDTH ,y); } // Uncommenting this draws the last line // if (y >= rect.y && y <= (rect.y + rect.height) && i == maxtime-1) { // g.drawLine(0,y+pixelPerHour,SCALE_WIDTH ,y+pixelPerHour); // } if (y >= rect.y -heightHour && y <= (rect.y + rect.height) + heightHour ) { if ( smallSize ) { g.setFont(fontSmall); } else { g.setFont(fontLarge); } if ( prefix != null ) { g.drawString(prefix, (indent[0]-fm.stringWidth(prefix)+1)/2,y + heightEnding); } g.drawString(hours[i],(hour < 10) ? indent[1]+2:indent[0]+2,y + ( smallSize ? heightEnding : heightHour)); if ( !smallSize ) { g.setFont(fontSmall); } g.drawString(ending, indent[2]+2,y + heightEnding); } } } } }
Java
package org.rapla.components.calendarview.swing.scaling; import java.util.Date; public interface IRowScale extends IRowScaleSmall { int calcHour( int index ); int calcMinute( int index ); int getSizeInPixel(); int getMaxRows(); int getRowsPerDay(); int getYCoord( Date time ); int getStartWorktimePixel(); int getEndWorktimePixel(); int getSizeInPixelBetween( int startRow, int endRow ); boolean isPaintRowThick( int row ); }
Java
package org.rapla.components.calendarview.swing.scaling; public class OneRowScale implements IRowScaleSmall { public int getYCoordForRow( int row ) { return 0; } public int getRowSizeForRow( int row ) { return 15; } public int calcRow( int y ) { return 0; } public int trim( int y ) { return 0; } public int getDraggingCorrection( int y) { return 15 / 2; } }
Java
package org.rapla.components.calendarview.swing.scaling; public interface IRowScaleSmall { int getYCoordForRow( int row ); int getRowSizeForRow( int row ); int calcRow( int y ); int trim( int y ); int getDraggingCorrection(int y); }
Java
package org.rapla.components.calendarview.swing.scaling; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; public class VariableRowScale implements IRowScale { PeriodRow[] periodRows; private int hourSize = 60; final private static int MINUTES_PER_HOUR= 60; private TimeZone timeZone = TimeZone.getDefault(); private int mintime =0 ; /* private int maxtime = 24; private int workstart = 0; private int workend = 24; */ class PeriodRow { int minutes; int ypos; int startMinute; PeriodRow( int minutes ) { this.minutes = minutes; } public int getRowSize() { return (minutes * hourSize) / 60; } } public VariableRowScale() { periodRows = new PeriodRow[] { new PeriodRow( 60 * 8 ), new PeriodRow( 45 ), new PeriodRow( 60 ), new PeriodRow( 10 ), new PeriodRow( 110 ), new PeriodRow( 60 + 15), new PeriodRow( 60 * 3 ), new PeriodRow( 60 * 8 ) }; for ( int i=0;i< periodRows.length-1;i++) { periodRows[i+1].ypos = periodRows[i].ypos + periodRows[i].getRowSize(); periodRows[i+1].startMinute = periodRows[i].startMinute + periodRows[i].minutes; } } public void setTimeZone( TimeZone timeZone) { this.timeZone = timeZone; } public int getRowsPerDay() { return periodRows.length; } public int getSizeInPixel() { PeriodRow lastRow = getLastRow(); return lastRow.ypos + lastRow.getRowSize(); } public int getMaxRows() { return periodRows.length; } private int getMinuteOfDay(Date time) { Calendar cal = getCalendar(); cal.setTime(time); return (cal.get(Calendar.HOUR_OF_DAY )) * MINUTES_PER_HOUR + cal.get(Calendar.MINUTE); } public int calcHour(int index) { return periodRows[index].startMinute / MINUTES_PER_HOUR; } public int calcMinute(int index) { return periodRows[index].startMinute % MINUTES_PER_HOUR; } public int getYCoord(Date time) { int diff = getMinuteOfDay(time) - mintime * MINUTES_PER_HOUR ; return (diff * hourSize) / MINUTES_PER_HOUR; } public int getStartWorktimePixel() { return periodRows[0].getRowSize(); } public int getEndWorktimePixel() { PeriodRow lastRow = getLastRow(); return lastRow.ypos; } private PeriodRow getLastRow() { PeriodRow lastRow = periodRows[periodRows.length-1]; return lastRow; } private Calendar calendar = null; private Calendar getCalendar() { // Lazy creation of the calendar if (calendar == null) calendar = Calendar.getInstance(timeZone); return calendar; } public boolean isPaintRowThick( int row ) { return true; } /* public void setTimeIntervall( int startHour, int endHour ) { mintime = startHour; maxtime = endHour; } public void setWorktime( int startHour, int endHour ) { workstart = startHour; workend = endHour; } */ public int getYCoordForRow( int row ) { if ( row < 0 || row >= periodRows.length) { return row* 400; } return periodRows[row].ypos; } public int getSizeInPixelBetween( int startRow, int endRow ) { if ( startRow < 0 || endRow < 0 || startRow >= periodRows.length || endRow >=periodRows.length) { return (endRow - startRow) * 400; } return periodRows[endRow].ypos - periodRows[startRow].ypos; } public int getRowSizeForRow( int row ) { /* if ( row < 0 || row >= periodRows.length) { return 60; } */ return periodRows[row].getRowSize(); } public int calcRow(int y) { for ( int i=0;i< periodRows.length;i++) { PeriodRow row =periodRows[i]; if (row.ypos + row.getRowSize() >=y) return i; } return 0; } public int trim(int y ) { int row = calcRow( y ); int rowSize = getRowSizeForRow( row); return (y / rowSize) * rowSize; } public int getDraggingCorrection(int y) { return 0; } }
Java
package org.rapla.components.calendarview.swing.scaling; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; public class LinearRowScale implements IRowScale { private int rowSize = 15; private int rowsPerHour = 4; final private static int MINUTES_PER_HOUR= 60; private TimeZone timeZone = TimeZone.getDefault(); private int mintime; private int maxtime; private int workstartMinutes; private int workendMinutes; public LinearRowScale() { } public void setTimeZone( TimeZone timeZone) { this.timeZone = timeZone; } public int getRowsPerDay() { return rowsPerHour * 24; } public void setRowSize( int rowSize ) { this.rowSize = rowSize; } public int getRowSize() { return rowSize; } public int getRowsPerHour() { return rowsPerHour; } public void setRowsPerHour( int rowsPerHour ) { this.rowsPerHour = rowsPerHour; } public int calcHour(int index) { return index / rowsPerHour; } public int calcMinute(int index) { double minutesPerRow = 60. / rowsPerHour; long minute = Math.round((index % rowsPerHour) * (minutesPerRow)); return (int)minute; } public int getSizeInPixel() { return rowSize * getMaxRows(); } public int getMaxRows() { int max; max = (rowsPerHour * (maxtime - mintime)) / 60 ; return max; } private int getMinuteOfDay(Date time) { Calendar cal = getCalendar(); cal.setTime(time); return (cal.get(Calendar.HOUR_OF_DAY )) * MINUTES_PER_HOUR + cal.get(Calendar.MINUTE); } public int getYCoord(Date time) { int diff = getMinuteOfDay(time) - mintime ; int pixelPerHour= rowSize * rowsPerHour; return (diff * pixelPerHour) / MINUTES_PER_HOUR; } public int getStartWorktimePixel() { int pixelPerHour= rowSize * rowsPerHour; int starty = (int) (pixelPerHour * workstartMinutes / 60.); return starty; } public int getEndWorktimePixel() { int pixelPerHour= rowSize * rowsPerHour; int endy = (int) (pixelPerHour * workendMinutes / 60.); return endy; } private Calendar calendar = null; private Calendar getCalendar() { // Lazy creation of the calendar if (calendar == null) calendar = Calendar.getInstance(timeZone); return calendar; } public boolean isPaintRowThick( int row ) { return row % rowsPerHour == 0; } public void setTimeIntervall( int startMinutes, int endMinutes ) { mintime = startMinutes; maxtime = endMinutes; } public void setWorktimeMinutes( int workstartMinutes, int workendMinutes ) { this.workstartMinutes = workstartMinutes; this.workendMinutes = workendMinutes; } public int getYCoordForRow( int row ) { return row * rowSize; } public int getSizeInPixelBetween( int startRow, int endRow ) { return (endRow - startRow) * rowSize; } public int getRowSizeForRow( int row ) { return rowSize; } public int calcRow(int y) { int rowsPerDay = getRowsPerDay(); int row = (y-3) / rowSize; return Math.min(Math.max(0, row), rowsPerDay -1); } public int trim(int y ) { return (y / rowSize) * rowSize; } public int getDraggingCorrection( int y) { return rowSize / 2; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview.swing; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Graphics; import java.awt.Point; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.HashMap; import java.util.Map; import javax.swing.JPanel; import javax.swing.UIManager; abstract class AbstractDaySlot extends JPanel implements DaySlot { private static final long serialVersionUID = 1L; private boolean bEditable = true; boolean paintDraggingGrid; int draggingSlot; int draggingY; SwingBlock draggingView; int draggingHeight; protected Map<Object,SwingBlock> blockViewMapper = new HashMap<Object,SwingBlock>(); // BJO 00000076 // protected Method getButtonMethod = null; // BJO 00000076 AbstractDaySlot() { /* // BJO 00000076 try { //is only available sind 1.4 getButtonMethod = MouseEvent.class.getMethod("getButton", new Class[] {}); } catch (Exception ex) { } // BJO 00000076 */ } public void setEditable(boolean b) { bEditable = b; } public boolean isEditable() { return bEditable; } SwingBlock getBlockFor(Object component) { return blockViewMapper.get(component); } protected void showPopup(MouseEvent evt) { Point p = new Point(evt.getX(),evt.getY()); SwingBlock block = getBlockFor(evt.getSource()); if (block != null) draggingHandler.blockPopup(block,p); } protected Color getSelectionColor() { return UIManager.getColor("Table.selectionBackground"); } public void paintDraggingGrid(int slot,int y, int height,SwingBlock draggingView,int oldY,int oldHeight,boolean bPaint) { this.paintDraggingGrid = bPaint; this.draggingSlot = slot; this.draggingY = y; this.draggingHeight = height; this.draggingView = draggingView; this.invalidateDragging(); } public int getX(Component component) { return component.getParent().getLocation().x; } void invalidateDragging() { repaint(); } void setDraggingHandler(DraggingHandler draggingHandler) { this.draggingHandler = draggingHandler; } private DraggingHandler draggingHandler; /** BlockListener handles the dragging events and the Block * Context Menu (right click). */ class BlockListener extends MouseAdapter { boolean preventDragging = false; public void mouseClicked(MouseEvent evt) { if (evt.isPopupTrigger()) { showPopup(evt); } else { if (evt.getClickCount()>1) blockEdit(evt); } //draggingPointOffset = evt.getY(); } private int calcResizeDirection( MouseEvent evt ) { if ( !draggingHandler.supportsResizing()) return 0; int height = ((Component)evt.getSource()).getHeight(); int diff = height- evt.getY() ; if ( diff <= 5 && diff >=0 ) return 1; if (evt.getY() >=0 && evt.getY() < 5) return -1; return 0; } public void mousePressed(MouseEvent evt) { if (evt.isPopupTrigger()) { showPopup(evt); } preventDragging = false; /* // BJO 00000076 //System.out.println ("Button:" +evt.getButton() ); if ( getButtonMethod != null) { try { Integer button = (Integer) getButtonMethod.invoke( evt, new Object [] {}); preventDragging = button.intValue() != 1; } catch (Exception ex) { } } */ preventDragging = evt.getButton() != 1; // BJO 00000076 if ( preventDragging ) return; SwingBlock block = getBlockFor(evt.getSource()); int resizeDirection = calcResizeDirection( evt ); if ( resizeDirection != 0) { draggingHandler.blockBorderPressed( AbstractDaySlot.this,block, evt, resizeDirection ); } } public void mouseReleased(MouseEvent evt) { if (evt.isPopupTrigger()) { showPopup(evt); } preventDragging = false; SwingBlock block = getBlockFor(evt.getSource()); draggingHandler.mouseReleased( AbstractDaySlot.this, block, evt); } public void mouseEntered(MouseEvent evt) { } public void mouseExited(MouseEvent evt) { if ( draggingHandler.isDragging()) return; setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } public void mouseMoved(MouseEvent evt) { if ( draggingHandler.isDragging()) { return; } SwingBlock block = getBlockFor(evt.getSource()); // BJO 00000137 if(!block.isMovable()) return; // BJO 00000137 if ( calcResizeDirection( evt ) == 1 && block.isEndResizable()) { setCursor(Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR)); } else if (calcResizeDirection( evt ) == -1 && block.isStartResizable()){ setCursor(Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR)); } else { setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } } public void mouseDragged(MouseEvent evt) { if ( preventDragging || !isEditable()) return; SwingBlock block = getBlockFor(evt.getSource()); draggingHandler.mouseDragged( AbstractDaySlot.this, block, evt); } private void blockEdit(MouseEvent evt) { SwingBlock block = getBlockFor(evt.getSource()); draggingHandler.blockEdit(block,new Point(evt.getX(),evt.getY())); } } protected void paintDraggingGrid(Graphics g, int x, int y, int width, int height) { /* Rectangle rect = g.getClipBounds(); int startx = draggingView.getView().getX(); int starty = draggingView.getView().getY(); g.setColor(Color.gray); for (int y1=10;y1<height-5; y1+=11) for (int x1=10;x1<width-5; x1+=11) { int x2 = startx + x1; int y2 = starty + y1; if ( x2 >= rect.x && x2 <= rect.x + rect.width && y2 >= rect.y && y2 <= rect.y + rect.height ) g.drawRect(x2,y2,2,2); } */ g.translate( x-1, y-1); if ( draggingView != null) { draggingView.paintDragging( g, width , height +1 ); } g.translate( -(x-1), -(y-1)); } static int count = 0; }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview.swing; import java.awt.Component; import java.awt.Cursor; import java.awt.Point; public interface DaySlot { void paintDraggingGrid(int x,int y, int height,SwingBlock block, int oldY,int oldHeight,boolean bPaint); Point getLocation(); void unselectAll(); int calcRow(int y); int calcSlot(int x); int getX(Component component); void select(int startRow,int endRow); void setCursor(Cursor cursor); }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview.swing; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Insets; import java.awt.Point; import java.awt.Rectangle; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JComponent; import javax.swing.JPanel; import org.rapla.components.calendarview.Block; import org.rapla.components.calendarview.swing.scaling.IRowScale; /** Komponente, welche eine beliebige anzahl von Slot-komponenten zusammenfasst. * die slots koennen zur laufzeit hinzugefuegt oder auch dynamisch bei bedarf *erzeugt werden. sie werden horizontal nebeneinander angeordnet. */ class LargeDaySlot extends AbstractDaySlot { private static final long serialVersionUID = 1L; public static Color THICK_LINE_COLOR = Color.black; public static Color LINE_COLOR = new Color(0xaa, 0xaa, 0xaa); public static Color WORKTIME_BACKGROUND = Color.white; public static Color NON_WORKTIME_BACKGROUND = new Color(0xcc, 0xcc, 0xcc); private List<Slot> slots= new ArrayList<Slot>(); private int slotxsize; private int selectionStart = -1; private int selectionEnd = -1; private int oldSelectionStart = -1; private int oldSelectionEnd = -1; BoxLayout boxLayout1 = new BoxLayout(this, BoxLayout.X_AXIS); int right_gap = 8; int left_gap = 5; int slot_space = 3; JComponent header; IRowScale rowScale; private BlockListener blockListener = new BlockListener(); /** es muss auch noch setTimeIntervall() aufgerufen werden, um die initialisierung fertig zu stellen (wie beim konstruktor von Slot). slotxsize ist die breite der einzelnen slots. "date" legt das Datum fest, fuer welches das Slot anzeigt (Uhrzeit bleibt unberuecksichtigt) */ public LargeDaySlot( int slotxsize ,IRowScale rowScale ,JComponent header) { this.slotxsize= slotxsize; this.rowScale = rowScale; this.header = header; setLayout(boxLayout1); this.add(Box.createHorizontalStrut(left_gap)); addSlot(); setBackground(getBackground()); setAlignmentX(0); setAlignmentY(TOP_ALIGNMENT); this.setBackground(Color.white); } public boolean isBorderVisible() { return true; // return getBackground() != Color.white; } public int getSlotCount() { return slots.size(); } public boolean isSelected() { return selectionStart >=0 ; } public void setVisible(boolean b) { super.setVisible(b); header.setVisible(b); } public JComponent getHeader() { return header; } public int calcSlot(int x) { int slot = ((x - left_gap) / (slotxsize + slot_space)); //System.out.println ( x + " slot " + slot); if (slot<0) slot = 0; if (slot >= slots.size()) slot = slots.size() -1; return slot; } public Collection<Block> getBlocks() { ArrayList<Block> list = new ArrayList<Block>(); for (int i=0;i<slots.size();i++) list.addAll(slots.get(i).getBlocks()); return list; } public void select(int start,int end) { if (start == selectionStart && end == selectionEnd) return; selectionStart = start; selectionEnd = end; invalidateSelection(); } public void unselectAll() { if (selectionStart == -1 || selectionEnd == -1) return; selectionStart = -1; selectionEnd = -1; invalidateSelection(); } public void setTimeIntervall() { Iterator<Slot> it= slots.iterator(); while (it.hasNext()) { Slot slot = it.next(); slot.setTimeIntervall(); } } private int addSlot() { Slot slot= new Slot(); slot.setTimeIntervall(); slots.add(slot); this.add(slot); this.add(Box.createHorizontalStrut(slot_space)); updateHeaderSize(); return slots.size()-1; } public void updateHeaderSize() { Dimension size = header.getPreferredSize(); Dimension newSize = new Dimension(slotxsize * slots.size() //Slotwidth and border + slot_space * slots.size() //Space between Slots + left_gap + right_gap // left and right gap , (int)size.getHeight()); header.setPreferredSize(newSize); header.setMaximumSize(newSize); header.invalidate(); } /** fuegt einen block im gewuenschten slot ein (konflikte werden ignoriert). */ public void putBlock(SwingBlock bl, int slotnr) { while (slotnr >= slots.size()) { addSlot(); } slots.get(slotnr).putBlock(bl); // The blockListener can be shared among all blocks, // as long es we can only click on one block simultanously bl.getView().addMouseListener(blockListener); bl.getView().addMouseMotionListener(blockListener); blockViewMapper.put(bl.getView(),bl); } public Dimension getMinimumSize() { return getPreferredSize(); } public Dimension getMaximumSize() { return getPreferredSize(); } Insets insets = new Insets(0,0,0, right_gap); Insets slotInsets = new Insets(0,0,0,0); public Insets getInsets() { return insets; } SwingBlock getBlockFor(Object component) { return blockViewMapper.get(component); } int getBlockCount() { int count = 0; Iterator<Slot> it = slots.iterator(); while (it.hasNext()) count += it.next().getBlockCount(); return count; } boolean isEmpty() { return getBlockCount() == 0; } protected void invalidateDragging(Point oldPoint) { int width = getSize().width; int startRow = Math.min(calcRow(draggingY),calcRow(oldPoint.y )); int endRow = Math.max(calcRow(draggingY),calcRow(oldPoint.y )) + 1; repaint(0 , rowScale.getYCoordForRow(startRow) -10 , width , rowScale.getSizeInPixelBetween(startRow, endRow) + draggingHeight + 20 ); } private void invalidateSelection() { int width = getSize().width; int startRow = Math.min(selectionStart,oldSelectionStart); int endRow = Math.max(selectionEnd,oldSelectionEnd) + 1; repaint(0,rowScale.getYCoordForRow(startRow ), width, rowScale.getSizeInPixelBetween(startRow, endRow )); // Update the values after calling repaint, because paint needs the old values. oldSelectionStart = selectionStart; oldSelectionEnd = selectionEnd; } public void paint(Graphics g) { Dimension dim = getSize(); Rectangle rect = g.getClipBounds(); if (!isEditable()) { g.setColor(Color.white); g.fillRect(rect.x ,rect.y ,rect.width ,rect.height); } else { int starty = rowScale.getStartWorktimePixel(); int endy = rowScale.getEndWorktimePixel(); int height = rowScale.getSizeInPixel(); Color firstColor = NON_WORKTIME_BACKGROUND; Color secondColor = WORKTIME_BACKGROUND; if ( starty >= endy) { int c = starty; starty = endy; endy = c; secondColor = NON_WORKTIME_BACKGROUND; firstColor = WORKTIME_BACKGROUND; } if (rect.y - rect.height <= starty) { g.setColor( firstColor ); g.fillRect(rect.x ,Math.max(rect.y,0) ,rect.width ,Math.min(rect.height,starty)); } if (rect.y + rect.height >= starty && rect.y <= endy ) { g.setColor( secondColor ); g.fillRect(rect.x ,Math.max(rect.y,starty) ,rect.width ,Math.min(rect.height,endy - starty)); } if (rect.y + rect.height >= endy) { g.setColor( firstColor ); g.fillRect(rect.x ,Math.max(rect.y,endy) ,rect.width ,Math.min(rect.height, height - endy)); } } if (isBorderVisible()) { g.setColor(LINE_COLOR); g.drawLine(0,rect.y,0,rect.y + rect.height); g.drawLine(dim.width - 1,rect.y,dim.width - 1 ,rect.y + rect.height); } int max = rowScale.getMaxRows() ; // Paint selection for (int i=0; i < max ; i++) { int rowSize = rowScale.getRowSizeForRow( i); int y = rowScale.getYCoordForRow( i); if ((y + rowSize) >= rect.y && y < (rect.y + rect.height)) { if (i>= selectionStart && i<=selectionEnd) { g.setColor(getSelectionColor()); g.fillRect(Math.max (rect.x,1) , y , Math.min (rect.width,dim.width - Math.max (rect.x,1) - 1) , rowSize); } boolean bPaintRowThick = (rowScale.isPaintRowThick(i)); g.setColor((bPaintRowThick) ? THICK_LINE_COLOR : LINE_COLOR); if (isEditable() || (bPaintRowThick && (i<max || isBorderVisible()))) g.drawLine(rect.x,y ,rect.x + rect.width , y); if ( i == max -1 ) { g.setColor( THICK_LINE_COLOR ); g.drawLine(rect.x,y+rowSize ,rect.x + rect.width , y+rowSize); } } } super.paintChildren(g); if ( paintDraggingGrid ) { int x = draggingSlot * (slotxsize + slot_space) + left_gap; paintDraggingGrid(g, x , draggingY, slotxsize -1, draggingHeight); } } /** grafische komponente, in die implementierungen von Block (genauer deren zugehoerige BlockViews) eingefuegt werden koennen. * entsprechend start- und end-zeit des blocks wird der view * im slot dargestellt. die views werden dabei vertikal angeordnet. */ class Slot extends JPanel { private static final long serialVersionUID = 1L; private Collection<Block> blocks= new ArrayList<Block>(); public Slot() { setLayout(null); setBackground(Color.white); setOpaque(false); } /** legt fest, fuer welches zeitintervall das slot gelten soll. (Beispiel 8:00 - 13:00) min und max sind uhrzeiten in vollen stunden. zur initialisierung der komponente muss diese methode mindestens einmal aufgerufen werden. */ public void setTimeIntervall() { int ysize= rowScale.getSizeInPixel() + 1; setSize(slotxsize, ysize); Dimension preferredSize = new Dimension(slotxsize, ysize ); setPreferredSize(preferredSize ); setMinimumSize(preferredSize ); } /** fuegt b in den Slot ein. */ public void putBlock(SwingBlock b) { blocks.add(b); add(b.getView()); updateBounds(b); } public void updateBounds(SwingBlock b) { //update bounds int y1= rowScale.getYCoord(b.getStart()); final int minimumSize = 15; int y2= Math.max( y1+minimumSize,rowScale.getYCoord(b.getEnd())); if ( y1 < 0) y1 = 0; if ( y2 > getMaximumSize().height) y2 = getMaximumSize().height; b.getView().setBounds(0, y1, slotxsize, y2 - y1 + 1); } public int getBlockCount() { return blocks.size(); } public Dimension getMinimumSize() { return getPreferredSize(); } public Dimension getMaximumSize() { return getPreferredSize(); } public Insets getInsets() { return slotInsets; } public Collection<Block> getBlocks() { return blocks; } } void updateSize(int slotsize) { this.slotxsize = slotsize; for ( Slot slot:slots) { slot.setTimeIntervall(); for (Block block:slot.getBlocks()) { slot.updateBounds((SwingBlock)block); } } updateHeaderSize(); } public int calcRow( int y ) { return rowScale.calcRow( y); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview.swing; import java.awt.Component; import java.awt.Point; import java.util.Date; import org.rapla.components.calendarview.Block; /** Listeners for user-changes in the weekview.*/ public interface ViewListener { /** Invoked when the user invokes the slot-contex (right-clicks on slot). The selected area and suggested coordinates at which the popup menu can be shown are passed.*/ void selectionPopup(Component slotComponent,Point p,Date start,Date end, int slotNr); /** Invoked when the selection has changed.*/ void selectionChanged(Date start,Date end); /** Invoked when the user invokes a block-context (right-clicks on a block). The suggested coordinates at which the popup menu can be shown are passed.*/ void blockPopup(Block block,Point p); /** Invoked when the user invokes a block-edit (double-clicks on a block). The suggested coordinates at which the popup menu can be shown are passed.*/ void blockEdit(Block block,Point p); /** Invoked when the user has dragged/moved a block */ void moved(Block block,Point p,Date newStart, int slotNr); /** Invoked when the user has resized a block */ void resized(Block block,Point p,Date newStart, Date newEnd, int slotNr); }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview.swing; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.Point; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.SwingConstants; import org.rapla.components.calendarview.AbstractCalendar; import org.rapla.components.calendarview.Block; import org.rapla.components.calendarview.Builder; import org.rapla.components.calendarview.swing.SelectionHandler.SelectionStrategy; import org.rapla.components.layout.TableLayout; import org.rapla.components.util.DateTools; /** Graphical component for displaying a calendar like weekview. * This view doesn't show the times and arranges the different slots * Vertically. */ public class SwingCompactWeekView extends AbstractSwingCalendar { private SmallDaySlot[] slots = new SmallDaySlot[0]; private List<List<Block>> rows = new ArrayList<List<Block>>(); DraggingHandler draggingHandler = new DraggingHandler(this, false); SelectionHandler selectionHandler = new SelectionHandler(this); String[] rowNames = new String[] {}; int leftColumnSize = 100; Map<Block, Integer> columnMap = new HashMap<Block, Integer>(); public SwingCompactWeekView() { this(true); } public SwingCompactWeekView(boolean showScrollPane) { super( showScrollPane ); selectionHandler.setSelectionStrategy(SelectionStrategy.BLOCK); } public Collection<Block> getBlocks() { ArrayList<Block> list = new ArrayList<Block>(); for (int i=0;i<slots.length;i++) { list.addAll(slots[i].getBlocks()); } return Collections.unmodifiableCollection( list ); } public void setEditable(boolean b) { super.setEditable( b); if ( slots == null ) return; // Hide the rest for (int i= 0;i<slots.length;i++) { SmallDaySlot slot = slots[i]; if (slot == null) continue; slot.setEditable(b); } } public void setSlots(String[] slotNames) { this.rowNames = slotNames; } TableLayout tableLayout; public void rebuild() { rows.clear(); columnMap.clear(); for ( int i=0; i<rowNames.length; i++ ) { addRow(); } // calculate the blocks Iterator<Builder> it= builders.iterator(); while (it.hasNext()) { Builder b= it.next(); b.prepareBuild(getStartDate(), getEndDate()); } // clear everything jHeader.removeAll(); jCenter.removeAll(); // build Blocks it= builders.iterator(); while (it.hasNext()) { Builder b= it.next(); if (b.isEnabled()) { b.build(this); } } tableLayout= new TableLayout(); jCenter.setLayout(tableLayout); Calendar calendar = createCalendar(); calendar.setTime(getStartDate()); int firstDayOfWeek = getFirstWeekday(); calendar.set( Calendar.DAY_OF_WEEK, firstDayOfWeek); if ( rowNames.length > 0) { tableLayout.insertColumn(0, leftColumnSize); jHeader.add( createColumnHeader( null ), "0,0,l,t" ); } else { tableLayout.insertColumn(0, 0); } int columns = getColumnCount(); // add headers for (int column=0;column<columns;column++) { if ( !isExcluded(column) ) { tableLayout.insertColumn(column + 1, slotSize ); jHeader.add( createColumnHeader( column ) ); } else { tableLayout.insertColumn(column + 1, 0.); } } int rowsize = rows.size(); slots = new SmallDaySlot[rowsize * columns]; for (int row=0;row<rowsize;row++) { tableLayout.insertRow(row, TableLayout.PREFERRED ); jCenter.add(createRowLabel( row ), "" + 0 + "," + row + ",f,t"); for (int column=0;column < columns; column++) { int fieldNumber = row * columns + column; SmallDaySlot field = createField( ); for (Block block:getBlocksForColumn(rows.get( row ), column)) { field.putBlock( (SwingBlock ) block); } slots[fieldNumber] = field; if ( !isExcluded( column ) ) { jCenter.add(slots[fieldNumber], "" + (column + 1) + "," + row); } } } selectionHandler.clearSelection(); jCenter.validate(); jHeader.validate(); if ( isEditable()) { updateSize(component.getSize().width); } component.revalidate(); component.repaint(); } protected int getColumnCount() { return getDaysInView(); } public int getLeftColumnSize() { return leftColumnSize; } public void setLeftColumnSize(int leftColumnSize) { this.leftColumnSize = leftColumnSize; } protected JComponent createRowLabel(int row) { JLabel label = new JLabel(); if ( row < rowNames.length ) { label.setText( rowNames[ row ] ); label.setToolTipText(rowNames[ row ]); } return label; } public boolean isSelected(int nr) { SmallDaySlot slot = getSlot(nr); if ( slot == null) { return false; } return slot.isSelected(); } /** override this method, if you want to create your own slot header. */ protected JComponent createColumnHeader(Integer column) { JLabel jLabel = new JLabel(); jLabel.setFont(new Font("SansSerif", Font.PLAIN, 13)); jLabel.setHorizontalAlignment(JLabel.CENTER); jLabel.setOpaque(false); jLabel.setForeground(Color.black); Dimension dim; if (column != null ) { Date date = getDateFromColumn(column); jLabel.setText(AbstractCalendar.formatDayOfWeekDateMonth(date,locale,getTimeZone())); jLabel.setBorder(isEditable() ? SLOTHEADER_BORDER : null); dim = new Dimension(this.slotSize,20); } else { dim = new Dimension(this.leftColumnSize,20); jLabel.setFont(jLabel.getFont().deriveFont((float)11.)); jLabel.setHorizontalAlignment(SwingConstants.LEFT); } jLabel.setPreferredSize( dim); jLabel.setMinimumSize( dim ); jLabel.setMaximumSize( dim ); return jLabel; } private SmallDaySlot createField( ) { SmallDaySlot c= new SmallDaySlot("",slotSize, Color.BLACK, null); c.setEditable(isEditable()); c.setDraggingHandler(draggingHandler); c.addMouseListener(selectionHandler); c.addMouseMotionListener(selectionHandler); return c; } protected List<Block> getBlocksForColumn(List<Block> blocks,int column) { List<Block> result = new ArrayList<Block>(); //Date startDate = getDateFromColumn(column); if ( blocks != null) { Iterator<Block> it = blocks.iterator(); while (it.hasNext()){ Block block = it.next(); if (columnMap.get( block) == column) { // if ( DateTools.cutDate( block.getStart()).equals( startDate)) { result.add( block); } } } return result; } protected Date getDateFromColumn(int column) { Date startDate = getStartDate(); return DateTools.addDays( startDate, column); } public void addBlock(Block block, int column,int slot) { if ( rows.size() <= slot) { return; } checkBlock( block ); List<Block> blocks = rows.get( slot ); blocks.add( block ); columnMap.put(block, column); } private void addRow() { rows.add( rows.size(), new ArrayList<Block>()); } public int getSlotNr( DaySlot slot) { for (int i=0;i<slots.length;i++) if (slots[i] == slot) return i; throw new IllegalStateException("Slot not found in List"); } int getRowsPerDay() { return 1; } SmallDaySlot getSlot(int nr) { if ( nr >=0 && nr< slots.length) return slots[nr]; else return null; } int getDayCount() { return slots.length; } int calcSlotNr(int x, int y) { for (int i=0;i<slots.length;i++) { if (slots[i] == null) continue; Point p = slots[i].getLocation(); if ((p.x <= x) && (x <= p.x + slots[i].getWidth()) && (p.y <= y) && (y <= p.y + slots[i].getHeight()) ) { return i; } } return -1; } SmallDaySlot calcSlot(int x,int y) { int nr = calcSlotNr(x, y); if (nr == -1) { return null; } else { return slots[nr]; } } Date createDate(DaySlot slot, int row, boolean startOfRow) { Calendar calendar = createCalendar(); Date startDate = getStartDate(); calendar.setTime( startDate ); calendar.set( Calendar.DAY_OF_WEEK, getFirstWeekday() ); calendar.add( Calendar.DATE , getSlotNr( slot ) % getDaysInView() ); //calendar.set( Calendar.DAY_OF_WEEK, getDayOfWeek(slot) ); if ( !startOfRow ) { calendar.add( Calendar.DATE , 1 ); } calendar.set( Calendar.HOUR_OF_DAY, 0 ); calendar.set( Calendar.MINUTE, 0 ); calendar.set( Calendar.SECOND, 0 ); calendar.set( Calendar.MILLISECOND, 0 ); return calendar.getTime(); } /** must be called after the slots are filled*/ protected boolean isEmpty(int column) { for (Integer value: columnMap.values()) { if ( value.equals( column)) { return false; } } return true; } @Override public void updateSize(int width) { int columnSize = tableLayout.getNumColumn(); int realColumns= columnSize; for ( int i=1;i< columnSize;i++) { if( isExcluded(i)) { realColumns--; } } int newWidth = Math.max( minBlockWidth ,(width - leftColumnSize -20 - realColumns) / (Math.max(1,realColumns-1))); for (SmallDaySlot slot: this.slots) { if ( slot != null) { slot.updateSize(newWidth); } } setSlotSize(newWidth); for ( int i=1;i< columnSize;i++) { if( !isExcluded(i-1)) { tableLayout.setColumn(i, newWidth); } } boolean first = true; for (Component comp:jHeader.getComponents()) { if ( first) { first = false; continue; } double height = comp.getPreferredSize().getHeight(); Dimension dim = new Dimension( newWidth,(int) height); comp.setPreferredSize(dim); comp.setMaximumSize(dim); comp.setMinimumSize( dim); comp.invalidate(); } jCenter.invalidate(); jCenter.repaint(); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview.swing; import java.awt.Component; import java.awt.Graphics; import org.rapla.components.calendarview.Block; public interface SwingBlock extends Block { Component getView(); public void paintDragging(Graphics g, int width, int height); boolean isMovable(); boolean isStartResizable(); boolean isEndResizable(); }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview.swing; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.Point; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Iterator; import javax.swing.JComponent; import javax.swing.JLabel; import org.rapla.components.calendarview.Block; import org.rapla.components.calendarview.Builder; import org.rapla.components.layout.TableLayout; import org.rapla.components.util.DateTools; /** Graphical component for displaying a calendar like monthview. * */ public class SwingMonthView extends AbstractSwingCalendar { public final static int ROWS = 6; //without the header row public final static int COLUMNS = 7; private SmallDaySlot[] slots; DraggingHandler draggingHandler = new DraggingHandler(this, false); SelectionHandler selectionHandler = new SelectionHandler(this); JLabel monthTitle = new JLabel(); public SwingMonthView() { this(true); } public SwingMonthView(boolean showScrollPane) { super( showScrollPane ); monthTitle.setOpaque( false); jTitlePanel.add(monthTitle, BorderLayout.NORTH); monthTitle.setHorizontalAlignment( JLabel.CENTER); monthTitle.setFont(monthTitle.getFont().deriveFont(Font.BOLD)); } protected boolean isEmpty(int column) { for ( int i=column;i < slots.length;i+=7 ) { if (!slots[i].isEmpty() ) { return false; } } return true; } public Collection<Block> getBlocks(int dayOfMonth) { int index = dayOfMonth-1; return Collections.unmodifiableCollection(slots[ index ].getBlocks()); } public Collection<Block> getBlocks() { ArrayList<Block> list = new ArrayList<Block>(); for (int i=0;i<slots.length;i++) { list.addAll(slots[i].getBlocks()); } return Collections.unmodifiableCollection( list ); } public void setEditable(boolean b) { super.setEditable( b); if ( slots == null ) return; // Hide the rest for (int i= 0;i<slots.length;i++) { SmallDaySlot slot = slots[i]; if (slot == null) continue; slot.setEditable(b); } } TableLayout tableLayout; public void rebuild() { // we need to clone the calendar, because we modify the calendar object in the getExclude() method Calendar counter = createCalendar(); Iterator<Builder> it= builders.iterator(); Date startDate = getStartDate(); while (it.hasNext()) { Builder b= it.next(); b.prepareBuild(startDate,getEndDate() ); } // create fields slots = new SmallDaySlot[daysInMonth]; counter.setTime(startDate); int year = counter.get(Calendar.YEAR); SimpleDateFormat format = new SimpleDateFormat("MMMMMM",locale); String monthname = format.format(counter.getTime()); // calculate the blocks for (int i=0; i<daysInMonth; i++) { createField(i, counter.getTime()); counter.add(Calendar.DATE,1); } // clear everything jHeader.removeAll(); jCenter.removeAll(); monthTitle.setText( monthname + " " + year); // build Blocks it= builders.iterator(); while (it.hasNext()) { Builder b= it.next(); if (b.isEnabled()) { b.build(this); } } tableLayout= new TableLayout(); jCenter.setLayout(tableLayout); counter.setTime(startDate); int firstDayOfWeek = getFirstWeekday(); if ( counter.get(Calendar.DAY_OF_WEEK) != firstDayOfWeek) { counter.set(Calendar.DAY_OF_WEEK, firstDayOfWeek); if ( counter.getTime().after( startDate)) { counter.add(Calendar.DATE, -7); } } // add headers int offset = (int) DateTools.countDays(counter.getTime(),startDate); for (int i=0;i<COLUMNS;i++) { int weekday = counter.get(Calendar.DAY_OF_WEEK); if ( !isExcluded(i) ) { tableLayout.insertColumn(i, slotSize ); jHeader.add( createSlotHeader( weekday ) ); } else { tableLayout.insertColumn(i, 0); } counter.add(Calendar.DATE,1); } for (int i=0;i<ROWS;i++) { tableLayout.insertRow(i, TableLayout.PREFERRED ); } // add Fields counter.setTime(startDate); for (int i=0; i<daysInMonth; i++) { int column = (offset + i) % 7; int row = (counter.get(Calendar.DATE) + 6 - column ) / 7; if ( !isExcluded( column ) ) { jCenter.add( slots[i] , "" + column + "," + row); } counter.add(Calendar.DATE,1); } selectionHandler.clearSelection(); jHeader.validate(); jCenter.validate(); if ( isEditable()) { updateSize(component.getSize().width); } component.revalidate(); component.repaint(); } private void createField(int pos, Date date) { slots[pos]= createSmallslot(pos, date); } protected SmallDaySlot createSmallslot(int pos, Date date) { String headerText = "" + (pos + 1); Color headerColor = getNumberColor( date); Color headerBackground = null; return createSmallslot(headerText, headerColor,headerBackground); } protected SmallDaySlot createSmallslot(String headerText, Color headerColor, Color headerBackground) { return createSmallslot(headerText, slotSize,headerColor,headerBackground); } protected SmallDaySlot createSmallslot(String headerText, int width, Color headerColor, Color headerBackground ) { SmallDaySlot c= new SmallDaySlot(headerText, width, headerColor, headerBackground); c.setEditable(isEditable()); c.setDraggingHandler(draggingHandler); c.addMouseListener(selectionHandler); c.addMouseMotionListener(selectionHandler); return c; } public static Color DATE_NUMBER_COLOR = Color.gray; /** * @param date */ protected Color getNumberColor( Date date) { return DATE_NUMBER_COLOR; } /** override this method, if you want to create your own header. */ protected JComponent createSlotHeader(int weekday) { JLabel jLabel = new JLabel(); jLabel.setBorder(isEditable() ? SLOTHEADER_BORDER : null); jLabel.setText( getWeekdayName(weekday) ); jLabel.setFont(new Font("SansSerif", Font.PLAIN, 13)); jLabel.setHorizontalAlignment(JLabel.CENTER); jLabel.setOpaque(false); jLabel.setForeground(Color.black); Dimension dim = new Dimension(this.slotSize,20); jLabel.setPreferredSize( dim); jLabel.setMinimumSize( dim ); jLabel.setMaximumSize( dim ); return jLabel; } public void addBlock(Block bl, int col,int slot) { checkBlock( bl ); // System.out.println("Put " + bl.getStart() + " into field " + (date -1)); slots[col].putBlock((SwingBlock)bl); } public int getSlotNr( DaySlot slot) { for (int i=0;i<slots.length;i++) if (slots[i] == slot) return i; throw new IllegalStateException("Slot not found in List"); } public boolean isSelected(int nr) { SmallDaySlot slot = getSlot(nr); if ( slot == null) { return false; } return slot.isSelected(); } int getRowsPerDay() { return 1; } SmallDaySlot getSlot(int nr) { if ( nr >=0 && nr< slots.length) return slots[nr]; else return null; } int getDayCount() { return slots.length; } int calcSlotNr(int x, int y) { for (int i=0;i<slots.length;i++) { if (slots[i] == null) continue; Point p = slots[i].getLocation(); if ((p.x <= x) && (x <= p.x + slots[i].getWidth()) && (p.y <= y) && (y <= p.y + slots[i].getHeight()) ) { return i; } } return -1; } SmallDaySlot calcSlot(int x,int y) { int nr = calcSlotNr(x, y); if (nr == -1) { return null; } else { return slots[nr]; } } Date createDate(DaySlot slot, int row, boolean startOfRow) { Calendar calendar = createCalendar(); calendar.setTime( getStartDate() ); int dayOfMonth = getSlotNr( slot ) +1; calendar.set( Calendar.DAY_OF_MONTH, dayOfMonth); if ( !startOfRow ) { calendar.add( Calendar.DATE , 1 ); } calendar.set( Calendar.HOUR_OF_DAY, 0 ); calendar.set( Calendar.MINUTE, 0 ); calendar.set( Calendar.SECOND, 0 ); calendar.set( Calendar.MILLISECOND, 0 ); return calendar.getTime(); } @Override public void updateSize(int width) { int columnSize = tableLayout.getNumColumn(); int newWidth = Math.max( minBlockWidth , (width - 10 ) / (Math.max(1,columnSize))); for (SmallDaySlot slot: this.slots) { if ( slot != null) { slot.updateSize(newWidth); } } setSlotSize(newWidth); for ( int i=0;i< columnSize;i++) { tableLayout.setColumn(i, newWidth); } for (Component comp:jHeader.getComponents()) { double height = comp.getPreferredSize().getHeight(); Dimension dim = new Dimension( newWidth,(int) height); comp.setPreferredSize(dim); comp.setMaximumSize(dim); comp.setMinimumSize( dim); comp.invalidate(); } jCenter.invalidate(); jCenter.repaint(); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview.swing; import java.awt.Cursor; import java.awt.Point; import java.awt.event.MouseEvent; import java.util.Date; import org.rapla.components.calendarview.swing.scaling.IRowScaleSmall; import org.rapla.components.calendarview.swing.scaling.OneRowScale; import org.rapla.components.util.TimeInterval; /** DraggingHandler coordinates the drag events from the Block-Components * between the different MultiSlots of a weekview. */ class DraggingHandler { int draggingPointOffset = 0; DaySlot oldSlot; int oldY = 0; int oldHeight = 0; AbstractSwingCalendar m_cv; Date start = null; Date newStart = null; Date end = null; Date newEnd = null; int resizeDirection; boolean bMoving; boolean bResizing; boolean supportsResizing; IRowScaleSmall rowScale; public DraggingHandler(AbstractSwingCalendar wv,IRowScaleSmall rowScale, boolean supportsResizing) { this.supportsResizing = supportsResizing; this.rowScale = rowScale; m_cv = wv; } public DraggingHandler(AbstractSwingCalendar wv, boolean supportsResizing) { this ( wv, new OneRowScale(), supportsResizing ); } public boolean supportsResizing() { return supportsResizing; } public void blockPopup(SwingBlock block,Point p) { m_cv.fireBlockPopup(block,p); } public void blockEdit(SwingBlock block,Point p) { m_cv.fireBlockEdit(block,p); } public void mouseReleased(DaySlot slot, SwingBlock block, MouseEvent evt) { if ( isDragging() ) stopDragging(slot, block, evt); } public void blockBorderPressed(DaySlot slot,SwingBlock block,MouseEvent evt, int direction) { if (!bResizing && supportsResizing ) { this.resizeDirection = direction; startResize( slot, block, evt); } } public boolean isDragging() { return bResizing || bMoving; } public void mouseDragged(DaySlot slot,SwingBlock block,MouseEvent evt) { if ( bResizing ) startResize( slot, block, evt ); else startMoving( slot, block, evt ); } private void dragging(DaySlot slot,SwingBlock block,int _x,int _y,boolean bDragging) { // 1. Calculate slot DaySlot newSlot = null; if ( bResizing ) { newSlot = slot; } else { int slotNr = m_cv.calcSlotNr( slot.getLocation().x + _x , slot.getLocation().y + _y); newSlot = m_cv.getSlot( slotNr ); if (newSlot == null) return; } // 2. Calculate new x relative to slot int y = _y; int xslot = 0; int height = block.getView().getHeight(); xslot = newSlot.calcSlot( slot.getLocation().x + _x - newSlot.getLocation().x ); if ( bResizing ) { if ( resizeDirection == 1) { y = block.getView().getLocation().y; // we must trim the endRow int endrow = newSlot.calcRow(_y ) + 1; endrow = Math.max( newSlot.calcRow(y) + 2, endrow); height = rowScale.getYCoordForRow(endrow) - y; if ( bDragging ) { start = block.getStart(); end = m_cv.createDate( newSlot, endrow, true); //System.out.println ( "Resizeing@end: start=" + start + ", end=" + end) ; } } else if (resizeDirection == -1){ // we must trim y y = rowScale.trim( y ); int row = newSlot.calcRow( y ) ; int rowSize = rowScale.getRowSizeForRow( row ); y = Math.min ( block.getView().getLocation().y + block.getView().getHeight() - rowSize, y ); height = block.getView().getLocation().y + block.getView().getHeight() - y; if ( bDragging ) { row = newSlot.calcRow( y ); if(y==0) start = m_cv.createDate( newSlot, row, true); else start = m_cv.createDate( newSlot, row, false); end = block.getEnd(); //System.out.println ( "Resizeing@start: start=" + start + ", end=" + end) ; } } } else if (bMoving){ // we must trim y //y = rowScale.trim( y); if ( bDragging ) { int newRow = newSlot.calcRow( y ); start = m_cv.createDate( newSlot, newRow, true); y = rowScale.trim( y ); //System.out.println ( "Moving: start=" + start + ", end=" + end +" row: " + row) ; } } if (oldSlot != null && oldSlot != newSlot) oldSlot.paintDraggingGrid(xslot, y, height, block, oldY, oldHeight, false); newSlot.paintDraggingGrid(xslot, y, height, block, oldY, oldHeight, bDragging); oldSlot = newSlot; oldY = y; oldHeight = height; } private void startMoving(DaySlot slot,SwingBlock block,MouseEvent evt) { if (!bMoving) { draggingPointOffset = evt.getY(); if (block.isMovable()) { bMoving = true; slot.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)); } else { bMoving = false; slot.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); return; } } if ( block == null) return; int x = evt.getX() + slot.getX(block.getView()); int y = evt.getY() + block.getView().getLocation().y; scrollTo( slot, x, y); // Correct y with the draggingPointOffset y = evt.getY() - draggingPointOffset + block.getView().getLocation().y ; y += rowScale.getDraggingCorrection(y ) ; dragging( slot, block, x, y, bMoving); } private void startResize(DaySlot slot,SwingBlock block, MouseEvent evt) { if ( block == null) return; int x = evt.getX() + slot.getX(block.getView()); int y = evt.getY() + block.getView().getLocation().y; if (!bResizing) { if (block.isMovable() && ( ( resizeDirection == -1 && block.isStartResizable() ) || ( resizeDirection == 1 && block.isEndResizable()))) { bResizing = true; } else { bResizing = false; return; } } scrollTo( slot, x, y); dragging( slot, block, x, y, bResizing); } private void stopDragging(DaySlot slot, SwingBlock block,MouseEvent evt) { slot.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); if ( block == null) { return ; } if (!m_cv.isEditable()) return; try { int x = evt.getX() + slot.getX( block.getView() ); int y = evt.getY() - draggingPointOffset + block.getView().getLocation().y ; y += rowScale.getDraggingCorrection(y ); dragging(slot,block,x,y,false); Point upperLeft = m_cv.getScrollPane().getViewport().getViewPosition(); Point newPoint = new Point(slot.getLocation().x + x -upperLeft.x ,y-upperLeft.y); int slotNr = m_cv.getSlotNr(oldSlot); TimeInterval normalizedInterval = m_cv.normalizeBlockIntervall(block); Date blockStart = normalizedInterval.getStart(); Date blockEnd = normalizedInterval.getEnd(); if ( bMoving ) { // Has the block moved //System.out.println("Moved to " + newStart + " - " + newEnd); if ( !start.equals( blockStart ) || oldSlot!= slot) { m_cv.fireMoved(block, newPoint, start, slotNr); } } if ( bResizing ) { // System.out.println("Resized to " + start + " - " + end); if ( !( start.equals( blockStart ) && end.equals( blockEnd) )) { m_cv.fireResized(block, newPoint, start, end, slotNr); } } } finally { bResizing = false; bMoving = false; start = null; end = null; } } // Begin scrolling when hitting the upper or lower border while // dragging or selecting. private void scrollTo(DaySlot slot,int x,int y) { // 1. Transfer p.x relative to jCenter m_cv.scrollTo(slot.getLocation().x + x, slot.getLocation().y + y); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview.swing; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.util.ArrayList; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import javax.swing.BoxLayout; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.JScrollBar; import javax.swing.JScrollPane; import javax.swing.JViewport; import javax.swing.ScrollPaneConstants; import javax.swing.SwingUtilities; import javax.swing.border.Border; import javax.swing.border.EtchedBorder; import org.rapla.components.calendarview.AbstractCalendar; import org.rapla.components.calendarview.Block; import org.rapla.components.calendarview.CalendarView; import org.rapla.components.layout.TableLayout; import org.rapla.components.util.TimeInterval; public abstract class AbstractSwingCalendar extends AbstractCalendar implements CalendarView { static Border SLOTHEADER_BORDER = new EtchedBorder(); int slotSize = 100; boolean bEditable = true; protected int minBlockWidth = 3; ArrayList<ViewListener> listenerList = new ArrayList<ViewListener>(); JScrollPane scrollPane = new JScrollPane(); JPanel jHeader = new JPanel(); BoxLayout boxLayout1 = new BoxLayout(jHeader, BoxLayout.X_AXIS); JPanel jCenter = new JPanel(); protected JPanel jTitlePanel = new JPanel(); protected JPanel component = new JPanel(); AbstractSwingCalendar(boolean showScrollPane) { jHeader.setLayout(boxLayout1); jHeader.setOpaque( false ); jCenter.setOpaque( false ); jTitlePanel.setOpaque( false); jTitlePanel.setLayout( new BorderLayout()); jTitlePanel.add(jHeader,BorderLayout.CENTER); if (showScrollPane) { component.setLayout(new BorderLayout()); component.add(scrollPane,BorderLayout.CENTER); scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED); scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); scrollPane.setViewportView(jCenter); scrollPane.setColumnHeaderView(jTitlePanel); scrollPane.getVerticalScrollBar().setUnitIncrement(10); scrollPane.getHorizontalScrollBar().setUnitIncrement(10); scrollPane.setBorder(null); } else { component.setLayout(new TableLayout(new double[][] { {TableLayout.PREFERRED,TableLayout.FILL} ,{TableLayout.PREFERRED,TableLayout.FILL} })); component.add(jTitlePanel,"1,0"); component.add(jCenter,"1,1"); } this.timeZone = TimeZone.getDefault(); setLocale( Locale.getDefault() ); if ( showScrollPane) { component.addComponentListener( new ComponentListener() { private boolean resizing = false; public void componentShown(ComponentEvent e) { } public void componentResized(ComponentEvent e) { if ( resizing) { return; } resizing = true; if ( isEditable() ) { int width = component.getSize().width; updateSize(width); } SwingUtilities.invokeLater(new Runnable() { public void run() { resizing = false; } }); } public void componentMoved(ComponentEvent e) { } public void componentHidden(ComponentEvent e) { } }); } } abstract public void updateSize(int width); public JComponent getComponent() { return component; } void checkBlock( Block bl ) { if ( !bl.getStart().before(this.getEndDate())) { throw new IllegalStateException("Start-date " +bl.getStart() + " must be before calendar end at " +this.getEndDate()); } } public boolean isEditable() { return bEditable; } public void setEditable( boolean editable ) { bEditable = editable; } /** Width of a single slot in pixel. */ public void setSlotSize(int slotSize) { this.slotSize = slotSize; } public int getSlotSize() { return slotSize; } /** the minimum width of a block in pixel */ public int getMinBlockWidth() { return minBlockWidth; } /** the minimum width of a block in pixel */ public void setMinBlockWidth(int minBlockWidth) { this.minBlockWidth = Math.max(3,minBlockWidth); } public void setBackground(Color color) { component.setBackground(color); if (scrollPane != null) scrollPane.setBackground(color); if (jCenter != null) jCenter.setBackground(color); if (jHeader != null) jHeader.setBackground(color); } public void addCalendarViewListener(ViewListener listener) { listenerList.add(listener); } public void removeCalendarViewListener(ViewListener listener) { listenerList.remove(listener); } JScrollPane getScrollPane() { return scrollPane; } void scrollTo(int x, int y) { JViewport viewport = scrollPane.getViewport(); Rectangle rect = viewport.getViewRect(); int leftBound = rect.x; int upperBound = rect.y; int lowerBound = rect.y + rect.height; int rightBound = rect.x + rect.width; int maxX = viewport.getView().getWidth(); int maxY = viewport.getView().getHeight(); JScrollBar scrollBar = scrollPane.getVerticalScrollBar(); if ( y > lowerBound && lowerBound < maxY) { scrollBar.setValue(scrollBar.getValue() + 20); } if ( y < upperBound && upperBound >0) { scrollBar.setValue(scrollBar.getValue() - 20); } scrollBar = scrollPane.getHorizontalScrollBar(); if ( x > rightBound && rightBound < maxX) { scrollBar.setValue(scrollBar.getValue() + 20); } if ( x < leftBound && leftBound >0) { scrollBar.setValue(scrollBar.getValue() - 20); } } public ViewListener[] getWeekViewListeners() { return listenerList.toArray(new ViewListener[]{}); } final void fireSelectionChanged(Date start, Date end) { // Fire the popup event ViewListener[] listeners = getWeekViewListeners(); for (int i=0;i<listeners.length;i++) { listeners[i].selectionChanged(start,end); } } final void fireSelectionPopup(Component slot, Point p, Date start, Date end, int slotNr) { // Fire the popup event ViewListener[] listeners = getWeekViewListeners(); for (int i=0;i<listeners.length;i++) { listeners[i].selectionPopup(slot,p,start,end, slotNr); } } final void fireMoved(SwingBlock block, Point p, Date newTime, int slotNr) { // Fire the popup event ViewListener[] listeners = getWeekViewListeners(); for (int i=0;i<listeners.length;i++) { listeners[i].moved(block,p,newTime, slotNr); } } final void fireResized(SwingBlock block, Point p, Date newStart, Date newEnd, int slotNr) { // Fire the popup event ViewListener[] listeners = getWeekViewListeners(); for (int i=0;i<listeners.length;i++) { listeners[i].resized(block,p,newStart,newEnd, slotNr); } } void fireResized(SwingBlock block, Point p, Date newTime, int slotNr) { // Fire the popup event ViewListener[] listeners = getWeekViewListeners(); for (int i=0;i<listeners.length;i++) { listeners[i].moved(block,p,newTime, slotNr); } } void fireBlockPopup(SwingBlock block, Point p) { // Fire the popup event ViewListener[] listeners = getWeekViewListeners(); for (int i=0;i<listeners.length;i++) { listeners[i].blockPopup(block,p); } } void fireBlockEdit(SwingBlock block, Point p) { // Fire the popup event ViewListener[] listeners = getWeekViewListeners(); for (int i=0;i<listeners.length;i++) { listeners[i].blockEdit(block,p); } } abstract int getDayCount(); abstract DaySlot getSlot(int num); abstract public boolean isSelected(int nr); abstract int calcSlotNr( int x, int y); abstract int getSlotNr( DaySlot slot); abstract int getRowsPerDay(); abstract Date createDate( DaySlot slot, int row, boolean startOfRow); public TimeInterval normalizeBlockIntervall(SwingBlock block) { return new TimeInterval(block.getStart(), block.getEnd()); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview.swing; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Insets; import java.awt.Rectangle; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.rapla.components.calendarview.Block; public class SmallDaySlot extends AbstractDaySlot { private static final long serialVersionUID = 1L; public static int BLOCK_HEIGHT = 32 +20; public static int START_GAP = 10; public static Color THICK_LINE_COLOR = Color.black; public static Color LINE_COLOR = new Color(0xaa, 0xaa, 0xaa); public static Color WORKTIME_BACKGROUND = Color.white; private List<Block> blocks = new LinkedList<Block>(); private int slotxsize; private Color headerColor; private Color headerBackground; private int rowSize = 15; private boolean selected; int slot_space = 3; private BlockListener blockListener = new BlockListener(); private String headerText; public SmallDaySlot(String headerText,int slotxsize,Color headerColor, Color headerBackground ) { this.headerColor = headerColor; this.headerBackground = headerBackground; this.slotxsize= slotxsize; this.headerText = headerText; setLayout( null ); setAlignmentX(0); setAlignmentY(TOP_ALIGNMENT); Dimension newSize = new Dimension(slotxsize, 10); setPreferredSize(newSize); this.setBackground(Color.white); } public boolean isBorderVisible() { return true; } public Collection<Block> getBlocks() { return blocks; } public void select(int startRow, int endRow) { boolean selected = (startRow >=0 || endRow>=0); if (this.selected == selected) return; this.selected = selected; invalidateSelection(); } public void unselectAll() { if (!selected ) return; selected = false; invalidateSelection(); } private void invalidateSelection() { repaint(); // Update the values after calling repaint, because paint needs the old values. } /** fuegt einen block im gewuenschten slot ein (konflikte werden ignoriert). */ public void putBlock(SwingBlock bl) { add( bl.getView() ); blocks.add( bl ); // The blockListener can be shared among all blocks, // as long as we can only click on one block simultaneously bl.getView().addMouseListener( blockListener ); bl.getView().addMouseMotionListener( blockListener ); blockViewMapper.put( bl.getView(), bl ); updateSize(); } public void updateSize() { int blockHeight = 0; for ( Block b:blocks) { blockHeight += getHeight( b); } int height = Math.max( 25, blockHeight + START_GAP ); Dimension newSize = new Dimension( slotxsize, height ); setPreferredSize( newSize ); updateBounds(); } private void updateBounds() { int y= START_GAP; for (int i=0;i< blocks.size();i++) { SwingBlock bl = (SwingBlock) blocks.get(i); int blockHeight = getHeight(bl); bl.getView().setBounds( 1 ,y, slotxsize -1, blockHeight-1); y+= blockHeight; } } /** * @param bl */ private int getHeight(Block bl) { int blockHeight = BLOCK_HEIGHT; // Special Solution for doubling the block height // if (DateTools.countMinutes(bl.getStart(), bl.getEnd()) >= 60) // { // blockHeight*= 2; // } return blockHeight; } public Dimension getMinimumSize() { return getPreferredSize(); } public Dimension getMaximumSize() { return getPreferredSize(); } Insets insets = new Insets(0,0,0, 0); public Insets getInsets() { return insets; } int getBlockCount() { return blocks.size(); } public boolean isEmpty() { return getBlockCount() == 0; } public int calcRow(int y) { return 0; } public int calcSlot(int x) { return 0; } public int getX(Component component) { return component.getLocation().x; } int max; public void paint(Graphics g) { Dimension dim = getSize(); Rectangle rect = g.getClipBounds(); g.setColor(getForeground()); if (selected) { g.setColor(getSelectionColor()); } else { g.setColor(getBackground()); } g.fillRect(rect.x , rect.y , rect.x + rect.width , rect.y + rect.height); if (isBorderVisible()) { g.setColor(LINE_COLOR); g.drawLine(0, rect.y, 0, rect.y + rect.height); g.drawLine(dim.width - 1, rect.y, dim.width - 1, rect.y + rect.height); g.drawLine(rect.x, 0, rect.x + rect.width, 0); g.drawLine(rect.x, dim.height - 1, rect.x + rect.width, dim.height - 1); } if ( headerText != null) { FontMetrics fontMetrics = g.getFontMetrics(); int headerWidth = fontMetrics.stringWidth(headerText); int headerHeight = 10;//fontMetrics.stringWidth(headerText); int x = Math.max(10, dim.width - headerWidth - 3); int y = Math.max(START_GAP, headerHeight); if ( headerBackground != null) { g.setColor(headerBackground); g.fillRect(1, y-headerHeight+1, dim.width -2, headerHeight); } g.setColor(headerColor); g.drawString(headerText, x, y); g.setColor(getForeground()); } super.paintChildren(g); if (paintDraggingGrid) { int height = draggingView.getView().getHeight() - 1; int x = 0; int y = draggingView.getView().getBounds().y; if (y + height + 2 > getHeight()) { y = getHeight() - height - 2; } paintDraggingGrid(g, x, y, slotxsize - 1, height); } } public int getRowSize() { return rowSize; } public boolean isSelected() { return selected ; } public void updateSize(int newWidth) { this.slotxsize = newWidth; updateSize(); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview.swing; import java.awt.Color; import java.awt.Font; import java.awt.Point; import java.awt.Rectangle; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Iterator; import java.util.Locale; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JScrollPane; import org.rapla.components.calendarview.AbstractCalendar; import org.rapla.components.calendarview.Block; import org.rapla.components.calendarview.Builder; import org.rapla.components.calendarview.swing.scaling.IRowScale; import org.rapla.components.calendarview.swing.scaling.LinearRowScale; import org.rapla.components.calendarview.swing.scaling.VariableRowScale; import org.rapla.components.util.DateTools; /** Graphical component for displaying a calendar like weekview. */ public class SwingWeekView extends AbstractSwingCalendar { public final static int SLOT_GAP= 5; LargeDaySlot[] daySlots = new LargeDaySlot[] {}; private int startMinutes= 0; private int endMinutes= 24 * 60; BoxLayout boxLayout2= new BoxLayout(jCenter, BoxLayout.X_AXIS); TimeScale timeScale = new TimeScale(); IRowScale rowScale = new LinearRowScale(); protected JLabel weekTitle; protected SelectionHandler selectionHandler ; public SwingWeekView() { this(true); } public SwingWeekView(boolean showScrollPane) { super(showScrollPane); weekTitle = new JLabel(); weekTitle.setHorizontalAlignment( JLabel.CENTER); weekTitle.setFont(weekTitle.getFont().deriveFont((float)11.)); jCenter.setLayout(boxLayout2); jCenter.setAlignmentY(JComponent.TOP_ALIGNMENT); jCenter.setAlignmentX(JComponent.LEFT_ALIGNMENT); if ( showScrollPane ) { scrollPane.setRowHeaderView(timeScale); scrollPane.setCorner( JScrollPane.UPPER_LEFT_CORNER, weekTitle); } else { component.add(weekTitle, "0,0"); component.add(timeScale,"0,1"); } selectionHandler = new SelectionHandler(this); } public void updateSize(int width) { int slotCount = 0; int columnCount = 0; for (int i=0; i<daySlots.length; i++) { LargeDaySlot largeDaySlot = daySlots[i]; if ( isExcluded(i) ) { continue; } if ( largeDaySlot != null) { slotCount += largeDaySlot.getSlotCount(); columnCount++; } } int newWidth = Math.round(((width - timeScale.getWidth() - 10- columnCount* (16 + SLOT_GAP)) / (Math.max(1,slotCount)))-2); newWidth = Math.max( newWidth , minBlockWidth); for (LargeDaySlot slot: daySlots) { if ( slot != null) { slot.updateSize(newWidth); } } setSlotSize(newWidth); } public void setWorktime(int startHour, int endHour) { this.startMinutes = startHour * 60; this.endMinutes = endHour * 60; } public void setWorktimeMinutes(int startMinutes, int endMinutes) { this.startMinutes = startMinutes; this.endMinutes = endMinutes; if (getStartDate() != null) calcMinMaxDates( getStartDate() ); } public void setLocale(Locale locale) { super.setLocale( locale ); if ( timeScale != null ) timeScale.setLocale( locale ); } public void scrollDateVisible(Date date) { LargeDaySlot slot = getSlot(date); if ( slot == null) { return; } if (!jCenter.isAncestorOf( slot) ) { return; } LargeDaySlot scrollSlot = slot; Rectangle viewRect = scrollPane.getViewport().getViewRect(); Rectangle slotRect = scrollSlot.getBounds(); // test if already visible if (slotRect.x>=viewRect.x && (slotRect.x + slotRect.width)< (viewRect.x + viewRect.width ) ) { return; } scrollSlot.scrollRectToVisible(new Rectangle(0 ,viewRect.y ,scrollSlot.getWidth() ,10)); } public void scrollToStart() { int y = rowScale.getStartWorktimePixel(); int x = 0; scrollPane.getViewport().setViewPosition(new Point(x,y)); } public Collection<Block> getBlocks() { ArrayList<Block> list = new ArrayList<Block>(); for (int i=0;i<getDaysInView();i++) { list.addAll(daySlots[i].getBlocks()); } return Collections.unmodifiableCollection( list ); } /** The granularity of the selection rows. * <ul> * <li>1: 1 rows per hour = 1 Hour</li> * <li>2: 2 rows per hour = 1/2 Hour</li> * <li>3: 3 rows per hour = 20 Minutes</li> * <li>4: 4 rows per hour = 15 Minutes</li> * <li>6: 6 rows per hour = 10 Minutes</li> * <li>12: 12 rows per hour = 5 Minutes</li> * </ul> * Default is 4. */ public void setRowsPerHour(int rowsPerHour) { if ( rowScale instanceof LinearRowScale) ((LinearRowScale)rowScale).setRowsPerHour(rowsPerHour); } /** @see #setRowsPerHour */ public int getRowsPerHour() { if ( rowScale instanceof LinearRowScale) return ((LinearRowScale)rowScale).getRowsPerHour(); return 0; } /** The size of each row (in pixel). Default is 15.*/ public void setRowSize(int rowSize) { if ( rowScale instanceof LinearRowScale) ((LinearRowScale)rowScale).setRowSize(rowSize); } public int getRowSize() { if ( rowScale instanceof LinearRowScale) return ((LinearRowScale)rowScale).getRowSize(); return 0; } public void setBackground(Color color) { super.setBackground(color); if (timeScale != null) timeScale.setBackground(color); } public void setEditable(boolean b) { super.setEditable( b ); // Hide the rest for (int i= 0;i<daySlots.length;i++) { LargeDaySlot slot = daySlots[i]; if (slot == null) continue; slot.setEditable(b); slot.getHeader().setBorder(b ? SLOTHEADER_BORDER : null); } } /** must be called after the slots are filled*/ protected boolean isEmpty(int column) { return daySlots[column].isEmpty(); } public void rebuild() { daySlots= new LargeDaySlot[getColumnCount()]; selectionHandler.clearSelection(); // clear everything jHeader.removeAll(); jCenter.removeAll(); int start = startMinutes ; int end = endMinutes ; // calculate the blocks Iterator<Builder> it= builders.iterator(); while (it.hasNext()) { Builder b= it.next(); b.prepareBuild(getStartDate(),getEndDate()); if (! bEditable) { start = Math.min(b.getMinMinutes(),start); end = Math.max(b.getMaxMinutes(),end); if (start<0) throw new IllegalStateException("builder.getMin() is smaller than 0"); if (end>24*60) throw new IllegalStateException("builder.getMax() is greater than 24"); } } //rowScale = new VariableRowScale(); if ( rowScale instanceof LinearRowScale) { LinearRowScale linearScale = (LinearRowScale) rowScale; int pixelPerHour = linearScale.getRowsPerHour() * linearScale.getRowSize(); timeScale.setBackground(component.getBackground()); linearScale.setTimeZone( timeZone ); if ( isEditable()) { timeScale.setTimeIntervall(0, 24, pixelPerHour); linearScale.setTimeIntervall( 0, 24 * 60); } else { timeScale.setTimeIntervall(start / 60, end / 60, pixelPerHour); linearScale.setTimeIntervall( (start /60) * 60, Math.min( 24 * 60, ((end / 60) + ((end%60 != 0) ? 1 : 0)) * 60 )); } linearScale.setWorktimeMinutes( this.startMinutes, this.endMinutes); } else { timeScale.setBackground(component.getBackground()); timeScale.setTimeIntervall(0, 24, 60); VariableRowScale periodScale = (VariableRowScale) rowScale; periodScale.setTimeZone( timeZone ); } // create Slots DraggingHandler draggingHandler = new DraggingHandler(this, rowScale,true); for (int i=0; i<getColumnCount(); i++) { createMultiSlot(i, i, draggingHandler, selectionHandler); } // build Blocks it= builders.iterator(); while (it.hasNext()) { Builder b= it.next(); if (b.isEnabled()) { b.build(this); } } // add Slots for (int i=0; i<daySlots.length; i++) { if ( isExcluded(i) ) { continue; } addToWeekView(daySlots[i]); } jHeader.add(Box.createGlue()); jHeader.validate(); jCenter.validate(); if ( isEditable()) { updateSize(component.getSize().width); } component.revalidate(); component.repaint(); } private void createMultiSlot(int pos, int column, DraggingHandler draggingHandler, SelectionHandler selectionHandler) { JComponent header = createSlotHeader(column); LargeDaySlot c= new LargeDaySlot(slotSize,rowScale, header); c.setEditable(isEditable()); c.setTimeIntervall(); c.setDraggingHandler(draggingHandler); c.addMouseListener(selectionHandler); c.addMouseMotionListener(selectionHandler); daySlots[pos]= c; } protected Date getDateFromColumn(int column) { return DateTools.addDays( getStartDate(), column); } /** override this method, if you want to create your own slot header. */ protected JComponent createSlotHeader(Integer column) { JLabel jLabel = new JLabel(); jLabel.setBorder(isEditable() ? SLOTHEADER_BORDER : null); Date date = getDateFromColumn(column); jLabel.setText(AbstractCalendar.formatDayOfWeekDateMonth(date,locale,getTimeZone())); jLabel.setFont(new Font("SansSerif", Font.PLAIN, 13)); jLabel.setHorizontalAlignment(JLabel.CENTER); jLabel.setOpaque(false); jLabel.setForeground(Color.black); return jLabel; } protected int getColumnCount() { return getDaysInView(); } public void addBlock(Block bl, int col,int slot) { checkBlock( bl ); LargeDaySlot dslot = daySlots[col]; dslot.putBlock((SwingBlock)bl, slot); } private LargeDaySlot getSlot(Date start) { long countDays = DateTools.countDays(DateTools.cutDate(getStartDate()), start); int slotNr = (int) countDays; if ( daySlots.length ==0) { return null; } int min = Math.min(daySlots.length-1,slotNr); return daySlots[min]; } private void addToWeekView(LargeDaySlot slot) { jHeader.add(slot.getHeader()); jHeader.add(Box.createHorizontalStrut(SLOT_GAP)); jCenter.add(slot); jCenter.add(Box.createHorizontalStrut(SLOT_GAP)); } public int getSlotNr(DaySlot slot) { for (int i=0;i<daySlots.length;i++) { if (daySlots[i] == slot) { return i; } } throw new IllegalStateException("Slot not found in List"); } int getRowsPerDay() { return rowScale.getRowsPerDay(); } LargeDaySlot getSlot( int nr ) { if ( nr >=0 && nr< daySlots.length) return daySlots[nr]; else return null; } public boolean isSelected(int slotNr) { LargeDaySlot slot = getSlot(slotNr); if ( slot == null) { return false; } return slot.isSelected(); } int getDayCount() { return daySlots.length; } int calcSlotNr(int x, int y) { for (int i=0;i<daySlots.length;i++) { if (getSlot(i) == null) continue; Point p = getSlot(i).getLocation(); if (p.x <= x && x <= p.x + daySlots[i].getWidth() && p.y <= y && y <= p.y + daySlots[i].getHeight() ) return i; } return -1; } public LargeDaySlot calcSlot(int x, int y) { int nr = calcSlotNr(x, y); if (nr == -1) return null; else return daySlots[nr]; } protected Date createDate(DaySlot slot,int index, boolean startOfRow) { Calendar calendar = createCalendar(); calendar.setTime( getStartDate() ); calendar.set( Calendar.DAY_OF_WEEK, getFirstWeekday() ); calendar.add( Calendar.DATE , getSlotNr( slot ) %getDaysInView()); if (!startOfRow) index++; calendar.set(Calendar.HOUR_OF_DAY,rowScale.calcHour(index)); calendar.set(Calendar.MINUTE,rowScale.calcMinute(index)); calendar.set(Calendar.SECOND,0); calendar.set(Calendar.MILLISECOND,0); return calendar.getTime(); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview; import java.util.Collection; import java.util.Date; import java.util.TimeZone; public interface CalendarView { public TimeZone getTimeZone(); /** returns the first Date that will be displayed in the calendar */ public Date getStartDate(); /** returns the last Date that will be displayed in the calendar */ public Date getEndDate(); /** sets the calendarview to the selected date*/ public void setToDate(Date weekDate); /** This method removes all existing blocks first. * Then it calls the build method of all added builders, so that they can add blocks into the CalendarView again. * After all blocks are added the Calendarthat repaints the screen. */ public void rebuild(); /** Adds a block. You can optionaly specify a slot, if the day-view supports multiple slots (like in the weekview). * If the selected slot does not exist it will be created. This method is usually called by the builders. */ public void addBlock(Block bl, int column,int slot); /** returns a collection of all the added blocks * @see #addBlock*/ Collection<Block> getBlocks(); }
Java
package org.rapla.components.calendarview; import java.text.DateFormat; import java.text.FieldPosition; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Iterator; import java.util.Locale; import java.util.TimeZone; import org.rapla.components.util.DateTools; public abstract class AbstractCalendar { private int daysInView = 7; private int firstWeekday = Calendar.getInstance().getFirstDayOfWeek(); /** shared calendar instance. Only used for temporary stored values. */ protected Calendar blockCalendar; protected Collection<Integer> excludeDays = Collections.emptySet(); private Date startDate; private Date endDate; protected Locale locale; protected TimeZone timeZone; protected int daysInMonth; protected Collection<Builder> builders = new ArrayList<Builder>(); public int getDaysInView() { return daysInView; } public void setDaysInView(int daysInView) { this.daysInView = daysInView; } public int getFirstWeekday() { return firstWeekday; } public void setFirstWeekday(int firstDayOfWeek) { this.firstWeekday = firstDayOfWeek; } public String getWeekdayName(int weekday) { SimpleDateFormat format = new SimpleDateFormat("EEEEEE",locale); Calendar calendar = createCalendar(); calendar.set(Calendar.DAY_OF_WEEK, weekday); String weekdayName = format.format(calendar.getTime()); return weekdayName; } protected boolean isExcluded(int column) { if ( daysInView == 1) { return false; } blockCalendar.set(Calendar.DAY_OF_WEEK, getFirstWeekday()); blockCalendar.add(Calendar.DATE, column); int weekday = blockCalendar.get(Calendar.DAY_OF_WEEK); if ( !excludeDays.contains(new Integer( weekday )) ) { return false; } boolean empty = isEmpty(column); return empty; } abstract protected boolean isEmpty(int column); public void setTimeZone(TimeZone timeZone) { this.timeZone = timeZone; blockCalendar = createCalendar(); } protected Calendar createCalendar() { return Calendar.getInstance(getTimeZone(),locale); } public TimeZone getTimeZone() { return timeZone; } public void setLocale(Locale locale) { this.locale = locale; // Constructor called? if (timeZone != null) { setTimeZone( timeZone ); blockCalendar = createCalendar(); } } public void setToDate(Date date) { calcMinMaxDates( date ); } public Date getStartDate() { return startDate; } public Date getEndDate() { return endDate; } protected void setStartDate(Date date) { this.startDate = date; } protected void setEndDate(Date date) { this.endDate = date; } public void setExcludeDays(Collection<Integer> excludeDays) { this.excludeDays = excludeDays; if (getStartDate() != null) calcMinMaxDates( getStartDate() ); } public void rebuild(Builder builder) { try { addBuilder( builder); rebuild(); } finally { removeBuilder( builder ); } } public void calcMinMaxDates(Date date) { Calendar blockCalendar = createCalendar(); blockCalendar.setTime( date ); blockCalendar.set(Calendar.HOUR_OF_DAY,0); blockCalendar.set(Calendar.MINUTE,0); blockCalendar.set(Calendar.SECOND,0); blockCalendar.set(Calendar.MILLISECOND,0); this.daysInMonth = blockCalendar.getActualMaximum( Calendar.DAY_OF_MONTH ) ; if ( daysInView > 14) { blockCalendar.set(Calendar.DAY_OF_MONTH, 1); this.startDate = blockCalendar.getTime(); blockCalendar.set(Calendar.MILLISECOND,1); blockCalendar.set(Calendar.MILLISECOND,0); blockCalendar.add(Calendar.DATE, this.daysInMonth); this.endDate = blockCalendar.getTime(); firstWeekday = blockCalendar.getFirstDayOfWeek(); } else { if ( daysInView >= 3) { int firstWeekday2 = getFirstWeekday(); blockCalendar.set(Calendar.DAY_OF_WEEK, firstWeekday2); if ( blockCalendar.getTime().after( date)) { blockCalendar.add(Calendar.DATE, -7); } } else { firstWeekday = blockCalendar.get( Calendar.DAY_OF_WEEK); } startDate = blockCalendar.getTime(); endDate =DateTools.addDays(startDate, daysInView); } } public abstract void rebuild(); public Iterator<Builder> getBuilders() { return builders.iterator(); } public void addBuilder(Builder b) { builders.add(b); } public void removeBuilder(Builder b) { builders.remove(b); } /** formats the date and month in the selected locale and timeZone*/ public static String formatDateMonth(Date date, Locale locale, TimeZone timeZone) { FieldPosition fieldPosition = new FieldPosition( DateFormat.YEAR_FIELD ); StringBuffer buf = new StringBuffer(); DateFormat format = DateFormat.getDateInstance( DateFormat.SHORT, locale); format.setTimeZone( timeZone ); buf = format.format(date, buf, fieldPosition ); if ( fieldPosition.getEndIndex()<buf.length() ) { buf.delete( fieldPosition.getBeginIndex(), fieldPosition.getEndIndex()+1 ); } else if ( (fieldPosition.getBeginIndex()>=0) ) { buf.delete( fieldPosition.getBeginIndex(), fieldPosition.getEndIndex() ); } char lastChar = buf.charAt(buf.length()-1); if (lastChar == '/' || lastChar == '-' ) { String result = buf.substring(0,buf.length()-1); return result; } else { String result = buf.toString(); return result; } } /** formats the day of week, date and month in the selected locale and timeZone*/ public static String formatDayOfWeekDateMonth(Date date, Locale locale, TimeZone timeZone) { SimpleDateFormat format = new SimpleDateFormat("EEE", locale); format.setTimeZone(timeZone); String datePart = format.format(date); String dateOfMonthPart = AbstractCalendar.formatDateMonth( date,locale,timeZone ); return datePart + " " + dateOfMonthPart ; } public static boolean isAmPmFormat(Locale locale) { // Determines if am-pm-format should be used. DateFormat format= DateFormat.getTimeInstance(DateFormat.SHORT, locale); FieldPosition amPmPos = new FieldPosition(DateFormat.AM_PM_FIELD); format.format(new Date(), new StringBuffer(),amPmPos); return (amPmPos.getEndIndex()>0); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas, Bettina Lademann | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Locale; /** maps weekday names to Calendar.DAY_OF_WEEK. Example: <pre> WeekdayMapper mapper = new WeekdayMapper(); // print name of Sunday System.out.println(mapper.getName(Calendar.SUNDAY)); // Create a weekday ComboBox JComboBox comboBox = new JComboBox(); comboBox.setModel(new DefaultComboBoxModel(mapper.getNames())); // select sunday comboBox.setSelectedIndex(mapper.getIndexForDay(Calendar.SUNDAY)); // weekday == Calendar.SUNDAY int weekday = mapper.getDayForIndex(comboBox.getSelectedIndex()); </pre> */ public class MonthMapper { String[] monthNames; public MonthMapper() { this(Locale.getDefault()); } public MonthMapper(Locale locale) { monthNames = new String[12]; SimpleDateFormat format = new SimpleDateFormat("MMMMMM",locale); Calendar calendar = Calendar.getInstance(locale); for (int i=0;i<12;i++) { calendar.set(Calendar.MONTH,i); monthNames[i] = format.format(calendar.getTime()); } } public String[] getNames() { return monthNames; } /** month are 0 based */ public String getName(int month) { return getNames()[month]; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview; import java.util.Date; public interface Builder { /** Calculate the blocks that should be displayed in the weekview. * This method should not be called manually. * It is called by the CalendarView during the build process. * @see #build * @param start * @param end */ void prepareBuild(Date start, Date end); /** The maximal ending-time of all blocks that should be displayed. Call prepareBuild first to calculate the blocks.*/ int getMaxMinutes(); /** The minimal starting-time of all blocks that should be displayed. Call prepareBuild first to calculate the blocks.*/ int getMinMinutes(); /** Build the calculated blocks into the weekview. This method should not be called manually. * It is called by the CalendarView during the build process. * @see #prepareBuild */ void build(CalendarView cv); void setEnabled(boolean enable); boolean isEnabled(); }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview; import java.util.Date; /** implementierung von block koennen in ein slot eingefuegt werden. Sie dienen als modell fuer beliebige grafische komponenten. mit getStart() und getEnd() wird anfangs- und endzeit des blocks definiert (nur uhrzeit ist fuer positionierung in slots relevant). */ public interface Block { Date getStart(); Date getEnd(); String getName(); }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas, Bettina Lademann | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; /** maps weekday names to Calendar.DAY_OF_WEEK. Example: <pre> WeekdayMapper mapper = new WeekdayMapper(); // print name of Sunday System.out.println(mapper.getName(Calendar.SUNDAY)); // Create a weekday ComboBox JComboBox comboBox = new JComboBox(); comboBox.setModel(new DefaultComboBoxModel(mapper.getNames())); // select sunday comboBox.setSelectedIndex(mapper.getIndexForDay(Calendar.SUNDAY)); // weekday == Calendar.SUNDAY int weekday = mapper.getDayForIndex(comboBox.getSelectedIndex()); </pre> */ public class WeekdayMapper { String[] weekdayNames; int[] weekday2index; int[] index2weekday; Map<Integer,String> map = new LinkedHashMap<Integer,String>(); public WeekdayMapper() { this(Locale.getDefault()); } public WeekdayMapper(Locale locale) { int days = 7; weekdayNames = new String[days]; weekday2index = new int[days+1]; index2weekday = new int[days+1]; SimpleDateFormat format = new SimpleDateFormat("EEEEEE",locale); Calendar calendar = Calendar.getInstance(locale); calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek()); for (int i=0;i<days;i++) { int weekday = calendar.get(Calendar.DAY_OF_WEEK); weekday2index[weekday] = i; index2weekday[i] = weekday; String weekdayName = format.format(calendar.getTime()); weekdayNames[i] = weekdayName; calendar.add(Calendar.DATE,1); map.put(weekday, weekdayName); } } public String[] getNames() { return weekdayNames; } public String getName(int weekday) { return map.get( weekday); } public int dayForIndex(int index) { return index2weekday[index]; } public int indexForDay(int weekday) { return weekday2index[weekday]; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** This strategy groups all blocks in a single group */ public class BestFitStrategy extends AbstractGroupStrategy { protected Collection<List<Block>> group(List<Block> blockList) { List<List<Block>> singleGroup = new ArrayList<List<Block>>(); singleGroup.add(blockList); return singleGroup; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.calendarview; import java.util.Comparator; /** Compares to blocks by the starting time. block1<block2 if * it block1.getStart()< block2.getStart(). */ public class BlockComparator implements Comparator<Block> { public static BlockComparator COMPARATOR = new BlockComparator(); public int compare(Block b1,Block b2) { int result = b1.getStart().compareTo(b2.getStart()); if (result != 0) return result; else return b1.getName().compareTo(b2.getName()); } }
Java
/* * Sun Microsystems grants you ("Licensee") a non-exclusive, royalty * free, license to use, modify and redistribute this software in * source and binary code form, provided that i) this copyright notice * and license appear on all copies of the software; and ii) Licensee * does not utilize the software in a manner which is disparaging to * Sun Microsystems. * * The software media is distributed on an "As Is" basis, without * warranty. Neither the authors, the software developers nor Sun * Microsystems make any representation, or warranty, either express * or implied, with respect to the software programs, their quality, * accuracy, or fitness for a specific purpose. Therefore, neither the * authors, the software developers nor Sun Microsystems shall have * any liability to you or any other person or entity with respect to * any liability, loss, or damage caused or alleged to have been * caused directly or indirectly by programs contained on the * media. This includes, but is not limited to, interruption of * service, loss of data, loss of classroom time, loss of consulting * or anticipatory *profits, or consequential damages from the use of * these programs. */ package org.rapla.components.treetable; import javax.swing.tree.TreeModel; /** * TreeTableModel is the model used by a JTreeTable. It extends TreeModel * to add methods for getting inforamtion about the set of columns each * node in the TreeTableModel may have. Each column, like a column in * a TableModel, has a name and a type associated with it. Each node in * the TreeTableModel can return a value for each of the columns and * set that value if isCellEditable() returns true. * * @author Philip Milne * @author Scott Violet */ public interface TreeTableModel extends TreeModel { /** * Returns the number ofs available columns. */ public int getColumnCount(); /** * Returns the name for column number <code>column</code>. */ public String getColumnName(int column); /** * Returns the type for column number <code>column</code>. * Should return TreeTableModel.class for the tree-column. */ public Class<?> getColumnClass(int column); /** * Returns the value to be displayed for node <code>node</code>, * at column number <code>column</code>. */ public Object getValueAt(Object node, int column); /** * Indicates whether the the value for node <code>node</code>, * at column number <code>column</code> is editable. */ public boolean isCellEditable(Object node, int column); /** * Sets the value for node <code>node</code>, * at column number <code>column</code>. */ public void setValueAt(Object aValue, Object node, int column); }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.treetable; import javax.swing.CellEditor; import javax.swing.JComponent; import javax.swing.JTree; public interface TreeTableEditor extends CellEditor { JComponent getEditorComponent(JTree tree,Object value,boolean isSelected,int row); int getGap(JTree tree, Object value, boolean isSelected, int row); }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.treetable; import javax.swing.JTable; public interface TableToolTipRenderer { public String getToolTipText(JTable table, int row, int column); }
Java
/* * Sun Microsystems grants you ("Licensee") a non-exclusive, royalty * free, license to use, modify and redistribute this software in * source and binary code form, provided that i) this copyright notice * and license appear on all copies of the software; and ii) Licensee * does not utilize the software in a manner which is disparaging to * Sun Microsystems. * * The software media is distributed on an "As Is" basis, without * warranty. Neither the authors, the software developers nor Sun * Microsystems make any representation, or warranty, either express * or implied, with respect to the software programs, their quality, * accuracy, or fitness for a specific purpose. Therefore, neither the * authors, the software developers nor Sun Microsystems shall have * any liability to you or any other person or entity with respect to * any liability, loss, or damage caused or alleged to have been * caused directly or indirectly by programs contained on the * media. This includes, but is not limited to, interruption of * service, loss of data, loss of classroom time, loss of consulting * or anticipatory *profits, or consequential damages from the use of * these programs. */ package org.rapla.components.treetable; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Insets; import java.awt.Point; import java.awt.Rectangle; import java.awt.Shape; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.ArrayList; import java.util.Enumeration; import java.util.EventObject; import java.util.List; import javax.swing.JComponent; import javax.swing.JTable; import javax.swing.JTree; import javax.swing.KeyStroke; import javax.swing.ListSelectionModel; import javax.swing.LookAndFeel; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.border.Border; import javax.swing.border.CompoundBorder; import javax.swing.event.CellEditorListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.event.TreeExpansionEvent; import javax.swing.event.TreeExpansionListener; import javax.swing.event.TreeModelEvent; import javax.swing.event.TreeModelListener; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeSelectionModel; import javax.swing.tree.TreeCellRenderer; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; /** * Original version Philip Milne and Scott Violet * Modified by Christopher Kohlhaas to support editing and keyboard handling. */ public class JTreeTable extends JTable { private static final long serialVersionUID = 1L; private RendererTree tree = new RendererTree(); private TreeTableEditor treeCellEditor; private TableToolTipRenderer toolTipRenderer = null; private int focusedRow = -1; private String cachedSearchKey = ""; public JTreeTable(TreeTableModel model) { super(); setTreeTableModel( model ); // Force the JTable and JTree to share their row selection models. ListToTreeSelectionModelWrapper selectionWrapper = new ListToTreeSelectionModelWrapper(); setSelectionModel(selectionWrapper.getListSelectionModel()); setShowGrid( false); // No intercell spacing setIntercellSpacing(new Dimension(1, 0)); setShowVerticalLines(true); tree.setEditable(false); tree.setSelectionModel(selectionWrapper); tree.setShowsRootHandles(true); tree.setRootVisible(false); setDefaultRenderer( TreeTableModel.class, tree ); setTreeCellEditor(null); // And update the height of the trees row to match that of // the table. if (tree.getRowHeight() < 1) { // Metal looks better like this. setRowHeight(22); } } public void setToolTipRenderer(TableToolTipRenderer renderer) { toolTipRenderer = renderer; } public TableToolTipRenderer getToolTipRenderer() { return toolTipRenderer; } public String getToolTipText(MouseEvent evt) { if (toolTipRenderer == null) return super.getToolTipText(evt); Point p = new Point(evt.getX(),evt.getY()); int column = columnAtPoint(p); int row = rowAtPoint(p); if (row >=0 && column>=0) return toolTipRenderer.getToolTipText(this,row,column); else return super.getToolTipText(evt); } /** * Overridden to message super and forward the method to the tree. * Since the tree is not actually in the component hierarchy it will * never receive this unless we forward it in this manner. */ public void updateUI() { super.updateUI(); if(tree != null) { tree.updateUI(); } // Use the tree's default foreground and background colors in the // table. LookAndFeel.installColorsAndFont(this, "Tree.background", "Tree.foreground", "Tree.font"); } /** Set a custom TreeCellEditor. The default one is a TextField.*/ public void setTreeCellEditor(TreeTableEditor editor) { treeCellEditor = editor; setDefaultEditor( TreeTableModel.class, new DelegationgTreeCellEditor(treeCellEditor) ); } /** Returns the tree that is being shared between the model. If you set a different TreeCellRenderer for this tree it should inherit from DefaultTreeCellRenderer. Otherwise the selection-color and focus color will not be set correctly. */ public JTree getTree() { return tree; } /** * search for given search term in child nodes of selected nodes * @param search what to search for * @param parentNode where to search fo * @return first childnode where its tostring representation in tree starts with search term, null if no one found */ private TreeNode getNextTreeNodeMatching(String search, TreeNode parentNode) { TreeNode result = null; Enumeration<?> children = parentNode.children(); while (children.hasMoreElements()) { TreeNode treeNode = (TreeNode) children.nextElement(); String compareS = treeNode.toString().toLowerCase(); if (compareS.startsWith(search)) { result = treeNode; break; } } return result; } /** * create treepath from treenode * @param treeNode Treenode * @return treepath object */ public static TreePath getPath(TreeNode treeNode) { List<Object> nodes = new ArrayList<Object>(); if (treeNode != null) { nodes.add(treeNode); treeNode = treeNode.getParent(); while (treeNode != null) { nodes.add(0, treeNode); treeNode = treeNode.getParent(); } } return nodes.isEmpty() ? null : new TreePath(nodes.toArray()); } /** overridden to support keyboard expand/collapse for the tree.*/ protected boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) { if (condition == JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT) { if (tree != null && !isEditing() && getSelectedColumn() == getTreeColumnNumber()) { if (e.getID() == KeyEvent.KEY_PRESSED) { if ( (e.getKeyCode() == KeyEvent.VK_ENTER || e.getKeyChar() =='+')) { int row = getSelectedRow(); if (row >= 0) { if (tree.isExpanded(row)) { tree.collapseRow(row); } else { tree.expandPath(tree.getPathForRow(row)); } } return true; } if (e.getKeyCode() == KeyEvent.VK_LEFT) { int row = getSelectedRow(); if (row >= 0) { TreePath pathForRow = tree.getPathForRow(row); // if selected node is expanded than collapse it // else selected parents node if (tree.isExpanded(pathForRow)) { // only if root is visible we should collapse first level final boolean canCollapse = pathForRow.getPathCount() > (tree.isRootVisible() ? 0 : 1); if (canCollapse) tree.collapsePath(pathForRow); } else { // only if root is visible we should collapse first level or select parent node final boolean canCollapse = pathForRow.getPathCount() > (tree.isRootVisible() ? 1 : 2); if (canCollapse) { pathForRow = pathForRow.getParentPath(); final int parentRow = tree.getRowForPath(pathForRow ); tree.setSelectionInterval(parentRow, parentRow); } } if (pathForRow != null) { Rectangle rect = getCellRect(tree.getRowForPath(pathForRow), 0, false); scrollRectToVisible(rect ); } } return true; } if (e.getKeyCode() == KeyEvent.VK_RIGHT) { int row = getSelectedRow(); if (row >= 0) { final TreePath path = tree.getPathForRow(row); if (tree.isCollapsed(path)) { tree.expandPath(path); } } return true; } // live search in current parent node if ((Character.isLetterOrDigit(e.getKeyChar()))) { char keyChar = e.getKeyChar(); // we are searching in the current parent node // first we assume that we have selected a parent node // so we should have children TreePath selectedPath = tree.getSelectionModel().getLeadSelectionPath(); TreeNode selectedNode = (TreeNode) selectedPath.getLastPathComponent(); // if we don't have children we might have selected a leaf so choose its parent if (selectedNode.getChildCount() == 0) { // set new selectedNode selectedPath = selectedPath.getParentPath(); selectedNode = (TreeNode) selectedPath.getLastPathComponent(); } // search term String search = ("" + keyChar).toLowerCase(); // try to find node with matching searchterm plus the search before TreeNode nextTreeNodeMatching = getNextTreeNodeMatching(cachedSearchKey + search, selectedNode); // if we did not find anything, try to find search term only: restart! if (nextTreeNodeMatching == null) { nextTreeNodeMatching = getNextTreeNodeMatching(search, selectedNode); cachedSearchKey = ""; } // if we found a node, select it, make it visible and return true if (nextTreeNodeMatching != null) { TreePath foundPath = getPath(nextTreeNodeMatching); // select our found path this.tree.getSelectionModel().setSelectionPath(foundPath); //make it visible this.tree.expandPath(foundPath); this.tree.makeVisible(foundPath); // Scroll to the found row int row = tree.getRowForPath( foundPath); int col = 0; Rectangle rect = getCellRect(row, col, false); scrollRectToVisible(rect ); // store found treepath cachedSearchKey = cachedSearchKey + search; return true; } } cachedSearchKey = ""; /* Uncomment this if you don't want to start tree-cell-editing on a non navigation key stroke. if (e.getKeyCode() != e.VK_TAB && e.getKeyCode() != e.VK_F2 && e.getKeyCode() != e.VK_DOWN && e.getKeyCode() != e.VK_UP && e.getKeyCode() != e.VK_LEFT && e.getKeyCode() != e.VK_RIGHT && e.getKeyCode() != e.VK_PAGE_UP && e.getKeyCode() != e.VK_PAGE_DOWN ) return true; */ } } } // reset cachedkey to null if we did not find anything return super.processKeyBinding(ks,e,condition,pressed); } public void setTreeTableModel(TreeTableModel model) { tree.setModel(model); super.setModel(new TreeTableModelAdapter(model)); } /** * Workaround for BasicTableUI anomaly. Make sure the UI never tries to * resize the editor. The UI currently uses different techniques to * paint the renderers and editors; overriding setBounds() below * is not the right thing to do for an editor. Returning -1 for the * editing row in this case, ensures the editor is never painted. */ public int getEditingRow() { int column = getEditingColumn(); if( getColumnClass(column) == TreeTableModel.class ) return -1; return editingRow; } /** * Returns the actual row that is editing as <code>getEditingRow</code> * will always return -1. */ private int realEditingRow() { return editingRow; } /** Overridden to pass the new rowHeight to the tree. */ public void setRowHeight(int rowHeight) { super.setRowHeight(rowHeight); if (tree != null && tree.getRowHeight() != rowHeight) tree.setRowHeight( rowHeight ); } private int getTreeColumnNumber() { for (int counter = getColumnCount() - 1; counter >= 0;counter--) if (getColumnClass(counter) == TreeTableModel.class) return counter; return -1; } /** <code>isCellEditable</code> returns true for the Tree-Column, even if it is not editable. <code>isCellRealEditable</code> returns true only if the underlying TreeTableModel-Cell is editable. */ private boolean isCellRealEditable(int row,int column) { TreePath treePath = tree.getPathForRow(row); if (treePath == null) return false; return (((TreeTableModel)tree.getModel()).isCellEditable(treePath.getLastPathComponent() ,column)); } class RendererTree extends JTree implements TableCellRenderer { private static final long serialVersionUID = 1L; protected int rowToPaint; Color borderColor = Color.gray; /** Border to draw around the tree, if this is non-null, it will * be painted. */ protected Border highlightBorder; public RendererTree() { super(); } public void setRowHeight(int rowHeight) { if (rowHeight > 0) { super.setRowHeight(rowHeight); if ( JTreeTable.this.getRowHeight() != rowHeight) { JTreeTable.this.setRowHeight(getRowHeight()); } } } // Move and resize the tree to the table position public void setBounds( int x, int y, int w, int h ) { super.setBounds( x, 0, w, JTreeTable.this.getHeight() ); } public void paintEditorBackground(Graphics g,int row) { tree.rowToPaint = row; g.translate( 0, -row * getRowHeight()); Rectangle rect = g.getClipBounds(); if (rect.width >0 && rect.height >0) super.paintComponent(g); g.translate( 0, row * getRowHeight()); } // start painting at the rowToPaint public void paint( Graphics g ) { int row = rowToPaint; g.translate( 0, -rowToPaint * getRowHeight() ); super.paint(g); int x = 0; TreePath path = getPathForRow(row); Object value = path.getLastPathComponent(); boolean isSelected = tree.isRowSelected(row); x = tree.getRowBounds(row).x; if (treeCellEditor != null) { x += treeCellEditor.getGap(tree,value,isSelected,row); } else { TreeCellRenderer tcr = getCellRenderer(); if (tcr instanceof DefaultTreeCellRenderer) { DefaultTreeCellRenderer dtcr = ((DefaultTreeCellRenderer)tcr); // super.paint must have been called before x += dtcr.getIconTextGap() + dtcr.getIcon().getIconWidth(); } } // Draw the Table border if we have focus. if (highlightBorder != null) { highlightBorder.paintBorder(this, g, x, rowToPaint * getRowHeight(), getWidth() -x, getRowHeight() ); } // Paint the selection rectangle } public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Color background; Color foreground; if (hasFocus) focusedRow = row; if(isSelected) { background = table.getSelectionBackground(); foreground = table.getSelectionForeground(); } else { background = table.getBackground(); foreground = table.getForeground(); } highlightBorder = null; if (realEditingRow() == row && getEditingColumn() == column) { background = UIManager.getColor("Table.focusCellBackground"); foreground = UIManager.getColor("Table.focusCellForeground"); } else if (hasFocus) { highlightBorder = UIManager.getBorder ("Table.focusCellHighlightBorder"); if (isCellRealEditable(row,convertColumnIndexToModel(column))) { background = UIManager.getColor ("Table.focusCellBackground"); foreground = UIManager.getColor ("Table.focusCellForeground"); } } this.rowToPaint = row; setBackground(background); TreeCellRenderer tcr = getCellRenderer(); if (tcr instanceof DefaultTreeCellRenderer) { DefaultTreeCellRenderer dtcr = ((DefaultTreeCellRenderer)tcr); if (isSelected) { dtcr.setTextSelectionColor(foreground); dtcr.setBackgroundSelectionColor(background); } else { dtcr.setTextNonSelectionColor(foreground); dtcr.setBackgroundNonSelectionColor(background); } } return this; } } class DelegationgTreeCellEditor implements TableCellEditor { TreeTableEditor delegate; JComponent lastComp = null; int textOffset = 0; MouseListener mouseListener = new MouseAdapter() { public void mouseClicked(MouseEvent evt) { if (lastComp == null) return; if (delegate == null) return; if (evt.getY() < 0 || evt.getY()>lastComp.getHeight()) delegate.stopCellEditing(); // User clicked left from the text if (textOffset > 0 && evt.getX()< textOffset ) delegate.stopCellEditing(); } }; public DelegationgTreeCellEditor(TreeTableEditor delegate) { this.delegate = delegate; } public void addCellEditorListener(CellEditorListener listener) { delegate.addCellEditorListener(listener); } public void removeCellEditorListener(CellEditorListener listener) { delegate.removeCellEditorListener(listener); } public void cancelCellEditing() { delegate.cancelCellEditing(); } public Object getCellEditorValue() { return delegate.getCellEditorValue(); } public boolean stopCellEditing() { return delegate.stopCellEditing(); } public boolean shouldSelectCell(EventObject anEvent) { return true; } private int getTextOffset(Object value,boolean isSelected,int row) { int gap = delegate.getGap(tree,value,isSelected,row); TreePath path = tree.getPathForRow(row); return tree.getUI().getPathBounds(tree,path).x + gap; } public boolean inHitRegion(int x,int y) { int row = tree.getRowForLocation(x,y); TreePath path = tree.getPathForRow(row); if (path == null) return false; int gap = (delegate != null) ? delegate.getGap(tree,null,false,row) :16; return (x - gap >= tree.getUI().getPathBounds(tree,path).x || x<0); } public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { JTreeTable.this.tree.rowToPaint = row; JComponent comp = delegate.getEditorComponent(tree,value,isSelected,row); if (lastComp != comp) { if (comp != null) { comp.removeMouseListener(mouseListener); comp.addMouseListener(mouseListener); } } lastComp = comp; textOffset = getTextOffset(value,isSelected,row); Border outerBorder = new TreeBorder(0, textOffset , 0, 0,row); Border editBorder = UIManager.getBorder("Tree.editorBorder"); Border border = new CompoundBorder(outerBorder ,editBorder ); if ( comp != null) { comp.setBorder(border); } return comp; } public boolean isCellEditable( EventObject evt ) { int col = getTreeColumnNumber(); if( evt instanceof MouseEvent ) { MouseEvent me = (MouseEvent)evt; if (col >= 0) { int xPosRelativeToCell = me.getX() - getCellRect(0, col, true).x; if (me.getClickCount() > 1 && inHitRegion(xPosRelativeToCell,me.getY()) && isCellRealEditable(tree.getRowForLocation(me.getX(),me.getY()) ,convertColumnIndexToModel(col))) return true; MouseEvent newME = new MouseEvent(tree, me.getID(), me.getWhen(), me.getModifiers(), xPosRelativeToCell, me.getY(), me.getClickCount(), me.isPopupTrigger()); if (! inHitRegion(xPosRelativeToCell,me.getY()) || me.getClickCount() > 1) tree.dispatchEvent(newME); } return false; } if (delegate != null && isCellRealEditable(focusedRow,convertColumnIndexToModel(col))) return delegate.isCellEditable(evt); else return false; } } class TreeBorder implements Border { int row; Insets insets; public TreeBorder(int top,int left,int bottom,int right,int row) { this.row = row; insets = new Insets(top,left,bottom,right); } public Insets getBorderInsets(Component c) { return insets; } public void paintBorder(Component c,Graphics g,int x,int y,int width,int height) { Shape originalClip = g.getClip(); g.clipRect(0,0,insets.left -1 ,tree.getHeight()); tree.paintEditorBackground(g,row); g.setClip(originalClip); } public boolean isBorderOpaque() { return false; } } /** * ListToTreeSelectionModelWrapper extends DefaultTreeSelectionModel * to listen for changes in the ListSelectionModel it maintains. Once * a change in the ListSelectionModel happens, the paths are updated * in the DefaultTreeSelectionModel. */ class ListToTreeSelectionModelWrapper extends DefaultTreeSelectionModel implements ListSelectionListener{ private static final long serialVersionUID = 1L; /** Set to true when we are updating the ListSelectionModel. */ protected boolean updatingListSelectionModel; public ListToTreeSelectionModelWrapper() { super(); getListSelectionModel().addListSelectionListener (createListSelectionListener()); } /** * Returns the list selection model. ListToTreeSelectionModelWrapper * listens for changes to this model and updates the selected paths * accordingly. */ ListSelectionModel getListSelectionModel() { return listSelectionModel; } /** * This is overridden to set <code>updatingListSelectionModel</code> * and message super. This is the only place DefaultTreeSelectionModel * alters the ListSelectionModel. */ public void resetRowSelection() { if(!updatingListSelectionModel) { updatingListSelectionModel = true; try { super.resetRowSelection(); } finally { updatingListSelectionModel = false; } } // Notice how we don't message super if // updatingListSelectionModel is true. If // updatingListSelectionModel is true, it implies the // ListSelectionModel has already been updated and the // paths are the only thing that needs to be updated. } /** * Creates and returns an instance of ListSelectionHandler. */ protected ListSelectionListener createListSelectionListener() { return this; } /** * If <code>updatingListSelectionModel</code> is false, this will * reset the selected paths from the selected rows in the list * selection model. */ protected void updateSelectedPathsFromSelectedRows() { if(!updatingListSelectionModel) { updatingListSelectionModel = true; try { // This is way expensive, ListSelectionModel needs an // enumerator for iterating. int min = listSelectionModel.getMinSelectionIndex(); int max = listSelectionModel.getMaxSelectionIndex(); clearSelection(); if(min != -1 && max != -1) { for(int counter = min; counter <= max; counter++) { if(listSelectionModel.isSelectedIndex(counter)) { TreePath selPath = tree.getPathForRow (counter); if(selPath != null) { addSelectionPath(selPath); } } } } } finally { updatingListSelectionModel = false; } } } /** Implemention of ListSelectionListener Interface: * Class responsible for calling updateSelectedPathsFromSelectedRows * when the selection of the list changse. */ public void valueChanged(ListSelectionEvent e) { updateSelectedPathsFromSelectedRows(); } } class TreeTableModelAdapter extends AbstractTableModel implements TreeExpansionListener,TreeModelListener { private static final long serialVersionUID = 1L; TreeTableModel treeTableModel; public TreeTableModelAdapter(TreeTableModel treeTableModel) { this.treeTableModel = treeTableModel; tree.addTreeExpansionListener(this); // Install a TreeModelListener that can update the table when // tree changes. We use delayedFireTableDataChanged as we can // not be guaranteed the tree will have finished processing // the event before us. treeTableModel.addTreeModelListener(this); } // Implementation of TreeExpansionListener public void treeExpanded(TreeExpansionEvent event) { int row = tree.getRowForPath(event.getPath()); if (row + 1 < tree.getRowCount()) fireTableRowsInserted(row + 1,row + 1); } public void treeCollapsed(TreeExpansionEvent event) { int row = tree.getRowForPath(event.getPath()); if (row < getRowCount()) fireTableRowsDeleted(row + 1,row + 1); } // Implementation of TreeModelLstener public void treeNodesChanged(TreeModelEvent e) { int firstRow = 0; int lastRow = tree.getRowCount() -1; delayedFireTableRowsUpdated(firstRow,lastRow); } public void treeNodesInserted(TreeModelEvent e) { delayedFireTableDataChanged(); } public void treeNodesRemoved(TreeModelEvent e) { delayedFireTableDataChanged(); } public void treeStructureChanged(TreeModelEvent e) { delayedFireTableDataChanged(); } // Wrappers, implementing TableModel interface. public int getColumnCount() { return treeTableModel.getColumnCount(); } public String getColumnName(int column) { return treeTableModel.getColumnName(column); } public Class<?> getColumnClass(int column) { return treeTableModel.getColumnClass(column); } public int getRowCount() { return tree.getRowCount(); } private Object nodeForRow(int row) { TreePath treePath = tree.getPathForRow(row); if (treePath == null) return null; return treePath.getLastPathComponent(); } public Object getValueAt(int row, int column) { Object node = nodeForRow(row); if (node == null) return null; return treeTableModel.getValueAt(node, column); } public boolean isCellEditable(int row, int column) { if (getColumnClass(column) == TreeTableModel.class) { return true; } else { Object node = nodeForRow(row); if (node == null) return false; return treeTableModel.isCellEditable(node, column); } } public void setValueAt(Object value, int row, int column) { Object node = nodeForRow(row); if (node == null) return; treeTableModel.setValueAt(value, node, column); } /** * Invokes fireTableDataChanged after all the pending events have been * processed. SwingUtilities.invokeLater is used to handle this. */ protected void delayedFireTableRowsUpdated(int firstRow,int lastRow) { SwingUtilities.invokeLater(new UpdateRunnable(firstRow,lastRow)); } class UpdateRunnable implements Runnable { int lastRow; int firstRow; UpdateRunnable(int firstRow,int lastRow) { this.firstRow = firstRow; this.lastRow = lastRow; } public void run() { fireTableRowsUpdated(firstRow,lastRow); } } /** * Invokes fireTableDataChanged after all the pending events have been * processed. SwingUtilities.invokeLater is used to handle this. */ protected void delayedFireTableDataChanged() { SwingUtilities.invokeLater(new Runnable() { public void run() { fireTableDataChanged(); } }); } } /* public void paintComponent(Graphics g) { super.paintComponent( g ); Rectangle r = g.getClipBounds(); g.setColor( Color.white); g.fillRect(0,0, r.width, r.height ); } */ }
Java
/* * AbstractTreeTableModel.java * * Copyright (c) 1998 Sun Microsystems, Inc. All Rights Reserved. * * Sun Microsystems grants you ("Licensee") a non-exclusive, royalty * free, license to use, modify and redistribute this software in * source and binary code form, provided that i) this copyright notice * and license appear on all copies of the software; and ii) Licensee * does not utilize the software in a manner which is disparaging to * Sun Microsystems. * * The software media is distributed on an "As Is" basis, without * warranty. Neither the authors, the software developers nor Sun * Microsystems make any representation, or warranty, either express * or implied, with respect to the software programs, their quality, * accuracy, or fitness for a specific purpose. Therefore, neither the * authors, the software developers nor Sun Microsystems shall have * any liability to you or any other person or entity with respect to * any liability, loss, or damage caused or alleged to have been * caused directly or indirectly by programs contained on the * media. This includes, but is not limited to, interruption of * service, loss of data, loss of classroom time, loss of consulting * or anticipatory *profits, or consequential damages from the use of * these programs. */ package org.rapla.components.treetable; import javax.swing.event.EventListenerList; import javax.swing.event.TreeModelEvent; import javax.swing.event.TreeModelListener; import javax.swing.tree.TreePath; /** * @version 1.2 10/27/98 * An abstract implementation of the TreeTableModel interface, handling the list * of listeners. * @author Philip Milne */ public abstract class AbstractTreeTableModel implements TreeTableModel { protected Object root; protected EventListenerList listenerList = new EventListenerList(); public AbstractTreeTableModel(Object root) { this.root = root; } // // Default implementations for methods in the TreeModel interface. // public Object getRoot() { return root; } public boolean isLeaf(Object node) { return getChildCount(node) == 0; } public void valueForPathChanged(TreePath path, Object newValue) {} // This is not called in the JTree's default mode: use a naive implementation. public int getIndexOfChild(Object parent, Object child) { for (int i = 0; i < getChildCount(parent); i++) { if (getChild(parent, i).equals(child)) { return i; } } return -1; } public void addTreeModelListener(TreeModelListener l) { listenerList.add(TreeModelListener.class, l); } public void removeTreeModelListener(TreeModelListener l) { listenerList.remove(TreeModelListener.class, l); } /* * Notify all listeners that have registered interest for * notification on this event type. The event instance * is lazily created using the parameters passed into * the fire method. * @see EventListenerList */ protected void fireTreeNodesChanged(Object source, Object[] path, int[] childIndices, Object[] children) { // Guaranteed to return a non-null array Object[] listeners = listenerList.getListenerList(); TreeModelEvent e = null; // Process the listeners last to first, notifying // those that are interested in this event for (int i = listeners.length-2; i>=0; i-=2) { if (listeners[i]==TreeModelListener.class) { // Lazily create the event: if (e == null) e = new TreeModelEvent(source, path, childIndices, children); ((TreeModelListener)listeners[i+1]).treeNodesChanged(e); } } } /* * Notify all listeners that have registered interest for * notification on this event type. The event instance * is lazily created using the parameters passed into * the fire method. * @see EventListenerList */ protected void fireTreeNodesInserted(Object source, Object[] path, int[] childIndices, Object[] children) { // Guaranteed to return a non-null array Object[] listeners = listenerList.getListenerList(); TreeModelEvent e = null; // Process the listeners last to first, notifying // those that are interested in this event for (int i = listeners.length-2; i>=0; i-=2) { if (listeners[i]==TreeModelListener.class) { // Lazily create the event: if (e == null) e = new TreeModelEvent(source, path, childIndices, children); ((TreeModelListener)listeners[i+1]).treeNodesInserted(e); } } } /* * Notify all listeners that have registered interest for * notification on this event type. The event instance * is lazily created using the parameters passed into * the fire method. * @see EventListenerList */ protected void fireTreeNodesRemoved(Object source, Object[] path, int[] childIndices, Object[] children) { // Guaranteed to return a non-null array Object[] listeners = listenerList.getListenerList(); TreeModelEvent e = null; // Process the listeners last to first, notifying // those that are interested in this event for (int i = listeners.length-2; i>=0; i-=2) { if (listeners[i]==TreeModelListener.class) { // Lazily create the event: if (e == null) e = new TreeModelEvent(source, path, childIndices, children); ((TreeModelListener)listeners[i+1]).treeNodesRemoved(e); } } } /* * Notify all listeners that have registered interest for * notification on this event type. The event instance * is lazily created using the parameters passed into * the fire method. * @see EventListenerList */ protected void fireTreeStructureChanged(Object source, Object[] path, int[] childIndices, Object[] children) { // Guaranteed to return a non-null array Object[] listeners = listenerList.getListenerList(); TreeModelEvent e = null; // Process the listeners last to first, notifying // those that are interested in this event for (int i = listeners.length-2; i>=0; i-=2) { if (listeners[i]==TreeModelListener.class) { // Lazily create the event: if (e == null) e = new TreeModelEvent(source, path, childIndices, children); ((TreeModelListener)listeners[i+1]).treeStructureChanged(e); } } } // // Default impelmentations for methods in the TreeTableModel interface. // public Class<?> getColumnClass(int column) { return Object.class; } /** By default, make the column with the Tree in it the only editable one. * Making this column editable causes the JTable to forward mouse * and keyboard events in the Tree column to the underlying JTree. */ public boolean isCellEditable(Object node, int column) { return getColumnClass(column) == TreeTableModel.class; } public void setValueAt(Object aValue, Object node, int column) {} // Left to be implemented in the subclass: /* * public Object getChild(Object parent, int index) * public int getChildCount(Object parent) * public int getColumnCount() * public String getColumnName(Object node, int column) * public Object getValueAt(Object node, int column) */ }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.iolayer; import java.awt.Component; import java.awt.FileDialog; import java.awt.Frame; import java.awt.Toolkit; import java.awt.datatransfer.ClipboardOwner; import java.awt.datatransfer.Transferable; import java.awt.print.PageFormat; import java.awt.print.Paper; import java.awt.print.Printable; import java.awt.print.PrinterException; import java.awt.print.PrinterJob; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.OutputStream; import java.net.URL; import javax.print.Doc; import javax.print.DocFlavor; import javax.print.PrintException; import javax.print.SimpleDoc; import javax.print.StreamPrintService; import javax.print.StreamPrintServiceFactory; import javax.print.attribute.HashPrintRequestAttributeSet; import javax.print.attribute.PrintRequestAttributeSet; import javax.print.attribute.Size2DSyntax; import javax.print.attribute.standard.MediaName; import javax.print.attribute.standard.MediaPrintableArea; import javax.print.attribute.standard.OrientationRequested; import javax.swing.JFileChooser; import javax.swing.filechooser.FileFilter; import org.rapla.framework.logger.Logger; public class DefaultIO implements IOInterface{ static DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE; /** * Name of all Rapla printjobs (used in dialogs, printerqueue, etc). */ public final static String RAPLA_JOB= "Rapla Printjob"; public PrinterJob job; Logger logger; public DefaultIO(Logger logger) { this.logger = logger; } public Logger getLogger() { return logger; } private PrinterJob getJob() { if (job == null) job = PrinterJob.getPrinterJob(); return job; } public PageFormat defaultPage() throws UnsupportedOperationException { try { PageFormat format = getJob().defaultPage(); return format; } catch (SecurityException ex) { return new PageFormat(); } } public PageFormat showFormatDialog(PageFormat format) throws UnsupportedOperationException { logPaperSize (format.getPaper()); format = getJob().pageDialog(format); logPaperSize (format.getPaper()); return format; } public void setContents(Transferable transferable, ClipboardOwner owner) { Toolkit.getDefaultToolkit().getSystemClipboard().setContents( transferable, owner ); } public Transferable getContents( ClipboardOwner owner) { return Toolkit.getDefaultToolkit().getSystemClipboard().getContents( owner); } public boolean supportsPostscriptExport() { if (!supportsPrintService()) return false; return getPSExportServiceFactory() != null; } private boolean supportsPrintService() { try { getClass().getClassLoader().loadClass("javax.print.StreamPrintServiceFactory"); return true; } catch (ClassNotFoundException ex) { getLogger().warn("No support for javax.print.StreamPrintServiceFactory"); return false; } } protected void callExport(Printable printable, PageFormat format,OutputStream out, boolean pdf) throws UnsupportedOperationException,IOException { if ( pdf) { ITextPrinter.createPdf(printable, out, format); } save(printable,format,out); } private static StreamPrintServiceFactory getPSExportServiceFactory() { StreamPrintServiceFactory []factories = StreamPrintServiceFactory.lookupStreamPrintServiceFactories(flavor,"application/postscript"); if (factories.length == 0) { return null; } /* for (int i=0;i<factories.length;i++) { System.out.println("Stream Factory " + factories[i]); System.out.println(" Output " + factories[i].getOutputFormat()); DocFlavor[] docFlavors = factories[i].getSupportedDocFlavors(); for (int j=0;j<docFlavors.length;j++) { System.out.println(" Flavor " + docFlavors[j].getMimeType()); } }*/ return factories[0]; } public void save(Printable print,PageFormat format,OutputStream out) throws IOException { StreamPrintService sps = null; try { StreamPrintServiceFactory spsf = getPSExportServiceFactory(); if (spsf == null) { throw new UnsupportedOperationException("No suitable factories for postscript-export."); } sps = spsf.getPrintService(out); Doc doc = new SimpleDoc(print, flavor, null); PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet(); if (format.getOrientation() == PageFormat.LANDSCAPE) { aset.add(OrientationRequested.LANDSCAPE); } if (format.getOrientation() == PageFormat.PORTRAIT) { aset.add(OrientationRequested.PORTRAIT); } if (format.getOrientation() == PageFormat.REVERSE_LANDSCAPE) { aset.add(OrientationRequested.REVERSE_LANDSCAPE); } aset.add(MediaName.ISO_A4_WHITE); Paper paper = format.getPaper(); if (sps.getSupportedAttributeValues(MediaPrintableArea.class,null,null) != null) { MediaPrintableArea printableArea = new MediaPrintableArea ( (float)(paper.getImageableX()/72) ,(float)(paper.getImageableY()/72) ,(float)(paper.getImageableWidth()/72) ,(float)(paper.getImageableHeight()/72) ,Size2DSyntax.INCH ); aset.add(printableArea); // System.out.println("new Area: " + printableArea); } sps.createPrintJob().print(doc,aset); } catch (PrintException ex) { throw new IOException(ex.getMessage()); } finally { if (sps != null) sps.dispose(); } } public String saveAsFileShowDialog(String dir,Printable printable,PageFormat format,boolean askFormat,Component owner, boolean pdf) throws UnsupportedOperationException,IOException { if (askFormat) { format= showFormatDialog(format); } JFileChooser chooser = new JFileChooser(); chooser.setAcceptAllFileFilterUsed(false); chooser.setApproveButtonText("Save"); if (dir != null) chooser.setCurrentDirectory(new File(dir)); // Note: source for ExampleFileFilter can be found in FileChooserDemo, // under the demo/jfc directory in the Java 2 SDK, Standard Edition. chooser.setFileFilter( pdf ? new PDFFileFilter() :new PSFileFilter()); int returnVal = chooser.showOpenDialog(owner); if(returnVal != JFileChooser.APPROVE_OPTION) return null; File selectedFile = chooser.getSelectedFile(); String suffix = pdf ? ".pdf" : ".ps"; String name = selectedFile.getName(); if (!name.endsWith(suffix)) { String parent = selectedFile.getParent(); selectedFile = new File( parent, name + suffix); } OutputStream out = new FileOutputStream(selectedFile); callExport(printable,format,out, pdf); out.close(); return selectedFile.getPath(); } private class PSFileFilter extends FileFilter { public boolean accept(File file) { return (file.isDirectory() || file.getName().toLowerCase().endsWith(".ps")); } public String getDescription() { return "Postscript"; } } private class PDFFileFilter extends FileFilter { public boolean accept(File file) { return (file.isDirectory() || file.getName().toLowerCase().endsWith(".pdf")); } public String getDescription() { return "PDF"; } } public void saveAsFile(Printable printable,PageFormat format,OutputStream out, boolean pdf) throws UnsupportedOperationException,IOException { callExport(printable,format,out, pdf); } /** Prints an awt or swing component. @param askFormat If true a dialog will show up to allow the user to edit printformat. */ public boolean print(Printable printable, PageFormat format, boolean askFormat) throws PrinterException { getJob().setPrintable(printable, format); getJob().setJobName(RAPLA_JOB); if (askFormat) { if (getJob().printDialog()) { logPaperSize (format.getPaper()); getJob().print(); return true; } } else { getJob().print(); return true; } getJob().cancel(); return false; } void logPaperSize(Paper paper) { if (getLogger().isDebugEnabled()) getLogger().debug( (paper.getImageableX()/72) * INCH_TO_MM +", " +(paper.getImageableY()/72) * INCH_TO_MM +", " +(paper.getImageableWidth() /72) * INCH_TO_MM +", " +(paper.getImageableHeight() /72) * INCH_TO_MM ); } public String saveFile(Frame frame,String dir,final String[] fileExtensions, String filename, byte[] content) throws IOException { final FileDialog fd = new FileDialog(frame, "Save File", FileDialog.SAVE); if ( dir == null) { try { dir = getDirectory(); } catch (Exception ex) { } } if ( dir != null) { fd.setDirectory(dir); } fd.setFile(filename); if ( fileExtensions.length > 0) { fd.setFilenameFilter( new FilenameFilter() { public boolean accept(File dir, String name) { final String[] split = name.split("."); if ( split.length > 1) { String extension = split[split.length -1].toLowerCase(); for ( String ext: fileExtensions) { if ( ext.toLowerCase().equals(extension )) { return true; } } } return false; } }); } fd.setLocation(50, 50); fd.setVisible( true); final String savedFileName = fd.getFile(); if (savedFileName == null) { return null; } String path = createFullPath(fd); final File savedFile = new File( path); writeFile(savedFile, content); return path; } public FileContent openFile(Frame frame,String dir, String[] fileExtensions) throws IOException { final FileDialog fd = new FileDialog(frame, "Open File", FileDialog.LOAD); if ( dir == null) { dir = getDirectory(); } fd.setDirectory(dir); fd.setLocation(50, 50); fd.setVisible( true); final String openFileName = fd.getFile(); if (openFileName == null) { return null; } String path = createFullPath(fd); final FileInputStream openFile = new FileInputStream( path); FileContent content = new FileContent(); content.setName( openFileName); content.setInputStream( openFile ); return content; } private String getDirectory() { final String userHome = System.getProperty("user.home"); if (userHome == null) { final File execDir = new File(""); return execDir.getAbsolutePath(); } return userHome; } private String createFullPath(final FileDialog fd) { return fd.getDirectory() + System.getProperty("file.separator").charAt(0) + fd.getFile(); } private void writeFile(final File savedFile, byte[] content) throws IOException { final FileOutputStream out; out = new FileOutputStream(savedFile); out.write( content); out.flush(); out.close(); } public boolean openUrl(URL url) throws IOException { try { java.awt.Desktop.getDesktop().browse(url.toURI()); return true; } catch (Throwable ex) { getLogger().error(ex.getMessage(), ex); return false; } } }
Java
package org.rapla.components.iolayer; import java.awt.Graphics2D; import java.awt.print.PageFormat; import java.awt.print.Printable; import com.itextpdf.text.Document; import com.itextpdf.text.Rectangle; import com.itextpdf.text.pdf.PdfContentByte; import com.itextpdf.text.pdf.PdfTemplate; import com.itextpdf.text.pdf.PdfWriter; public class ITextPrinter { static public void createPdf( Printable printable, java.io.OutputStream fileOutputStream, PageFormat format) { float width = (float)format.getWidth(); float height = (float)format.getHeight(); Rectangle pageSize = new Rectangle(width, height); Document document = new Document(pageSize); try { PdfWriter writer = PdfWriter.getInstance(document, fileOutputStream); document.open(); PdfContentByte cb = writer.getDirectContent(); for (int page = 0;page<5000;page++) { Graphics2D g2; PdfTemplate tp = cb.createTemplate(width, height); g2 = tp.createGraphics(width, height); int status = printable.print(g2, format, page); g2.dispose(); if ( status == Printable.NO_SUCH_PAGE) { break; } if ( status != Printable.PAGE_EXISTS) { break; } cb.addTemplate(tp, 0, 0); document.newPage(); } } catch (Exception e) { System.err.println(e.getMessage()); } document.close(); } }
Java
package org.rapla.components.iolayer; import java.io.InputStream; public class FileContent { String name; InputStream inputStream; public InputStream getInputStream() { return inputStream; } void setInputStream(InputStream inputStream) { this.inputStream = inputStream; } public String getName() { return name; } void setName(String name) { this.name = name; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.iolayer; import java.awt.Frame; import java.awt.datatransfer.ClipboardOwner; import java.awt.datatransfer.Transferable; import java.awt.print.PageFormat; import java.awt.print.Printable; import java.awt.print.PrinterException; import java.io.IOException; import java.io.OutputStream; import java.net.URL; /** The IO layer is an abstraction from the io differences in webstart or desktop mode */ public interface IOInterface { String saveAsFileShowDialog( String toDir ,Printable printable ,PageFormat format ,boolean askFormat ,java.awt.Component owner ,boolean pdf ) throws IOException,UnsupportedOperationException; void saveAsFile( Printable printable ,PageFormat format ,OutputStream out ,boolean pdf ) throws IOException,UnsupportedOperationException; boolean print( Printable printable ,PageFormat format ,boolean askFormat ) throws PrinterException,UnsupportedOperationException; PageFormat defaultPage() throws UnsupportedOperationException; PageFormat showFormatDialog(PageFormat format) throws UnsupportedOperationException; void setContents(Transferable transferable, ClipboardOwner owner); Transferable getContents( ClipboardOwner owner); public String saveFile(Frame frame,String dir, String[] fileExtensions,String path, byte[] content) throws IOException; public FileContent openFile(Frame frame,String dir, String[] fileExtensions) throws IOException; public boolean openUrl(final URL url) throws IOException; boolean supportsPostscriptExport(); public double INCH_TO_MM = 25.40006; public double MM_TO_INCH = 1.0 / INCH_TO_MM; }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.iolayer; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.print.PageFormat; import java.awt.print.Printable; import java.awt.print.PrinterException; import javax.swing.RepaintManager; /** Use this to print an awt-Component on one page. */ public class ComponentPrinter implements Printable { private Component component; protected Dimension scaleToFit; public ComponentPrinter(Component c, Dimension scaleToFit) { component= c; this.scaleToFit = scaleToFit; } protected boolean setPage( int pageNumber) { // default is one page return pageNumber == 0; } public int print(Graphics g, PageFormat format, int pagenumber) throws PrinterException { if (!setPage( pagenumber)) { return Printable.NO_SUCH_PAGE; } Graphics2D g2 = (Graphics2D) g; if ( scaleToFit != null) { scaleToFit(g2, format, scaleToFit); } RepaintManager rm = RepaintManager.currentManager(component); boolean db= rm.isDoubleBufferingEnabled(); try { rm.setDoubleBufferingEnabled(false); component.printAll(g2); } finally { rm.setDoubleBufferingEnabled(db); } return Printable.PAGE_EXISTS; } private static void scaleToFit(Graphics2D g, PageFormat format, Dimension dim) { scaleToFit(g, format, dim.getWidth(),dim.getHeight()); } public static void scaleToFit(Graphics2D g, PageFormat format, double width, double height) { g.translate(format.getImageableX(), format.getImageableY()); double sx = format.getImageableWidth() / width; double sy = format.getImageableHeight() / height; if (sx < sy) { sy = sx; } else { sx = sy; } g.scale(sx, sy); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.iolayer; import java.awt.Component; import java.awt.Frame; import java.awt.datatransfer.ClipboardOwner; import java.awt.datatransfer.Transferable; import java.awt.print.PageFormat; import java.awt.print.Printable; import java.awt.print.PrinterException; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import org.rapla.framework.logger.Logger; final public class WebstartIO extends DefaultIO { Method lookup; Method getDefaultPage; Method showPageFormatDialog; Method print; Method saveFileDialog; Method openFileDialog; Method getName; Method getInputStream; Method setContents; Method getContents; Method showDocument; Class<?> unavailableServiceException; String basicService = "javax.jnlp.BasicService"; String printService = "javax.jnlp.PrintService"; String fileSaveService = "javax.jnlp.FileSaveService"; String fileOpenService = "javax.jnlp.FileOpenService"; String clipboardService = "javax.jnlp.ClipboardService"; public WebstartIO(Logger logger) throws UnsupportedOperationException { super( logger); try { Class<?> serviceManagerC = Class.forName("javax.jnlp.ServiceManager"); Class<?> printServiceC = Class.forName(printService); Class<?> fileSaveServiceC = Class.forName(fileSaveService); Class<?> fileOpenServiceC = Class.forName(fileOpenService); Class<?> clipboardServiceC = Class.forName(clipboardService); Class<?> basicServiceC = Class.forName(basicService); Class<?> fileContents = Class.forName("javax.jnlp.FileContents"); unavailableServiceException = Class.forName("javax.jnlp.UnavailableServiceException"); getName = fileContents.getMethod("getName", new Class[] {} ); getInputStream = fileContents.getMethod("getInputStream", new Class[] {} ); lookup = serviceManagerC.getMethod("lookup", new Class[] {String.class}); getDefaultPage = printServiceC.getMethod("getDefaultPage",new Class[] {}); showPageFormatDialog = printServiceC.getMethod("showPageFormatDialog",new Class[] {PageFormat.class}); print = printServiceC.getMethod("print",new Class[] {Printable.class}); saveFileDialog = fileSaveServiceC.getMethod("saveFileDialog",new Class[] {String.class,String[].class,InputStream.class,String.class}); openFileDialog = fileOpenServiceC.getMethod("openFileDialog",new Class[] {String.class,String[].class}); setContents = clipboardServiceC.getMethod("setContents", new Class[] {Transferable.class}); getContents = clipboardServiceC.getMethod("getContents", new Class[] {}); showDocument = basicServiceC.getMethod("showDocument", new Class[] {URL.class}); } catch (ClassNotFoundException ex) { getLogger().error(ex.getMessage()); throw new UnsupportedOperationException("Java Webstart not available due to " + ex.getMessage()); } catch (Exception ex) { getLogger().error(ex.getMessage()); throw new UnsupportedOperationException(ex.getMessage()); } } private Object invoke(String serviceName, Method method, Object[] args) throws Exception { Object service; try { service = lookup.invoke( null, new Object[] { serviceName }); return method.invoke( service, args); } catch (InvocationTargetException e) { throw (Exception) e.getTargetException(); } catch (Exception e) { if ( unavailableServiceException.isInstance( e ) ) { throw new UnsupportedOperationException("The java-webstart service " + serviceName + " is not available!"); } throw new UnsupportedOperationException(e.getMessage()); } } public PageFormat defaultPage() throws UnsupportedOperationException { if ( isJDK1_5orHigher() ) return super.defaultPage(); PageFormat format = null; try { format = (PageFormat) invoke ( printService, getDefaultPage, new Object[] {} ) ; } catch (Exception ex) { getLogger().error("Can't get print service using default PageFormat." + ex.getMessage()); } if (format == null) format = new PageFormat(); logPaperSize (format.getPaper()); return format; } public void setContents(Transferable transferable, ClipboardOwner owner) { try { invoke( clipboardService, setContents, new Object[] {transferable}); } catch (Exception ex) { throw new UnsupportedOperationException(ex.getMessage()); } } public Transferable getContents( ClipboardOwner owner) { try { return (Transferable)invoke( clipboardService, getContents, new Object[] {}); } catch (Exception ex) { throw new UnsupportedOperationException(ex.getMessage()); } } public PageFormat showFormatDialog(PageFormat format) throws UnsupportedOperationException { if ( isJDK1_5orHigher() ) return super.showFormatDialog( format ); logPaperSize (format.getPaper()); try { // format = getPrintService().showPageFormatDialog(format); format = (PageFormat) invoke( printService, showPageFormatDialog, new Object[] {format}); } catch (Exception ex) { throw new UnsupportedOperationException(ex.getMessage()); } return format; } /** in the new JDK we don't need the webstart print service */ private boolean isJDK1_5orHigher() { try { String version = System.getProperty("java.version"); boolean oldVersion = version.startsWith("1.4") || version.startsWith("1.3"); //System.out.println( version + " new=" + !oldVersion); return !oldVersion; //return false; } catch (SecurityException ex) { return false; } } /** Prints an printable object. The format parameter is ignored, if askFormat is not set. Call showFormatDialog to set the PageFormat. @param askFormat If true a dialog will show up to allow the user to edit printformat. */ public boolean print(Printable printable, PageFormat format, boolean askFormat) throws PrinterException,UnsupportedOperationException { if ( isJDK1_5orHigher() ) { return super.print( printable , format, askFormat ); } logPaperSize (format.getPaper()); if ( askFormat ) { format= showFormatDialog(format); } try { Boolean result = (Boolean) invoke( printService , print, new Object[] { printable }); return result.booleanValue(); } catch (PrinterException ex) { throw ex; } catch (Exception ex) { throw new UnsupportedOperationException(ex.getMessage()); } } public String saveAsFileShowDialog(String dir,Printable printable,PageFormat format,boolean askFormat,Component owner, boolean pdf) throws IOException,UnsupportedOperationException { if (askFormat) { format= showFormatDialog(format); } ByteArrayOutputStream out = new ByteArrayOutputStream(); callExport(printable,format,out, pdf); if (dir == null) dir = ""; if ( pdf){ return saveFile( null, dir, new String[] {"pdf"},"RaplaOutput.pdf", out.toByteArray()); } else { return saveFile( null, dir, new String[] {"ps"},"RaplaOutput.ps", out.toByteArray()); } } public String saveFile(Frame frame,String dir, String[] fileExtensions, String filename, byte[] content) throws IOException { try { InputStream in = new ByteArrayInputStream( content); Object result = invoke( fileSaveService, saveFileDialog, new Object[] { dir ,fileExtensions ,in ,filename }); if (result != null) return (String) getName.invoke( result, new Object[] {}); else return null; } catch (IOException ex) { throw ex; } catch (Exception ex) { throw new UnsupportedOperationException("Can't invoke save Method " + ex.getMessage() ); } } public FileContent openFile(Frame frame,String dir, String[] fileExtensions) throws IOException { try { Object result = invoke( fileOpenService, openFileDialog, new Object[] { dir ,fileExtensions }); if (result != null) { String name = (String) getName.invoke( result, new Object[] {}); InputStream in = (InputStream) getInputStream.invoke( result, new Object[] {}); FileContent content = new FileContent(); content.setName( name ); content.setInputStream( in ); return content; } return null; } catch (IOException ex) { throw ex; } catch (Exception ex) { throw new UnsupportedOperationException("Can't invoke open Method " + ex.getMessage() ); } } public boolean openUrl(URL url) throws IOException { try { // Lookup the javax.jnlp.BasicService object invoke(basicService,showDocument, new Object[] {url}); // Invoke the showDocument method return true; } catch(Exception ex) { return false; } } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.util; import java.util.Date; import java.util.Locale; import java.util.TimeZone; /** Tools for manipulating dates. * At the moment of writing rapla internaly stores all appointments * in the GMT timezone. */ public abstract class DateTools { public static final int DAYS_PER_WEEK= 7; public static final long MILLISECONDS_PER_MINUTE = 1000 * 60; public static final long MILLISECONDS_PER_HOUR = MILLISECONDS_PER_MINUTE * 60; public static final long MILLISECONDS_PER_DAY = 24 * MILLISECONDS_PER_HOUR; public static final long MILLISECONDS_PER_WEEK = 7 * MILLISECONDS_PER_DAY; public static final int SUNDAY = 1, MONDAY = 2, TUESDAY = 3, WEDNESDAY = 4, THURSDAY = 5, FRIDAY = 6, SATURDAY = 7; public static int getHourOfDay(long date) { return (int) ((date % MILLISECONDS_PER_DAY)/ MILLISECONDS_PER_HOUR); } public static int getMinuteOfHour(long date) { return (int) ((date % MILLISECONDS_PER_HOUR)/ MILLISECONDS_PER_MINUTE); } public static int getMinuteOfDay(long date) { return (int) ((date % MILLISECONDS_PER_DAY)/ MILLISECONDS_PER_MINUTE); } public static String formatDate(Date date) { SerializableDateTimeFormat format = new SerializableDateTimeFormat(); String string = format.formatDate( date); return string; } public static String formatDate(Date date, @SuppressWarnings("unused") Locale locale) { // FIXME has to be replaced with locale implementation // DateFormat format = DateFormat.getDateInstance(DateFormat.SHORT,locale); // format.setTimeZone(DateTools.getTimeZone()); // String string = format.format( date); // return string; return formatDate(date); } public static String formatTime(Date date) { SerializableDateTimeFormat format = new SerializableDateTimeFormat(); String string = format.formatTime( date); return string; } public static String formatDateTime(Date date) { SerializableDateTimeFormat format = new SerializableDateTimeFormat(); String dateString = format.formatDate( date); String timeString = format.formatTime( date); String string = dateString + " " + timeString; return string; } public static int getDaysInMonth(int year, int month) { int _month = month+1; if ( _month == 2) { if ( isLeapYear(year)) { return 29; } return 28; } else if ( _month == 4 || _month == 6 || _month == 9 || _month == 11 ) { return 30; } else { return 31; } } public static boolean isLeapYear(int year) { return year % 4 == 0 && ((year % 100) != 0 || (year % 400) == 0); } /** sets time of day to 0:00. @see #cutDate(Date) */ public static long cutDate(long date) { long dateModMillis = date % MILLISECONDS_PER_DAY; if ( dateModMillis == 0) { return date; } if ( date >= 0) { return (date - dateModMillis); } else { return (date - (MILLISECONDS_PER_DAY + dateModMillis)); } } public static boolean isMidnight(long date) { return cutDate( date ) == date ; } public static boolean isMidnight(Date date) { return isMidnight( date.getTime()); } /** sets time of day to 0:00. */ public static Date cutDate(Date date) { long time = date.getTime(); if ( time %MILLISECONDS_PER_DAY == 0) { return date; } return new Date(cutDate(time)); } private static TimeZone timeZone =TimeZone.getTimeZone("GMT"); /** same as TimeZone.getTimeZone("GMT"). */ public static TimeZone getTimeZone() { return timeZone; } /** sets time of day to 0:00 and increases day. @see #fillDate(Date) */ public static long fillDate(long date) { // cut date long cuttedDate = (date - (date % MILLISECONDS_PER_DAY)); return cuttedDate + MILLISECONDS_PER_DAY; } public static Date fillDate(Date date) { return new Date(fillDate(date.getTime())); } /** Monday 24:00 = tuesday 0:00. But the first means end of monday and the second start of tuesday. The default DateFormat always displays tuesday. If you want to edit the first interpretation in calendar components. call addDay() to add 1 day to the given date before displaying and subDay() for mapping a day back after editing. @see #subDay @see #addDays */ public static Date addDay(Date date) { return addDays( date, 1); } public static Date addYear(Date date) { return addYears(date, 1); } public static Date addWeeks(Date date, int weeks) { Date result = new Date(date.getTime() + MILLISECONDS_PER_WEEK * weeks); return result; } public static Date addYears(Date date, int yearModifier) { int monthModifier = 0; return modifyDate(date, yearModifier, monthModifier); } public static Date addMonth(Date startDate) { return addMonths(startDate, 1); } public static Date addMonths(Date startDate, int monthModifier) { int yearModifier = 0; return modifyDate(startDate, yearModifier, monthModifier); } private static Date modifyDate(Date startDate, int yearModifier, int monthModifier) { long original = startDate.getTime(); long millis = original - DateTools.cutDate( original ); DateWithoutTimezone date = toDate( original); int year = date.year + yearModifier; int month = date.month + monthModifier; if ( month < 1 ) { year += month/ 12 -1 ; month = ((month +11) % 12) + 1; } if ( month >12 ) { year += month/ 12; month = ((month -1) % 12) + 1; } int day = date.day ; long newDate = toDate(year, month, day); Date result = new Date( newDate + millis); return result; } /** see #addDay*/ public static Date addDays(Date date,long days) { return new Date(date.getTime() + MILLISECONDS_PER_DAY * days); } /** @see #addDay @see #subDays */ public static Date subDay(Date date) { return new Date(date.getTime() - MILLISECONDS_PER_DAY); } /** @see #addDay */ public static Date subDays(Date date,int days) { return new Date(date.getTime() - MILLISECONDS_PER_DAY * days); } /** returns if the two dates are one the same date. * Dates must be in GMT */ static public boolean isSameDay( Date d1, Date d2) { return cutDate( d1 ).equals( cutDate ( d2 )); } /** returns if the two dates are one the same date. * Dates must be in GMT */ static public boolean isSameDay( long d1, long d2) { return cutDate( d1 ) == cutDate ( d2 ); } /** returns the day of week SUNDAY = 1, MONDAY = 2, TUESDAY = 3, WEDNESDAY = 4, THURSDAY = 5, FRIDAY = 6, SATURDAY = 7 */ public static int getWeekday(Date date) { long days = countDays(0,date.getTime()); int weekday_zero = THURSDAY; int alt = (int) days%7; int weekday = weekday_zero + alt; if ( weekday > 7) { weekday -=7; } else if ( weekday <=0 ) { weekday += 7 ; } return weekday; } public static int getDayOfWeekInMonth(Date date) { DateWithoutTimezone date2 = toDate( date.getTime()); int day = date2.day; int occurances = (day-1) / 7 + 1; return occurances; } // public static int getWeekOfYear(Date date) // { // // 1970/1/1 is a thursday // long millis = date.getTime(); // long daysSince1970 = millis >= 0 ? millis/ MILLISECONDS_PER_DAY : ((millis + MILLISECONDS_PER_DAY - 1)/ MILLISECONDS_PER_DAY + 1) ; // int weekday = daysSince1970 + 4; // // } public static int getDayOfMonth(Date date) { DateWithoutTimezone date2 = toDate( date.getTime()); int result = date2.day; return result; } // /** uses the calendar-object for date comparison. // * Use this for non GMT Dates*/ // static public boolean isSameDay( Calendar calendar, Date d1, Date d2 ) { // calendar.setTime( d1 ); // int era1 = calendar.get( Calendar.ERA ); // int year1 = calendar.get( Calendar.YEAR ); // int day_of_year1 = calendar.get( Calendar.DAY_OF_YEAR ); // calendar.setTime( d2 ); // int era2 = calendar.get( Calendar.ERA ); // int year2 = calendar.get( Calendar.YEAR ); // int day_of_year2 = calendar.get( Calendar.DAY_OF_YEAR ); // return ( era1 == era2 && year1 == year2 && day_of_year1 == day_of_year2 ); // } static public long countDays(Date start,Date end) { return countDays(start.getTime(), end.getTime()); } static public long countDays(long start,long end) { return (cutDate(end) - cutDate(start)) / MILLISECONDS_PER_DAY; } static public long countMinutes(Date start, Date end) { return (end.getTime()- start.getTime())/ MILLISECONDS_PER_MINUTE; } static public long countMinutes(long start, long end){ return (end-start)/ MILLISECONDS_PER_MINUTE; } // static public Calendar createGMTCalendar() // { // return Calendar.getInstance( GMT); // } static int date_1970_1_1 = calculateJulianDayNumberAtNoon(1970, 1, 1); /** Return a the whole number, with no fraction. The JD at noon is 1 more than the JD at midnight. */ private static int calculateJulianDayNumberAtNoon(int y, int m, int d) { //http://www.hermetic.ch/cal_stud/jdn.htm int result = (1461 * (y + 4800 + (m - 14) / 12)) / 4 + (367 * (m - 2 - 12 * ((m - 14) / 12))) / 12 - (3 * ((y + 4900 + (m - 14) / 12) / 100)) / 4 + d - 32075; return result; } /** * * @param year * @param month ranges from 1-12 * @param day * @return */ public static long toDate(int year, int month, int day ) { int days = calculateJulianDayNumberAtNoon(year, month, day); int diff = days - date_1970_1_1; long millis = diff * MILLISECONDS_PER_DAY; return millis; } public static class DateWithoutTimezone { public int year; public int month; public int day; public String toString() { return year+"-" +month + "-" + day; } } public static class TimeWithoutTimezone { public int hour; public int minute; public int second; public int milliseconds; public String toString() { return hour+":" +minute + ":" + second + "." + milliseconds; } } public static TimeWithoutTimezone toTime(long millis) { long millisInDay = millis - DateTools.cutDate( millis); TimeWithoutTimezone result = new TimeWithoutTimezone(); result.hour = (int) (millisInDay / MILLISECONDS_PER_HOUR); result.minute = (int) ((millisInDay % MILLISECONDS_PER_HOUR) / MILLISECONDS_PER_MINUTE); result.second = (int) ((millisInDay % MILLISECONDS_PER_MINUTE) / 1000); result.milliseconds = (int) (millisInDay % 1000 ); return result; } public static long toTime(int hour, int minute, int second) { return toTime(hour, minute, second, 0); } public static long toTime(int hour, int minute, int second, int millisecond) { long millis = hour * MILLISECONDS_PER_HOUR; millis += minute * MILLISECONDS_PER_MINUTE; millis += second * 1000; millis += millisecond; return millis; } public static DateWithoutTimezone toDate(long millis) { // special case for negative milliseconds as day rounding needs to get the lower day int day = millis >= 0 ? (int) (millis/ MILLISECONDS_PER_DAY) : (int) (( millis + MILLISECONDS_PER_DAY -1) / MILLISECONDS_PER_DAY); int julianDateAtNoon = day + date_1970_1_1; DateWithoutTimezone result = fromJulianDayNumberAtNoon( julianDateAtNoon); return result; } private static DateWithoutTimezone fromJulianDayNumberAtNoon(int julianDateAtNoon) { //http://www.hermetic.ch/cal_stud/jdn.htm int l = julianDateAtNoon + 68569; int n = (4 * l) / 146097; l = l - (146097 * n + 3) / 4; int i = (4000 * (l + 1)) / 1461001; l = l - (1461 * i) / 4 + 31; int j = (80 * l) / 2447; int d = l - (2447 * j) / 80; l = j / 11; int m = j + 2 - (12 * l); int y = 100 * (n - 49) + i + l; DateWithoutTimezone dt = new DateWithoutTimezone(); dt.year = y; dt.month = m; dt.day = d; return dt; } /** returns the largest date null dates count as postive infinity*/ public static Date max(Date... param) { Date max = null; boolean set = false; for (Date d:param) { if ( !set) { max = d; set = true; } else if ( max != null ) { if ( d == null || max.before( d)) { max = d; } } } return max; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.util.iterator; import java.util.Iterator; import java.util.NoSuchElementException; /** concatenates two Iterators */ public class IteratorChain<T> implements Iterator<T>, Iterable<T> { protected Iterator<T> firstIt; protected Iterator<T> secondIt; protected Iterator<T> thirdIt; public IteratorChain(Iterable<T> firstIt, Iterable<T> secondIt) { this( firstIt.iterator(), secondIt.iterator()); } public IteratorChain(Iterable<T> firstIt, Iterable<T> secondIt, Iterable<T> thirdIt) { this( firstIt.iterator(), secondIt.iterator(), thirdIt.iterator()); } public IteratorChain(Iterator<T> firstIt, Iterator<T> secondIt) { this.firstIt = firstIt; this.secondIt = secondIt; } public IteratorChain(Iterator<T> firstIt, Iterator<T> secondIt, Iterator<T> thirdIt) { this.firstIt = firstIt; this.secondIt = secondIt; this.thirdIt = thirdIt; } public boolean hasNext() { return (firstIt!=null && firstIt.hasNext()) || (secondIt != null && secondIt.hasNext()) || (thirdIt != null && thirdIt.hasNext()); } public void remove() { throw new UnsupportedOperationException(); } public T next() { if (firstIt!=null && !firstIt.hasNext()) { firstIt = null; } else if (secondIt!=null && !secondIt.hasNext()) { secondIt = null; } // else if (thirdIt!=null && !thirdIt.hasNext()) // { // thirdIt = null; // } if ( firstIt != null ) return firstIt.next(); else if ( secondIt != null) return secondIt.next(); else if (thirdIt != null) return thirdIt.next(); else throw new NoSuchElementException(); } public Iterator<T> iterator() { return this; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.util.iterator; import java.util.NoSuchElementException; /** This class can iterate over a string containing a list of integers. Its tuned for performance, so it will return int instead of Integer */ public class IntIterator { int parsePosition = 0; String text; char[] delimiter; int len; int next; boolean hasNext=false; char endingDelimiter; public IntIterator(String text,char delimiter) { this(text,new char[] {delimiter}); } public IntIterator(String text,char[] delimiter) { this.text = text; len = text.length(); this.delimiter = delimiter; parsePosition = 0; parseNext(); } public boolean hasNext() { return hasNext; } public int next() { if (!hasNext()) throw new NoSuchElementException(); int result = next; parseNext(); return result; } private void parseNext() { boolean isNegative = false; int relativePos = 0; next = 0; if (parsePosition == len) { hasNext = false; return; } while (parsePosition< len) { char c = text.charAt(parsePosition ); if (relativePos == 0 && c=='-') { isNegative = true; parsePosition++; continue; } boolean delimiterFound = false; for ( char d:delimiter) { if (c == d ) { parsePosition++; delimiterFound = true; break; } } if (delimiterFound || c == endingDelimiter ) { break; } int digit = c-'0'; if (digit<0 || digit>9) { hasNext = false; return; } next *= 10; next += digit; parsePosition++; relativePos++; } if (isNegative) next *= -1; hasNext = parsePosition > 0; } public int getPos() { return parsePosition; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.util.iterator; import java.util.Iterator; import java.util.NoSuchElementException; /**Successivly iterates over the elements specified in the nested Iterators. Example of an recursive traversal of an Entity Tree: <pre> class RecursiveEntityIterator extends NestedIterator { public RecursiveEntityIterator(Iterator it) { super(it); } public Iterator getNestedIterator(Object obj) { return new RecursiveEntityIterator(((Entity)obj).getSubEntities()); } } </pre> */ public abstract class NestedIterator<T,S> implements Iterator<T>, Iterable<T> { protected Iterator<S> outerIt; protected Iterator<T> innerIt; T nextElement; boolean isInitialized; public NestedIterator(Iterable<S> outerIt) { this.outerIt = outerIt.iterator(); } private T nextElement() { while (outerIt.hasNext() || (innerIt != null && innerIt.hasNext())) { if (innerIt != null && innerIt.hasNext()) return innerIt.next(); innerIt = getNestedIterator(outerIt.next()).iterator(); } return null; } public abstract Iterable<T> getNestedIterator(S obj); public boolean hasNext() { if (!isInitialized) { nextElement = nextElement(); isInitialized = true; } return nextElement != null; } public void remove() { throw new UnsupportedOperationException(); } public T next() { if (!hasNext()) throw new NoSuchElementException(); T result = nextElement; nextElement = nextElement(); return result; } public Iterator<T> iterator() { return this; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.util.iterator; import java.util.Iterator; import java.util.NoSuchElementException; /** Filters the objects of an Iterator by overiding the isInIterator method*/ public abstract class FilterIterator<T> implements Iterator<T>, Iterable<T> { Iterator<? extends Object> it; Object obj; public FilterIterator(Iterable<? extends Object> it) { this.it = it.iterator(); obj = getNextObject(); } public boolean hasNext() { return obj != null; } protected abstract boolean isInIterator(Object obj); public void remove() { throw new UnsupportedOperationException(); } private Object getNextObject() { Object o; do { if ( !it.hasNext() ) { return null; } o = it.next(); } while (!isInIterator( o)); return o; } @SuppressWarnings("unchecked") public T next() { if ( obj == null) throw new NoSuchElementException(); Object result = obj; obj = getNextObject(); return (T)result; } public Iterator<T> iterator() { return this; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.util; import java.util.Comparator; /** * * Reverts the Original Comparator * -1 -> 1 * 1 -> -1 * 0 -> 0 */ public class InverseComparator<T> implements Comparator<T> { Comparator<T> original; public InverseComparator( Comparator<T> original) { this.original = original; } public int compare( T arg0, T arg1 ) { return -1 * original.compare( arg0, arg1); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.util; public interface Command { public void execute() throws Exception; }
Java
package org.rapla.components.util; public class ParseDateException extends Exception { private static final long serialVersionUID = 1L; public ParseDateException(String message) { super(message); } }
Java
package org.rapla.components.util.xml; import java.util.Collections; import java.util.Map; public class RaplaSAXAttributes { final Map<String,String> attributeMap; public RaplaSAXAttributes(Map<String,String> map) { this.attributeMap = map; } public String getValue(@SuppressWarnings("unused") String uri,String key) { return getValue( key); } public String getValue(String key) { return attributeMap.get( key); } public Map<String, String> getMap() { return Collections.unmodifiableMap( attributeMap); } }
Java
/*---------------------------------------------------------------------------* | (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.util.xml; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; final public class XMLReaderAdapter { static SAXParserFactory spfvalidating; static SAXParserFactory spfnonvalidating; static private SAXParserFactory getFactory( boolean validating) { if ( validating && spfvalidating != null) { return spfvalidating; } if ( !validating && spfnonvalidating != null) { return spfnonvalidating; } SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); spf.setValidating(validating); if ( validating) { spfvalidating = spf; } else { spfnonvalidating = spf; } return spf; } public static XMLReader createXMLReader(boolean validating) throws SAXException { try { SAXParserFactory spf = getFactory(validating); return spf.newSAXParser().getXMLReader(); } catch (Exception ex2) { throw new SAXException("Couldn't create XMLReader " + ex2.getMessage(), ex2); } } }
Java
package org.rapla.components.util.xml; import org.rapla.framework.RaplaException; public class RaplaSAXParseException extends RaplaException{ public RaplaSAXParseException(String text, Throwable cause) { super(text, cause); } /** * */ private static final long serialVersionUID = 1L; }
Java
package org.rapla.components.util.xml; public interface RaplaSAXHandler { public void startElement(String namespaceURI, String localName, RaplaSAXAttributes atts) throws RaplaSAXParseException; public void endElement( String namespaceURI, String localName ) throws RaplaSAXParseException; public void characters( char[] ch, int start, int length ); }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.util.xml; import java.io.IOException; import java.util.Map; /** Provides some basic functionality for xml-file creation. This * is the SAX like alternative to the creation of a DOM Tree.*/ public class XMLWriter { Appendable appendable; //BufferedWriter writer; boolean xmlSQL = false; public void setWriter(Appendable writer) { this.appendable = writer; } public Appendable getWriter() { return this.appendable; } int level = 0; private void indent() throws IOException { if( !xmlSQL) //BJO do not indent for sql db, XML_VALUE column will be too small for (int i = 0; i < level * 3; i++) write(' '); } protected void increaseIndentLevel() { level ++; } protected void decreaseIndentLevel() { if (level > 0) level --; } public int getIndentLevel() { return level; } public void setIndentLevel(int level) { this.level = level; } public static String encode(String text) { boolean needsEncoding = false; int size = text.length(); for ( int i= 0; i<size && !needsEncoding; i++) { char c = text.charAt(i); switch ( c) { case '<': case '>': case '&': case '"': needsEncoding = true; break; } } if ( !needsEncoding ) return text; StringBuilder buf = new StringBuilder(); for ( int i= 0; i<size; i++) { char c = text.charAt(i); switch ( c) { case '<': buf.append("&lt;"); break; case '>': buf.append("&gt;"); break; case '&': buf.append("&amp;"); break; case '"': buf.append("&quot;"); break; default: buf.append(c); break; } // end of switch () } // end of for () return buf.toString(); } protected void printEncode(String text) throws IOException { if (text == null) return; write( encode(text) ); } protected void openTag(String start) throws IOException { indent(); write('<'); write(start); level++; } protected void openElement(String start) throws IOException { indent(); write('<'); write(start); write('>');newLine(); level++; } protected void openElementOnLine(String start) throws IOException { indent(); write('<'); write(start); write('>'); level++; } protected void att(Map<String,String> attributes) throws IOException{ for (Map.Entry<String, String> entry: attributes.entrySet()) { att(entry.getKey(),entry.getValue()); } } protected void att(String attribute,String value) throws IOException { write(' '); write(attribute); write('='); write('"'); printEncode(value); write('"'); } protected void closeTag() throws IOException { write('>');newLine(); } protected void closeTagOnLine() throws IOException{ write('>'); } protected void closeElementOnLine(String element) throws IOException { level--; write('<'); write('/'); write(element); write('>'); } protected void closeElement(String element) throws IOException { level--; indent(); write('<'); write('/'); write(element); write('>');newLine(); } protected void closeElementTag() throws IOException { level--; write('/'); write('>');newLine(); } /** writes the line to the specified PrintWriter */ public void println(String text) throws IOException { indent(); write(text);newLine(); } protected void newLine() throws IOException { appendable.append("\n"); } protected void write(String text) throws IOException { appendable.append( text); } protected void write(char c) throws IOException { appendable.append( c ); } /** writes the text to the specified PrintWriter */ public void print(String text) throws IOException { write(text); } /** writes the line to the specified PrintWriter */ public void println() throws IOException { newLine(); } public void setSQL(boolean sql) { this.xmlSQL = sql; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.util.xml; import org.rapla.framework.RaplaException; import org.rapla.framework.logger.Logger; /** Reads the data in xml format from an InputSource into the LocalCache and converts it to a newer version if necessary. */ public interface RaplaNonValidatedInput { public void read(String xml, RaplaSAXHandler handler, Logger logger) throws RaplaException; }
Java
package org.rapla.components.util.xml; import org.rapla.framework.logger.Logger; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; public class RaplaErrorHandler implements ErrorHandler { Logger logger; public RaplaErrorHandler(Logger logger) { this.logger = logger; } public void error(SAXParseException exception) throws SAXException { throw exception; } public void fatalError(SAXParseException exception) throws SAXException { throw exception; } public void warning(SAXParseException exception) throws SAXException { if (logger != null) logger.error("Warning: " + getString(exception)); } public String getString(SAXParseException exception) { // return "Line " + exception.getLineNumber() // + "\t Col " + exception.getColumnNumber() // + "\t " + return exception.getMessage(); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.util.xml; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import org.xml.sax.Attributes; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler; public class RaplaContentHandler extends DefaultHandler { Locator locator; RaplaSAXHandler handler; public RaplaContentHandler(RaplaSAXHandler handler) { this.handler = handler; } public void setDocumentLocator( Locator locator ) { this.locator = locator; } final public void startElement( String namespaceURI, String localName, String qName, Attributes atts ) throws SAXException { try { Map<String,String> attributeMap; if ( atts != null) { int length = atts.getLength(); if ( length == 0) { attributeMap = Collections.emptyMap(); } else if ( length == 1) { String key = atts.getLocalName( 0); String value = atts.getValue( 0); attributeMap = Collections.singletonMap(key, value); } else { attributeMap = new LinkedHashMap<String, String>(); for ( int i=0;i<length;i++) { String key = atts.getLocalName( i); String value = atts.getValue( i); attributeMap.put( key, value); } } } else { attributeMap = Collections.emptyMap(); } handler.startElement( namespaceURI, localName, new RaplaSAXAttributes(attributeMap) ); } catch (RaplaSAXParseException ex) { throw new SAXParseException(ex.getMessage(), locator, ex); } catch (Exception ex) { throw new SAXException( ex ); } } final public void endElement( String namespaceURI, String localName, String qName ) throws SAXException { try { handler.endElement( namespaceURI, localName); } catch ( RaplaSAXParseException ex) { throw new SAXParseException(ex.getMessage(), locator, ex); } } final public void characters( char[] ch, int start, int length ) throws SAXException { handler.characters( ch, start, length ); } }
Java
package org.rapla.components.util; import java.util.Date; import org.rapla.components.util.DateTools.TimeWithoutTimezone; import org.rapla.components.util.iterator.IntIterator; /** Provides methods for parsing and formating dates and times in the following format: <br> <code>2002-25-05</code> for dates and <code>13:00:00</code> for times. This is according to the xschema specification for dates and time and ISO8601 */ public class SerializableDateTimeFormat { public static SerializableDateTimeFormat INSTANCE = new SerializableDateTimeFormat(); // we ommit T private final static char DATE_TIME_SEPERATOR = 'T'; //private final static char DATE_TIME_SEPERATOR = ' '; private Date parseDate( String date, String time, boolean fillDate ) throws ParseDateException { if( date == null || date.length()==0 ) throwParseDateException("empty" ); long millis = parseDate_(date, fillDate); if ( time != null ) { long timeMillis = parseTime_(time); millis+= timeMillis; } // logger.log( "parsed to " + calendar.getTime() ); return new Date( millis); } private long parseTime_(String time) throws ParseDateException { int length = time.length(); if ( length <1) { throwParseTimeException( time ); } if ( time.charAt( length-1) == 'Z') { time = time.substring(0,length-1); } IntIterator it = new IntIterator( time, new char[]{':','.',','} ); if ( !it.hasNext() ) throwParseTimeException( time ); int hour = it.next(); if ( !it.hasNext() ) throwParseTimeException( time ); int minute = it.next(); int second; if ( it.hasNext() ) { second = it.next(); } else { second = 0; } int millisecond; if ( it.hasNext() ) { millisecond = it.next(); } else { millisecond = 0; } long result = DateTools.toTime( hour, minute,second, millisecond); return result; } private long parseDate_(String date, boolean fillDate) throws ParseDateException { int indexOfSeperator = indexOfSeperator(date); if ( indexOfSeperator > 0) { date = date.substring(0, indexOfSeperator); } IntIterator it = new IntIterator(date,'-'); if ( !it.hasNext() ) throwParseDateException( date ); int year = it.next(); if ( !it.hasNext() ) throwParseDateException( date); int month = it.next(); if ( !it.hasNext() ) throwParseDateException( date); int day = it.next(); if (fillDate ) { day+=1; } return DateTools.toDate( year, month, day); } private int indexOfSeperator(String date) { // First try the new ISO8601 int indexOfSeperator = date.indexOf( 'T' ); if ( indexOfSeperator<0) { //then search for a space indexOfSeperator = date.indexOf( ' ' ); } return indexOfSeperator; } private void throwParseDateException( String date) throws ParseDateException { throw new ParseDateException( "No valid date format: " + date); } private void throwParseTimeException( String time) throws ParseDateException { throw new ParseDateException( "No valid time format: " + time); } /** The date-string must be in the following format <strong>2001-10-21</strong>. The format of the time-string is <strong>18:00:00</strong>. @return The parsed date @throws ParseDateException when the date cannot be parsed. */ public Date parseDateTime( String date, String time) throws ParseDateException { return parseDate( date, time, false); } /** The format of the time-string is <strong>18:00:00</strong>. @return The parsed time @throws ParseDateException when the date cannot be parsed. */ public Date parseTime( String time) throws ParseDateException { if( time == null || time.length()==0 ) throwParseDateException("empty"); long millis = parseTime_( time); Date result = new Date( millis); return result; } /** The date-string must be in the following format <strong>2001-10-21</strong>. * @param fillDate if this flag is set the time will be 24:00 instead of 0:00 <strong> When this flag is set the time parameter should be null</strong> @return The parsed date @throws ParseDateException when the date cannot be parsed. */ public Date parseDate( String date, boolean fillDate ) throws ParseDateException { return parseDate( date, null, fillDate); } public Date parseTimestamp(String timestamp) throws ParseDateException { boolean fillDate = false; timestamp = timestamp.trim(); long millisDate = parseDate_(timestamp, fillDate); int indexOfSeperator = indexOfSeperator(timestamp); if ( timestamp.indexOf(':') >= indexOfSeperator && indexOfSeperator > 0) { String timeString = timestamp.substring( indexOfSeperator + 1); if ( timeString.length() > 0) { long time = parseTime_( timeString); millisDate+= time; } } Date result = new Date( millisDate); return result; } /** returns the time object in the following format: <strong>13:00:00</strong>. <br> */ public String formatTime( Date date ) { return formatTime(date, false); } private String formatTime(Date date, boolean includeMilliseconds) { StringBuilder buf = new StringBuilder(); if ( date == null) { date = new Date(); } TimeWithoutTimezone time = DateTools.toTime( date.getTime()); append( buf, time.hour, 2 ); buf.append( ':' ); append( buf, time.minute, 2 ); buf.append( ':' ); append( buf, time.second, 2 ); if ( includeMilliseconds) { buf.append('.'); append( buf, time.milliseconds, 4 ); } //buf.append( 'Z'); return buf.toString(); } /** returns the date object in the following format: <strong>2001-10-21</strong>. <br> @param adaptDay if the flag is set 2001-10-21 will be stored as 2001-10-20. This is usefull for end-dates: 2001-10-21 00:00 is then interpreted as 2001-10-20 24:00. */ public String formatDate( Date date, boolean adaptDay ) { StringBuilder buf = new StringBuilder(); DateTools.DateWithoutTimezone splitDate; splitDate = DateTools.toDate( date.getTime() - (adaptDay ? DateTools.MILLISECONDS_PER_DAY : 0)); append( buf, splitDate.year, 4 ); buf.append( '-' ); append( buf, splitDate.month, 2 ); buf.append( '-' ); append( buf, splitDate.day, 2 ); return buf.toString(); } public String formatTimestamp( Date date ) { StringBuilder builder = new StringBuilder(); builder.append(formatDate( date, false)); builder.append( DATE_TIME_SEPERATOR); builder.append( formatTime( date , true)); builder.append( 'Z'); String timestamp = builder.toString();; return timestamp; } /** same as formatDate(date, false). @see #formatDate(Date,boolean) */ public String formatDate( Date date ) { return formatDate( date, false ); } private void append( StringBuilder buf, int number, int minLength ) { int limit = 1; for ( int i=0;i<minLength-1;i++ ) { limit *= 10; if ( number<limit ) buf.append( '0' ); } buf.append( number ); } }
Java
package org.rapla.components.util; public interface Cancelable { public void cancel(); }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.util; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Enumeration; import java.util.StringTokenizer; /** Some IOHelper methods. */ abstract public class IOUtil { /** returns the path of the url without the last path component */ public static URL getBase(URL url) { try { String file = url.getPath(); String separator = "/"; if (url.getProtocol().equals("file") && file.indexOf(File.separator)>0) { separator = File.separator; } int index = file.lastIndexOf(separator); String dir = (index<0) ? file: file.substring(0,index + 1); return new URL(url.getProtocol() ,url.getHost() ,url.getPort() ,dir); } catch ( MalformedURLException e) { // This should not happen e.printStackTrace(); throw new RuntimeException("Unknown error while getting the base of the url!"); } // end of try-catch } /** reads the content form an url into a ByteArray*/ public static byte[] readBytes(URL url) throws IOException { InputStream in = null; ByteArrayOutputStream out = new ByteArrayOutputStream(); try { in = url.openStream(); byte[] buffer = new byte[1024]; int count = 0; do { out.write(buffer, 0, count); count = in.read(buffer, 0, buffer.length); } while (count != -1); return out.toByteArray(); } finally { if ( in != null) { in.close(); } // end of if () } } /** same as {@link URLDecoder#decode}. * But calls the deprecated method under 1.3. */ public static String decode(String s,String enc) throws UnsupportedEncodingException { return callEncodeDecode(URLDecoder.class,"decode",s,enc); } /** same as {@link URLEncoder#encode}. * But calls the deprecated method under 1.3. */ public static String encode(String s,String enc) throws UnsupportedEncodingException { return callEncodeDecode(URLEncoder.class,"encode",s,enc); } private static String callEncodeDecode(Class<?> clazz,String methodName,String s,String enc) throws UnsupportedEncodingException { Assert.notNull(s); Assert.notNull(enc); try { Method method = clazz.getMethod(methodName ,new Class[] { String.class ,String.class } ); return (String) method.invoke(null,new Object[] {s,enc}); } catch (NoSuchMethodException ex) { try { Method method = URLDecoder.class.getMethod(methodName ,new Class[] {String.class} ); return (String) method.invoke(null,new Object[] {s}); } catch (Exception ex2) { ex2.printStackTrace(); throw new IllegalStateException("Should not happen" + ex2.getMessage()); } } catch (InvocationTargetException ex) { throw (UnsupportedEncodingException) ex.getTargetException(); } catch (IllegalAccessException ex) { ex.printStackTrace(); throw new IllegalStateException("Should not happen" + ex.getMessage()); } } /** returns a BufferedInputStream from the url. If the url-protocol is "file" no url connection will be opened. */ public static InputStream getInputStream(URL url) throws IOException { if (url.getProtocol().equals("file")) { String path = decode(url.getPath(),"UTF-8"); return new BufferedInputStream(new FileInputStream(path)); } else { return new BufferedInputStream(url.openStream()); } // end of else } public static File getFileFrom(URL url) throws IOException { String path = decode(url.getPath(),"UTF-8"); return new File( path ); } /** copies a file. * @param srcPath the source-path. Thats the path of the file that should be copied. * @param destPath the destination-path */ public static void copy( String srcPath, String destPath) throws IOException{ copy( srcPath, destPath, false); } /** copies a file. * @param srcPath the source-path. Thats the path of the file that should be copied. * @param destPath the destination-path */ public static void copy( String srcPath, String destPath,boolean onlyOverwriteIfNewer ) throws IOException{ copy ( new File( srcPath ) , new File( destPath ), onlyOverwriteIfNewer ); } /** copies a file. */ public static void copy(File srcFile, File destFile, boolean onlyOverwriteIfNewer) throws IOException { if ( ! srcFile.exists() ) { throw new IOException( srcFile.getPath() + " doesn't exist!!"); } if ( destFile.exists() && destFile.lastModified() >= srcFile.lastModified() && onlyOverwriteIfNewer) { return; } FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream( srcFile ); out = new FileOutputStream( destFile); copyStreams ( in, out ); } finally { if ( in != null ) in.close(); if ( out != null ) out.close(); } } /** copies the contents of the input stream to the output stream. * @param in * @param out * @throws IOException */ public static void copyStreams( InputStream in, OutputStream out ) throws IOException { byte[] buf = new byte[ 32000 ]; int n = 0; while ( n != -1 ) { out.write( buf, 0, n ); n = in.read(buf, 0, buf.length ); } return; } public static void deleteAll(File f) { if (f.isDirectory()) { File[] files = f.listFiles(); for (File file:files) { deleteAll(file); } } f.delete(); } /** returns the relative path of file to base. * @throws IOException if position of file is not relative to base */ public static String getRelativePath(File base,File file) throws IOException { String filePath = file.getAbsoluteFile().getCanonicalPath(); String basePath = base.getAbsoluteFile().getCanonicalPath(); int start = filePath.indexOf(basePath); if (start != 0) throw new IOException(basePath + " not ancestor of " + filePath); return filePath.substring(basePath.length()); } /** returns the relative path of file to base. * same as {@link #getRelativePath(File, File)} but replaces windows-plattform-specific * file separator <code>\</code> with <code>/</code> * @throws IOException if position of file is not relative to base */ public static String getRelativeURL(File base,File file) throws IOException { StringBuffer result= new StringBuffer(getRelativePath(base,file)); for (int i=0;i<result.length();i++) { if (result.charAt(i) == '\\') result.setCharAt(i, '/'); } return result.toString(); } public static File[] getJarFiles(String baseDir,String dirList) throws IOException { ArrayList<File> completeList = new ArrayList<File>(); StringTokenizer tokenizer = new StringTokenizer(dirList,","); while (tokenizer.hasMoreTokens()) { File jarDir = new File(baseDir,tokenizer.nextToken()); if (jarDir.exists() && jarDir.isDirectory()) { File[] jarFiles = jarDir.listFiles(); for (int i = 0; i < jarFiles.length; i++) { if (jarFiles[i].getAbsolutePath().endsWith(".jar")) { completeList.add(jarFiles[i].getCanonicalFile()); } } } } return completeList.toArray(new File[] {}); } public static String getStackTraceAsString(Throwable ex) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); PrintWriter writer = new PrintWriter(bytes,true); writer.println("<h2>" + ex.getMessage() +"</h2><br/>"); ex.printStackTrace(writer); while (true) { ex = ex.getCause(); if (ex != null) { writer.println("<br/><h2>Caused by: "+ ex.getMessage() + "</h2><br/>"); ex.printStackTrace(writer); } else { break; } } return bytes.toString(); } public static boolean isSigned() { try { final ClassLoader classLoader = IOUtil.class.getClassLoader(); { final Enumeration<URL> resources = classLoader.getResources("META-INF/RAPLA.SF"); if (resources.hasMoreElements() ) return true; } { final Enumeration<URL> resources = classLoader.getResources("META-INF/RAPLA.DSA"); if (resources.hasMoreElements() ) return true; } } catch ( IOException ex) { } return false; } }
Java
package org.rapla.components.util; import java.io.Serializable; import java.util.Date; public final class TimeInterval implements Serializable { private static final long serialVersionUID = -8387919392038291664L; Date start; Date end; TimeInterval() { } public TimeInterval(Date start, Date end) { this.start = start; this.end = end; } public Date getStart() { return start; } public void setStart(Date start) { this.start = start; } public Date getEnd() { return end; } public void setEnd(Date end) { this.end = end; } public String toString() { return start + " - " + end; } public boolean equals(Object obj) { if (obj == null || !(obj instanceof TimeInterval) ) { return false; } TimeInterval other = (TimeInterval) obj; Date start2 = other.getStart(); Date end2 = other.getEnd(); if ( start == null ) { if (start != start2) { return false; } } else { if ( start2 == null || !start.equals(start2)) { return false; } } if ( end == null ) { if (end != end2) { return false; } } else { if ( end2 == null || !end.equals(end2)) { return false; } } return true; } @Override public int hashCode() { int hashCode; if ( start!=null ) { hashCode = start.hashCode(); if ( end!=null ) { hashCode *= end.hashCode(); } } else if ( end!=null ) { hashCode = end.hashCode(); } else { hashCode =super.hashCode(); } return hashCode; } public boolean overlaps(TimeInterval other) { Date start2 = other.getStart(); Date end2 = other.getEnd(); if ( start != null) { if ( end2 != null) { if ( !start.before(end2)) { return false; } } } if ( end != null) { if ( start2 != null) { if ( !start2.before(end)) { return false; } } } return true; } public TimeInterval union(TimeInterval interval) { Date start = getStart(); Date end = getEnd(); if ( interval == null ) { interval = new TimeInterval(start, end); } if ( start == null || (interval.getStart() != null && interval.getStart().after( start))) { interval = new TimeInterval( start, interval.getEnd()); } if ( end == null || ( interval.getEnd() != null && end.after( interval.getEnd()))) { interval = new TimeInterval( interval.getStart(), end); } return interval; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.util; import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.List; /** miscellaneous util methods.*/ public abstract class Tools { /** same as new Object[0].*/ public static final Object[] EMPTY_ARRAY = new Object[0]; public static final Class<?>[] EMPTY_CLASS_ARRAY = new Class[0]; public static final String[] EMPTY_STRING_ARRAY = new String[0]; /** test if 2 char arrays match. */ public static boolean match(char[] p1, char[] p2) { boolean bMatch = true; if (p1.length == p2.length) { for (int i = 0; i<p1.length; i++) { if (p1[i] != p2[i]) { bMatch = false; break; } } } else { bMatch = false; } return bMatch; } private static boolean validStart(char c) { return (c == '_' || c =='-' || Character.isLetter(c)) ? true : false; } private static boolean validLetter(char c) { return (validStart(c) || Character.isDigit(c)); } /** Rudimentary tests if the string is a valid xml-tag.*/ public static boolean isKey(String key) { // A tag name must start with a letter (a-z, A-Z) or an underscore (_) and can contain letters, digits 0-9, the period (.), the underscore (_) or the hyphen (-). char[] c = key.toCharArray(); if (c.length == 0) return false; if (!validStart(c[0])) return false; for (int i=0;i<c.length;i++) { if (!validLetter(c[i])) return false; } return true; } /** same as substring(0,width-1) except that it will not not throw an <code>ArrayIndexOutOfBoundsException</code> if string.length()&lt;width. */ public static String left(String string,int width) { return string.substring(0, Math.min(string.length(), width -1)); } /** Convert a byte array into a printable format containing aString of hexadecimal digit characters (two per byte). * This method is taken form the apache jakarata * tomcat project. */ public static String convert(byte bytes[]) { StringBuffer sb = new StringBuffer(bytes.length * 2); for (int i = 0; i < bytes.length; i++) { sb.append(convertDigit(bytes[i] >> 4)); sb.append(convertDigit(bytes[i] & 0x0f)); } return (sb.toString()); } /** Convert the specified value (0-15) to the corresponding hexadecimal digit. * This method is taken form the apache jakarata tomcat project. */ public static char convertDigit(int value) { value &= 0x0f; if (value >= 10) return ((char) (value - 10 + 'a')); else return ((char) (value + '0')); } public static boolean equalsOrBothNull(Object o1, Object o2) { if (o1 == null) { if (o2 != null) { return false; } } else if ( o2 == null) { return false; } else if (!o1.equals( o2 ) ) { return false; } return true; } /** 1.3 compatibility method */ public static String[] split(String stringToSplit, char delimiter) { List<String> keys = new ArrayList<String>(); int lastIndex = 0; while( true ) { int index = stringToSplit.indexOf( delimiter,lastIndex); if ( index < 0) { String token = stringToSplit.substring( lastIndex ); if ( token.length() >= 0) { keys.add( token ); } break; } String token = stringToSplit.substring( lastIndex , index ); keys.add( token ); lastIndex = index + 1; } return keys.toArray( new String[] {}); } // /** 1.3 compatibility method */ // public static String replaceAll( String string, String stringToReplace, String newString ) { // if ( stringToReplace.equals( newString)) // return string; // int length = stringToReplace.length(); // int oldPos = 0; // while ( true ) { // int pos = string.indexOf( stringToReplace,oldPos); // if ( pos < 0 ) // return string; // // string = string.substring(0, pos) + newString + string.substring( pos + length); // oldPos = pos + 1; // if ( oldPos >= string.length() ) // return string; // // } // } /** reads a table from a csv file. You can specify a minimum number of columns */ public static String[][] csvRead(Reader reader, int expectedColumns) throws IOException { return csvRead(reader, ';', expectedColumns); } /** reads a table from a csv file. You can specify the seperator and a minimum number of columns */ public static String[][] csvRead(Reader reader, char seperator,int expectedColumns) throws IOException { //System.out.println( "Using Encoding " + reader.getEncoding() ); StringBuffer buf = new StringBuffer(); while (true) { int c = reader.read(); if ( c == -1 ) break; buf.append( (char) c ); } String[] lines = buf.toString().split(System.getProperty("line.separator")); //BJO //String[] lines = split( buf.toString(),'\n'); String[][] lineEntries = new String[ lines.length ][]; for ( int i=0;i<lines.length; i++ ) { String stringToSplit = lines[i]; //String firstIterator =stringToSplit.replaceAll("\"\"", "DOUBLEQUOTEQUOTE"); lineEntries[i] = split( stringToSplit,seperator); if ( lineEntries[i].length < expectedColumns ) { throw new IOException("Can't parse line " + i + ":" + stringToSplit + "Expected " + expectedColumns + " Entries. Found " + lineEntries[i].length); // BJO } } return lineEntries; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.util; public class AssertionError extends RuntimeException { private static final long serialVersionUID = 1L; String text = ""; public AssertionError() { } public AssertionError(String text) { this.text = text; } public String toString() { return text; } }
Java
package org.rapla.components.util; public interface Predicate<T> { boolean apply(T t); }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.util; /** Some of the assert functionality of 1.4 for 1.3 versions of Rapla*/ public class Assert { static String NOT_NULL_ASSERTION = "notNull-Assertion"; static String IS_TRUE_ASSERTION = "isTrue-Assertion"; static String ASSERTION_FAIL = "Assertion fail"; static boolean _bActivate = true; public static void notNull(Object obj,String text) { if ( obj == null && isActivated()) { doAssert(getText(NOT_NULL_ASSERTION,text)); } } public static void notNull(Object obj) { if ( obj == null && isActivated()) { doAssert(getText(NOT_NULL_ASSERTION,"")); } } public static void isTrue(boolean condition,String text) { if ( !condition && isActivated()) { doAssert(getText(IS_TRUE_ASSERTION,text)); } // end of if () } public static void isTrue(boolean condition) { if ( !condition && isActivated()) { doAssert(getText(IS_TRUE_ASSERTION,"")); } // end of if () } public static void fail() throws AssertionError { doAssert(getText(ASSERTION_FAIL,"")); } public static void fail(String text) throws AssertionError { doAssert(getText(ASSERTION_FAIL,text)); } private static void doAssert(String text) throws AssertionError { System.err.println(text); throw new AssertionError(text); } static boolean isActivated() { return _bActivate; } static void setActivated(boolean bActivate) { _bActivate = bActivate; } static String getText(String type, String text) { return ( type + " failed '" + text + "'"); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.util; import java.util.Vector; /** Creates a new thread that successively executes the queued command objects * @see Command * @deprecated use CommandScheduler instead */ @Deprecated public class CommandQueue { private Vector<Command> v = new Vector<Command>(); public synchronized void enqueue(Command object) { v.addElement( object ); } public synchronized Command dequeue() { if ( v.size() == 0) return null; Object firstElement =v.firstElement(); if ( firstElement != null) { v.removeElementAt( 0 ); } return (Command) firstElement; } public void dequeueAll() { while ( dequeue() != null){} } /** Creates a new Queue for Command Object. The commands will be executed in succession in a seperate Daemonthread. @see Command */ public static CommandQueue createCommandQueue() { CommandQueue commandQueue = new CommandQueue(); Thread eventThread= new MyEventThread(commandQueue); eventThread.setDaemon(true); eventThread.start(); return commandQueue; } static class MyEventThread extends Thread { CommandQueue commandQueue; MyEventThread(CommandQueue commandQueue) { this.commandQueue = commandQueue; } public void run() { try { while (true) { Command command = commandQueue.dequeue(); if (command == null) { sleep(100); continue; } try { command.execute(); } catch (Exception ex) { ex.printStackTrace(); } } } catch (InterruptedException ex) { } } } }
Java
package org.rapla.components.util.undo; import java.util.EventListener; public interface CommandHistoryChangedListener extends EventListener { public void historyChanged(); }
Java
package org.rapla.components.util.undo; import java.util.ArrayList; import java.util.List; import java.util.Vector; /** * This is where all the committed actions are saved. * A list will be initialized, every action is an item of this list. * There is a list for the calendar view, and one for the edit view. * @author Jens Fritz * */ //Erstellt von Dominick Krickl-Vorreiter public class CommandHistory { private List<CommandUndo<?>> history = new ArrayList<CommandUndo<?>>(); private int current = -1; private int maxSize = 100; private Vector<CommandHistoryChangedListener> listenerList = new Vector<CommandHistoryChangedListener>(); private void fireChangeEvent() { for (CommandHistoryChangedListener listener: listenerList.toArray(new CommandHistoryChangedListener[] {})) { listener.historyChanged(); } } public <T extends Exception> boolean storeAndExecute(CommandUndo<T> cmd) throws T { while (!history.isEmpty() && (current < history.size() - 1)) { history.remove(history.size() - 1); } while (history.size() >= maxSize) { history.remove(0); current--; } if (cmd.execute()) { history.add(cmd); current++; fireChangeEvent(); return true; } else { return false; } } public void undo() throws Exception { if (!history.isEmpty() && (current >= 0)) { if (history.get(current).undo()) { current--; } fireChangeEvent(); } } public void redo() throws Exception { if (!history.isEmpty() && (current < history.size() - 1)) { if (history.get(current + 1).execute()) { current++; } fireChangeEvent(); } } public void clear() { history.clear(); current = -1; fireChangeEvent(); } public int size() { return history.size(); } public int getCurrent() { return current; } public int getMaxSize() { return maxSize; } public void setMaxSize(int maxSize) { if (maxSize > 0) { this.maxSize = maxSize; } } public boolean canUndo() { return current >= 0; } public boolean canRedo() { return current < history.size() - 1; } public String getRedoText() { if ( !canRedo()) { return ""; } else { return history.get(current + 1).getCommandoName(); } } public String getUndoText() { if ( !canUndo()) { return ""; } else { return history.get(current ).getCommandoName(); } } public void addCommandHistoryChangedListener(CommandHistoryChangedListener actionListener) { this.listenerList.add( actionListener); } public void removeCommandHistoryChangedListener(CommandHistoryChangedListener actionListener) { this.listenerList.remove( actionListener); } public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Undo=["); for (int i=current;i>0;i--) { CommandUndo<?> command = history.get(i); builder.append(command.getCommandoName()); if ( i > 0) { builder.append(", "); } } builder.append("]"); builder.append(", "); builder.append("Redo=["); for (int i=current+1;i<history.size();i++) { CommandUndo<?> command = history.get(i); builder.append(command.getCommandoName()); if ( i < history.size() -1) { builder.append(", "); } } builder.append("]"); return builder.toString(); } }
Java
package org.rapla.components.util.undo; //Erstellt von Dominick Krickl-Vorreiter public interface CommandUndo<T extends Exception> { // Der Rückgabewert signalisiert, ob alles korrekt ausgeführt wurde public boolean execute() throws T; public boolean undo() throws T; public String getCommandoName(); }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.util; import java.lang.reflect.Method; import java.net.URL; /** returns the codebase in an webstart application */ abstract public class JNLPUtil { final static String basicService = "javax.jnlp.BasicService"; final public static URL getCodeBase() throws Exception { try { Class<?> serviceManagerC = Class.forName("javax.jnlp.ServiceManager"); Class<?> basicServiceC = Class.forName( basicService ); //Class unavailableServiceException = Class.forName("javax.jnlp.UnavailableServiceException"); Method lookup = serviceManagerC.getMethod("lookup", new Class[] {String.class}); Method getCodeBase = basicServiceC.getMethod("getCodeBase", new Class[] {}); Object service = lookup.invoke( null, new Object[] { basicService }); return (URL) getCodeBase.invoke( service, new Object[] {}); } catch (ClassNotFoundException ex ) { throw new Exception( "Webstart not available :" + ex.getMessage()); } } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.util; /** Creates a new thread that successively executes the queued command objects * @see Command */ public interface CommandScheduler { public Cancelable schedule(Command object, long delay); public Cancelable schedule(Command object, long delay, long period); }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.xmlbundle; import java.util.EventListener; public interface LocaleChangeListener extends EventListener{ void localeChanged(LocaleChangeEvent evt); }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.xmlbundle; import java.util.Locale; import java.util.MissingResourceException; import javax.swing.ImageIcon; /** Allows the combination of two resource-bundles. First the inner bundle will be searched. If the requested resource was not found the outer bundle will be searched. */ public class CompoundI18n implements I18nBundle { I18nBundle inner; I18nBundle outer; public CompoundI18n(I18nBundle inner,I18nBundle outer) { this.inner = inner; this.outer = outer; } public String format(String key,Object obj1) { Object[] array1 = new Object[1]; array1[0] = obj1; return format(key,array1); } public String format(String key,Object obj1,Object obj2) { Object[] array2 = new Object[2]; array2[0] = obj1; array2[1] = obj2; return format(key,array2); } @Override public String format(String key,Object[] obj) { try { return inner.format(key, obj); } catch (MissingResourceException ex) { return outer.format( key, obj); } } public ImageIcon getIcon(String key) { try { return inner.getIcon(key); } catch (MissingResourceException ex) { return outer.getIcon(key); } } public String getString(String key) { try { return inner.getString(key); } catch (MissingResourceException ex) { return outer.getString(key); } } public String getLang() { return inner.getLang(); } public Locale getLocale() { return inner.getLocale(); } public String getString(String key, Locale locale) { try { return inner.getString(key,locale); } catch (MissingResourceException ex) { return outer.getString(key, locale); } } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.xmlbundle; import java.util.Locale; import java.util.MissingResourceException; import javax.swing.ImageIcon; /**The interface provides access to a resourcebundle that can be defined in XML or as an java-object. Example Usage: <pre> I18nBundle i18n = serviceManager.lookup(I18nBundle.class); i18n.getString("yes"); // will get the translation for yes. </pre> */ public interface I18nBundle { /** same as </code>format(key,new Object[] {obj1});</code> @see #format(String,Object[]) */ String format(String key,Object obj1) throws MissingResourceException; /** same as </code>format(key,new Object[] {obj1, obj2});</code> @see #format(String,Object[]) */ String format(String key,Object obj1,Object obj2) throws MissingResourceException; /** same as <code> (new MessageFormat(getString(key))).format(obj); </code> @see java.text.MessageFormat */ String format(String key,Object... obj) throws MissingResourceException; /** returns the specified icon from the image-resource-file. @throws MissingResourceException if not found or can't be loaded. */ ImageIcon getIcon(String key) throws MissingResourceException; /** returns the specified string from the selected resource-file. * Same as getString(key,getLocale()) * @throws MissingResourceException if not found or can't be loaded. */ String getString(String key) throws MissingResourceException; /** returns the specified string from the selected resource-file for the specified locale @throws MissingResourceException if not found or can't be loaded. */ String getString( String key, Locale locale); /** @return the selected language. */ String getLang(); /** @return the selected Locale. */ Locale getLocale(); }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.xmlbundle.impl; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.net.URL; import java.text.MessageFormat; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.TreeMap; import javax.swing.Icon; import javax.swing.ImageIcon; import org.rapla.components.util.IOUtil; import org.rapla.components.xmlbundle.I18nBundle; import org.rapla.components.xmlbundle.LocaleChangeEvent; import org.rapla.components.xmlbundle.LocaleChangeListener; import org.rapla.components.xmlbundle.LocaleSelector; import org.rapla.framework.Configuration; import org.rapla.framework.DefaultConfiguration; import org.rapla.framework.Disposable; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.framework.logger.Logger; /** The default implementation of the xmlbundle component allows reading from a compiled ResourceBundle as well as directly from the source-xml-file. <p> Sample Configuration 1: (Resources are loaded from the compiled ResourceBundles) <pre> &lt;resource-bundle id="org.rapla.RaplaResources"/> </pre> </p> <p> Sample Configuration 2: (Resources will be loaded directly from the resource-file) <pre> &lt;resource-bundle id="org.rapla.plugin.periodwizard.WizardResources"> &lt;file>/home/christopher/Rapla/src/org/rapla/periodwizard/WizardResources.xml&lt;/file> &lt;/resource-bundle> </pre> </p> <p> This class looks for a LocaleSelector on the context and registers itself as a LocaleChangeListener and switches to the new Locale on a LocaleChangeEvent. </p> @see TranslationParser @see LocaleSelector */ public class I18nBundleImpl implements I18nBundle, LocaleChangeListener, Disposable { String className; Locale locale; Logger logger = null; LocaleSelectorImpl m_localeSelector; final String dictionaryFile; final RaplaDictionary dict; LinkedHashMap<Locale,LanguagePack> packMap = new LinkedHashMap<Locale,LanguagePack>(); String parentId = null; class LanguagePack { Locale locale; Map<String,Icon> iconCache = Collections.synchronizedMap( new TreeMap<String,Icon>() ); ResourceBundle resourceBundle; public String getString( String key ) throws MissingResourceException { String lang = locale.getLanguage(); if ( dictionaryFile != null ) { String lookup = dict.lookup(key, lang); if ( lookup == null) { throw new MissingResourceException("Entry not found for "+ key, dictionaryFile, key); } return lookup; } DictionaryEntry entry = dict.getEntry(key); String string; if ( entry != null) { string = entry.get( lang ); if ( string == null ) { string = resourceBundle.getString( key ); entry.add(lang, key); } } else { string = resourceBundle.getString( key ); entry = new DictionaryEntry( key); entry.add(lang, string); try { dict.addEntry( entry); } catch (UniqueKeyException e) { // we can ignore it here } } return string; } public ImageIcon getIcon( String key ) throws MissingResourceException { String iconfile; try { iconfile = getString( key ); } catch ( MissingResourceException ex ) { getLogger().debug( ex.getMessage() ); //BJO throw ex; } try { ImageIcon icon = (ImageIcon) iconCache.get( iconfile ); if ( icon == null ) { icon = new ImageIcon( loadResource( iconfile ), key ); iconCache.put( iconfile, icon ); } // end of if () return icon; } catch ( Exception ex ) { String message = "Icon " + iconfile + " can't be created: " + ex.getMessage(); getLogger().error( message ); throw new MissingResourceException( message, className, key ); } } private final byte[] loadResource( String fileName ) throws IOException { return IOUtil.readBytes( getResourceFromFile( fileName ) ); } private URL getResourceFromFile( String fileName ) throws IOException { URL resource = null; String base; if ( dictionaryFile == null ) { if ( resourceBundle == null) { throw new IOException("Resource Bundle for locale " + locale + " is missing while looking up " + fileName); } if ( resourceBundle instanceof PropertyResourceBundleWrapper) { base = ((PropertyResourceBundleWrapper) resourceBundle).getName(); } else { base = resourceBundle.getClass().getName(); } base = base.substring(0,base.lastIndexOf(".")); base = base.replaceAll("\\.", "/"); String file = "/" + base + "/" + fileName; resource = I18nBundleImpl.class.getResource( file ); } else { if ( getLogger().isDebugEnabled() ) getLogger().debug( "Looking for resourcefile " + fileName + " in classpath "); URL resourceBundleURL = getClass().getClassLoader().getResource(dictionaryFile); if (resourceBundleURL != null) { resource = new URL( resourceBundleURL, fileName); base = resource.getPath(); } else { base = ( new File( dictionaryFile ) ).getParent(); if ( base != null) { if ( getLogger().isDebugEnabled() ) getLogger().debug( "Looking for resourcefile " + fileName + " in directory " + base ); File resourceFile = new File( base, fileName ); if ( resourceFile.exists() ) resource = resourceFile.toURI().toURL(); } } } if ( resource == null ) throw new IOException( "File '" + fileName + "' not found. " + " in bundle " + className + " It must be in the same location as '" + base + "'" ); return resource; } } /** * @throws RaplaException when the resource-file is missing or can't be accessed or can't be parsed */ public I18nBundleImpl( RaplaContext context, Configuration config, Logger logger ) throws RaplaException { enableLogging( logger ); Locale locale; m_localeSelector = (LocaleSelectorImpl) context.lookup( LocaleSelector.class ) ; if ( m_localeSelector != null ) { m_localeSelector.addLocaleChangeListenerFirst( this ); locale = m_localeSelector.getLocale(); } else { locale = Locale.getDefault(); } String filePath = config.getChild( "file" ).getValue( null ); try { InputStream resource; if ( filePath == null ) { className = config.getChild( "classname" ).getValue( null ); if ( className == null ) { className = config.getAttribute( "id" ); } else { className = className.trim(); } String resourceFile = "" + className.replaceAll("\\.", "/") + ".xml"; resource = getClass().getClassLoader().getResourceAsStream(resourceFile); dictionaryFile = resource != null ? resourceFile : null; } else { File file = new File( filePath); getLogger().info( "getting lanaguageResources from " + file.getCanonicalPath() ); resource = new FileInputStream( file ); dictionaryFile = filePath; } if ( resource != null) { dict = new TranslationParser().parse( resource ); resource.close(); } else { dict = new RaplaDictionary(locale.getLanguage()); } } catch ( Exception ex ) { throw new RaplaException( ex ); } setLocale( locale ); try { parentId = getPack(locale).getString( TranslationParser.PARENT_BUNDLE_IDENTIFIER ); } catch ( MissingResourceException ex ) { } } public String getParentId() { return parentId; } public static Configuration createConfig( String resourceFile ) { DefaultConfiguration config = new DefaultConfiguration( "component"); config.setAttribute( "id", resourceFile.toString() ); return config; } public void dispose() { if ( m_localeSelector != null ) m_localeSelector.removeLocaleChangeListener( this ); } public void localeChanged( LocaleChangeEvent evt ) { try { setLocale( evt.getLocale() ); } catch ( Exception ex ) { getLogger().error( "Can't set new locale " + evt.getLocale(), ex ); } } public void enableLogging( Logger logger ) { this.logger = logger; } protected Logger getLogger() { return logger; } public String format( String key, Object obj1 ) { Object[] array1 = new Object[1]; array1[0] = obj1; return format( key, array1 ); } public String format( String key, Object obj1, Object obj2 ) { Object[] array2 = new Object[2]; array2[0] = obj1; array2[1] = obj2; return format( key, array2 ); } public String format( String key, Object... obj ) { MessageFormat msg = new MessageFormat( getString( key ) ); return msg.format( obj ); } public ImageIcon getIcon( String key ) throws MissingResourceException { ImageIcon icon = getPack(getLocale()).getIcon( key); return icon; } public Locale getLocale() { if ( locale == null ) throw new IllegalStateException( "Call setLocale first!" ); return locale; } public String getLang() { if ( locale == null ) throw new IllegalStateException( "Call setLocale first!" ); return locale.getLanguage(); } public String getString( String key ) throws MissingResourceException { if ( locale == null ) throw new IllegalStateException( "Call setLocale first!" ); return getString(key, locale); } public String getString( String key, Locale locale) throws MissingResourceException { LanguagePack pack = getPack(locale); return pack.getString(key); } // /* replaces XHTML with HTML because swing can't display proper XHTML*/ // String filterXHTML( String text ) // { // if ( text.indexOf( "<br/>" ) >= 0 ) // { // return applyXHTMLFilter( text ); // } // else // { // return text; // } // end of else // } // public static String replaceAll( String text, String token, String with ) // { // StringBuffer buf = new StringBuffer(); // int i = 0; // int lastpos = 0; // while ( ( i = text.indexOf( token, lastpos ) ) >= 0 ) // { // if ( i > 0 ) // buf.append( text.substring( lastpos, i ) ); // buf.append( with ); // i = ( lastpos = i + token.length() ); // } // end of if () // buf.append( text.substring( lastpos, text.length() ) ); // return buf.toString(); // } // // private String applyXHTMLFilter( String text ) // { // return replaceAll( text, "<br/>", "<br></br>" ); // } public void setLocale( Locale locale ) { this.locale = locale; getLogger().debug( "Locale changed to " + locale ); try { getPack(locale); } catch (MissingResourceException ex) { getLogger().error(ex.getMessage(), ex); } } private LanguagePack getPack(Locale locale) throws MissingResourceException { LanguagePack pack = packMap.get(locale); if (pack != null) { return pack; } synchronized ( packMap ) { // again, now with synchronization pack = packMap.get(locale); if (pack != null) { return pack; } pack = new LanguagePack(); pack.locale = locale; if ( dictionaryFile == null ) { pack.resourceBundle = new ResourceBundleLoader().loadResourceBundle( className, locale ); } packMap.put( locale, pack); return pack; } } } class ResourceBundleLoader { /** this method imitates the orginal * <code>ResourceBundle.getBundle(String className,Locale * locale)</code> which causes problems when the locale is changed * to the base locale (english). For a full description see * ResourceBundle.getBundle(String className) in the java-api.*/ public ResourceBundle loadResourceBundle( String className, Locale locale ) throws MissingResourceException { String tries[] = new String[7]; StringBuffer buf = new StringBuffer(); tries[6] = className; buf.append( className ); if ( locale.getLanguage().length() > 0 ) { buf.append( '_' ); buf.append( locale.getLanguage() ); tries[2] = buf.toString(); } if ( locale.getCountry().length() > 0 ) { buf.append( '_' ); buf.append( locale.getCountry() ); tries[1] = buf.toString(); } if ( locale.getVariant().length() > 0 ) { buf.append( '_' ); buf.append( locale.getVariant() ); tries[0] = buf.toString(); } buf.delete( className.length(), buf.length() - 1 ); Locale defaultLocale = Locale.getDefault(); if ( defaultLocale.getLanguage().length() > 0 ) { buf.append( defaultLocale.getLanguage() ); tries[5] = buf.toString(); } if ( defaultLocale.getCountry().length() > 0 ) { buf.append( '_' ); buf.append( defaultLocale.getCountry() ); tries[4] = buf.toString(); } if ( defaultLocale.getVariant().length() > 0 ) { buf.append( '_' ); buf.append( defaultLocale.getVariant() ); tries[3] = buf.toString(); } ResourceBundle bundle = null; for ( int i = 0; i < tries.length; i++ ) { if ( tries[i] == null ) continue; bundle = loadBundle( tries[i] ); if ( bundle != null ) { loadParent( tries, i, bundle ); return bundle; } } throw new MissingResourceException( "'" + className + "' not found. The resource-file is missing.", className, "" ); } private ResourceBundle loadBundle( String name ) { InputStream io = null; try { String pathName = getPropertyFileNameFromClassName( name ); io = this.getClass().getResourceAsStream( pathName ); if ( io != null ) { return new PropertyResourceBundleWrapper(io , name); } ResourceBundle bundle = (ResourceBundle) this.getClass().getClassLoader().loadClass( name ).newInstance(); return bundle; } catch ( Exception ex ) { return null; } catch ( ClassFormatError ex ) { return null; } finally { if ( io != null) { try { io.close(); } catch (IOException e) { return null; } } } } private void loadParent( String[] tries, int i, ResourceBundle bundle ) { ResourceBundle parent = null; if ( i == 0 || i == 3 ) { parent = loadBundle( tries[i++] ); if ( parent != null ) setParent( bundle, parent ); bundle = parent; } if ( i == 1 || i == 4 ) { parent = loadBundle( tries[i++] ); if ( parent != null ) setParent( bundle, parent ); bundle = parent; } if ( i == 2 || i == 5 ) { parent = loadBundle( tries[6] ); if ( parent != null ) setParent( bundle, parent ); } } private void setParent( ResourceBundle bundle, ResourceBundle parent ) { try { Method method = bundle.getClass().getMethod( "setParent", new Class[] { ResourceBundle.class } ); method.invoke( bundle, new Object[] { parent } ); } catch ( Exception ex ) { } } private String getPropertyFileNameFromClassName( String classname ) { StringBuffer result = new StringBuffer( classname ); for ( int i = 0; i < result.length(); i++ ) { if ( result.charAt( i ) == '.' ) result.setCharAt( i, '/' ); } result.insert( 0, '/' ); result.append( ".properties" ); return result.toString(); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.xmlbundle.impl; import java.io.IOException; import java.io.InputStream; import java.net.URL; import org.rapla.components.util.Assert; import org.rapla.components.util.IOUtil; import org.rapla.components.util.xml.XMLReaderAdapter; import org.rapla.framework.ConfigurationException; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; /** This class reads *Resources.xml files and generates the appropriate ResourceBundle java-files. <pre> Usage : org.rapla.components.xmlbundle.TranslationParser PATH_TO_SOURCES [DESTINATION_PATH] Note: a xml-parser must be on your classpath. Example usage under windows: java -classpath lib\saxon.jar;lib\fortress.jar;build\classes org.rapla.components.xmlbundle.TranslationParser src </pre> */ public class TranslationParser extends DefaultHandler { RaplaDictionary dict; DictionaryEntry currentEntry = null; String currentLang = null; String defaultLang = null; String currentIconSrc = null; int level = 0; // used to store the nested content in the translation element StringBuffer charBuffer; XMLReader xmlReader; /** The translation parser will add an extra identifer {$i18nbundle_parent$} to the translation table if a parentbundle is specified. */ public final static String PARENT_BUNDLE_IDENTIFIER = "{$i18nbundle_parent$}"; DefaultHandler handler = new DefaultHandler() { public InputSource resolveEntity( String publicId, String systemId ) throws SAXException { if ( systemId.endsWith( "resources.dtd" ) ) { try { URL resource = getClass().getResource( "/org/rapla/components/xmlbundle/resources.dtd" ); Assert.notNull( resource, "resources.dtd not found on classpath" ); return new InputSource( IOUtil.getInputStream( resource ) ); } catch ( IOException ex ) { throw new SAXException( ex ); } } else { // use the default behaviour try { return super.resolveEntity( publicId, systemId ); } catch ( SAXException ex ) { throw ex; } catch ( Exception ex ) { throw new SAXException( ex ); } } } public void startElement( String uri, String name, String qName, Attributes atts ) throws SAXException { // if ( log.isDebugEnabled() ) // log.debug( indent() + "Start element: " + qName + "(" + name + ")" ); level: { if ( name.equals( "resources" ) ) { String defaultLang = atts.getValue( "", "default" ); String parentDict = atts.getValue( "", "parent" ); dict = new RaplaDictionary( defaultLang ); if ( parentDict != null && parentDict.trim().length() > 0 ) { DictionaryEntry entry = new DictionaryEntry( PARENT_BUNDLE_IDENTIFIER ); entry.add( "en", parentDict.trim() ); try { dict.addEntry( entry ); } catch ( UniqueKeyException ex ) { //first entry must be unique } } break level; } if ( name.equals( "entry" ) ) { String key = atts.getValue( "", "key" ); currentEntry = new DictionaryEntry( key ); break level; } if ( name.equals( "text" ) ) { currentLang = atts.getValue( "", "lang" ); if ( currentLang == null ) currentLang = dict.getDefaultLang(); charBuffer = new StringBuffer(); break level; } if ( name.equals( "icon" ) ) { currentLang = atts.getValue( "", "lang" ); if ( currentLang == null ) currentLang = dict.getDefaultLang(); currentIconSrc = atts.getValue( "", "src" ); charBuffer = new StringBuffer(); break level; } // copy startag if ( charBuffer != null ) { copyStartTag( name, atts ); } } level++; } public void endElement( String uri, String name, String qName ) throws SAXException { level--; // if ( log.isDebugEnabled() ) // log.debug( indent() + "End element: " + qName + "(" + name + ")" ); level: { if ( name.equals( "icon" ) ) { if ( currentIconSrc != null ) currentEntry.add( currentLang, currentIconSrc ); break level; } if ( name.equals( "text" ) ) { removeWhiteSpaces( charBuffer ); currentEntry.add( currentLang, charBuffer.toString() ); break level; } if ( name.equals( "entry" ) ) { try { dict.addEntry( currentEntry ); } catch ( UniqueKeyException e ) { throw new SAXException( e.getMessage() ); } // end of try-catch currentEntry = null; break level; } // copy endtag if ( charBuffer != null ) { copyEndTag( name ); } // end of if () } } public void characters( char ch[], int start, int length ) { // copy nested content if ( charBuffer != null ) { charBuffer.append( ch, start, length ); } // end of if () } }; TranslationParser() throws ConfigurationException { super(); try { xmlReader = XMLReaderAdapter.createXMLReader( false ); xmlReader.setContentHandler( handler ); xmlReader.setErrorHandler( handler ); xmlReader.setDTDHandler( handler ); xmlReader.setEntityResolver( handler ); } catch ( SAXException ex ) { if ( ex.getException() != null ) { throw new ConfigurationException( "", ex.getException() ); } else { throw new ConfigurationException( "", ex ); } // end of else } } RaplaDictionary parse( InputStream in ) throws IOException, SAXException { dict = null; xmlReader.parse( new InputSource( in ) ); checkDict(); return dict; } RaplaDictionary parse( String systemID ) throws IOException, SAXException { dict = null; xmlReader.parse( systemID ); checkDict(); return dict; } private void checkDict() throws IOException { if ( dict == null ) { throw new IOException( "Dictionary file empty " ); } } private void copyStartTag( String name, Attributes atts ) { charBuffer.append( '<' ); charBuffer.append( name ); for ( int i = 0; i < atts.getLength(); i++ ) { charBuffer.append( ' ' ); charBuffer.append( atts.getLocalName( i ) ); charBuffer.append( '=' ); charBuffer.append( '\"' ); charBuffer.append( atts.getValue( i ) ); charBuffer.append( '\"' ); } charBuffer.append( '>' ); } private void copyEndTag( String name ) { if ( ( charBuffer != null ) && ( charBuffer.length() > 0 ) && ( charBuffer.charAt( charBuffer.length() - 1 ) == '>' ) ) { // <some-tag></some-tag> --> <some-tag/> charBuffer.insert( charBuffer.length() - 1, "/" ); } else { // </some-tag> charBuffer.append( "</" + name + ">" ); } // end of else } private void removeWhiteSpaces( StringBuffer buf ) { for ( int i = 1; i < buf.length(); i++ ) { if ( ( buf.charAt( i ) == ' ' ) && ( buf.charAt( i - 1 ) == ' ' ) ) buf.deleteCharAt( --i ); } // end of for () } /** @deprecated moved to {@link ResourceFileGenerator}*/ @Deprecated public static void main( String[] args ) { ResourceFileGenerator.main(args); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.xmlbundle.impl; /** thrown by the RaplaDictionary when a duplicated entry is found */ class UniqueKeyException extends Exception { private static final long serialVersionUID = 1L; public UniqueKeyException(String text) { super(text); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.xmlbundle.impl; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Collections; import java.util.Enumeration; import java.util.HashSet; import java.util.Iterator; import java.util.Properties; import java.util.Set; import java.util.Stack; import java.util.Vector; import org.rapla.framework.ConfigurationException; import org.rapla.framework.logger.ConsoleLogger; import org.rapla.framework.logger.Logger; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; class ResourceFileGenerator { public static final String encoding = "UTF-8"; static Logger log = new ConsoleLogger( ConsoleLogger.LEVEL_INFO ); boolean writeProperties = true; public void transform(RaplaDictionary dict ,String packageName ,String classPrefix ,File destDir ) throws IOException { String[] languages = dict.getAvailableLanguages(); for (String lang:languages) { String className = classPrefix; if (!lang.equals(dict.getDefaultLang())) { className += "_" + lang; } String ending = writeProperties ? ".properties" : ".java"; File file = new File(destDir, className + ending); PrintWriter w = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),encoding))); if ( writeProperties) { Properties properties = new Properties(); Iterator<DictionaryEntry> it = dict.getEntries().iterator(); while ( it.hasNext()) { DictionaryEntry entry = it.next(); String key = entry.getKey(); String value = entry.get(lang); if ( value != null) { properties.put(key, value); } } @SuppressWarnings("serial") Properties temp = new Properties() { @SuppressWarnings({ "rawtypes", "unchecked" }) public synchronized Enumeration keys() { Enumeration<Object> keysEnum = super.keys(); Vector keyList = new Vector<Object>(); while(keysEnum.hasMoreElements()){ keyList.add(keysEnum.nextElement()); } Collections.sort(keyList); return keyList.elements(); } }; temp.putAll( properties); String comment = packageName + "." + className + "_" + lang; temp.store(w, comment); } else { generateJavaHeader(w,packageName); generateJavaContent(w,dict, className, lang); } w.flush(); w.close(); } } // public void transformSingleLanguage(RaplaDictionary dict // ,String packageName // ,String classPrefix // ,String lang // ) { // String className = classPrefix + "_" + lang; // w = new PrintWriter(System.out); // generateHeader(packageName); // generateContent(dict,className, lang); // w.flush(); // } public static String toPackageName(String pathName) { StringBuffer buf = new StringBuffer(); char[] c =pathName.toCharArray(); for (int i=0;i<c.length;i++) { if (c[i] == File.separatorChar ) { if (i>0 && i<c.length-1) buf.append('.'); } else { buf.append(c[i]); } } return buf.toString(); } private void generateJavaHeader(PrintWriter w, String packageName) { w.println("/*******************************************"); w.println(" * Autogenerated file. Please do not edit. *"); w.println(" * Edit the *Resources.xml file. *"); w.println(" *******************************************/"); w.println(); w.println("package " + packageName + ";"); } private void generateJavaContent(PrintWriter w, RaplaDictionary dict ,String className ,String lang ) { w.println("import java.util.ListResourceBundle;"); w.println("import java.util.ResourceBundle;"); w.println(); w.println("public class " + className + " extends ListResourceBundle {"); w.println(" public Object[][] getContents() { return contents; }"); // We make the setParent method public, so that we can use it in I18nImpl w.println(" public void setParent(ResourceBundle parent) { super.setParent(parent); }"); w.println(" static final Object[][] contents = { {\"\",\"\"} "); Iterator<DictionaryEntry> it = dict.getEntries().iterator(); while ( it.hasNext()) { DictionaryEntry entry = it.next(); String value = entry.get(lang); if (value != null) { String content = convertToJava(value); w.println(" , { \"" + entry.getKey() + "\",\"" + content + "\"}"); } } w.println(" };"); w.println("}"); } static public String byteToHex(byte b) { // Returns hex String representation of byte b char hexDigit[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; char[] array = { hexDigit[(b >> 4) & 0x0f], hexDigit[b & 0x0f] }; return new String(array); } static public String charToHex(char c) { // Returns hex String representation of char c byte hi = (byte) (c >>> 8); byte lo = (byte) (c & 0xff); return byteToHex(hi) + byteToHex(lo); } private String convertToJava(String text) { StringBuffer result = new StringBuffer(); for ( int i = 0;i< text.length();i++) { char c = text.charAt(i); switch ( c) { case '\n': // LineBreaks result.append("\" \n + \""); break; case '\\': // \ result.append("\\\\"); break; case '\"': // " result.append("\\\""); break; default: if ( c > 127) { result.append("\\u" + charToHex(c)); } else { result.append(c); } // end of else break; } // end of switch () } // end of for () return result.toString(); } public static final String USAGE = new String( "Usage : \n" + "PATH_TO_SOURCES [DESTINATION_PATH]\n" + "Example usage under windows:\n" + "java -classpath build\\classes " + "org.rapla.components.xmlbundle.ResourceFileGenerator " + "src \n" ); public static void processDir( String srcDir, String destDir ) throws IOException, SAXException, ConfigurationException { TranslationParser parser = new TranslationParser(); ResourceFileGenerator generator = new ResourceFileGenerator(); Set<String> languages = new HashSet<String>(); Stack<File> stack = new Stack<File>(); File topDir = new File( srcDir ); stack.push( topDir ); while ( !stack.empty() ) { File file = stack.pop(); if ( file.isDirectory() ) { // System.out.println("Checking Dir: " + file.getName()); File[] files = file.listFiles(); for ( int i = 0; i < files.length; i++ ) stack.push( files[i] ); } else { // System.out.println("Checking File: " + file.getName()); if ( file.getName().endsWith( "Resources.xml" ) ) { String absolut = file.getAbsolutePath(); System.out.println( "Transforming source:" + file ); String relativePath = absolut.substring( topDir.getAbsolutePath().length() ); String prefix = file.getName().substring( 0, file.getName().length() - "Resources.xml".length() ); String pathName = relativePath.substring( 0, relativePath.indexOf( file.getName() ) ); RaplaDictionary dict = parser.parse( file.toURI().toURL().toExternalForm() ); File dir = new File( destDir, pathName ); System.out.println( "destination:" + dir ); dir.mkdirs(); String packageName = ResourceFileGenerator.toPackageName( pathName ); generator.transform( dict, packageName, prefix + "Resources", dir ); String[] langs = dict.getAvailableLanguages(); for ( int i = 0; i < langs.length; i++ ) languages.add( langs[i] ); } } } } public static void main( String[] args ) { try { if ( args.length < 1 ) { System.out.println( USAGE ); return; } // end of if () String sourceDir = args[0]; String destDir = ( args.length > 1 ) ? args[1] : sourceDir; processDir( sourceDir, destDir ); } catch ( SAXParseException ex ) { log.error( "Line:" + ex.getLineNumber() + " Column:" + ex.getColumnNumber() + " " + ex.getMessage(), ex ); System.exit( 1 ); } catch ( Throwable e ) { log.error( e.getMessage(), e ); System.exit( 1 ); } } // end of main () }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.xmlbundle.impl; import java.util.ArrayList; import java.util.Collection; import java.util.Map; import java.util.TreeMap; class RaplaDictionary { Map<String,DictionaryEntry> entries = new TreeMap<String,DictionaryEntry>(); Collection<String> availableLang = new ArrayList<String>(); String defaultLang; public RaplaDictionary(String defaultLang) { this.defaultLang = defaultLang; } public void addEntry(DictionaryEntry entry) throws UniqueKeyException { if ( entries.get(entry.getKey()) != null) { throw new UniqueKeyException("Key '" + entry.getKey() + "' already in map."); } // end of if () String[] lang = entry.availableLanguages(); for ( int i = 0; i<lang.length;i++) if (!availableLang.contains(lang[i])) availableLang.add(lang[i]); entries.put(entry.getKey(),entry); } public Collection<DictionaryEntry> getEntries() { return entries.values(); } public String getDefaultLang() { return defaultLang; } public String[] getAvailableLanguages() { return availableLang.toArray(new String[0]); } public String lookup(String key,String lang) { DictionaryEntry entry = getEntry(key); if ( entry != null) { return entry.get(lang,defaultLang); } else { return null; } // end of else } public DictionaryEntry getEntry(String key) { return entries.get(key); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.xmlbundle.impl; import java.util.Locale; import java.util.Vector; import org.rapla.components.xmlbundle.LocaleChangeEvent; import org.rapla.components.xmlbundle.LocaleChangeListener; import org.rapla.components.xmlbundle.LocaleSelector; /** If you want to change the locales during runtime put a LocaleSelector in the base-context. Instances of {@link I18nBundleImpl} will then register them-self as {@link LocaleChangeListener LocaleChangeListeners}. Change the locale with {@link #setLocale} and all bundles will try to load the appropriate resources. */ public class LocaleSelectorImpl implements LocaleSelector { Locale locale; Vector<LocaleChangeListener> localeChangeListeners = new Vector<LocaleChangeListener>(); public LocaleSelectorImpl() { locale = Locale.getDefault(); } public void addLocaleChangeListener(LocaleChangeListener listener) { localeChangeListeners.add(listener); } public void removeLocaleChangeListener(LocaleChangeListener listener) { localeChangeListeners.remove(listener); } public void setLocale(Locale locale) { this.locale = locale; fireLocaleChanged(); } public Locale getLocale() { return this.locale; } public LocaleChangeListener[] getLocaleChangeListeners() { return localeChangeListeners.toArray(new LocaleChangeListener[]{}); } public void setLanguage(String language) { setLocale(new Locale(language,locale.getCountry())); } public void setCountry(String country) { setLocale(new Locale(locale.getLanguage(),country)); } public String getLanguage() { return locale.getLanguage(); } protected void fireLocaleChanged() { if (localeChangeListeners.size() == 0) return; LocaleChangeListener[] listeners = getLocaleChangeListeners(); LocaleChangeEvent evt = new LocaleChangeEvent(this,getLocale()); for (int i=0;i<listeners.length;i++) listeners[i].localeChanged(evt); } /** This Listeners is for the bundles only, it will ensure the bundles are always notified first. */ void addLocaleChangeListenerFirst(LocaleChangeListener listener) { localeChangeListeners.add(0,listener); } }
Java
package org.rapla.components.xmlbundle.impl; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.util.Enumeration; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Properties; import java.util.ResourceBundle; import java.util.Set; import java.util.Vector; public class PropertyResourceBundleWrapper extends ResourceBundle { private Map<String,Object> lookup; String name; static Charset charset = Charset.forName("UTF-8"); @SuppressWarnings({ "unchecked", "rawtypes" }) public PropertyResourceBundleWrapper(InputStream stream,String name) throws IOException { Properties properties = new Properties(); properties.load(new InputStreamReader(stream, charset)); lookup = new LinkedHashMap(properties); this.name = name; } public String getName() { return name; } // We make the setParent method public, so that we can use it in I18nImpl public void setParent(ResourceBundle parent) { super.setParent(parent); } // Implements java.util.ResourceBundle.handleGetObject; inherits javadoc specification. public Object handleGetObject(String key) { if (key == null) { throw new NullPointerException(); } return lookup.get(key); } /** * Returns an <code>Enumeration</code> of the keys contained in * this <code>ResourceBundle</code> and its parent bundles. * * @return an <code>Enumeration</code> of the keys contained in * this <code>ResourceBundle</code> and its parent bundles. * @see #keySet() */ public Enumeration<String> getKeys() { ResourceBundle parent = this.parent; Set<String> set = new LinkedHashSet<String>(lookup.keySet()); if ( parent != null) { set.addAll( parent.keySet()); } Vector<String> vector = new Vector<String>(set); Enumeration<String> enum1 = vector.elements(); return enum1; } /** * Returns a <code>Set</code> of the keys contained * <em>only</em> in this <code>ResourceBundle</code>. * * @return a <code>Set</code> of the keys contained only in this * <code>ResourceBundle</code> * @since 1.6 * @see #keySet() */ protected Set<String> handleKeySet() { return lookup.keySet(); } // ==================privates==================== }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.xmlbundle.impl; import java.util.Collections; import java.util.Iterator; import java.util.Map; import java.util.TreeMap; class DictionaryEntry { String key; Map<String,String> translations = Collections.synchronizedMap(new TreeMap<String,String>()); public DictionaryEntry(String key) { this.key = key; } public void add(String lang,String value) { translations.put(lang,value); } public String getKey() { return key; } public String get(String lang) { return translations.get(lang); } public String get(String lang,String defaultLang) { String content = translations.get(lang); if ( content == null) { content = translations.get(defaultLang); } // end of if () if ( content == null) { Iterator<String> it = translations.values().iterator(); content = it.next(); } return content; } public String[] availableLanguages() { String[] result = new String[translations.keySet().size()]; Iterator<String> it = translations.keySet().iterator(); int i = 0; while ( it.hasNext()) { result[i++] = it.next(); } return result; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.xmlbundle; import java.util.EventObject; import java.util.Locale; public class LocaleChangeEvent extends EventObject{ private static final long serialVersionUID = 1L; Locale locale; public LocaleChangeEvent(Object source,Locale locale) { super(source); this.locale = locale; } public Locale getLocale() { return locale; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.xmlbundle; import java.util.Locale; /** If you want to change the locales during runtime put a LocaleSelector in the base-context. Instances of I18nBundle will then register them-self as {@link LocaleChangeListener LocaleChangeListeners}. Change the locale with {@link #setLocale} and all bundles will try to load the appropriate resources. */ public interface LocaleSelector { void addLocaleChangeListener(LocaleChangeListener listener); void removeLocaleChangeListener(LocaleChangeListener listener); void setLocale(Locale locale); Locale getLocale(); void setLanguage(String language); void setCountry(String country); String getLanguage(); }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla; import java.net.MalformedURLException; import java.net.URL; import org.rapla.components.util.IOUtil; import org.rapla.components.util.JNLPUtil; import org.rapla.framework.Configuration; import org.rapla.framework.RaplaException; import org.rapla.framework.StartupEnvironment; import org.rapla.framework.internal.ConfigTools; import org.rapla.framework.logger.ConsoleLogger; import org.rapla.framework.logger.Logger; final public class RaplaStartupEnvironment implements StartupEnvironment { private int startupMode = CONSOLE; //private LoadingProgress progressbar; private Logger bootstrapLogger = new ConsoleLogger( ConsoleLogger.LEVEL_WARN ); private URL configURL; private URL contextRootURL; private URL downloadURL; public Configuration getStartupConfiguration() throws RaplaException { return ConfigTools.createConfig( getConfigURL().toExternalForm() ); } public URL getConfigURL() throws RaplaException { if ( configURL != null ) { return configURL; } else { return ConfigTools.configFileToURL( null, "rapla.xconf" ); } } public Logger getBootstrapLogger() { return bootstrapLogger; } public void setStartupMode( int startupMode ) { this.startupMode = startupMode; } /* (non-Javadoc) * @see org.rapla.framework.IStartupEnvironment#getStartupMode() */ public int getStartupMode() { return startupMode; } public void setBootstrapLogger( Logger logger ) { bootstrapLogger = logger; } public void setConfigURL( URL configURL ) { this.configURL = configURL; } public URL getContextRootURL() throws RaplaException { if ( contextRootURL != null ) return contextRootURL; return IOUtil.getBase( getConfigURL() ); } public void setContextRootURL(URL contextRootURL) { this.contextRootURL = contextRootURL; } public URL getDownloadURL() throws RaplaException { if ( downloadURL != null ) { return downloadURL; } if ( startupMode == WEBSTART ) { try { return JNLPUtil.getCodeBase(); } catch ( Exception e ) { throw new RaplaException( e ); } } else { URL base = IOUtil.getBase( getConfigURL() ); if ( base != null) { return base; } try { return new URL( "http://localhost:8051" ); } catch ( MalformedURLException e ) { throw new RaplaException( "Invalid URL" ); } } } public void setDownloadURL( URL downloadURL ) { this.downloadURL = downloadURL; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.gui; import org.rapla.entities.Named; import org.rapla.entities.configuration.Preferences; import org.rapla.framework.RaplaException; import org.rapla.gui.toolkit.RaplaWidget; public interface OptionPanel extends RaplaWidget, Named { void setPreferences(Preferences preferences); /** commits the changes in the option Dialog.*/ void commit() throws RaplaException; /** called when the option Panel is selected for displaying.*/ void show() throws RaplaException; }
Java
package org.rapla.gui; import java.awt.Component; import java.awt.Point; import javax.swing.JComponent; import org.rapla.framework.RaplaException; import org.rapla.gui.toolkit.DialogUI; public interface InfoFactory { <T> JComponent createInfoComponent( T object ) throws RaplaException; /** same as getToolTip(obj, true) */ <T> String getToolTip( T obj ); /** @param wrapHtml wraps an html Page arround the tooltip */ <T> String getToolTip( T obj, boolean wrapHtml ); <T> void showInfoDialog( T object, Component owner ) throws RaplaException; <T> void showInfoDialog( T object, Component owner, Point point ) throws RaplaException; DialogUI createDeleteDialog( Object[] deletables, Component owner ) throws RaplaException; }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.gui.toolkit; import javax.swing.JComponent; /** Should be implemented by all rapla-gui-components that have a view.*/ public interface RaplaWidget { public JComponent getComponent(); }
Java
package org.rapla.gui.toolkit; import javax.swing.MenuElement; /** Adds an id to the standard Swing Menu Component as JSeperator, JMenuItem and JMenu*/ public interface IdentifiableMenuEntry { String getId(); MenuElement getMenuElement(); }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.gui.toolkit; import java.net.URL; import javax.swing.JTextPane; final public class HTMLView extends JTextPane { private static final long serialVersionUID = 1L; public HTMLView() { setOpaque(false); setEditable(false); setContentType("text/html"); setDefaultDocBase(); } public static String DEFAULT_STYLE = "body {font-family:SansSerif;font-size:12;}\n" + ".infotable{padding:0px;margin:0px;}\n" + ".label {vertical-align:top;}\n" + ".value {vertical-align:top;}\n" ; private static URL base; private static Exception error = null; /** will only work for resources inside the same jar as org/rapla/gui/images/repeating.png */ private void setDefaultDocBase() { if (base == null && error == null) { try { String marker = "org/rapla/gui/images/repeating.png"; URL url= HTMLView.class.getClassLoader().getResource(marker); if (url == null) { System.err.println("Marker not found " + marker); return; } //System.out.println("resource:" + url); String urlPath = url.toString(); base = new URL(urlPath.substring(0,urlPath.lastIndexOf(marker))); //System.out.println("document-base:" + base); } catch (Exception ex) { error = ex; System.err.println("Can't get document-base: " + ex + " in class: " + HTMLView.class.getName()); } } if (error == null) ((javax.swing.text.html.HTMLDocument)getDocument()).setBase(base); } /** calls setText(createHTMLPage(body)) */ public void setBody(String body) { try { setText(createHTMLPage(body)); } catch (Exception ex) { setText(body); } } static public String createHTMLPage(String body,String styles) { StringBuffer buf = new StringBuffer(); buf.append("<html>"); buf.append("<head>"); buf.append("<style type=\"text/css\">"); buf.append(styles); buf.append("</style>"); buf.append("</head>"); buf.append("<body>"); buf.append(body); buf.append("</body>"); buf.append("</html>"); return buf.toString(); } static public String createHTMLPage(String body) { return createHTMLPage(body,DEFAULT_STYLE); } public void setText( String message, boolean packText ) { if (packText) { JEditorPaneWorkaround.packText(this, message ,600); } else { setText( message); } } }
Java