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

383 lines
13 KiB
Java
Raw Normal View History

2019-12-07 10:44:25 +01:00
package envoy.client.ui;
import java.awt.Color;
2019-12-07 10:44:25 +01:00
import java.awt.ComponentOrientation;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Toolkit;
2019-12-07 10:44:25 +01:00
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.border.EmptyBorder;
import envoy.client.Chat;
import envoy.client.Client;
import envoy.client.Config;
import envoy.client.LocalDB;
2019-12-07 14:50:20 +01:00
import envoy.client.Settings;
2019-12-07 10:44:25 +01:00
import envoy.schema.Message;
import envoy.schema.User;
/**
* 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 {
private static final long serialVersionUID = 6865098428255463649L;
2019-12-07 14:50:20 +01:00
// user specific objects
2019-12-07 10:44:25 +01:00
private Client client;
private LocalDB localDB;
2019-12-07 14:50:20 +01:00
// GUI components
2019-12-14 13:52:47 +01:00
private JPanel contentPane = new JPanel();
private PrimaryTextArea messageEnterTextArea = new PrimaryTextArea(space);
private JList<User> userList = new JList<>();
2019-12-07 14:50:20 +01:00
private Chat currentChat;
2019-12-14 13:52:47 +01:00
private JList<Message> messageList = new JList<>();
private JScrollPane scrollPane = new JScrollPane();
private JTextPane textPane = new JTextPane();
2019-12-07 14:50:20 +01:00
// private JCheckBox jCbChangeMode;
2019-12-14 13:52:47 +01:00
private PrimaryButton postButton = new PrimaryButton("Post");
private PrimaryButton settingsButton = new PrimaryButton("Settings");
2019-12-07 14:50:20 +01:00
private static int space = 4;
2019-12-07 10:44:25 +01:00
private static final Logger logger = Logger.getLogger(ChatWindow.class.getSimpleName());
public ChatWindow(Client client, LocalDB localDB) {
this.client = client;
this.localDB = localDB;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 600, 800);
setTitle("Envoy");
setLocationRelativeTo(null);
2019-12-14 13:52:47 +01:00
setIconImage(Toolkit.getDefaultToolkit().createImage(getClass().getClassLoader().getResource("envoy_logo.png")));
2019-12-07 10:44:25 +01:00
// Save chats when window closes
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent evt) {
try {
localDB.save();
2019-12-07 14:50:20 +01:00
Settings.getInstance().save();
2019-12-07 10:44:25 +01:00
} catch (IOException e1) {
e1.printStackTrace();
logger.log(Level.WARNING, "Unable to save the messages", e1);
}
}
});
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 };
gbl_contentPane.rowHeights = new int[] { 1, 1, 1 };
gbl_contentPane.columnWeights = new double[] { 0.3, 1.0, 0.1 };
gbl_contentPane.rowWeights = new double[] { 0.05, 1.0, 0.07 };
contentPane.setLayout(gbl_contentPane);
messageList.setCellRenderer(new MessageListRenderer());
messageList.setFocusTraversalKeysEnabled(false);
messageList.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
DefaultListModel<Message> messageListModel = new DefaultListModel<>();
messageList.setModel(messageListModel);
messageList.setFont(new Font("Arial", Font.PLAIN, 17));
messageList.setFixedCellHeight(60);
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);
scrollPane.setBorder(null);
GridBagConstraints gbc_scrollPane = new GridBagConstraints();
gbc_scrollPane.fill = GridBagConstraints.BOTH;
gbc_scrollPane.gridwidth = 2;
gbc_scrollPane.gridx = 1;
gbc_scrollPane.gridy = 1;
2019-12-07 14:50:20 +01:00
gbc_scrollPane.insets = new Insets(space, space, space, space);
2019-12-07 10:44:25 +01:00
contentPane.add(scrollPane, gbc_scrollPane);
// Message enter field
messageEnterTextArea.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER
2019-12-14 13:52:47 +01:00
&& ((Settings.getInstance().isEnterToSend() && e.getModifiersEx() == 0) || (e.getModifiersEx() == KeyEvent.CTRL_DOWN_MASK))) {
2019-12-07 10:44:25 +01:00
postMessage(messageList);
}
2019-12-07 10:44:25 +01:00
}
});
2019-12-07 10:44:25 +01:00
GridBagConstraints gbc_messageEnterTextfield = new GridBagConstraints();
gbc_messageEnterTextfield.fill = GridBagConstraints.BOTH;
gbc_messageEnterTextfield.gridx = 1;
gbc_messageEnterTextfield.gridy = 2;
2019-12-07 14:50:20 +01:00
gbc_messageEnterTextfield.insets = new Insets(space, space, space, space);
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;
gbc_moveSelectionPostButton.gridy = 2;
2019-12-07 14:50:20 +01:00
gbc_moveSelectionPostButton.insets = new Insets(space, space, space, space);
2019-12-07 10:44:25 +01:00
postButton.addActionListener((evt) -> { postMessage(messageList); });
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;
2019-12-07 14:50:20 +01:00
gbc_moveSelectionSettingsButton.insets = new Insets(space, space, space, space);
2019-12-07 10:44:25 +01:00
settingsButton.addActionListener((evt) -> {
try {
2019-12-07 14:50:20 +01:00
SettingsScreen.open();
changeChatWindowColors(Settings.getInstance().getCurrentTheme());
} catch (Exception e) {
2019-12-07 10:44:25 +01:00
SettingsScreen.open();
logger.log(Level.WARNING, "An error occured while opening the settings screen", e);
e.printStackTrace();
}
});
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;
2019-12-07 14:50:20 +01:00
gbc_partnerName.insets = new Insets(space, space, space, space);
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 (!listSelectionEvent.getValueIsAdjusting()) {
@SuppressWarnings("unchecked")
final JList<User> selectedUserList = (JList<User>) listSelectionEvent.getSource();
final User user = selectedUserList.getSelectedValue();
client.setRecipient(user);
2019-12-14 13:52:47 +01:00
currentChat = localDB.getChats().stream().filter(chat -> chat.getRecipient().getID() == user.getID()).findFirst().get();
2019-12-07 10:44:25 +01:00
// Set all unread messages in the chat to read
readCurrentChat();
client.setRecipient(user);
textPane.setText(currentChat.getRecipient().getName());
messageList.setModel(currentChat.getModel());
contentPane.revalidate();
}
});
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 = 1;
gbc_userList.anchor = GridBagConstraints.PAGE_START;
2019-12-07 14:50:20 +01:00
gbc_userList.insets = new Insets(space, space, space, space);
2019-12-07 10:44:25 +01:00
2019-12-07 14:50:20 +01:00
changeChatWindowColors(Settings.getInstance().getCurrentTheme());
2019-12-07 10:44:25 +01:00
contentPane.add(userList, gbc_userList);
contentPane.revalidate();
loadUsersAndChats();
if (client.isOnline()) startSyncThread(Config.getInstance().getSyncTimeout());
2019-12-07 10:44:25 +01:00
contentPane.revalidate();
}
2019-12-07 14:50:20 +01:00
/**
* Used to immediately reload the ChatWindow when settings were changed.
*
* @since Envoy v0.1-alpha
*/
public void changeChatWindowColors(String key) {
Theme theme = Settings.getInstance().getThemes().get(key);
// contentPane
contentPane.setBackground(theme.getBackgroundColor());
contentPane.setForeground(theme.getUserNameColor());
// messageList
messageList.setSelectionForeground(theme.getUserNameColor());
messageList.setSelectionBackground(theme.getSelectionColor());
messageList.setForeground(theme.getMessageColorChat());
messageList.setBackground(theme.getCellColor());
// scrollPane
scrollPane.setForeground(theme.getBackgroundColor());
scrollPane.setBackground(theme.getCellColor());
// scrollPane.getVerticalScrollBar()
// .setBackground(
// new Color(theme.getBackgroundColor().getRed() + 50,
// theme.getBackgroundColor().getGreen() + 50,
// theme.getBackgroundColor().getBlue() + 50));
scrollPane.getVerticalScrollBar().setBackground(theme.getCellColor());
scrollPane.getVerticalScrollBar()
.setUI(new PrimaryScrollBar(5, theme.getInteractableBackgroundColor(),
new Color(theme.getInteractableBackgroundColor().getRGB() - 50),
new Color(theme.getInteractableBackgroundColor().getRGB() + 170), true));
scrollPane.getHorizontalScrollBar().setBackground(theme.getCellColor());
scrollPane.getHorizontalScrollBar()
.setUI(new PrimaryScrollBar(5, theme.getInteractableBackgroundColor(), new Color(theme.getInteractableBackgroundColor().getRGB() - 50),
new Color(theme.getInteractableBackgroundColor().getRGB() + 170), false));
// int currentVerticalScrollBarValue =
// scrollPane.getVerticalScrollBar().getValue() +
// scrollPane.getVerticalScrollBar().getVisibleAmount(); Work in Progress for
// 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());
}
2019-12-07 10:44:25 +01:00
private void postMessage(JList<Message> messageList) {
if (!client.hasRecipient()) {
2019-12-14 13:52:47 +01:00
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 and send message object
2019-12-14 13:52:47 +01:00
final Message message = localDB.createMessage(messageEnterTextArea.getText(), currentChat.getRecipient().getID());
2019-12-07 10:44:25 +01:00
currentChat.appendMessage(message);
messageList.setModel(currentChat.getModel());
// Clear text field
messageEnterTextArea.setText("");
contentPane.revalidate();
} catch (Exception e) {
JOptionPane.showMessageDialog(this,
"An exception occured while sending a message. See the log for more details.",
"Exception occured",
JOptionPane.ERROR_MESSAGE);
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(() -> {
DefaultListModel<User> userListModel = new DefaultListModel<>();
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));
});
SwingUtilities.invokeLater(() -> userList.setModel(userListModel));
}).start();
}
/**
* Updates the data model and the UI repeatedly after a certain amount of
* time.
2019-12-07 11:22:47 +01:00
*
2019-12-07 10:44:25 +01:00
* @param timeout the amount of time that passes between two requests sent to
* the server
* @since Envoy v0.1-alpha
*/
private void startSyncThread(int timeout) {
new Timer(timeout, (evt) -> {
new Thread(() -> {
// Synchronize
try {
localDB.applySync(client.sendSync(client.getSender().getID(), localDB.fillSync(client.getSender().getID())));
} catch (Exception e) {
logger.log(Level.SEVERE, "Could not perform sync", e);
}
2019-12-07 10:44:25 +01:00
// Process unread messages
localDB.addUnreadMessagesToLocalDB();
localDB.clearUnreadMessagesSync();
// Mark unread messages as read when they are in the current chat
readCurrentChat();
// Update UI
2019-12-14 13:52:47 +01:00
SwingUtilities.invokeLater(() -> { updateUserStates(); contentPane.revalidate(); contentPane.repaint(); });
2019-12-07 10:44:25 +01:00
}).start();
}).start();
}
private void updateUserStates() {
for (int i = 0; i < userList.getModel().getSize(); i++)
for (int j = 0; j < localDB.getChats().size(); j++)
if (userList.getModel().getElementAt(i).getID() == localDB.getChats().get(j).getRecipient().getID())
userList.getModel().getElementAt(i).setStatus(localDB.getChats().get(j).getRecipient().getStatus());
}
/**
* Marks messages in the current chat as {@code READ}.
*/
private void readCurrentChat() { if (currentChat != null) { localDB.setMessagesToRead(currentChat); } }
}