/**
* Sort.java
* Copyright (C) 2010 New Zealand Digital Library, http://expeditee.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
package org.expeditee.agents;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import org.expeditee.core.Point;
import org.expeditee.gui.DisplayController;
import org.expeditee.gui.Frame;
import org.expeditee.gui.FrameUtils;
import org.expeditee.items.Text;
public class Sort extends DefaultAgent {
/**
* Sorts all the text Items on the given Frame alphabetically. The Items are
* then rearranged to reflect this ordering.
*/
public Frame process(Frame start) {
// Check the position of the cursor and only format stuff inside the
// same box as the cursor
Collection itemsToSort = FrameUtils.getCurrentTextItems();
if (itemsToSort.size() < 1) {
itemsToSort = start.getBodyTextItems(false);
}
ArrayList textItems = new ArrayList();
textItems.addAll(itemsToSort);
// copy current positions of items
ArrayList positions = new ArrayList(textItems.size());
for (int i = 0; i < textItems.size(); i++)
positions.add(i, textItems.get(i).getPosition());
// Sort text items by their strings
Collections.sort(textItems, new Comparator() {
public int compare(Text a, Text b) {
return String.CASE_INSENSITIVE_ORDER.compare(a.getText(), b
.getText());
}
});
// update positions based on new order
for (int i = 0; i < positions.size(); i++)
textItems.get(i)
.setPosition(positions.get(i).getX(), positions.get(i).getY());
// items will need to be resorted after this
start.invalidateSorted();
DisplayController.requestRefresh(true);
return null;
}
@Override
protected void finalise(Frame start) {
message("Sorting Complete.");
}
}