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