source: java/main/src/main/java/com/framsticks/gui/windows/console/ConsoleFrame.java @ 96

Last change on this file since 96 was 96, checked in by psniegowski, 11 years ago

HIGHLIGHTS:

  • cleanup Instance management
    • extract Instance interface
    • extract Instance common algorithms to InstanceUtils?
  • fix closing issues: Ctrl+C or window close button

properly shutdown whole program

by Java Framsticks framework

  • fix parsing and printing of all request types
  • hide exception passing in special handle method of closures
    • substantially improve readability of closures
    • basically enable use of exception in asynchronous closures

(thrown exception is transported back to the caller)

  • implement call request on both sides

CHANGELOG:
Further improve calling.

Improve instance calling.

Calling is working on both sides.

Improve exception handling in testing.

Waiters do not supercede other apllication exception being thrown.

Finished parsing and printing of all request types (with tests).

Move implementation and tests of request parsing to Request.

Add tests for Requests.

Improve waits in asynchronours tests.

Extract more algorithms to InstanceUtils?.

Extract Instance.resolve to InstanceUtils?.

Improve naming.

Improve passing exception in InstanceClient?.

Hide calling of passed functor in StateCallback?.

Hide Exception passing in asynchronous closures.

Hide exception passing in Future.

Make ResponseCallback? an abstract class.

Make Future an abstract class.

Minor change.

Move getPath to Path.to()

Move bindAccess to InstanceUtils?.

Extract common things to InstanceUtils?.

Fix synchronization bug in Connection.

Move resolve to InstanceUtils?.

Allow names of Joinable to be dynamic.

Add support for set request server side.

More fixes in communication.

Fix issues with parsing in connection.

Cut new line characters when reading.

More improvements.

Migrate closures to FramsticksException?.

Several changes.

Extract resolveAndFetch to InstanceUtils? algorithms.

Test resolving and fetching.

More fixes with function signature deduction.

Do not print default values in SimpleAbstractAccess?.

Add test of FramsClass? printing.

Improve FramsticksException? messages.

Add explicit dispatcher synchronization feature.

Rework assertions in tests.

Previous solution was not generic enough.

Allow addition of joinables to collection after start.

Extract SimulatorInstance? from RemoteInstance?.

Remove PrivateJoinableCollection?.

Improve connections.

Move shutdown hook to inside the Monitor.

It should work in TestNG tests, but it seems that
hooks are not called.

In ServerTest? client connects to testing server.

Move socket initialization to receiver thread.

