This repository has been archived on 2021-12-05. You can view files and clone it, but cannot push or open issues or pull requests.
envoy/src/main/java/envoy/client/ui/ChatWindow.java

580 lines
19 KiB
Java
Raw Normal View History

2019-12-07 10:44:25 +01:00
package envoy.client.ui;
import java.awt.*;
2019-12-07 10:44:25 +01:00
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.IOException;
2019-12-07 10:44:25 +01:00
import java.util.logging.Level;
import java.util.logging.Logger;
2019-12-07 10:44:25 +01:00
import javax.swing.*;
2019-12-07 10:44:25 +01:00
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
2019-12-07 10:44:25 +01:00
import envoy.client.Settings;
import envoy.client.data.Chat;
import envoy.client.data.LocalDb;
2020-02-11 17:17:22 +01:00
import envoy.client.event.MessageCreationEvent;
import envoy.client.event.ThemeChangeEvent;
import envoy.client.net.Client;
import envoy.client.net.WriteProxy;
import envoy.client.ui.list.ComponentList;
import envoy.client.ui.list.ComponentListModel;
import envoy.client.ui.settings.SettingsScreen;
import envoy.client.util.EnvoyLog;
import envoy.data.Message;
import envoy.data.Message.MessageStatus;
import envoy.data.MessageBuilder;
import envoy.data.User;
import envoy.event.*;
2019-12-07 10:44:25 +01:00
/**
* Project: <strong>envoy-client</strong><br>
* File: <strong>ChatWindow.java</strong><br>
* Created: <strong>28 Sep 2019</strong><br>
2019-12-07 11:22:47 +01:00
*
2019-12-07 10:44:25 +01:00
* @author Kai S. K. Engelbart
* @author Maximilian K&auml;fer
* @author Leon Hofmeister
* @since Envoy v0.1-alpha
*/
public class ChatWindow extends JFrame {
2019-12-15 16:26:11 +01:00
// User specific objects
private Client client;
private WriteProxy writeProxy;
private LocalDb localDb;
2019-12-15 16:26:11 +01:00
2019-12-07 14:50:20 +01:00
// GUI components
private JPanel contentPane = new JPanel();
private PrimaryTextArea messageEnterTextArea = new PrimaryTextArea(space);
private JList<User> userList = new JList<>();
private DefaultListModel<User> userListModel = new DefaultListModel<>();
private Chat currentChat;
private ComponentList<Message> messageList = new ComponentList<>(new MessageListRenderer());
private PrimaryScrollPane scrollPane = new PrimaryScrollPane();
private JTextPane textPane = new JTextPane();
private PrimaryButton postButton = new PrimaryButton("Post");
private PrimaryButton settingsButton = new PrimaryButton("Settings");
2020-02-06 22:19:33 +01:00
// Contacts Header
private JPanel contactsHeader = new JPanel();
private JTextPane contactsDisplay = new JTextPane();
2020-02-06 22:19:33 +01:00
private PrimaryButton addContact = new PrimaryButton("+");
// Search Contacts
private final JPanel searchPane = new JPanel();
private final PrimaryButton cancelButton = new PrimaryButton("x");
private final PrimaryTextArea searchField = new PrimaryTextArea(space);
private final PrimaryScrollPane possibleContacts = new PrimaryScrollPane();
private final ContactsSearchRenderer contactRenderer = new ContactsSearchRenderer();
private final ComponentListModel<User> contactsModel = new ComponentListModel<>();
private final ComponentList<User> contactList = new ComponentList<>(contactRenderer);
2020-02-06 22:19:33 +01:00
private static final Logger logger = EnvoyLog.getLogger(ChatWindow.class.getSimpleName());
2019-12-07 10:44:25 +01:00
// GUI component spacing
private final static int space = 4;
private static final Insets insets = new Insets(space, space, space, space);
private static final long serialVersionUID = 6865098428255463649L;
/**
* Initializes a {@link JFrame} with UI elements used to send and read messages
* to different users.
*
* @since Envoy v0.1-alpha
*/
public ChatWindow() {
2019-12-07 10:44:25 +01:00
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 600, 800);
setTitle("Envoy");
setLocationRelativeTo(null);
setIconImage(Toolkit.getDefaultToolkit().createImage(getClass().getClassLoader().getResource("envoy_logo.png")));
2019-12-07 10:44:25 +01:00
2019-12-07 14:50:20 +01:00
contentPane.setBorder(new EmptyBorder(space, space, space, space));
2019-12-07 10:44:25 +01:00
setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
gbl_contentPane.columnWidths = new int[] { 1, 1, 1 };
2020-02-06 22:19:33 +01:00
gbl_contentPane.rowHeights = new int[] { 1, 1, 1, 1 };
2019-12-07 10:44:25 +01:00
gbl_contentPane.columnWeights = new double[] { 0.3, 1.0, 0.1 };
2020-02-06 22:19:33 +01:00
gbl_contentPane.rowWeights = new double[] { 0.03, 0.001, 1.0, 0.005 };
2019-12-07 10:44:25 +01:00
contentPane.setLayout(gbl_contentPane);
2019-12-07 14:50:20 +01:00
messageList.setBorder(new EmptyBorder(space, space, space, space));
2019-12-07 10:44:25 +01:00
scrollPane.setViewportView(messageList);
GridBagConstraints gbc_scrollPane = new GridBagConstraints();
gbc_scrollPane.fill = GridBagConstraints.BOTH;
gbc_scrollPane.gridwidth = 2;
2020-02-06 22:19:33 +01:00
gbc_scrollPane.gridheight = 2;
2019-12-07 10:44:25 +01:00
gbc_scrollPane.gridx = 1;
gbc_scrollPane.gridy = 1;
gbc_scrollPane.insets = insets;
2020-02-06 22:19:33 +01:00
drawChatBox(gbc_scrollPane);
2019-12-07 10:44:25 +01:00
// Message enter field
messageEnterTextArea.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER
&& (Settings.getInstance().isEnterToSend() && e.getModifiersEx() == 0 || e.getModifiersEx() == KeyEvent.CTRL_DOWN_MASK))
postMessage();
2019-12-07 10:44:25 +01:00
}
});
GridBagConstraints gbc_messageEnterTextfield = new GridBagConstraints();
gbc_messageEnterTextfield.fill = GridBagConstraints.BOTH;
gbc_messageEnterTextfield.gridx = 1;
2020-02-06 22:19:33 +01:00
gbc_messageEnterTextfield.gridy = 3;
2019-12-07 10:44:25 +01:00
gbc_messageEnterTextfield.insets = insets;
2019-12-07 10:44:25 +01:00
contentPane.add(messageEnterTextArea, gbc_messageEnterTextfield);
// Post Button
GridBagConstraints gbc_moveSelectionPostButton = new GridBagConstraints();
gbc_moveSelectionPostButton.fill = GridBagConstraints.BOTH;
gbc_moveSelectionPostButton.gridx = 2;
2020-02-06 22:19:33 +01:00
gbc_moveSelectionPostButton.gridy = 3;
2019-12-07 10:44:25 +01:00
gbc_moveSelectionPostButton.insets = insets;
2019-12-07 10:44:25 +01:00
postButton.addActionListener((evt) -> { postMessage(); });
2019-12-07 10:44:25 +01:00
contentPane.add(postButton, gbc_moveSelectionPostButton);
// Settings Button
GridBagConstraints gbc_moveSelectionSettingsButton = new GridBagConstraints();
gbc_moveSelectionSettingsButton.fill = GridBagConstraints.BOTH;
gbc_moveSelectionSettingsButton.gridx = 2;
gbc_moveSelectionSettingsButton.gridy = 0;
gbc_moveSelectionSettingsButton.insets = insets;
2019-12-07 10:44:25 +01:00
settingsButton.addActionListener(evt -> new SettingsScreen().setVisible(true));
2019-12-07 10:44:25 +01:00
contentPane.add(settingsButton, gbc_moveSelectionSettingsButton);
// Partner name display
textPane.setFont(new Font("Arial", Font.PLAIN, 20));
2019-12-07 14:50:20 +01:00
textPane.setEditable(false);
2019-12-07 10:44:25 +01:00
GridBagConstraints gbc_partnerName = new GridBagConstraints();
gbc_partnerName.fill = GridBagConstraints.HORIZONTAL;
gbc_partnerName.gridx = 1;
gbc_partnerName.gridy = 0;
gbc_partnerName.insets = insets;
2019-12-07 10:44:25 +01:00
contentPane.add(textPane, gbc_partnerName);
userList.setCellRenderer(new UserListRenderer());
userList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
userList.addListSelectionListener((listSelectionEvent) -> {
if (client != null && localDb != null && !listSelectionEvent.getValueIsAdjusting()) {
2019-12-07 10:44:25 +01:00
final JList<User> selectedUserList = (JList<User>) listSelectionEvent.getSource();
final User user = selectedUserList.getSelectedValue();
2020-02-06 22:19:33 +01:00
for (int i = 0; i < contentPane.getComponents().length; i++) {
if (contentPane.getComponent(i).equals(searchPane)) { drawChatBox(gbc_scrollPane); }
}
if (user != null) {
// Select current chat
currentChat = localDb.getChats().stream().filter(chat -> chat.getRecipient().getId() == user.getId()).findFirst().get();
2019-12-07 10:44:25 +01:00
2020-02-06 22:19:33 +01:00
// Read current chat
readCurrentChat();
2019-12-07 10:44:25 +01:00
2020-02-06 22:19:33 +01:00
// Set chat title
textPane.setText(currentChat.getRecipient().getName());
2019-12-07 10:44:25 +01:00
2020-02-06 22:19:33 +01:00
// Update model and scroll down
messageList.setModel(currentChat.getModel());
scrollPane.setChatOpened(true);
2020-02-06 22:19:33 +01:00
messageList.synchronizeModel();
revalidate();
repaint();
}
2019-12-07 10:44:25 +01:00
}
});
userList.setFont(new Font("Arial", Font.PLAIN, 17));
2019-12-07 14:50:20 +01:00
userList.setBorder(new EmptyBorder(space, space, space, space));
2019-12-07 10:44:25 +01:00
GridBagConstraints gbc_userList = new GridBagConstraints();
gbc_userList.fill = GridBagConstraints.VERTICAL;
gbc_userList.gridx = 0;
gbc_userList.gridy = 2;
gbc_userList.gridheight = 2;
gbc_userList.anchor = GridBagConstraints.PAGE_START;
gbc_userList.insets = insets;
2019-12-07 10:44:25 +01:00
contentPane.add(userList, gbc_userList);
contentPane.revalidate();
2020-02-06 22:19:33 +01:00
// Contacts Search
GridBagConstraints gbc_searchPane = new GridBagConstraints();
gbc_searchPane.fill = GridBagConstraints.BOTH;
gbc_searchPane.gridwidth = 2;
gbc_searchPane.gridheight = 2;
gbc_searchPane.gridx = 1;
gbc_searchPane.gridy = 1;
gbc_searchPane.insets = insets;
GridBagLayout gbl_contactsSearch = new GridBagLayout();
gbl_contactsSearch.columnWidths = new int[] { 1, 1 };
gbl_contactsSearch.rowHeights = new int[] { 1, 1 };
gbl_contactsSearch.columnWeights = new double[] { 1, 0.1 };
gbl_contactsSearch.rowWeights = new double[] { 0.001, 1 };
searchPane.setLayout(gbl_contactsSearch);
GridBagConstraints gbc_searchField = new GridBagConstraints();
gbc_searchField.fill = GridBagConstraints.BOTH;
gbc_searchField.gridx = 0;
gbc_searchField.gridy = 0;
gbc_searchField.insets = new Insets(7, 4, 4, 4);
2020-02-06 22:19:33 +01:00
searchPane.add(searchField, gbc_searchField);
// Sends event to server, if input has changed
searchField.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void removeUpdate(DocumentEvent evt) {
if (client.isOnline()) {
if (searchField.getText().isEmpty()) {
contactsModel.clear();
revalidate();
repaint();
} else {
try {
client.sendEvent(new ContactSearchRequest(searchField.getText()));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Override
public void insertUpdate(DocumentEvent evt) {
if (client.isOnline()) {
try {
client.sendEvent(new ContactSearchRequest(searchField.getText()));
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void changedUpdate(DocumentEvent evt) {}
});
2020-02-06 22:19:33 +01:00
GridBagConstraints gbc_cancelButton = new GridBagConstraints();
gbc_cancelButton.fill = GridBagConstraints.BOTH;
gbc_cancelButton.gridx = 1;
gbc_cancelButton.gridy = 0;
gbc_cancelButton.insets = new Insets(7, 4, 4, 4);
cancelButton.addActionListener((evt) -> { drawChatBox(gbc_scrollPane); });
searchPane.add(cancelButton, gbc_cancelButton);
contactList.setModel(contactsModel);
possibleContacts.setBorder(new EmptyBorder(space, space, space, space));
2020-02-06 22:19:33 +01:00
possibleContacts.setViewportView(contactList);
GridBagConstraints gbc_possibleContacts = new GridBagConstraints();
gbc_possibleContacts.fill = GridBagConstraints.BOTH;
gbc_possibleContacts.gridwidth = 2;
gbc_possibleContacts.gridx = 0;
gbc_possibleContacts.gridy = 1;
gbc_possibleContacts.insets = insets;
2020-02-06 22:19:33 +01:00
searchPane.add(possibleContacts, gbc_possibleContacts);
// Contacts Header
GridBagConstraints gbc_contactsHeader = new GridBagConstraints();
gbc_contactsHeader.fill = GridBagConstraints.BOTH;
gbc_contactsHeader.gridx = 0;
gbc_contactsHeader.gridy = 1;
gbc_contactsHeader.insets = insets;
GridBagLayout gbl_contactHeader = new GridBagLayout();
gbl_contactHeader.columnWidths = new int[] { 1, 1 };
gbl_contactHeader.rowHeights = new int[] { 1 };
gbl_contactHeader.columnWeights = new double[] { 1, 1 };
gbl_contactHeader.rowWeights = new double[] { 1 };
contactsHeader.setLayout(gbl_contactHeader);
contactsDisplay.setEditable(false);
contactsDisplay.setFont(new Font("Arial", Font.PLAIN, 12));
contactsDisplay.setText("Contacts");
GridBagConstraints gbc_contactsDisplay = new GridBagConstraints();
gbc_contactsDisplay.fill = GridBagConstraints.BOTH;
gbc_contactsDisplay.gridx = 0;
gbc_contactsDisplay.gridy = 0;
contactsHeader.add(contactsDisplay, gbc_contactsDisplay);
addContact.setFont(new Font("Arial", Font.PLAIN, 15));
GridBagConstraints gbc_addContact = new GridBagConstraints();
gbc_addContact.fill = GridBagConstraints.BOTH;
gbc_addContact.gridx = 1;
gbc_addContact.gridy = 0;
gbc_addContact.insets = insets;
2020-02-06 22:19:33 +01:00
addContact.addActionListener((evt) -> { drawContactSearch(gbc_searchPane); });
contactsHeader.add(addContact, gbc_addContact);
applyTheme(Settings.getInstance().getThemes().get(Settings.getInstance().getCurrentTheme()));
contentPane.add(contactsHeader, gbc_contactsHeader);
contentPane.revalidate();
// Listen to theme changes
EventBus.getInstance().register(ThemeChangeEvent.class, evt -> applyTheme(evt.get()));
2019-12-07 10:44:25 +01:00
// Listen to user status changes
EventBus.getInstance().register(UserStatusChangeEvent.class, evt -> { userList.revalidate(); userList.repaint(); });
// Listen to received messages
EventBus.getInstance().register(MessageCreationEvent.class, evt -> {
Message message = evt.get();
Chat chat = localDb.getChats().stream().filter(c -> c.getRecipient().getId() == message.getSenderId()).findFirst().get();
chat.appendMessage(message);
// Read message and update UI if in current chat
if (chat == currentChat) readCurrentChat();
revalidate();
repaint();
});
// Listen to message status changes
EventBus.getInstance().register(MessageStatusChangeEvent.class, evt -> {
final long id = evt.getId();
final MessageStatus status = evt.get();
for (Chat c : localDb.getChats())
for (Message m : c.getModel())
if (m.getId() == id) {
// Update message status
m.setStatus(status);
// Update model and scroll down if current chat
if (c == currentChat) {
messageList.setModel(currentChat.getModel());
scrollPane.setChatOpened(true);
} else messageList.synchronizeModel();
}
revalidate();
repaint();
});
// Listen to contact search results
EventBus.getInstance().register(ContactSearchResult.class, evt -> {
contactsModel.clear();
final java.util.List<User> contacts = evt.get();
logger.info("Received contact search result " + contacts);
contacts.forEach(contactsModel::add);
revalidate();
repaint();
});
// Add new contacts to the contact list
EventBus.getInstance().register(ContactOperationEvent.class, evt -> {
User contact = evt.get();
2020-02-11 17:17:22 +01:00
// Clearing the search field and the searchResultList
searchField.setText("");
contactsModel.clear();
// Update LocalDB
userListModel.addElement(contact);
localDb.getUsers().put(contact.getName(), contact);
localDb.getChats().add(new Chat(contact));
revalidate();
repaint();
});
revalidate();
repaint();
2019-12-07 10:44:25 +01:00
}
2019-12-07 14:50:20 +01:00
/**
* Used to immediately reload the {@link ChatWindow} when settings were changed.
*
* @param theme the theme to change colors into
* @since Envoy v0.2-alpha
2019-12-07 14:50:20 +01:00
*/
private void applyTheme(Theme theme) {
2019-12-07 14:50:20 +01:00
// contentPane
contentPane.setBackground(theme.getBackgroundColor());
contentPane.setForeground(theme.getUserNameColor());
// messageList
// messageList.setSelectionForeground(theme.getUserNameColor());
// messageList.setSelectionBackground(theme.getSelectionColor());
2019-12-07 14:50:20 +01:00
messageList.setForeground(theme.getMessageColorChat());
messageList.setBackground(theme.getCellColor());
// scrollPane
scrollPane.applyTheme(theme);
scrollPane.autoscroll();
2019-12-07 14:50:20 +01:00
// messageEnterTextArea
messageEnterTextArea.setCaretColor(theme.getTypingMessageColor());
messageEnterTextArea.setForeground(theme.getTypingMessageColor());
messageEnterTextArea.setBackground(theme.getCellColor());
// postButton
postButton.setForeground(theme.getInteractableForegroundColor());
postButton.setBackground(theme.getInteractableBackgroundColor());
// settingsButton
settingsButton.setForeground(theme.getInteractableForegroundColor());
settingsButton.setBackground(theme.getInteractableBackgroundColor());
// textPane
textPane.setBackground(theme.getBackgroundColor());
textPane.setForeground(theme.getUserNameColor());
// userList
userList.setSelectionForeground(theme.getUserNameColor());
userList.setSelectionBackground(theme.getSelectionColor());
userList.setForeground(theme.getUserNameColor());
userList.setBackground(theme.getCellColor());
2020-02-06 22:19:33 +01:00
// contacts header
contactsHeader.setBackground(theme.getCellColor());
contactsDisplay.setBackground(theme.getCellColor());
contactsDisplay.setForeground(theme.getUserNameColor());
addContact.setBackground(theme.getInteractableBackgroundColor());
addContact.setForeground(theme.getInteractableForegroundColor());
// SearchPane
searchPane.setBackground(theme.getCellColor());
searchField.setBackground(theme.getBackgroundColor());
searchField.setForeground(theme.getUserNameColor());
cancelButton.setBackground(theme.getInteractableBackgroundColor());
cancelButton.setForeground(theme.getInteractableForegroundColor());
contactList.setForeground(theme.getMessageColorChat());
contactList.setBackground(theme.getCellColor());
2020-02-06 22:19:33 +01:00
possibleContacts.applyTheme(theme);
2019-12-07 14:50:20 +01:00
}
private void postMessage() {
if (userList.isSelectionEmpty()) {
JOptionPane.showMessageDialog(this, "Please select a recipient!", "Cannot send message", JOptionPane.INFORMATION_MESSAGE);
2019-12-07 11:22:47 +01:00
return;
2019-12-07 10:44:25 +01:00
}
if (!messageEnterTextArea.getText().isEmpty()) try {
// Create message
final Message message = new MessageBuilder(localDb.getUser().getId(), currentChat.getRecipient().getId(), localDb.getIdGenerator())
.setText(messageEnterTextArea.getText())
.build();
// Send message
writeProxy.writeMessage(message);
// Add message to PersistentLocalDb and update UI
2019-12-07 10:44:25 +01:00
currentChat.appendMessage(message);
// Clear text field
messageEnterTextArea.setText("");
// Update UI
revalidate();
repaint();
// Request a new id generator if all IDs were used
if (!localDb.getIdGenerator().hasNext()) client.requestIdGenerator();
2019-12-07 10:44:25 +01:00
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Error sending message:\n" + e.toString(), "Message sending error", JOptionPane.ERROR_MESSAGE);
2019-12-07 10:44:25 +01:00
e.printStackTrace();
}
}
/**
* Initializes the elements of the user list by downloading them from the
* server.
2019-12-07 11:22:47 +01:00
*
2019-12-07 10:44:25 +01:00
* @since Envoy v0.1-alpha
*/
private void loadUsersAndChats() {
new Thread(() -> {
localDb.getUsers().values().forEach(user -> {
2019-12-07 10:44:25 +01:00
userListModel.addElement(user);
// Check if user exists in local DB
if (localDb.getChats().stream().filter(c -> c.getRecipient().getId() == user.getId()).count() == 0)
localDb.getChats().add(new Chat(user));
2019-12-07 10:44:25 +01:00
});
SwingUtilities.invokeLater(() -> userList.setModel(userListModel));
revalidate();
repaint();
2019-12-07 10:44:25 +01:00
}).start();
}
private void readCurrentChat() {
try {
currentChat.read(writeProxy);
messageList.synchronizeModel();
} catch (IOException e) {
e.printStackTrace();
logger.log(Level.WARNING, "Couldn't notify server about message status change", e);
}
}
2020-02-06 22:19:33 +01:00
private void drawChatBox(GridBagConstraints gbc_scrollPane) {
contentPane.remove(searchPane);
contentPane.add(scrollPane, gbc_scrollPane);
contentPane.revalidate();
contentPane.repaint();
}
2020-02-06 22:19:33 +01:00
private void drawContactSearch(GridBagConstraints gbc_searchPane) {
currentChat = null;
userList.removeSelectionInterval(0, userList.getModel().getSize() - 1);
messageList.setModel(null);
textPane.setText("");
contentPane.remove(scrollPane);
contentPane.add(searchPane, gbc_searchPane);
contentPane.revalidate();
contentPane.repaint();
}
2019-12-07 10:44:25 +01:00
/**
* Initializes the components responsible server communication and
* persistence.<br>
* <br>
* This will trigger the display of the contact list.
*
* @param client the client used to send and receive messages
* @param localDb the local database used to manage stored messages
* and users
* @param writeProxy the write proxy used to send messages and status change
* events to the server or cache them inside the local
* database
* @since Envoy v0.3-alpha
*/
public void initContent(Client client, LocalDb localDb, WriteProxy writeProxy) {
this.client = client;
this.localDb = localDb;
this.writeProxy = writeProxy;
loadUsersAndChats();
}
2019-12-07 10:44:25 +01:00
}