1 package org.simantics.spreadsheet.ui;
3 import java.awt.Toolkit;
4 import java.awt.datatransfer.Clipboard;
5 import java.awt.datatransfer.ClipboardOwner;
6 import java.awt.datatransfer.DataFlavor;
7 import java.awt.datatransfer.StringSelection;
8 import java.awt.datatransfer.Transferable;
9 import java.awt.datatransfer.UnsupportedFlavorException;
10 import java.awt.event.ActionEvent;
11 import java.awt.event.ActionListener;
12 import java.awt.event.KeyEvent;
13 import java.io.IOException;
14 import java.util.ArrayList;
15 import java.util.regex.Pattern;
17 import javax.swing.JComponent;
18 import javax.swing.JOptionPane;
19 import javax.swing.JTable;
20 import javax.swing.KeyStroke;
22 import org.simantics.databoard.Bindings;
23 import org.simantics.databoard.binding.mutable.MutableVariant;
24 import org.simantics.databoard.binding.mutable.Variant;
25 import org.simantics.spreadsheet.Adaptable;
26 import org.simantics.spreadsheet.CellEditor;
27 import org.simantics.spreadsheet.CellEditor.Transaction;
28 import org.simantics.spreadsheet.ClientModel.OperationMode;
29 import org.simantics.spreadsheet.ClientModel;
30 import org.simantics.spreadsheet.Range;
31 import org.simantics.spreadsheet.common.cell.StringCellParser;
32 import org.simantics.spreadsheet.util.SpreadsheetUtils;
33 import org.simantics.utils.threads.logger.ITask;
34 import org.simantics.utils.threads.logger.ThreadLogger;
37 * ExcelAdapter enables Copy-Paste Clipboard functionality on JTables.
38 * The clipboard data format used by the adapter is compatible with
39 * the clipboard format used by Excel. This provides for clipboard
40 * interoperability between enabled JTables and Excel.
42 public class ExcelAdapter implements ActionListener {
44 final private JTable table;
45 final private ClientModel model;
46 //final private SheetManipulator manager;
47 final private CellEditor editor;
48 final static private Pattern newline = Pattern.compile("\n");
49 final static private Pattern tab = Pattern.compile("\t");
50 final private StringCellParser[] parsers;
52 // public boolean ownClipboard = false;
53 private Object clipboard = null;
54 private ClipboardOwner clipboardOwner = null;
55 private String rowstring, value;
57 public ExcelAdapter(JTable table, ClientModel model, Adaptable serverInterface, StringCellParser[] parsers) {
61 //this.manager = serverInterface.getAdapter(SheetManipulator.class);
62 this.editor = serverInterface.getAdapter(CellEditor.class);
63 this.parsers = parsers;
65 // system = Toolkit.getDefaultToolkit().getSystemClipboard();
67 KeyStroke copy = KeyStroke.getKeyStroke(KeyEvent.VK_C,ActionEvent.CTRL_MASK,false);
68 // Identifying the copy KeyStroke user can modify this
69 // to copy on some other Key combination.
70 KeyStroke paste = KeyStroke.getKeyStroke(KeyEvent.VK_V,ActionEvent.CTRL_MASK,false);
71 // Identifying the Paste KeyStroke user can modify this
72 //to copy on some other Key combination.
73 table.registerKeyboardAction(this,"Copy",copy,JComponent.WHEN_FOCUSED);
74 table.registerKeyboardAction(this,"Paste",paste,JComponent.WHEN_FOCUSED);
78 // * Public Accessor methods for the Table on which this adapter acts.
80 // public JTable getJTable() {return jTable1;}
81 // public void setJTable(JTable jTable1) {this.jTable1=jTable1;}
83 * This method is activated on the Keystrokes we are listening to
84 * in this implementation. Here it listens for Copy and Paste ActionCommands.
85 * Selections comprising non-adjacent cells result in invalid selection and
86 * then copy action cannot be performed.
87 * Paste is done by aligning the upper left corner of the selection with the
88 * 1st element in the current selection of the JTable.
90 public void actionPerformed(ActionEvent e)
93 Clipboard system = Toolkit.getDefaultToolkit().getSystemClipboard();
95 if (e.getActionCommand().compareTo("Copy")==0)
98 // Check to ensure we have selected only a contiguous block of
100 int numcols=table.getSelectedColumnCount();
101 int numrows=table.getSelectedRowCount();
102 if (numcols == 0 || numrows == 0)
105 int[] rowsselected=table.getSelectedRows();
106 int[] colsselected=table.getSelectedColumns();
107 if (!((numrows-1==rowsselected[rowsselected.length-1]-rowsselected[0] &&
108 numrows==rowsselected.length) &&
109 (numcols-1==colsselected[colsselected.length-1]-colsselected[0] &&
110 numcols==colsselected.length)))
112 JOptionPane.showMessageDialog(null, "Invalid Copy Selection",
113 "Invalid Copy Selection",
114 JOptionPane.ERROR_MESSAGE);
118 Object[] rows = new Object[numrows];
119 for (int i=0;i<numrows;i++) {
120 Object[] cols = new Object[numcols];
122 for (int j=0;j<numcols;j++) {
123 cols[j] = SpreadsheetUtils.getLabel(model, rowsselected[i],colsselected[j]);
127 StringBuilder builder = new StringBuilder();
128 for(int i=0;i<rows.length;i++) {
129 Object[] cols = (Object[])rows[i];
130 for(int j=0;j<cols.length;j++) {
131 if(j>0) builder.append("\t");
132 Object value=(Object)cols[j];
134 builder.append(value.toString());
137 builder.append("\n");
140 clipboard = new Range(rowsselected[0],rowsselected[0]+numrows-1,colsselected[0],colsselected[0]+numcols-1);
141 clipboardOwner = new ClipboardOwner() {
144 public void lostOwnership(Clipboard arg0, Transferable arg1) {
145 if(clipboardOwner == this) {
146 clipboardOwner = null;
153 system.setContents(new StringSelection(builder.toString()), clipboardOwner);
156 if (e.getActionCommand().compareTo("Paste")==0)
158 int[] selectedRows = table.getSelectedRows();
159 int[] selectedColumns = table.getSelectedColumns();
160 if (selectedRows.length == 0 || selectedColumns.length == 0)
162 int startRow = selectedRows[0];
163 int startCol = selectedColumns[0];
165 if(clipboardOwner == null) {
167 //if(manager == null) return;
168 if(editor == null) return;
170 String trstring = null;
172 trstring = (String)(system.getContents(this).getTransferData(DataFlavor.stringFlavor));
173 } catch (UnsupportedFlavorException e1) {
174 e1.printStackTrace();
175 } catch (IOException e1) {
176 e1.printStackTrace();
179 if(trstring == null || trstring.isEmpty()) return;
181 ITask task = ThreadLogger.getInstance().begin("Spreadsheet.paste");
184 * Analyse the target area. No computed cells are allowed. Collect cells to remove.
187 ArrayList<String> removals = new ArrayList<String>();
189 String[] rows = newline.split(trstring);
190 for(int i=0;i<rows.length;i++) {
191 String[] cols = tab.split(rows[i]);
192 for(int j=0;j<cols.length;j++) {
194 if (value.length() > 0 && startRow+i< table.getRowCount() &&
195 startCol+j< table.getColumnCount()) {
197 CellValue cell = (CellValue)table.getValueAt(startRow+i, startCol+j);
198 if(cell.label != null) {
199 String location = SpreadsheetUtils.cellName(startRow+i, startCol+j);
200 Boolean computed = model.getPropertyAt(location, ClientModel.COMPUTED);
201 if(computed != null && computed) return;
202 removals.add(location);
210 * Create the cell data
214 Transaction tr = editor.startTransaction(OperationMode.OPERATION);
216 for(int i=0;i<rows.length;i++) {
217 String[] cols = tab.split(rows[i]);
218 for(int j=0;j<cols.length;j++) {
220 if (value.length() > 0 && startRow+i< table.getRowCount() &&
221 startCol+j< table.getColumnCount()) {
223 if (value.startsWith("=")) {
224 editor.edit(tr, SpreadsheetUtils.cellName(startRow+i, startCol+j), ClientModel.CONTENT_EXPRESSION, value, Bindings.STRING, null);
226 editor.edit(tr, SpreadsheetUtils.cellName(startRow+i, startCol+j), Variant.ofInstance(value), null);
239 Range from = (Range)clipboard;
240 Range to = new Range(startRow, startRow+from.height()-1, startCol, startCol+from.width()-1);
242 Transaction tr = editor.startTransaction(OperationMode.OPERATION);
244 for(int i=0;i<from.height();i++) {
245 for(int j=0;j<from.width();j++) {
246 String fromCell = SpreadsheetUtils.cellName(from.startRow+i, from.startColumn+j);
247 String toCell = SpreadsheetUtils.cellName(to.startRow+i, to.startColumn+j);
248 Object obj = model.getPropertyAt(fromCell, "content");
251 MutableVariant variant = SpreadsheetUtils.createVariant();
252 System.out.println("asdasd fromCell toCell " + fromCell + " " + toCell);
253 editor.copy(tr, fromCell, variant, null);
254 editor.edit(tr, toCell, variant, null);