Skip to content

Commit

Permalink
Introduces a stylesHash in order to not waste time updating lines tha…
Browse files Browse the repository at this point in the history
…t already match the required styles.
  • Loading branch information
matty-r committed Mar 2, 2024
1 parent 5b051f3 commit a6755c2
Show file tree
Hide file tree
Showing 8 changed files with 190 additions and 32 deletions.
4 changes: 2 additions & 2 deletions src/urChatBasic/base/IRCChannelBase.java
Original file line number Diff line number Diff line change
Expand Up @@ -188,14 +188,14 @@ private void initChannel()

fontDialog = new FontDialog(channelName, gui.getStyle(), channelPrefs);

lineFormatter = new LineFormatter(getFontPanel().getStyle(), channelTextArea , getServer(), channelPrefs);
lineFormatter = new LineFormatter(getFontPanel().getStyle(), channelTextArea , channelScroll, getServer(), channelPrefs);
} else
{
markerName = channelName;
setSettingsPath(URProfilesUtil.getActiveFavouritesPath().node(channelName));
fontDialog = new FontDialog(channelName, gui.getStyle(), channelPrefs);

lineFormatter = new LineFormatter(getFontPanel().getStyle() , channelTextArea, null, channelPrefs);
lineFormatter = new LineFormatter(getFontPanel().getStyle() , channelTextArea, channelScroll, null, channelPrefs);
}

// Add Logging Marker
Expand Down
118 changes: 102 additions & 16 deletions src/urChatBasic/frontend/LineFormatter.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

import java.awt.Color;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.net.URL;
import java.time.Duration;
Expand All @@ -22,7 +24,9 @@
import javax.swing.AbstractAction;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.JViewport;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.text.AttributeSet;
Expand Down Expand Up @@ -56,6 +60,7 @@ public class LineFormatter
// private URStyle mediumStyle;
// private URStyle lowStyle;
private JTextPane docOwner;
private JScrollPane docScroller;
public StyledDocument doc;
// public URStyle myStyle;
private Map<String, URStyle> formatterStyles = new HashMap<>();
Expand All @@ -64,12 +69,13 @@ public class LineFormatter
private AtomicLong updateStylesTime = new AtomicLong(0);
public AtomicBoolean updateStylesInProgress = new AtomicBoolean(false);

public LineFormatter(URStyle baseStyle, JTextPane docOwner ,final IRCServerBase server, Preferences settingsPath)
public LineFormatter(URStyle baseStyle, JTextPane docOwner ,JScrollPane docScroller, final IRCServerBase server, Preferences settingsPath)
{
// TODO: Need to load attributes from formatterPrefs
this.settingsPath = settingsPath;

this.docOwner = docOwner;
this.docScroller = docScroller;

// this.docOwner.setBackground(UIManager.getColor(Constants.DEFAULT_BACKGROUND_STRING));
doc = this.docOwner.getStyledDocument();
Expand Down Expand Up @@ -144,6 +150,42 @@ public void initStyles (URStyle baseStyle)
}
}

public int getStylesHash ()
{
int formatterStylesHash = formatterStyles.hashCode();
int nickFormatHash = String.join("", DriverGUI.gui.getNickFormatString("nick")).hashCode();
int timeStampHash = DriverGUI.gui.getTimeStampString(new Date(0L)).hashCode();


return formatterStylesHash + nickFormatHash + timeStampHash;
}

class ViewPortRange {
private int start;
private int end;

public ViewPortRange ()
{
JViewport viewport = docScroller.getViewport();
Point startPoint = viewport.getViewPosition();
Dimension size = viewport.getExtentSize();
Point endPoint = new Point(startPoint.x + size.width, startPoint.y + size.height);

start = docOwner.viewToModel2D(startPoint);
end = docOwner.viewToModel2D(endPoint);
}

public int getStart ()
{
return start;
}

public int getEnd ()
{
return end;
}
}

