summaryrefslogtreecommitdiffstats
path: root/logo/src/xlogo/gui/welcome/WelcomeScreen.java
blob: 011081ec4b7bfdc380fde72ca01bea39f2ff506e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
/* XLogo4Schools - A Logo Interpreter specialized for use in schools, based on XLogo by Lo�c Le Coq
 * Copyright (C) 2013 Marko Zivkovic
 * 
 * Contact Information: marko88zivkovic at gmail dot com
 * 
 * This program is free software; you can redistribute it and/or modify it 
 * under the terms of the GNU General Public License as published by the Free 
 * Software Foundation; either version 2 of the License, or (at your option) 
 * any later version.  This program is distributed in the hope that it will be 
 * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General 
 * Public License for more details.  You should have received a copy of the 
 * GNU General Public License along with this program; if not, write to the Free 
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 
 * MA 02110-1301, USA.
 * 
 * 
 * This Java source code belongs to XLogo4Schools, written by Marko Zivkovic
 * during his Bachelor thesis at the computer science department of ETH Z�rich,
 * in the year 2013 and/or during future work.
 * 
 * It is a reengineered version of XLogo written by Lo�c Le Coq, published
 * under the GPL License at http://xlogo.tuxfamily.org/
 * 
 * Contents of this file were entirely written by Marko Zivkovic
 */

package xlogo.gui.welcome;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.JTextComponent;

import java.awt.*;
import java.io.IOException;

import xlogo.messages.MessageKeys;
import xlogo.messages.async.AsyncMediumAdapter;
import xlogo.messages.async.AsyncMessage;
import xlogo.messages.async.AsyncMessenger;
import xlogo.messages.async.dialog.DialogMessenger;
import xlogo.storage.Storable;
import xlogo.storage.WSManager;
import xlogo.storage.global.GlobalConfig;
import xlogo.storage.workspace.WorkspaceConfig;
import xlogo.utils.Utils;
import xlogo.utils.WebPage;
import xlogo.Application;
import xlogo.Logo;

/**
 * This was initially called {@code Selection_Langue} and it was only displayed when the Application was opened for the very first time.
 * Now this has become {@code WelcomeScreen}, as it was enhanced with more options than just language selection:
 * <li> User Account Selection / Creation </li>
 * <li> Storage Location (master password required) </li>
 * @author Marko
 */
public class WelcomeScreen extends JFrame {
	private static final long serialVersionUID = 1L;

	private JLabel label;
	
	private JLabel workspace = new JLabel("Workspace");
	private JLabel username = new JLabel("User");

	private JComboBox workspaceSelection = new JComboBox();
	private JComboBox userSelection = new JComboBox();

	private JButton openWorkspaceSettingsBtn = new JButton("Settings");
	private JButton enterButton = new JButton("Enter");
	
	private JButton infoButton = new JButton();
	private JButton gplButton = new JButton();
	
	private JPanel panel = new JPanel();
	private GroupLayout groupLayout;
	
	private ActionListener onApplicationEnterListener;

	private WorkspaceSettings workspaceSettings;
	
