]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.charts/src/org/simantics/charts/editor/ChartCopyHandler.java
Migrated source code from Simantics SVN
[simantics/platform.git] / bundles / org.simantics.charts / src / org / simantics / charts / editor / ChartCopyHandler.java
1 /*******************************************************************************\r
2  * Copyright (c) 2011 Association for Decentralized Information Management in\r
3  * Industry THTH ry.\r
4  * All rights reserved. This program and the accompanying materials\r
5  * are made available under the terms of the Eclipse Public License v1.0\r
6  * which accompanies this distribution, and is available at\r
7  * http://www.eclipse.org/legal/epl-v10.html\r
8  *\r
9  * Contributors:\r
10  *     VTT Technical Research Centre of Finland - initial API and implementation\r
11  *******************************************************************************/\r
12 package org.simantics.charts.editor;\r
13 \r
14 import java.awt.Toolkit;\r
15 import java.awt.datatransfer.Clipboard;\r
16 import java.awt.datatransfer.StringSelection;\r
17 import java.io.BufferedWriter;\r
18 import java.io.File;\r
19 import java.io.FileOutputStream;\r
20 import java.io.IOException;\r
21 import java.io.OutputStreamWriter;\r
22 import java.lang.reflect.InvocationTargetException;\r
23 import java.nio.charset.Charset;\r
24 import java.util.Collections;\r
25 import java.util.List;\r
26 import java.util.concurrent.atomic.AtomicBoolean;\r
27 \r
28 import org.eclipse.core.commands.AbstractHandler;\r
29 import org.eclipse.core.commands.ExecutionEvent;\r
30 import org.eclipse.core.commands.ExecutionException;\r
31 import org.eclipse.core.runtime.IProgressMonitor;\r
32 import org.eclipse.core.runtime.preferences.InstanceScope;\r
33 import org.eclipse.jface.action.IStatusLineManager;\r
34 import org.eclipse.jface.operation.IRunnableWithProgress;\r
35 import org.eclipse.jface.preference.IPreferenceStore;\r
36 import org.eclipse.swt.SWT;\r
37 import org.eclipse.swt.widgets.FileDialog;\r
38 import org.eclipse.swt.widgets.Shell;\r
39 import org.eclipse.ui.IEditorPart;\r
40 import org.eclipse.ui.PlatformUI;\r
41 import org.eclipse.ui.handlers.HandlerUtil;\r
42 import org.eclipse.ui.preferences.ScopedPreferenceStore;\r
43 import org.simantics.charts.ui.CSVProgressMonitor;\r
44 import org.simantics.databoard.binding.error.BindingException;\r
45 import org.simantics.databoard.parser.StringEscapeUtils;\r
46 import org.simantics.databoard.util.Bean;\r
47 import org.simantics.databoard.util.StreamUtil;\r
48 import org.simantics.history.HistoryException;\r
49 import org.simantics.history.ItemManager;\r
50 import org.simantics.history.csv.CSVFormatter;\r
51 import org.simantics.history.csv.ColumnSeparator;\r
52 import org.simantics.history.csv.DecimalSeparator;\r
53 import org.simantics.history.csv.ExportInterpolation;\r
54 import org.simantics.history.util.subscription.SamplingFormat;\r
55 import org.simantics.modeling.preferences.CSVPreferences;\r
56 import org.simantics.trend.configuration.TrendItem;\r
57 import org.simantics.trend.impl.TrendNode;\r
58 import org.simantics.utils.format.FormattingUtils;\r
59 import org.simantics.utils.ui.ErrorLogger;\r
60 \r
61 /**\r
62  * @author Tuukka Lehtonen\r
63  */\r
64 public class ChartCopyHandler extends AbstractHandler {\r
65 \r
66         String lastFile;\r
67         \r
68     @Override\r
69     public Object execute(ExecutionEvent event) throws ExecutionException {\r
70         IEditorPart ep = HandlerUtil.getActiveEditor(event);\r
71         if (ep instanceof TimeSeriesEditor == false) return null;\r
72         TimeSeriesEditor editor = (TimeSeriesEditor) ep;\r
73         final TrendNode trendNode = editor.trendNode;\r
74         IStatusLineManager status = editor.getEditorSite().getActionBars().getStatusLineManager();\r
75         final Shell shell = HandlerUtil.getActiveShell(event);\r
76 \r
77         final AtomicBoolean result = new AtomicBoolean(false);\r
78         try {\r
79             PlatformUI.getWorkbench().getProgressService().busyCursorWhile(new IRunnableWithProgress() {\r
80                 @Override\r
81                 public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {\r
82                     result.set( copyDataToClipboard(monitor, trendNode, Format.JOINED_TIME, shell) );\r
83                 }\r
84             });\r
85             if (!result.get()) {\r
86                 status.setMessage("No data to copy");\r
87             } else {\r
88                 status.setMessage("Copied chart data to clipboard");\r
89             }\r
90             status.setErrorMessage(null);\r
91         } catch (InvocationTargetException e) {\r
92             ErrorLogger.defaultLogError(e.getCause());\r
93         } catch (InterruptedException e) {\r
94             ErrorLogger.defaultLogError(e);\r
95         }\r
96 \r
97         return null;\r
98     }\r
99 \r
100     static enum Format {\r
101         TIME_VALUE_PAIRS,\r
102         JOINED_TIME\r
103     }\r
104 \r
105     public boolean copyDataToClipboard(IProgressMonitor monitor, TrendNode t, Format format, final Shell shell) {\r
106         Charset UTF8        = Charset.forName("UTF-8");\r
107         try {\r
108                 // String builder can be really slow when it is extended many times over. \r
109                 // Instead stream to file with buffering\r
110 //            StringBuilder sb = new StringBuilder();\r
111                 IPreferenceStore csvnode = new ScopedPreferenceStore( InstanceScope.INSTANCE, CSVPreferences.P_NODE );\r
112                 String ext = csvnode.getString(CSVPreferences.P_CSV_FILE_EXTENSION);\r
113                 File tmpFile = File.createTempFile("clipboard", ext);\r
114                 tmpFile.deleteOnExit();\r
115                 FileOutputStream fos = new FileOutputStream(tmpFile); \r
116                 BufferedWriter w = new BufferedWriter(new OutputStreamWriter(fos, UTF8));\r
117                 try {\r
118                         ItemManager im = new ItemManager( t.historian.getItems() );\r
119                     CSVFormatter formatter = new CSVFormatter();            \r
120                     formatter.setTimeRange(t.horizRuler.from, t.horizRuler.end);\r
121                     \r
122                     // Write preferences\r
123                     formatter.setStartTime( csvnode.getDouble(CSVPreferences.P_CSV_START_TIME) );\r
124                     formatter.setTimeStep( csvnode.getDouble(CSVPreferences.P_CSV_TIME_STEP) );\r
125                     formatter.setDecimalSeparator( DecimalSeparator.fromPreference(csvnode.getString(CSVPreferences.P_CSV_DECIMAL_SEPARATOR) ) );\r
126                     formatter.setColumnSeparator( ColumnSeparator.fromPreference(StringEscapeUtils.unescape( csvnode.getString(CSVPreferences.P_CSV_COLUMN_SEPARATOR) ) ) );\r
127                     formatter.setResample( csvnode.getBoolean(CSVPreferences.P_CSV_RESAMPLE) );\r
128                     formatter.setNumberInterpolation( ExportInterpolation.fromPreference (csvnode.getString(CSVPreferences.P_CSV_SAMPLING_MODE) ) );\r
129                     formatter.setTimeFormat( FormattingUtils.significantDigitFormat( csvnode.getInt(CSVPreferences.P_CSV_TIME_DIGITS) ) );\r
130                     formatter.setFloatFormat( FormattingUtils.significantDigitFormat( csvnode.getInt(CSVPreferences.P_CSV_FLOAT_DIGITS) ) );\r
131                     formatter.setNumberFormat( FormattingUtils.significantDigitFormat( csvnode.getInt(CSVPreferences.P_CSV_DOUBLE_DIGITS) ) );\r
132                     \r
133                     for (TrendItem i : t.spec.items) {\r
134                         if (i.hidden) continue;\r
135                         List<Bean> items = im.search("variableId", i.variableId);\r
136                         Collections.sort(items, SamplingFormat.INTERVAL_COMPARATOR);\r
137                         if (items.isEmpty()) continue;\r
138                         Bean config = items.get(0);\r
139                         String historyId = (String) config.getFieldUnchecked("id");\r
140                         formatter.addItem( t.historian, historyId, i.simpleLabel, i.variableReference, i.unit);\r
141                     }\r
142                     formatter.sort();\r
143                     switch (format) {\r
144                         case TIME_VALUE_PAIRS: \r
145 //                                              formatter.formulate1(new CSVProgressMonitor(monitor), w);\r
146                             break;\r
147                         case JOINED_TIME:\r
148                             formatter.formulate2(new CSVProgressMonitor(monitor), w);\r
149                             break;\r
150                         default:\r
151                             throw new UnsupportedOperationException("unsupported format " + format);\r
152                     }\r
153                     w.flush();\r
154         \r
155                     if (tmpFile.length()==0) return false;\r
156         \r
157                     Toolkit toolkit = Toolkit.getDefaultToolkit();\r
158                     Clipboard clipboard = toolkit.getSystemClipboard();\r
159                     w.flush();\r
160                     fos.close();\r
161                     fos = null;\r
162                         \r
163                     System.out.println("Exported to "+tmpFile+" size: "+tmpFile.length());\r
164                     if ( tmpFile.length() > 10*1024*1024 ) {\r
165 //                      String msg = "The data has been written to temporary file:\n"+tmpFile.getCanonicalPath();\r
166 //                      ShowMessage.showInformation( shell.getDisplay(), "Too much data for clipboard.", msg);\r
167                         final File csvFile = tmpFile;\r
168                         tmpFile = null;\r
169                         shell.getDisplay().asyncExec( new Runnable() {\r
170                                                 @Override\r
171                                                 public void run() {\r
172                                         FileDialog fd = new FileDialog(shell, SWT.SAVE);\r
173                                         fd.setText("Write CSV to File");\r
174                                         fd.setFileName( lastFile!=null ? lastFile : csvFile.getAbsolutePath() );\r
175                                         String newFile = fd.open();\r
176                                         if ( newFile != null ) {\r
177                                                 lastFile = newFile;\r
178                                                 File ff = new File( newFile );\r
179                                                 ff.delete();\r
180                                                 csvFile.renameTo( ff );\r
181                                         } else {\r
182                                                 csvFile.delete();\r
183                                         }\r
184                                                 }} ); \r
185                     } else {\r
186                             String str = StreamUtil.readString(tmpFile, UTF8);\r
187                             \r
188                             StringSelection strSel = new StringSelection(str);\r
189                             clipboard.setContents(strSel, null);\r
190                     }\r
191                     \r
192                         } catch (BindingException e1) {\r
193                                 ErrorLogger.defaultLogError(e1);\r
194                                 return false;\r
195                         } catch (IOException e) {\r
196                                 ErrorLogger.defaultLogError(e);\r
197                         } finally {\r
198                         if ( fos != null ) try { fos.close(); } catch (IOException e) { ErrorLogger.defaultLogError(e); }\r
199                         if ( tmpFile != null ) tmpFile.delete();\r
200                         }                       \r
201 \r
202             return true;\r
203         } catch (HistoryException e) {\r
204             ErrorLogger.defaultLogError(e);\r
205         } catch (IOException e) {\r
206             ErrorLogger.defaultLogError(e);\r
207                 }\r
208         return false;\r
209     }\r
210 \r
211 }\r