]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.spreadsheet.ui/src/org/simantics/spreadsheet/ui/ExcelAdapter.java
Fixed all line endings of the repository
[simantics/platform.git] / bundles / org.simantics.spreadsheet.ui / src / org / simantics / spreadsheet / ui / ExcelAdapter.java
1 package org.simantics.spreadsheet.ui;
2
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;
16
17 import javax.swing.JComponent;
18 import javax.swing.JOptionPane;
19 import javax.swing.JTable;
20 import javax.swing.KeyStroke;
21
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;
35
36 /**
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.
41  */
42 public class ExcelAdapter implements ActionListener {
43
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;
51
52 //      public boolean ownClipboard = false;
53         private Object clipboard = null;
54         private ClipboardOwner clipboardOwner = null;
55         private String rowstring, value;
56
57         public ExcelAdapter(JTable table, ClientModel model, Adaptable serverInterface, StringCellParser[] parsers) {
58
59                 this.table = table;
60                 this.model = model;
61                 //this.manager = serverInterface.getAdapter(SheetManipulator.class);
62                 this.editor = serverInterface.getAdapter(CellEditor.class);
63                 this.parsers = parsers;
64
65                 //            system = Toolkit.getDefaultToolkit().getSystemClipboard();
66
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);
75
76         }
77         //              /**
78         //               * Public Accessor methods for the Table on which this adapter acts.
79         //               */
80         //              public JTable getJTable() {return jTable1;}
81         //              public void setJTable(JTable jTable1) {this.jTable1=jTable1;}
82         /**
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.
89          */
90         public void actionPerformed(ActionEvent e)
91         {
92
93                 Clipboard system = Toolkit.getDefaultToolkit().getSystemClipboard();
94
95                 if (e.getActionCommand().compareTo("Copy")==0)
96                 {
97
98                         // Check to ensure we have selected only a contiguous block of
99                         // cells
100                         int numcols=table.getSelectedColumnCount();
101                         int numrows=table.getSelectedRowCount();
102                         if (numcols == 0 || numrows == 0)
103                                 return;
104
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)))
111                         {
112                                 JOptionPane.showMessageDialog(null, "Invalid Copy Selection",
113                                                 "Invalid Copy Selection",
114                                                 JOptionPane.ERROR_MESSAGE);
115                                 return;
116                         }
117
118                         Object[] rows = new Object[numrows];
119                         for (int i=0;i<numrows;i++)     {
120                                 Object[] cols = new Object[numcols];
121                                 rows[i] = cols;
122                                 for (int j=0;j<numcols;j++)     {
123                                         cols[j] = SpreadsheetUtils.getLabel(model, rowsselected[i],colsselected[j]);
124                                 }
125                         }
126
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];
133                                         if(value != null) {
134                                                 builder.append(value.toString());
135                                         }
136                                 }
137                                 builder.append("\n");
138                         }
139                         
140                         clipboard = new Range(rowsselected[0],rowsselected[0]+numrows-1,colsselected[0],colsselected[0]+numcols-1);
141                         clipboardOwner = new ClipboardOwner() {
142                                 
143                                 @Override
144                                 public void lostOwnership(Clipboard arg0, Transferable arg1) {
145                                         if(clipboardOwner == this) {
146                                                 clipboardOwner = null;
147                                                 clipboard = null;
148                                         }
149                                 }
150                                 
151                         };
152
153                         system.setContents(new StringSelection(builder.toString()), clipboardOwner);
154
155                 }
156                 if (e.getActionCommand().compareTo("Paste")==0)
157                 {
158                         int[] selectedRows = table.getSelectedRows();
159                         int[] selectedColumns = table.getSelectedColumns();
160                         if (selectedRows.length == 0 || selectedColumns.length == 0)
161                                 return;
162                         int startRow = selectedRows[0];
163                         int startCol = selectedColumns[0];
164
165                         if(clipboardOwner == null) {
166                                 
167                                 //if(manager == null) return;
168                                 if(editor == null) return;
169
170                                 String trstring = null;
171                                 try {
172                                         trstring = (String)(system.getContents(this).getTransferData(DataFlavor.stringFlavor));
173                                 } catch (UnsupportedFlavorException e1) {
174                                         e1.printStackTrace();
175                                 } catch (IOException e1) {
176                                         e1.printStackTrace();
177                                 }
178
179                                 if(trstring == null || trstring.isEmpty()) return;
180
181                                 ITask task = ThreadLogger.getInstance().begin("Spreadsheet.paste");
182
183                                 /*
184                                  * Analyse the target area. No computed cells are allowed. Collect cells to remove.
185                                  */
186
187                                 ArrayList<String> removals = new ArrayList<String>();
188                                 
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++) {
193                                                 value=cols[j];
194                                                 if (value.length() > 0 && startRow+i< table.getRowCount()  &&
195                                                                 startCol+j< table.getColumnCount()) {
196
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);
203                                                         }
204
205                                                 }
206                                         }
207                                 }
208                                 
209                                 /*
210                                  * Create the cell data
211                                  * 
212                                  */
213
214                                 Transaction tr = editor.startTransaction(OperationMode.OPERATION);
215                                 
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++) {
219                                                 value=cols[j];
220                                                 if (value.length() > 0 && startRow+i< table.getRowCount()  &&
221                                                                 startCol+j< table.getColumnCount()) {
222
223                                                         if (value.startsWith("=")) {
224                                                                 editor.edit(tr, SpreadsheetUtils.cellName(startRow+i, startCol+j), ClientModel.CONTENT_EXPRESSION, value, Bindings.STRING, null);
225                                                         } else {
226                                                                 editor.edit(tr, SpreadsheetUtils.cellName(startRow+i, startCol+j), Variant.ofInstance(value), null);
227                                                         }
228
229                                                 }
230                                         }
231                                 }
232                                 
233                                 tr.commit();
234
235                                 task.finish();
236
237                         } else {
238
239                                 Range from = (Range)clipboard;
240                                 Range to = new Range(startRow, startRow+from.height()-1, startCol, startCol+from.width()-1);
241                                 
242                                 Transaction tr = editor.startTransaction(OperationMode.OPERATION);
243
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");
249                                                 if (obj == null)
250                                                     continue;
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);
255                                         }
256                                 }
257                                 
258                                 tr.commit();                            
259
260                         }
261                 }
262         }
263 }