From e8bee1c2912146da6fac1e1da2599b81dbb03c25 Mon Sep 17 00:00:00 2001 From: admin Date: Tue, 12 Dec 2023 06:35:29 +1000 Subject: [PATCH] Remove references to 'doc', this is instead set when LineFormatter is initialized. --- src/urChatBasic/base/IRCRoomBase.java | 11 +-- src/urChatBasic/frontend/LineFormatter.java | 93 ++++++++++++++------- src/urChatBasic/frontend/UserGUI.java | 22 ++--- tests/backend/MessageHandlerTests.java | 38 ++++----- 4 files changed, 96 insertions(+), 68 deletions(-) diff --git a/src/urChatBasic/base/IRCRoomBase.java b/src/urChatBasic/base/IRCRoomBase.java index 9915d4d..452b9de 100644 --- a/src/urChatBasic/base/IRCRoomBase.java +++ b/src/urChatBasic/base/IRCRoomBase.java @@ -256,6 +256,8 @@ private void setupMainTextArea() channelTextArea.setEditable(false); channelTextArea.setFont(getFontPanel().getFont()); channelTextArea.setEditorKit(new StyledEditorKit()); + // This is needed because the channelTextArea isn't the same after it was initialized. + resetLineFormatter(); } private void setupUsersList() @@ -458,8 +460,8 @@ public void run() String line = messagePair.getLine(); String fromUser = messagePair.getUser(); - Document document = channelTextArea.getDocument(); - Element root = document.getDefaultRootElement(); + Document document = lineFormatter.getDocument(); + Element root = lineFormatter.getDocument().getDefaultRootElement(); int lineLimit = gui.getLimitChannelLinesCount(); @@ -519,7 +521,7 @@ public void run() if (fromUser.equals(Constants.EVENT_USER) || !fromIRCUser.isMuted()) { - lineFormatter.formattedDocument(doc, new Date(), fromIRCUser, fromUser, line); + lineFormatter.formattedDocument(new Date(), fromIRCUser, fromUser, line); if (server.getNick() != null && line.indexOf(server.getNick()) > -1) { @@ -951,8 +953,7 @@ public void run() { fontDialog.getFontPanel().setDefaultFont(f); - lineFormatter.setFont((StyledDocument) channelTextArea.getDocument(), - fontDialog.getFontPanel().getFont()); + lineFormatter.setFont(fontDialog.getFontPanel().getFont()); // TODO: Should this updateStyles if the font is changed? // lineFormatter.updateStyles((StyledDocument) channelTextArea.getDocument(), 0); } diff --git a/src/urChatBasic/frontend/LineFormatter.java b/src/urChatBasic/frontend/LineFormatter.java index e65ecbe..b6b82c5 100644 --- a/src/urChatBasic/frontend/LineFormatter.java +++ b/src/urChatBasic/frontend/LineFormatter.java @@ -49,6 +49,7 @@ public class LineFormatter private URStyle mediumStyle; private URStyle lowStyle; private JTextPane docOwner; + private StyledDocument doc; public URStyle myStyle; private Map formatterStyles = new HashMap<>(); @@ -62,6 +63,7 @@ public LineFormatter(URStyle baseStyle, JTextPane docOwner ,final IRCServerBase // The JTextPane is technically 'disabled', so we need to change the colour to be the enabled colour. this.docOwner.setBackground(UIManager.getColor(Constants.DEFAULT_BACKGROUND_STRING)); + doc = this.docOwner.getStyledDocument(); if (null != server) { @@ -103,11 +105,11 @@ public LineFormatter(URStyle baseStyle, JTextPane docOwner ,final IRCServerBase formatterStyles.put(lowStyle.getName(), lowStyle); } - public void setFont(StyledDocument doc, Font newFont) + public void setFont(Font newFont) { targetStyle.setFont(newFont); if (doc.getLength() > 0) - updateStyles(doc, 0); + updateStyles(0); } public URStyle defaultStyle(String name, boolean load) @@ -359,7 +361,7 @@ public void actionPerformed(ActionEvent e) } // Inserts the string at the position - private void insertString(StyledDocument doc, String insertedString, SimpleAttributeSet style, int position) + private void insertString(String insertedString, SimpleAttributeSet style, int position) throws BadLocationException { // remove the existing attributes @@ -373,12 +375,12 @@ private void insertString(StyledDocument doc, String insertedString, SimpleAttri } // Adds the string (with all needed attributes) to the end of the document - private void appendString(StyledDocument doc, String insertedString, SimpleAttributeSet style) + private void appendString(String insertedString, SimpleAttributeSet style) throws BadLocationException { int position = doc.getLength(); - insertString(doc, insertedString, style, position); + insertString(insertedString, style, position); } public URStyle getStyleDefault(String styleName) @@ -419,10 +421,9 @@ public URStyle getStyle(String styleName, boolean load) /** * Reloads all the styles, then updates the doc - * @param doc * @param startPosition */ - public void updateStyles(StyledDocument doc, int startPosition) + public void updateStyles(int startPosition) { targetStyle.load(formatterPrefs); @@ -431,10 +432,10 @@ public void updateStyles(StyledDocument doc, int startPosition) } Constants.LOGGER.log(Level.INFO, "Updating styles."); - updateDocStyles(doc, startPosition); + updateDocStyles(startPosition); } - private void updateDocStyles(StyledDocument doc, int startPosition) + private void updateDocStyles(int startPosition) { SimpleAttributeSet textStyle = new SimpleAttributeSet(doc.getCharacterElement(startPosition).getAttributes()); @@ -472,7 +473,7 @@ private void updateDocStyles(StyledDocument doc, int startPosition) SimpleAttributeSet timeStyle = getStyle(styleName, false); timeStyle.addAttribute("date", lineDate); timeStyle.addAttribute("type", "time"); - insertString(doc, newTimeString, timeStyle, styleStart); + insertString(newTimeString, timeStyle, styleStart); styleLength = newTimeString.length(); } else { @@ -524,10 +525,37 @@ private void updateDocStyles(StyledDocument doc, int startPosition) doc.setCharacterAttributes(styleStart, styleLength, matchingStyle, true); if ((styleStart + styleLength) < doc.getLength()) - updateDocStyles(doc, (styleStart + styleLength)); + updateDocStyles((styleStart + styleLength)); } - public String getLatestLine(StyledDocument doc) throws BadLocationException + public String getFirstLine() throws BadLocationException + { + Element root = doc.getDefaultRootElement(); + int linePos = 0; + + String finalLine = ""; + + while (finalLine.isEmpty()) + { + + if (linePos < 0) + break; + + Element line = root.getElement(linePos++); + + if (null == line) + continue; + + int start = line.getStartOffset(); + int end = line.getEndOffset(); + String text = doc.getText(start, end - start); + finalLine = text.trim(); + } + + return finalLine; + } + + public String getLatestLine() throws BadLocationException { Element root = doc.getDefaultRootElement(); int lines = root.getElementCount(); @@ -554,7 +582,7 @@ public String getLatestLine(StyledDocument doc) throws BadLocationException return finalLine; } - private int getLinePosition(StyledDocument doc, String targetLine) throws BadLocationException + private int getLinePosition(String targetLine) throws BadLocationException { Element root = doc.getDefaultRootElement(); int lines = root.getElementCount(); @@ -579,25 +607,25 @@ private int getLinePosition(StyledDocument doc, String targetLine) throws BadLoc return 0; } - public SimpleAttributeSet getStyleAtPosition(StyledDocument doc, int position, String relativeLine) + public SimpleAttributeSet getStyleAtPosition(int position, String relativeLine) throws BadLocationException { if (!relativeLine.isBlank()) - position = position + getLinePosition(doc, relativeLine); + position = position + getLinePosition(relativeLine); AttributeSet textStyle = doc.getCharacterElement(position).getAttributes(); return new SimpleAttributeSet(textStyle); } - private void parseClickableText(StyledDocument doc, IRCUser fromUser, String line, URStyle defaultStyle) + private void parseClickableText(IRCUser fromUser, String line, URStyle defaultStyle) throws BadLocationException { HashMap regexStrings = new HashMap<>(); regexStrings.put(Constants.URL_REGEX, urlStyle); regexStrings.put(Constants.CHANNEL_REGEX, channelStyle); // final String line = getLatestLine(doc); - final int relativePosition = getLinePosition(doc, getLatestLine(doc)); + final int relativePosition = getLinePosition(getLatestLine()); ArrayList clickableLines = new ArrayList(); @@ -645,25 +673,23 @@ private void parseClickableText(StyledDocument doc, IRCUser fromUser, String lin int nextLineLength = Integer.parseInt(nextLine.getAttribute("styleLength").toString()); // Append the string that comes before the next clickable text - appendString(doc, remainingLine.substring(0, nextLineStart - offset), defaultStyle); + appendString(remainingLine.substring(0, nextLineStart - offset), defaultStyle); - appendString(doc, nextLine.getAttribute("clickableText").toString(), nextLine); + appendString(nextLine.getAttribute("clickableText").toString(), nextLine); remainingLine = remainingLine.substring((nextLineStart + nextLineLength) - offset); } - appendString(doc, remainingLine, defaultStyle); + appendString(remainingLine, defaultStyle); } /** * Inserts a string onto the end of the doc. - * - * @param doc - * @param timeLine * @param fromUser * @param line + * @param timeLine */ - public void formattedDocument(StyledDocument doc, Date lineDate, IRCUser fromUser, String fromString, String line) + public void formattedDocument(Date lineDate, IRCUser fromUser, String fromString, String line) { // build the timeLine string String timeLine = UserGUI.getTimeLineString(lineDate); @@ -708,7 +734,7 @@ public void formattedDocument(StyledDocument doc, Date lineDate, IRCUser fromUse timePositionStyle.addAttribute("date", lineDate); timePositionStyle.removeAttribute("type"); timePositionStyle.addAttribute("type", "time"); - appendString(doc, timeLine + " ", timePositionStyle); + appendString(timeLine + " ", timePositionStyle); timePositionStyle.removeAttribute("type"); linePositionStyle.removeAttribute("date"); } else @@ -716,7 +742,7 @@ public void formattedDocument(StyledDocument doc, Date lineDate, IRCUser fromUse linePositionStyle.addAttribute("date", lineDate); } - appendString(doc, "<", linePositionStyle); + appendString("<", linePositionStyle); linePositionStyle.removeAttribute("date"); if (fromUser != null) @@ -727,25 +753,30 @@ public void formattedDocument(StyledDocument doc, Date lineDate, IRCUser fromUse new ClickableText(fromUser.toString(), nickPositionStyle, fromUser)); // doc.insertString(doc.getLength(), fromUser.toString(), clickableNameStyle); - appendString(doc, fromUser.toString(), clickableNameStyle); + appendString(fromUser.toString(), clickableNameStyle); } else { - appendString(doc, fromString, nickPositionStyle); + appendString(fromString, nickPositionStyle); } - appendString(doc, ">", linePositionStyle); + appendString(">", linePositionStyle); // print the remaining text // appendString(doc, " "+line, lineStyle); // parse the outputted line for clickable text - parseClickableText(doc, fromUser, " " + line, linePositionStyle); + parseClickableText(fromUser, " " + line, linePositionStyle); - appendString(doc, System.getProperty("line.separator"), linePositionStyle); + appendString(System.getProperty("line.separator"), linePositionStyle); } catch (BadLocationException e) { Constants.LOGGER.log(Level.SEVERE, e.getLocalizedMessage()); } } + public StyledDocument getDocument() + { + return doc; + } + } diff --git a/src/urChatBasic/frontend/UserGUI.java b/src/urChatBasic/frontend/UserGUI.java index 91cad79..c18ee9f 100644 --- a/src/urChatBasic/frontend/UserGUI.java +++ b/src/urChatBasic/frontend/UserGUI.java @@ -920,19 +920,14 @@ public void updatePreviewTextArea() IRCUser tempUser = new IRCUser(null, "matty_r"); IRCUser tempUser2 = new IRCUser(null, System.getProperty("user.name")); previewLineFormatter.setNick(System.getProperty("user.name")); - previewLineFormatter.formattedDocument(previewDoc, new Date(), null, Constants.EVENT_USER, - "urChat has loaded - this is an Event"); - previewLineFormatter.formattedDocument(previewDoc, new Date(), tempUser, "matty_r", - "Normal line. Hello, world!"); - previewLineFormatter.formattedDocument(previewDoc, new Date(), tempUser, "matty_r", - "This is what it looks like when your nick is mentioned, " + System.getProperty("user.name") + "!"); - previewLineFormatter.formattedDocument(previewDoc, new Date(), tempUser2, System.getProperty("user.name"), - "Go to https://github.com/matty-r/urChat"); - previewLineFormatter.formattedDocument(previewDoc, new Date(), tempUser2, System.getProperty("user.name"), - "Join #urchatclient on irc.libera.chat or #anotherroom"); + previewLineFormatter.formattedDocument(new Date(), null, Constants.EVENT_USER, "urChat has loaded - this is an Event"); + previewLineFormatter.formattedDocument(new Date(), tempUser, "matty_r", "Normal line. Hello, world!"); + previewLineFormatter.formattedDocument(new Date(), tempUser, "matty_r", "This is what it looks like when your nick is mentioned, " + System.getProperty("user.name") + "!"); + previewLineFormatter.formattedDocument(new Date(), tempUser2, System.getProperty("user.name"), "Go to https://github.com/matty-r/urChat"); + previewLineFormatter.formattedDocument(new Date(), tempUser2, System.getProperty("user.name"), "Join #urchatclient on irc.libera.chat or #anotherroom"); } else { - previewLineFormatter.updateStyles(previewDoc, 0); + previewLineFormatter.updateStyles(0); } } @@ -955,7 +950,7 @@ public void mouseClicked(MouseEvent mouseEvent) // List actionListeners = styleFontDialog.getFontPanel().getActionListeners(); // TODO: Need to save attributes and updateStyles after.. // Currently runs the save after updateStyles - previewLineFormatter.updateStyles(doc, 0); + previewLineFormatter.updateStyles(0); }); // styleFontDialog.addResetListener(new ActionListener() { @@ -1901,7 +1896,7 @@ public void actionPerformed(ActionEvent arg0) } // previewLineFormatter.setFont(previewTextArea.getStyledDocument(), clientFontPanel.getFont()); - previewLineFormatter.updateStyles(previewTextArea.getStyledDocument(), 0); + previewLineFormatter.updateStyles(0); } } @@ -2070,6 +2065,7 @@ private void updateExtras() ((IRCRoomBase) tab).getFontPanel().setDefaultFont(clientFontPanel.getFont()); SwingUtilities.updateComponentTreeUI(((IRCRoomBase) tab).myMenu); SwingUtilities.updateComponentTreeUI(((IRCRoomBase) tab).getFontPanel()); + // TODO: Update styles ((IRCRoomBase) tab).getChannelTextPane() } } diff --git a/tests/backend/MessageHandlerTests.java b/tests/backend/MessageHandlerTests.java index e8aad3b..2599743 100644 --- a/tests/backend/MessageHandlerTests.java +++ b/tests/backend/MessageHandlerTests.java @@ -54,8 +54,7 @@ public void nickIsHighStyleTest() throws BadLocationException, InterruptedExcept String rawMessage = ":someuser!~someuser@urchatclient PRIVMSG testUser :hello testUser!"; Message testMessage = testHandler.new Message(rawMessage); testHandler.parseMessage(testMessage); - StyledDocument testDoc = testChannel.getChannelTextPane().getStyledDocument(); - String testLine = testChannel.getLineFormatter().getLatestLine(testDoc); // "[0629] hello testUser!" + String testLine = testChannel.getLineFormatter().getLatestLine(); // "[0629] hello testUser!" while (testChannel.messageQueueWorking()) { @@ -64,7 +63,7 @@ public void nickIsHighStyleTest() throws BadLocationException, InterruptedExcept // Should be highStyle because someuser mentioned my nick, testUser assertEquals("highStyle", - testChannel.getLineFormatter().getStyleAtPosition(testDoc, 11, testLine).getAttribute("name")); + testChannel.getLineFormatter().getStyleAtPosition(11, testLine).getAttribute("name")); } @Test(groups = {"Test #001"}) @@ -99,7 +98,7 @@ public void nickIsNickStyleTest() throws BadLocationException, InterruptedExcept Message testMessage = testHandler.new Message(rawMessage); testHandler.parseMessage(testMessage); StyledDocument testDoc = testChannel.getChannelTextPane().getStyledDocument(); - String testLine = testChannel.getLineFormatter().getLatestLine(testDoc); // "[0629] hello world!" + String testLine = testChannel.getLineFormatter().getLatestLine(); // "[0629] hello world!" while (testChannel.messageQueueWorking()) { @@ -108,7 +107,7 @@ public void nickIsNickStyleTest() throws BadLocationException, InterruptedExcept // Should be nickStyle because the user didn't mention testUser and is just a normal message assertEquals("nickStyle", - testChannel.getLineFormatter().getStyleAtPosition(testDoc, 11, testLine).getAttribute("name")); + testChannel.getLineFormatter().getStyleAtPosition(11, testLine).getAttribute("name")); } @Test(groups = {"Test #003"}, dependsOnMethods = {"backend.MessageHandlerTests.nickIsNickStyleTest"}) @@ -231,17 +230,19 @@ public void testChannelLineLimit() throws BadLocationException, InterruptedExcep // int serverLinesCount = // testServer.getChannelTextPane().getStyledDocument().getDefaultRootElement().getElementCount(); int channelLinesCount = - testChannel.getChannelTextPane().getStyledDocument().getDefaultRootElement().getElementCount(); + testChannel.getLineFormatter().getDocument().getDefaultRootElement().getElementCount(); - StyledDocument testDoc = testChannel.getChannelTextPane().getStyledDocument(); - String testLine = testChannel.getLineFormatter().getLatestLine(testDoc); // " line # 509" - assertTrue("Last line should line # 19 but it was" + testLine, testLine.endsWith("line # 19")); + + String firstLine = testChannel.getLineFormatter().getFirstLine(); + String lastLine = testChannel.getLineFormatter().getLatestLine(); // " line # 509" + + assertTrue("Last line should line # 19 but it was" + lastLine, lastLine.endsWith("line # 19")); assertTrue( "First line should be line # 10 but it was " - + testChannel.getChannelTextPane().getText().split(System.lineSeparator())[0], - testChannel.getChannelTextPane().getText().split(System.lineSeparator())[0].trim().endsWith("line # 10")); + + firstLine, + firstLine.endsWith("line # 10")); assertSame("Channel line count should equal the line limit", channelLinesLimit, channelLinesCount - 1); } @@ -269,8 +270,7 @@ public void testServerLineLimit() throws BadLocationException, InterruptedExcept int serverLinesCount = testServer.getChannelTextPane().getStyledDocument().getDefaultRootElement().getElementCount(); - StyledDocument testDoc = testServer.getChannelTextPane().getStyledDocument(); - String testLine = testServer.getLineFormatter().getLatestLine(testDoc); // " line # 19" + String testLine = testServer.getLineFormatter().getLatestLine(); // " line # 19" assertTrue("Last line should line # 19 but it was" + testLine, testLine.endsWith("line # 19")); @@ -306,11 +306,11 @@ public void urlInMessage() throws BadLocationException, InterruptedException TimeUnit.SECONDS.sleep(1); } - String testLine = testChannel.getLineFormatter().getLatestLine(testDoc); // "[0629] + String testLine = testChannel.getLineFormatter().getLatestLine(); // "[0629] // https://google.com" // Should be urlStyle, i.e a clickable link assertEquals("urlStyle", - testChannel.getLineFormatter().getStyleAtPosition(testDoc, 19, testLine).getAttribute("name")); + testChannel.getLineFormatter().getStyleAtPosition(19, testLine).getAttribute("name")); } @Test @@ -354,13 +354,13 @@ public void channelInMessage() throws BadLocationException, InterruptedException TimeUnit.SECONDS.sleep(1); } - String testLine = testChannel.getLineFormatter().getLatestLine(testDoc); + String testLine = testChannel.getLineFormatter().getLatestLine(); // Should be channel, i.e clickable name which allows you to join the channel assertEquals("channelStyle", - testChannel.getLineFormatter().getStyleAtPosition(testDoc, 33, testLine).getAttribute("name")); + testChannel.getLineFormatter().getStyleAtPosition(33, testLine).getAttribute("name")); assertEquals("urlStyle", - testChannel.getLineFormatter().getStyleAtPosition(testDoc, 58, testLine).getAttribute("name")); + testChannel.getLineFormatter().getStyleAtPosition(58, testLine).getAttribute("name")); assertEquals("channelStyle", - testChannel.getLineFormatter().getStyleAtPosition(testDoc, 110, testLine).getAttribute("name")); + testChannel.getLineFormatter().getStyleAtPosition(110, testLine).getAttribute("name")); } }