b11ade4932f09a769f4e96e3ca34489fb48dd56a
[scilab.git] / scilab / modules / xcos / src / java / org / scilab / modules / xcos / actions / dialog / SetContextDialog.java
1 /*
2  * Scilab ( http://www.scilab.org/ ) - This file is part of Scilab
3  * Copyright (C) 2010 - DIGITEO - Clement DAVID
4  * Copyright (C) 2015 - Scilab Enterprises - Clement DAVID
5  *
6  * Copyright (C) 2012 - 2016 - Scilab Enterprises
7  *
8  * This file is hereby licensed under the terms of the GNU GPL v2.0,
9  * pursuant to article 5.3.4 of the CeCILL v.2.1.
10  * This file was originally licensed under the terms of the CeCILL v2.1,
11  * and continues to be available under such terms.
12  * For more information, see the COPYING file which you should have received
13  * along with this program.
14  *
15  */
16
17 package org.scilab.modules.xcos.actions.dialog;
18
19 import java.awt.Component;
20 import java.awt.Dimension;
21 import java.awt.GridBagConstraints;
22 import java.awt.GridBagLayout;
23 import java.awt.Image;
24 import java.awt.Insets;
25 import java.awt.event.ActionEvent;
26 import java.awt.event.ActionListener;
27 import java.awt.event.KeyEvent;
28 import java.beans.PropertyVetoException;
29 import java.io.File;
30 import java.io.FileWriter;
31 import java.io.IOException;
32 import java.io.OutputStreamWriter;
33 import java.io.Writer;
34 import java.io.FileOutputStream;
35 import java.util.logging.Logger;
36
37 import javax.swing.BorderFactory;
38 import javax.swing.Box;
39 import javax.swing.BoxLayout;
40 import javax.swing.ImageIcon;
41 import javax.swing.JButton;
42 import javax.swing.JDialog;
43 import javax.swing.JLabel;
44 import javax.swing.JPanel;
45 import javax.swing.JScrollPane;
46 import javax.swing.JTextArea;
47 import javax.swing.ScrollPaneConstants;
48 import org.scilab.modules.action_binding.highlevel.ScilabInterpreterManagement;
49
50 import org.scilab.modules.commons.gui.FindIconHelper;
51 import org.scilab.modules.gui.utils.ScilabSwingUtilities;
52 import org.scilab.modules.xcos.JavaController;
53 import org.scilab.modules.xcos.VectorOfString;
54 import org.scilab.modules.xcos.actions.SetContextAction;
55 import org.scilab.modules.xcos.graph.ScicosParameters;
56 import org.scilab.modules.xcos.graph.XcosDiagram;
57 import org.scilab.modules.xcos.io.scicos.ScilabDirectHandler;
58 import org.scilab.modules.xcos.utils.XcosMessages;
59
60 /**
61  * Dialog associated with the {@link SetContextAction}.
62  *
63  * Note that this dialog break the Data Abstraction Coupling metric because of
64  * the numbers of graphical components involved in the GUI creation. For the
65  * same reason (GUI class), constants are not used on this code.
66  */
67 // CSOFF: ClassDataAbstractionCoupling
68 // CSOFF: ClassFanOutComplexity
69 // CSOFF: MagicNumber
70 @SuppressWarnings(value = { "serial" })
71 public class SetContextDialog extends JDialog {
72     private static final Dimension PREFERRED_SIZE = new Dimension(480, 320);
73     private static final String SHARED_NEW_LINE = "\n";
74
75     private final ScicosParameters parameters;
76     private final XcosDiagram rootGraph;
77
78     private JTextArea contextArea;
79
80     /**
81      * Default constructor
82      *
83      * @param parent
84      *            the parent component
85      * @param graph
86      *            THe current graph
87      * @param parameters
88      *            the Scicos parameters
89      */
90     public SetContextDialog(Component parent, XcosDiagram graph, ScicosParameters parameters) {
91         this.parameters = parameters;
92
93         ImageIcon scilabIcon = new ImageIcon(FindIconHelper.findIcon("scilab"));
94         Image imageForIcon = scilabIcon.getImage();
95         setLayout(new GridBagLayout());
96         setIconImage(imageForIcon);
97         setTitle(XcosMessages.SET_CONTEXT);
98         setModal(true);
99         setLocationRelativeTo(parent);
100         rootGraph = graph;
101         setDefaultCloseOperation(DISPOSE_ON_CLOSE);
102         ScilabSwingUtilities.closeOnEscape(this);
103
104         initComponents();
105     }
106
107     /**
108      * Initialize the components
109      */
110     private void initComponents() {
111         JLabel textLabel = new JLabel(XcosMessages.SET_CONTEXT_LABEL_TEXT);
112         contextArea = new JTextArea();
113
114         /*
115          * Construct a text from a String array context
116          */
117         VectorOfString v = parameters.getContext(new JavaController());
118         final int len = v.size();
119         for (int i = 0; i < len; i++) {
120             contextArea.append(v.get(i) + SHARED_NEW_LINE);
121         }
122
123         JScrollPane contextAreaScroll = new JScrollPane(contextArea, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
124                 ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
125
126         JButton cancelButton = new JButton(XcosMessages.CANCEL);
127         JButton okButton = new JButton(XcosMessages.OK);
128         okButton.setMnemonic(KeyEvent.VK_ENTER);
129         okButton.setPreferredSize(cancelButton.getPreferredSize());
130
131         JPanel buttonPane = new JPanel();
132         buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));
133         buttonPane.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
134         buttonPane.add(okButton);
135         buttonPane.add(Box.createRigidArea(new Dimension(10, 0)));
136         buttonPane.add(cancelButton);
137
138         /*
139          * Perform layout
140          */
141         GridBagConstraints gbc = new GridBagConstraints();
142
143         gbc.gridwidth = GridBagConstraints.REMAINDER;
144         gbc.gridx = 0;
145         gbc.gridy = 1;
146         gbc.fill = GridBagConstraints.BOTH;
147         gbc.weightx = 1.0;
148         gbc.insets = new Insets(10, 10, 10, 10);
149
150         add(textLabel, gbc);
151
152         gbc.gridy = GridBagConstraints.RELATIVE;
153         gbc.fill = GridBagConstraints.BOTH;
154         gbc.weighty = 1.0;
155         add(contextAreaScroll, gbc);
156
157         gbc.gridheight = 1;
158         gbc.gridwidth = 1;
159
160         gbc.anchor = GridBagConstraints.LAST_LINE_END;
161         gbc.fill = GridBagConstraints.NONE;
162         gbc.weighty = 0;
163         gbc.insets = new Insets(5, 0, 10, 10);
164         add(buttonPane, gbc);
165
166         installActionListeners(cancelButton, okButton);
167
168         setPreferredSize(PREFERRED_SIZE);
169     }
170
171     /**
172      * Install the action listener on the buttons
173      *
174      * @param cancelButton
175      *            the cancel button
176      * @param okButton
177      *            the OK button
178      */
179     private void installActionListeners(JButton cancelButton, JButton okButton) {
180         /*
181          * The cancel button just exit without doing anything
182          */
183         cancelButton.addActionListener((ActionEvent e) -> {
184             dispose();
185         });
186
187         /*
188          * The ok button parse the contextArea, reconstruct the real context and
189          * set the scicosParameters before exiting.
190          */
191         okButton.addActionListener(new ActionListenerImpl());
192     }
193
194     private class ActionListenerImpl implements ActionListener {
195
196         @Override
197         public void actionPerformed(ActionEvent e) {
198             try {
199                 String context = contextArea.getText();
200                 final VectorOfString v = new VectorOfString();
201
202                 // Force a carriage return if needed so the last line is not ignored
203                 if (context.length() > 0 && !context.endsWith("\n")) {
204                     context += '\n';
205                 }
206                 int off = 0;
207                 int next;
208                 while ((next = context.indexOf('\n', off)) != -1) {
209                     v.add(context.substring(off, next));
210                     off = next + 1;
211                 }
212                 parameters.setContext(new JavaController(), v);
213
214                 /*
215                  * Validate the context
216                  */
217                 try {
218                     File f = File.createTempFile(ScilabDirectHandler.CONTEXT, ".sce");
219                     try (Writer writer =  new OutputStreamWriter(new FileOutputStream(f), "UTF-8")) {
220                         writer.write(context, 0, context.length());
221                     }
222
223                     ScilabInterpreterManagement.putCommandInScilabQueue("var = script2var(mgetl(\"" + f.getAbsolutePath() + "\"), struct()); mdelete(\"" + f.getAbsolutePath() + "\");");
224                 } catch (IOException ex) {
225                     Logger.getLogger(SetContextAction.class.getName()).severe(ex.toString());
226                 }
227
228                 dispose();
229             } catch (PropertyVetoException e2) {
230                 Logger.getLogger(SetContextAction.class.getName()).severe(e2.toString());
231             }
232         }
233     }
234 }
235 // CSON: ClassDataAbstractionCoupling
236 // CSON: ClassFanOutComplexity
237 // CSON: MagicNumber