01: /*******************************************************************************
02: * Copyright (c) 2000, 2006 IBM Corporation and others.
03: * All rights reserved. This program and the accompanying materials
04: * are made available under the terms of the Eclipse Public License v1.0
05: * which accompanies this distribution, and is available at
06: * http://www.eclipse.org/legal/epl-v10.html
07: *
08: * Contributors:
09: * IBM Corporation - initial API and implementation
10: *******************************************************************************/package org.eclipse.jdt.ui.text.java;
11:
12: import java.util.Comparator;
13:
14: import org.eclipse.jface.text.contentassist.ICompletionProposal;
15: import org.eclipse.jface.text.templates.TemplateProposal;
16:
17: import org.eclipse.jdt.internal.ui.text.java.AbstractJavaCompletionProposal;
18:
19: /**
20: * Comparator for java completion proposals. Completion proposals can be sorted by relevance or
21: * alphabetically.
22: * <p>
23: * Note: this comparator imposes orderings that are inconsistent with equals.
24: * </p>
25: *
26: * @since 3.1
27: */
28: public final class CompletionProposalComparator implements Comparator {
29:
30: private boolean fOrderAlphabetically;
31:
32: /**
33: * Creates a comparator that sorts by relevance.
34: */
35: public CompletionProposalComparator() {
36: fOrderAlphabetically = false;
37: }
38:
39: /**
40: * Sets the sort order. Default is <code>false</code>, i.e. order by
41: * relevance.
42: *
43: * @param orderAlphabetically <code>true</code> to order alphabetically,
44: * <code>false</code> to order by relevance
45: */
46: public void setOrderAlphabetically(boolean orderAlphabetically) {
47: fOrderAlphabetically = orderAlphabetically;
48: }
49:
50: /*
51: * @see Comparator#compare(Object, Object)
52: */
53: public int compare(Object o1, Object o2) {
54: ICompletionProposal p1 = (ICompletionProposal) o1;
55: ICompletionProposal p2 = (ICompletionProposal) o2;
56:
57: if (!fOrderAlphabetically) {
58: int r1 = getRelevance(p1);
59: int r2 = getRelevance(p2);
60: int relevanceDif = r2 - r1;
61: if (relevanceDif != 0) {
62: return relevanceDif;
63: }
64: }
65: /*
66: * TODO the correct (but possibly much slower) sorting would use a
67: * collator.
68: */
69: // fix for bug 67468
70: return getSortKey(p1).compareToIgnoreCase(getSortKey(p2));
71: }
72:
73: private String getSortKey(ICompletionProposal p) {
74: if (p instanceof AbstractJavaCompletionProposal)
75: return ((AbstractJavaCompletionProposal) p).getSortString();
76: return p.getDisplayString();
77: }
78:
79: private int getRelevance(ICompletionProposal obj) {
80: if (obj instanceof IJavaCompletionProposal) {
81: IJavaCompletionProposal jcp = (IJavaCompletionProposal) obj;
82: return jcp.getRelevance();
83: } else if (obj instanceof TemplateProposal) {
84: TemplateProposal tp = (TemplateProposal) obj;
85: return tp.getRelevance();
86: }
87: // catch all
88: return 0;
89: }
90:
91: }
|