Add proper closing on Ctrl+C (don't use signals).

Fix bugs with server accepting connections.

Merge Entity into Joinable.

Reworking ServerInstance?.

Extract more algorithm to InstanceUtils?.

Extract some common functionality from AbstractInstance?.

Functions were placed in InstanceUtils?.

Hide registry of Instance.

Use ValueParam? in Instance interface.

Minor change.

Extract Instance interface.

Old Instance is now AbstractInstance?.

File size: 6.2 KB
Line 
1package com.framsticks.gui.windows.console;
2
3import com.framsticks.communication.*;
4import com.framsticks.gui.ImageProvider;
5import com.framsticks.util.lang.Pair;
6import com.framsticks.util.lang.Strings;
7import org.apache.log4j.Logger;
8
9import javax.swing.*;
10import java.awt.*;
11import java.awt.event.*;
12import java.util.ArrayList;
13import java.util.Collections;
14
15/**
16 * Frame with text field for sending commands and text pane for displaying manager responses.
17 */
18@SuppressWarnings("serial")
19public class ConsoleFrame extends JFrame {
20
21        private static final Logger log = Logger.getLogger(ConsoleFrame.class.getName());
22
23        /**
24         * Painter coloring manager responses before display.
25         */
26        private final ConsolePainter consolePainter;
27
28        /**
29         * Text field for typing commands.
30         */
31        private final JTextField commandLine;
32        /**
33         * Reference to connection.
34         */
35        protected final ClientConnection connection;
36
37        /**
38         * List of sent messages.
39         * TODO: is it used at all?
40         */
41        private final ArrayList<String> sentMessages = new ArrayList<String>();
42
43        /**
44         * Current visible tip list.
45         */
46        private ArrayList<String> tipList = null;
47
48        private int msgIndex = 0;
49        private int tipIndex = 0;
50        private Boolean clearMsgIndex = false;
51
52
53        /**
54         * Default constructor creates frame with console.
55         */
56        @SuppressWarnings("unchecked")
57        public ConsoleFrame(ClientConnection connection) {
58                this.connection = connection;
59                this.setTitle("Console");
60                this.setLayout(new BorderLayout());
61                this.setSize(new Dimension(440, 400));
62                this.setMinimumSize(new Dimension(440, 400));
63                this.setIconImage(ImageProvider.loadImage(ImageProvider.LOGO).getImage());
64                JFrame.setDefaultLookAndFeelDecorated(true);
65
66                JTextPane text = new JTextPane();
67                consolePainter = new ConsolePainter(text);
68
69                text.setEditable(false);
70                final JScrollPane scrollText = new JScrollPane(text);
71                scrollText.setBorder(BorderFactory.createEtchedBorder());
72
73                JPanel scrollPanel = new JPanel();
74                scrollPanel.setLayout(new BorderLayout());
75                scrollPanel.add(scrollText, BorderLayout.CENTER);
76                scrollPanel.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7));
77
78                commandLine = new JTextField();
79
80                commandLine.addKeyListener(new KeyListener() {
81                        @Override
82                        public void keyTyped(KeyEvent e) {
83
84                        }
85
86                        @Override
87                        public void keyPressed(KeyEvent e) {
88                                onKeyPressed(e.getKeyCode());
89                        }
90
91                        @Override
92                        public void keyReleased(KeyEvent e) {
93                        }
94                });
95
96                commandLine.setFocusTraversalKeys(
97                                KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
98                                Collections.EMPTY_SET);
99
100                this.addWindowListener(new WindowAdapter() {
101                        public void windowActivated(WindowEvent e) {
102                                commandLine.requestFocusInWindow();
103                        }
104                });
105
106                JButton sendButton = new JButton("Send");
107                sendButton.addActionListener(new ActionListener() {
108
109                        public void actionPerformed(final ActionEvent e) {
110                                buttonSendAction();
111                        }
112
113                });
114
115                final Box cmdBox = new Box(BoxLayout.LINE_AXIS);
116                cmdBox.add(commandLine);
117                cmdBox.add(Box.createHorizontalStrut(10));
118                cmdBox.add(sendButton);
119                cmdBox.setBorder(BorderFactory.createEmptyBorder(0, 7, 7, 7));
120
121                this.getContentPane().add(scrollPanel, BorderLayout.CENTER);
122                this.getContentPane().add(cmdBox, BorderLayout.PAGE_END);
123                this.setVisible(false);
124
125        }
126
127        public void setCommandLine(String command) {
128                commandLine.setText(command);
129        }
130
131
132        /**
133         * Shows console frame, sets location relative to parent.
134         *
135         * @param parent Frame relative to which console window will be localized.
136         */
137        public void show(JFrame parent) {
138                final Point parentLocation = parent.getLocation();
139                final Point location = new Point(parentLocation.x + 20, parentLocation.y + 20);
140                this.setLocation(location);
141                this.setVisible(true);
142        }
143
144        /**
145         * Adds query to console window.
146         *
147         * @param line Line of string query.
148         */
149        private void addQuery(String line) {
150                consolePainter.userMsg(line + "\n");
151        }
152
153
154        /**
155         * Sends message to manager and adds message to console frame.
156         */
157        public void buttonSendAction() {
158                if (!connection.isConnected()) {
159                        JOptionPane.showMessageDialog(this, "missing connection to manager");
160                        return;
161                }
162                String commandText = commandLine.getText();
163                Pair<String, String> command = Strings.splitIntoPair(commandText, ' ', "");
164                Request request = Request.createRequestByTypeString(command.first);
165                if (request == null) {
166                        log.warn("not a valid request: " + commandText);
167                        return;
168                }
169                request.parseRest(command.second);
170
171                addQuery(commandText);
172                addSentMessage(commandText);
173                commandLine.setText("");
174                connection.send(request, new ResponseCallback<Connection>() {
175                        @Override
176                        public void process(Response response) {
177                                for (File f : response.getFiles()) {
178                                        consolePainter.paintMessage(f);
179                                }
180                        }
181                });
182        }
183
184        private void onKeyPressed(int keyCode) {
185                if (keyCode == KeyEvent.VK_TAB) {
186                        String tmp = commandLine.getText();
187                        int selStart = commandLine.getSelectionStart();
188
189                        tmp = tmp.substring(0, selStart);
190
191                        if (selStart > 0) {
192
193                                if (tipList == null) {
194                                        createTipList(tmp.substring(0, selStart));
195                                        tipIndex = tipList.size() - 1;
196                                }
197
198                                if (tipList.size() > 0) {
199                                        String element = tipList.get(tipIndex);
200                                        tipIndex--;
201                                        if (tipIndex < 0) {
202                                                tipIndex = tipList.size() - 1;
203                                        }
204                                        commandLine.setText(element);
205                                }
206
207                        }
208                } else {
209                        tipList = null;
210                }
211
212                if (keyCode == KeyEvent.VK_UP || keyCode == KeyEvent.VK_DOWN) {
213                        int dir = (keyCode == KeyEvent.VK_UP ? -1 : 1);
214                        if (clearMsgIndex) {
215                                msgIndex = sentMessages.size();
216                                clearMsgIndex = false;
217                        }
218
219                        msgIndex += dir;
220                        if (msgIndex < 0) {
221                                msgIndex = 0;
222                        } else if (msgIndex >= sentMessages.size()) {
223                                msgIndex = sentMessages.size() - 1;
224                        }
225
226                        String element = sentMessages.get(msgIndex);
227                        commandLine.setText(element);
228                        return;
229
230                }
231
232                if (keyCode == KeyEvent.VK_ENTER) {
233                        clearMsgIndex = true;
234                        buttonSendAction();
235                        return;
236                }
237
238                clearMsgIndex = true;
239
240        }
241
242        /**
243         * Creates commands tip list.
244         * @param startText Text that user typed.
245         */
246        private void createTipList(String startText) {
247                tipList = new ArrayList<String>();
248
249                for (String next : sentMessages) {
250                        if (next.startsWith(startText)) {
251                                tipList.add(next);
252                        }
253                }
254        }
255
256        public void addSentMessage(String msg) {
257                if (!sentMessages.contains(msg)) {
258                        sentMessages.add(msg);
259                }
260        }
261
262}
Note: See TracBrowser for help on using the repository browser.