public URStyle dateStyle(URStyle baseStyle, Date date, boolean load)
{
// TODO: date style can only be lowStyle or defaultStyle
Expand Down Expand Up @@ -539,8 +581,14 @@ public URStyle getStyle(String styleName, boolean load)
*/
public void updateStyles (URStyle newBaseStyle)
{
int lastStylesHash = getStylesHash();

updateStylesInProgress.set(true);

initStyles(newBaseStyle);

int currentStylesHash = getStylesHash();

if (doc.getLength() > 0)
{
SwingUtilities.invokeLater(new Runnable()
Expand All @@ -549,13 +597,12 @@ public void run ()
{
try
{
if(!updateStylesInProgress.get())
if (currentStylesHash != lastStylesHash)
{
Constants.LOGGER.info( "Updating styles for " + settingsPath.name());
updateStylesTime.set(Instant.now().getEpochSecond());
updateDocStyles(0);
updateDocStyles(0, getStylesHash());
} else {
Constants.LOGGER.info( "Update already in progress.");
Constants.LOGGER.debug("NOT updating styles for " + settingsPath.name()+". Styles hash matches.");
}
} catch (BadLocationException e)
{
Expand All @@ -568,9 +615,9 @@ public void run ()
}
}

private void updateDocStyles (int currentPosition) throws BadLocationException
private void updateDocStyles (int currentPosition, int updateHash) throws BadLocationException
{
updateStylesInProgress.set(true);
updateStylesTime.set(Instant.now().getEpochSecond());
Element root = doc.getDefaultRootElement();
int lineCount = root.getElementCount();
int lineIndex = 0;
Expand All @@ -593,6 +640,10 @@ private void updateDocStyles (int currentPosition) throws BadLocationException
// Has style to update
if (currentStyle != null && currentStyle.getAttributeCount() > 0)
{
// this line has already been updated
if(currentStyle.getAttribute("stylesHash") != null && currentStyle.getAttribute("stylesHash").equals(updateHash))
break;

int styleLength = Integer.parseInt(currentStyle.getAttribute("styleLength").toString());
String styleString = doc.getText(currentPosition, styleLength);

Expand All @@ -610,8 +661,10 @@ private void updateDocStyles (int currentPosition) throws BadLocationException
doc.remove(currentPosition, styleLength);
currentStyle = dateStyle(currentStyle, lineDate, false);
// Inserts the new timestamp, and updates the formatting
currentStyle.addAttribute("stylesHash", getStylesHash());
insertString(newTimeStamp, currentStyle, currentPosition);
} else {
currentStyle.addAttribute("stylesHash", getStylesHash());
setDocAttributes(currentPosition, styleLength, currentStyle);
}
} else
Expand All @@ -626,6 +679,7 @@ private void updateDocStyles (int currentPosition) throws BadLocationException

currentStyle = dateStyle(currentStyle, lineDate, false);
// Inserts the new string, and updates the formatting
currentStyle.addAttribute("stylesHash", getStylesHash());
insertString(newTimeStamp, currentStyle, currentPosition);
}
}
Expand Down Expand Up @@ -773,6 +827,33 @@ public String getLatestLine() throws BadLocationException
return finalLine;
}

public String getLine(int lineNumber) throws BadLocationException
{
Element root = doc.getDefaultRootElement();
int lines = root.getElementCount();

String finalLine = "";

while (finalLine.isEmpty())
{

if (lines < 0)
break;

Element line = root.getElement(lineNumber);

if (null == line)
continue;

int start = line.getStartOffset();
int end = line.getEndOffset();
String text = doc.getText(start, end - start);
finalLine = text.trim();
}

return finalLine;
}

// New method to get line at position
public String getLineAtPosition(int position) throws BadLocationException {
Element root = doc.getDefaultRootElement();
Expand All @@ -798,29 +879,32 @@ public int getLineCount ()
return root.getElementCount();
}

private int getLinePosition(String targetLine) throws BadLocationException
{
private int getLinePosition(String targetLine) throws BadLocationException {
Element root = doc.getDefaultRootElement();
int lines = root.getElementCount();

for (int i = 0; i < lines; i++)
{
// Create a regex pattern to match the target line
Pattern pattern = Pattern.compile(".*"+Pattern.quote(targetLine.trim())+"$");

for (int i = 0; i < lines; i++) {
Element line = root.getElement(i);

if (null == line)
if (line == null)
continue;

int start = line.getStartOffset();
int end = line.getEndOffset();
String text = doc.getText(start, end - start);

if (text.trim().equals(targetLine.trim()))
{
Matcher matcher = pattern.matcher(text.trim());

// If the pattern matches, return the start offset of the line
if (matcher.find()) {
return start;
}
}

return 0;
return -1; // Return -1 if the target line is not found
}

public URStyle getStyleAtPosition(int position, String relativeLine)
Expand Down Expand Up @@ -967,7 +1051,9 @@ public void appendMessage(Optional<Date> lineDate, IRCUser fromUser, String from
{
// add the date to the end of the string to preserve the timestamp of the line
// when updating styles
insertPosition = addString(DriverGUI.gui.getTimeStampString(timeLine.get()) + " ", dateStyle(timePositionStyle, lineDate.get(), false), Optional.of(insertPosition));
URStyle lineDateStyle = dateStyle(timePositionStyle, lineDate.get(), false);
lineDateStyle.addAttribute("stylesHash", getStylesHash());
insertPosition = addString(DriverGUI.gui.getTimeStampString(timeLine.get()) + " ", lineDateStyle, Optional.of(insertPosition));
}

linePositionStyle.addAttribute("type", "nickPart0");
Expand Down
2 changes: 1 addition & 1 deletion src/urChatBasic/frontend/UserGUI.java
Original file line number Diff line number Diff line change
Expand Up @@ -334,7 +334,7 @@ public void updatePreviewTextArea ()
// previewTextArea.setFont(clientFontPanel.getFont());
if (previewLineFormatter == null)
{
previewLineFormatter = new LineFormatter(clientFontPanel.getStyle(), previewTextArea, null, URProfilesUtil.getActiveProfilePath());
previewLineFormatter = new LineFormatter(clientFontPanel.getStyle(), previewTextArea, previewTextScroll, null, URProfilesUtil.getActiveProfilePath());

URProfilesUtil.addListener(EventType.CHANGE, e -> {
previewLineFormatter.setSettingsPath(URProfilesUtil.getActiveProfilePath());
Expand Down
1 change: 1 addition & 0 deletions src/urChatBasic/frontend/panels/ConnectionPanel.java
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,7 @@ public String getChannelName ()
public void createPopUp ()
{
myMenu = new FavouritesPopUp();
myMenu.setUI(new JPopupMenu().getUI());
}

private class FavouritesPopUp extends JPopupMenu
Expand Down
30 changes: 23 additions & 7 deletions tests/frontend/AppearanceTests.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import javax.swing.text.BadLocationException;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
Expand All @@ -34,7 +35,7 @@ public class AppearanceTests
IRCServer testServer;
TestDriverGUI testDriver;
UserGUI testGUI;
final static int MAX_CHANNEL_NAMES = 10;
final static int MAX_CHANNEL_NAMES = 1;
final static String CHANNEL_PREFIX = "#someChannel";
final List<String> PUB_CHANNEL_NAMES = new ArrayList<>();
IRCUser testUser;
Expand Down Expand Up @@ -100,13 +101,21 @@ public void changeDefaultFontAndSizeTest () throws BadLocationException, Interru
{
IRCChannel pubChannel = testServer.getCreatedChannel(pubChannelName);
log("Have joined " + pubChannelName + " successfully?", true);
String welcomeMessage = pubChannel.getLineFormatter().getLineAtPosition(13).split("] ")[1].trim();
String welcomeMessage = String.join("",testGUI.getNickFormatString("someuser")) + " Welcome to " + pubChannelName;
assertEquals("<someuser> Welcome to " + pubChannelName, welcomeMessage);

log("Check current style in the channel is correct.", true);
log("Wait for styles to update correctly..", true);
TestDriverGUI.waitForEverything(testGUI);
URStyle channelStyle = pubChannel.getLineFormatter().getStyleAtPosition(22, welcomeMessage);

URStyle channelStyle = null;

while (channelStyle == null || !channelStyle.equals(guiStyle))
{
TimeUnit.MILLISECONDS.sleep(10);
channelStyle = pubChannel.getLineFormatter().getStyleAtPosition(22, welcomeMessage);
}

log("Check current style in the channel is correct.", true);
assertTrue(guiStyle.equals(channelStyle));
}

Expand All @@ -126,10 +135,17 @@ public void changeDefaultFontAndSizeTest () throws BadLocationException, Interru
TestDriverGUI.waitForEverything(testGUI);

IRCChannel pubChannel = testServer.getCreatedChannel(pubChannelName);
String welcomeMessage = pubChannel.getLineFormatter().getLineAtPosition(13).split("] ")[1].trim();
log("Check current style has updated.", true);
String welcomeMessage = pubChannel.getLineFormatter().getLineAtPosition(22).split("] ")[1].trim();
log("Wait for current style has updated.", true);

URStyle channelStyle = pubChannel.getLineFormatter().getStyleAtPosition(22, welcomeMessage);
URStyle channelStyle = null;

while (channelStyle == null || !channelStyle.equals(newStyle))
{
TimeUnit.MILLISECONDS.sleep(10);
channelStyle = pubChannel.getLineFormatter().getStyleAtPosition(22, welcomeMessage);
channelStyle.removeAttribute("name");
}

log("Test Style: " + guiStyle, true);
log("Channel Style: " + channelStyle, true);
Expand Down
10 changes: 9 additions & 1 deletion tests/frontend/LAFTests.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import static org.testng.AssertJUnit.*;
import java.awt.Color;
import java.util.concurrent.TimeUnit;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.text.StyleConstants;
Expand Down Expand Up @@ -69,7 +70,14 @@ public void changingLAFUpdatesPreviewStyle() throws Exception

TestDriverGUI.waitForEverything(gui);

Color newBackgroundColor = (Color) gui.previewLineFormatter.getStyleAtPosition(0, "urChat has loaded - this is an Event").getAttribute(StyleConstants.Background);
Color newBackgroundColor = null;

while (newBackgroundColor == null || !newBackgroundColor.equals(UIManager.getColor(Constants.DEFAULT_BACKGROUND_STRING)))
{
TimeUnit.MILLISECONDS.sleep(10);
newBackgroundColor = (Color) gui.previewLineFormatter.getStyleAtPosition(0, "urChat has loaded - this is an Event").getAttribute(StyleConstants.Background);
}

Color lineFormatterBackground = gui.previewTextArea.getBackground();


Expand Down
2 changes: 1 addition & 1 deletion tests/frontend/LineFormatterTests.java
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ public void run()

while(!canContinue.get())
{
TimeUnit.SECONDS.sleep(1);
TimeUnit.MILLISECONDS.sleep(10);
}

// Right-Click mouse event at the x-y coords of the caret in the text pane
Expand Down
Loading

0 comments on commit a6755c2

Please sign in to comment.