1package autotest.common.spreadsheet; 2 3import autotest.common.Utils; 4import autotest.common.spreadsheet.Spreadsheet.CellInfo; 5 6import java.util.ArrayList; 7import java.util.Collection; 8import java.util.HashSet; 9import java.util.List; 10 11// TODO: hopefully some of this could be combined with autotest.common.table.SelectionManager using 12// generics 13// TODO: get rid of header selection 14public class SpreadsheetSelectionManager { 15 private Spreadsheet spreadsheet; 16 private Collection<CellInfo> selectedCells = new HashSet<CellInfo>(); 17 private SpreadsheetSelectionListener listener; 18 19 public static interface SpreadsheetSelectionListener { 20 public void onCellsSelected(List<CellInfo> cells); 21 public void onCellsDeselected(List<CellInfo> cells); 22 } 23 24 public SpreadsheetSelectionManager(Spreadsheet spreadsheet, 25 SpreadsheetSelectionListener listener) { 26 this.spreadsheet = spreadsheet; 27 this.listener = listener; 28 } 29 30 public void toggleSelected(CellInfo cell) { 31 if (selectedCells.contains(cell)) { 32 deselectCell(cell); 33 notifyDeselected(Utils.wrapObjectWithList(cell)); 34 } else { 35 selectCell(cell); 36 notifySelected(Utils.wrapObjectWithList(cell)); 37 } 38 } 39 40 private void selectCell(CellInfo cell) { 41 selectedCells.add(cell); 42 spreadsheet.setHighlighted(cell, true); 43 } 44 45 private void deselectCell(CellInfo cell) { 46 selectedCells.remove(cell); 47 spreadsheet.setHighlighted(cell, false); 48 } 49 50 public List<CellInfo> getSelectedCells() { 51 return new ArrayList<CellInfo>(selectedCells); 52 } 53 54 public boolean isEmpty() { 55 return selectedCells.isEmpty(); 56 } 57 58 public void clearSelection() { 59 List<CellInfo> cells = getSelectedCells(); 60 for (CellInfo cell : cells) { 61 deselectCell(cell); 62 } 63 notifyDeselected(cells); 64 } 65 66 public void selectAll() { 67 List<CellInfo> selectedCells = new ArrayList<CellInfo>(); 68 for (CellInfo[] row : spreadsheet.dataCells) { 69 for (CellInfo cell : row) { 70 if (cell == null || cell.isEmpty()) { 71 continue; 72 } 73 selectCell(cell); 74 selectedCells.add(cell); 75 } 76 } 77 notifySelected(selectedCells); 78 } 79 80 private void notifyDeselected(List<CellInfo> cells) { 81 if (listener != null) { 82 listener.onCellsDeselected(cells); 83 } 84 } 85 86 private void notifySelected(List<CellInfo> selectedCells) { 87 if (listener != null) { 88 listener.onCellsSelected(selectedCells); 89 } 90 } 91} 92