	/**
	 * 
	 * @param listener to be informed when the user is ready to enter the application
	 */
	public WelcomeScreen(ActionListener onApplicationEnterListener){
		this.onApplicationEnterListener = onApplicationEnterListener;
		// Window
		super.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setIconImage(Toolkit.getDefaultToolkit().createImage(Utils.class.getResource("Icon_x4s.png")));
		setTitle("XLogo4Schools");

		// The XLogo4Schools logo
		//ImageIcon logo = Utils.dimensionne_image("Logo_xlogo4schools.png", this);
		
		infoButton.setIcon(createImageIcon("info_icon.png", "Info", 40, 40));
		gplButton.setIcon(createImageIcon("gnu_gpl.png", "GPL", 40, 40));
		label = new JLabel(createImageIcon("Logo_xlogo4schools.png", "XLogo4Schools", 250, 40));
		
		// Select workspace combo box
		initWorkspaceListModel();
		workspaceSelection.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e) {
				String workspace = (String) workspaceSelection.getSelectedItem();
		    	enterWorkspace(workspace);
			}
		});
		// Open workspace settings button
		openWorkspaceSettingsBtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				showWorkspaceSettings();
			}
		});
		
		// Select user combo box
		populateUserList();
		final JTextComponent tc = (JTextComponent) userSelection.getEditor().getEditorComponent();
		tc.getDocument().addDocumentListener(new DocumentListener() {
			public void removeUpdate(DocumentEvent arg0) { enableOrDisableEnter(); }
			public void insertUpdate(DocumentEvent arg0) { enableOrDisableEnter(); }
			public void changedUpdate(DocumentEvent arg0) { enableOrDisableEnter(); }
			private void enableOrDisableEnter()
			{
				String username = tc.getText();
				enterButton.setEnabled(username != null && username.length() != 0);
			}
		});
		
		userSelection.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String username = (String) userSelection.getSelectedItem();
				enterButton.setEnabled(username != null && username.length() != 0);
			}
		});
		
		// Enter user space button
		enterButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				enterApplication();
			}
		});
		
		gplButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e)
			{
				showGPL();
			}
		});
		
		infoButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e)
			{
				showInfo();
			}
		});
		
		// Add all
		initLayout();
		getContentPane().add(panel);
		setText();
		pack();
		setVisible(true);

		/*
		 * Make this component the parent for popups and dialogs.
		 */
		setMessageManagerParent();
		
		workspaceSettings = new WorkspaceSettings(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				// When the window is closed, repopulate workspace and user lists, update language, enable this window again.
				setMessageManagerParent();
				setText();
				populateWorkspaceList();
				populateUserList();
				setEnabled(true);
			}
		});
	}
	
	private void initWorkspaceListModel()
	{
		WSManager wsManager = WSManager.getInstance();
		try
		{
			String lastUsedWorkspace = wsManager.getGlobalConfigInstance().getLastUsedWorkspace();
			wsManager.enterWorkspace(lastUsedWorkspace);
			populateWorkspaceList();
		}
		catch (IOException e)
		{
			DialogMessenger
				.getInstance()
					.dispatchMessage(
							"I'm sorry, something very bad happened",
							"Please report this error message. You could try to delete the file X4S_GlobalConfig from your home directory, "
							+ "and restart XLogo4Schools. You will have to import your Workspaces again.\n\n"
							+ e.toString());
		}
	}
	
	private void populateWorkspaceList()
	{
		GlobalConfig gc = WSManager.getInstance().getGlobalConfigInstance();
		String[] workspaces = gc.getAllWorkspaces();
		workspaceSelection.setModel(new DefaultComboBoxModel(workspaces));
		workspaceSelection.setSelectedItem(gc.getLastUsedWorkspace());
	}
	
	private void populateUserList()
	{
		WorkspaceConfig wc = WSManager.getInstance().getWorkspaceConfigInstance();
		String[] users = wc.getUserList();
		userSelection.setModel(new DefaultComboBoxModel(users));
		String lastUser = wc.getLastActiveUser();
		userSelection.setSelectedItem(lastUser);
		enterButton.setEnabled(lastUser != null && lastUser.length() > 0);
		userSelection.setEditable(wc.isUserCreationAllowed());
	}
	
	protected void enterWorkspace(String workspaceName) {
		try {
			WSManager.getInstance().enterWorkspace(workspaceName);
			populateUserList();
		} catch (IOException e) {
			DialogMessenger.getInstance().dispatchMessage(
						Logo.messages.getString("ws.error.title"),
						Logo.messages.getString("ws.settings.could.not.enter.wp") + "\n\n" + e.toString());
		}
	}

	private void initLayout()
	{
		setResizable(false);
		infoButton.setBorder(null);
		gplButton.setBorder(null);
		
		infoButton.setOpaque(false);
		gplButton.setOpaque(false);
		
		panel.add(workspace);
		panel.add(username);
		panel.add(workspaceSelection);
		panel.add(userSelection);
		panel.add(openWorkspaceSettingsBtn);
		panel.add(enterButton);
		panel.add(infoButton);
		panel.add(gplButton);

		workspaceSelection.setMinimumSize(new Dimension(200, 25));
		userSelection.setMinimumSize(new Dimension(200, 25));
		workspaceSelection.setMaximumSize(new Dimension(200, 25));
		userSelection.setMaximumSize(new Dimension(200, 25));
		
		groupLayout = new GroupLayout(panel);
		panel.setLayout(groupLayout);
		
		groupLayout.setAutoCreateGaps(true);
		groupLayout.setAutoCreateContainerGaps(true);
		
		groupLayout.setVerticalGroup(
				groupLayout.createSequentialGroup()
					.addGroup(groupLayout.createParallelGroup()
							.addComponent(gplButton)
							.addComponent(infoButton)
							.addComponent(label))
					.addGroup(groupLayout.createParallelGroup()
						.addComponent(workspace)
						.addComponent(workspaceSelection)
						.addComponent(openWorkspaceSettingsBtn))
					.addGroup(groupLayout.createParallelGroup()
						.addComponent(username)
						.addComponent(userSelection)
						.addComponent(enterButton))
					);
		
		groupLayout.setHorizontalGroup(
				groupLayout.createParallelGroup()
					.addGroup(
						groupLayout.createSequentialGroup()
							.addComponent(label)
							.addComponent(gplButton)
							.addComponent(infoButton))
					.addGroup(
						groupLayout.createSequentialGroup()
							.addGroup(groupLayout.createParallelGroup()
								.addComponent(workspace)
								.addComponent(username))
							.addGroup(groupLayout.createParallelGroup()
								.addComponent(workspaceSelection)
								.addComponent(userSelection))
							.addGroup(groupLayout.createParallelGroup()
								.addComponent(openWorkspaceSettingsBtn)
								.addComponent(enterButton))
						)
					);
	}
		
	/**
	 * Display {@link xlogo.gui.welcome.WelcomeScreen} when starting the application.
	 */
	private synchronized void showWorkspaceSettings()
	{		
		Runnable runnable = new Runnable() {
			public void run() {
				String authentification = null;
				GlobalConfig gc = WSManager.getInstance().getGlobalConfigInstance();
				if (gc.isPasswordRequired())
				{
					authentification = showPasswordPopup();
					if (authentification == null)
						return; // user cancelled the process
					
					if(!gc.authenticate(new String(authentification)))
					{
						// Could not authenticate => cancel
						DialogMessenger.getInstance().dispatchMessage(
								Logo.messages.getString("i.am.sorry"),
								Logo.messages.getString("welcome.wrong.pw"));
						return;
					}
				}
				
				setEnabled(false);
				workspaceSettings.showFrame(authentification);
			}
		};
		
		new Thread(runnable).start();
	}
	
	private void setMessageManagerParent()
	{
		DialogMessenger.getInstance().setMedium(new AsyncMediumAdapter<AsyncMessage<JFrame>, JFrame>(){
			public boolean isReady()
			{
				return getThis().isDisplayable();
			}
			public JFrame getMedium()
			{
				return getThis();
			}
			public void addMediumReadyListener(final AsyncMessenger messenger)
			{
				getThis().addWindowStateListener(new WindowStateListener(){
					
					@Override
					public void windowStateChanged(WindowEvent e)
					{
						if (getThis().isDisplayable())
							messenger.onMediumReady();
					}
				});
			}
		});
	}
	
	private JFrame getThis()
	{
		return this;
	}
	
	
	protected String showPasswordPopup() {
		JPasswordField passwordField = new JPasswordField();
		int option = JOptionPane.showConfirmDialog(this, passwordField, Logo.messages.getString("welcome.enter.pw"),
				JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);

		if (option == JOptionPane.OK_OPTION) {
			return new String(passwordField.getPassword());
		}
		return null;
	}

	public void enterApplication()
	{
		String username = (String) userSelection.getSelectedItem();
		
		if ((username == null) || (username.length() == 0))
			return; // this should not happen since the enter button is disabled
		
		if(!Storable.checkLegalName(username))
		{
			DialogMessenger.getInstance().dispatchError(
					Logo.messages.getString(MessageKeys.NAME_ERROR_TITLE), 
					Logo.messages.getString(MessageKeys.ILLEGAL_NAME));
			return;
		}
		
		
		WorkspaceConfig wc = WSManager.getInstance().getWorkspaceConfigInstance();
		if (!wc.existsUserLogically(username))
			wc.createUser(username);
		
		try {
			WSManager.getInstance().enterUserSpace(username);
		} catch (IOException e) {
			DialogMessenger.getInstance().dispatchMessage(
					Logo.messages.getString("ws.error.title"),
					Logo.messages.getString("welcome.could.not.enter.user") + e.toString());
			return;
		}
		workspaceSettings.stopEventListeners();
		onApplicationEnterListener.actionPerformed(new ActionEvent(this, 0, null));
		System.gc();
	}
	
	@Override
	public void dispose()
	{
		try {
			WSManager.getInstance().getGlobalConfigInstance().store();
		} catch (IOException e) {
			DialogMessenger.getInstance().dispatchMessage(
					Logo.messages.getString("ws.error.title"),
					Logo.messages.getString("storage.could.not.store.gc"));
		}

		System.gc();
		super.dispose();
	}
	
	public void setText()
	{
		workspace.setText(Logo.messages.getString("welcome.workspace"));
		username.setText(Logo.messages.getString("welcome.username"));
		openWorkspaceSettingsBtn.setText(Logo.messages.getString("welcome.settings"));
		enterButton.setText(Logo.messages.getString("welcome.enter"));
		setTitle(Logo.messages.getString("welcome.title"));
		pack();
	}
	
	/**
	 * Like in XLogo, almost unmodified.
	 * It is displayed in the language of the currently selected workspace.
	 */
	private void showGPL()
	{
		JFrame frame = new JFrame(Logo.messages.getString("menu.help.licence"));
		frame.setIconImage(Toolkit.getDefaultToolkit().createImage(WebPage.class.getResource("Logo_xlogo4schools.png")));
		frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		frame.setSize(500, 500);
		WebPage editorPane = new WebPage();
		editorPane.setEditable(false);
		
		String langCode = WSManager.getWorkspaceConfig().getLanguage().getLanguageCode();
		
		String path = "gpl/gpl-" + langCode + ".html";

		java.net.URL helpURL = Application.class.getResource(path);
		if (helpURL != null)
		{
			try
			{
				editorPane.setPage(helpURL);
			}
			catch (IOException e1)
			{
				System.err.println("Attempted to read a bad URL: " + helpURL);
			}
		}
		else
		{
			System.err.println("Couldn't find file: " + path);
		}
		
		// Put the editor pane in a scroll pane.
		JScrollPane editorScrollPane = new JScrollPane(editorPane);
		editorScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		editorScrollPane.setPreferredSize(new Dimension(250, 145));
		editorScrollPane.setMinimumSize(new Dimension(10, 10));
		frame.getContentPane().add(editorScrollPane);
		frame.setVisible(true);
	}

	private void showInfo()
	{
		JFrame frame = new JFrame(Logo.messages.getString("menu.help.licence"));
		frame.setIconImage(Toolkit.getDefaultToolkit().createImage(WebPage.class.getResource("Icon_x4s.png")));
		frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		frame.setSize(500, 500);
		WebPage editorPane = new WebPage();
		editorPane.setEditable(false);
		
		String path = "gpl/x4s_info.html";

		java.net.URL helpURL = Application.class.getResource(path);
		if (helpURL != null)
		{
			try
			{
				editorPane.setPage(helpURL);
			}
			catch (IOException e1)
			{
				System.err.println("Attempted to read a bad URL: " + helpURL);
			}
		}
		else
		{
			System.err.println("Couldn't find file: " + path);
		}
		
		// Put the editor pane in a scroll pane.
		JScrollPane editorScrollPane = new JScrollPane(editorPane);
		editorScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		editorScrollPane.setPreferredSize(new Dimension(250, 145));
		editorScrollPane.setMinimumSize(new Dimension(10, 10));
		frame.getContentPane().add(editorScrollPane);
		frame.setVisible(true);
	}
	
	/*
	 * Helper
	 */
	
	private ImageIcon createImageIcon(String path, String description, int width, int heigth) {
		Image img = Toolkit.getDefaultToolkit().getImage(Utils.class.getResource(path));
		return new ImageIcon(img.getScaledInstance(width, heigth, Image.SCALE_SMOOTH));
	}
}