1 | package org.expeditee.agents;
|
---|
2 |
|
---|
3 | import java.awt.Point;
|
---|
4 | import java.util.ArrayList;
|
---|
5 | import java.util.Collection;
|
---|
6 | import java.util.Collections;
|
---|
7 | import java.util.Comparator;
|
---|
8 |
|
---|
9 | import org.expeditee.gui.Frame;
|
---|
10 | import org.expeditee.gui.FrameGraphics;
|
---|
11 | import org.expeditee.gui.FrameUtils;
|
---|
12 | import org.expeditee.items.Text;
|
---|
13 |
|
---|
14 | public class Sort extends DefaultAgent {
|
---|
15 |
|
---|
16 | /**
|
---|
17 | * Sorts all the text Items on the given Frame alphabetically. The Items are
|
---|
18 | * then rearranged to reflect this ordering.
|
---|
19 | */
|
---|
20 | public Frame process(Frame start) {
|
---|
21 | // Check the position of the cursor and only format stuff inside the
|
---|
22 | // same box as the cursor
|
---|
23 | Collection<Text> itemsToSort = FrameUtils.getCurrentTextItems();
|
---|
24 | if (itemsToSort.size() < 1) {
|
---|
25 | itemsToSort = start.getBodyTextItems(false);
|
---|
26 | }
|
---|
27 |
|
---|
28 | ArrayList<Text> textItems = new ArrayList<Text>();
|
---|
29 | textItems.addAll(itemsToSort);
|
---|
30 |
|
---|
31 | // copy current positions of items
|
---|
32 | ArrayList<Point> positions = new ArrayList<Point>(textItems.size());
|
---|
33 |
|
---|
34 | for (int i = 0; i < textItems.size(); i++)
|
---|
35 | positions.add(i, textItems.get(i).getPosition());
|
---|
36 |
|
---|
37 | // Sort text items by their strings
|
---|
38 | Collections.sort(textItems, new Comparator<Text>() {
|
---|
39 | public int compare(Text a, Text b) {
|
---|
40 | return String.CASE_INSENSITIVE_ORDER.compare(a.getText(), b
|
---|
41 | .getText());
|
---|
42 | }
|
---|
43 | });
|
---|
44 |
|
---|
45 | // update positions based on new order
|
---|
46 | for (int i = 0; i < positions.size(); i++)
|
---|
47 | textItems.get(i)
|
---|
48 | .setPosition(positions.get(i).x, positions.get(i).y);
|
---|
49 |
|
---|
50 | // items will need to be resorted after this
|
---|
51 | start.setResort(true);
|
---|
52 | FrameGraphics.Repaint();
|
---|
53 |
|
---|
54 | return null;
|
---|
55 | }
|
---|
56 |
|
---|
57 | @Override
|
---|
58 | protected void finalise(Frame start) {
|
---|
59 | message("Sorting Complete.");
|
---|
60 | }
|
---|
61 | } |
---|