package org.expeditee.agents; import org.expeditee.gui.Frame; import org.expeditee.gui.FrameCreator; import org.expeditee.gui.FrameGraphics; import org.expeditee.gui.FrameIO; import org.expeditee.io.Conversion; import org.expeditee.items.Item; import org.expeditee.items.Text; public abstract class SearchAgent extends DefaultAgent { protected FrameCreator _results; protected String _pattern; protected String _replacementString; protected String _startName; @Override public boolean initialise(Frame frame, Item item) { String pattern = item.getText(); String resultFrameset = null; //TODO use a results frame specified on the profile frame if (item.getLink() == null) { resultFrameset = frame.getFramesetName(); } else { resultFrameset = Conversion.getFramesetName(item.getAbsoluteLink(), false); } return initialise(frame, item, frame.getFramesetName(), resultFrameset, null, pattern); } public boolean initialise(Frame frame, Item item, String startName, String resultsFrameset, String replacementString, String pattern) { _pattern = pattern; _replacementString = replacementString; _startName = startName; // Create a frame to put the results on with the search query // and type as the title String title = this.getClass().getSimpleName() + " [" + startName + "] [" + pattern + "]"; _results = new FrameCreator(resultsFrameset, null, title, false); // Set the frame to be displayed after running the agent _end = _results.getFirstFrame(); return super.initialise(frame, item); } public String getResultsFrameName() { return _results.getName(); } public static boolean searchItem(Text itemToSearch, String pattern, String replacementString) { String searchStr = itemToSearch.getText().toLowerCase(); String[] result = searchStr.split(pattern.toLowerCase(), 2); boolean bFound = result.length > 1; // If it is a find and replace... then replace with the replacement // string if (bFound && replacementString != null) { itemToSearch.setText(searchStr.replaceAll(pattern, replacementString)); } return bFound; } public static boolean searchFrame(FrameCreator results, String frameName, String pattern, String replacementString) { int oldMode = FrameGraphics.getMode(); FrameGraphics.setMode(FrameGraphics.MODE_XRAY, false); Frame frameToSearch = FrameIO.LoadFrame(frameName); FrameGraphics.setMode(oldMode, false); if (frameToSearch == null) return false; for (Text itemToSearch : frameToSearch.getTextItems()) { // Search for the item and add it to the results page if // it is found if (searchItem(itemToSearch, pattern, replacementString)) { // Add a linked item to the results frame results.addText(frameName, null, frameName, null, false); } } FrameGraphics.requestRefresh(true); FrameIO.SaveFrame(frameToSearch, false); return true; } }