0d30cf1a3fb2a2480407af799a6056dc2293fbe0
[phpeclipse.git] / net.sourceforge.phpeclipse.ui / src / net / sourceforge / phpdt / internal / ui / filters / CustomFiltersDialog.java
1 /*******************************************************************************
2  * Copyright (c) 2000, 2004 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Common Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/cpl-v10.html
7  *
8  * Contributors:
9  *     IBM Corporation - initial API and implementation
10  *******************************************************************************/
11 package net.sourceforge.phpdt.internal.ui.filters;
12
13 import java.util.ArrayList;
14 import java.util.Arrays;
15 import java.util.HashSet;
16 import java.util.Iterator;
17 import java.util.List;
18 import java.util.Set;
19 import java.util.Stack;
20 import java.util.StringTokenizer;
21
22 import net.sourceforge.phpdt.internal.ui.IJavaHelpContextIds;
23 import net.sourceforge.phpdt.internal.ui.util.SWTUtil;
24
25 import org.eclipse.jface.dialogs.IDialogConstants;
26 //incastrix
27 //import org.eclipse.jface.text.Assert;
28 import org.eclipse.core.runtime.Assert;
29 import org.eclipse.jface.viewers.ArrayContentProvider;
30 import org.eclipse.jface.viewers.CheckStateChangedEvent;
31 import org.eclipse.jface.viewers.CheckboxTableViewer;
32 import org.eclipse.jface.viewers.ICheckStateListener;
33 import org.eclipse.jface.viewers.ILabelProvider;
34 import org.eclipse.jface.viewers.ISelection;
35 import org.eclipse.jface.viewers.ISelectionChangedListener;
36 import org.eclipse.jface.viewers.IStructuredSelection;
37 import org.eclipse.jface.viewers.LabelProvider;
38 import org.eclipse.jface.viewers.SelectionChangedEvent;
39 import org.eclipse.swt.SWT;
40 import org.eclipse.swt.events.SelectionAdapter;
41 import org.eclipse.swt.events.SelectionEvent;
42 import org.eclipse.swt.events.SelectionListener;
43 import org.eclipse.swt.graphics.Image;
44 import org.eclipse.swt.layout.GridData;
45 import org.eclipse.swt.layout.GridLayout;
46 import org.eclipse.swt.widgets.Button;
47 import org.eclipse.swt.widgets.Composite;
48 import org.eclipse.swt.widgets.Control;
49 import org.eclipse.swt.widgets.Label;
50 import org.eclipse.swt.widgets.Shell;
51 import org.eclipse.swt.widgets.Text;
52 import org.eclipse.ui.PlatformUI;
53 import org.eclipse.ui.dialogs.SelectionDialog;
54
55 public class CustomFiltersDialog extends SelectionDialog {
56
57         private static final String SEPARATOR = ","; //$NON-NLS-1$
58
59         private String fViewId;
60
61         private boolean fEnablePatterns;
62
63         private String[] fPatterns;
64
65         private String[] fEnabledFilterIds;
66
67         private FilterDescriptor[] fBuiltInFilters;
68
69         private CheckboxTableViewer fCheckBoxList;
70
71         private Button fEnableUserDefinedPatterns;
72
73         private Text fUserDefinedPatterns;
74
75         private Stack fFilterDescriptorChangeHistory;
76
77         /**
78          * Creates a dialog to customize Java element filters.
79          * 
80          * @param shell
81          *            the parent shell
82          * @param viewId
83          *            the id of the view
84          * @param enablePatterns
85          *            <code>true</code> if pattern filters are enabled
86          * @param patterns
87          *            the filter patterns
88          * @param enabledFilterIds
89          *            the Ids of the enabled filters
90          */
91         public CustomFiltersDialog(Shell shell, String viewId,
92                         boolean enablePatterns, String[] patterns, String[] enabledFilterIds) {
93
94                 super(shell);
95                 Assert.isNotNull(viewId);
96                 Assert.isNotNull(patterns);
97                 Assert.isNotNull(enabledFilterIds);
98
99                 fViewId = viewId;
100                 fPatterns = patterns;
101                 fEnablePatterns = enablePatterns;
102                 fEnabledFilterIds = enabledFilterIds;
103
104                 fBuiltInFilters = FilterDescriptor.getFilterDescriptors(fViewId);
105                 fFilterDescriptorChangeHistory = new Stack();
106                 setShellStyle(getShellStyle() | SWT.RESIZE);
107         }
108
109         protected void configureShell(Shell shell) {
110                 setTitle(FilterMessages.getString("CustomFiltersDialog.title")); //$NON-NLS-1$
111                 setMessage(FilterMessages
112                                 .getString("CustomFiltersDialog.filterList.label")); //$NON-NLS-1$
113                 super.configureShell(shell);
114                 PlatformUI.getWorkbench().getHelpSystem().setHelp(shell,
115                                 IJavaHelpContextIds.CUSTOM_FILTERS_DIALOG);
116         }
117
118         /**
119          * Overrides method in Dialog
120          * 
121          * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(Composite)
122          */
123         protected Control createDialogArea(Composite parent) {
124                 initializeDialogUnits(parent);
125                 // create a composite with standard margins and spacing
126                 Composite composite = new Composite(parent, SWT.NONE);
127                 GridLayout layout = new GridLayout();
128                 layout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
129                 layout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
130                 layout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
131                 layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
132                 composite.setLayout(layout);
133                 composite.setLayoutData(new GridData(GridData.FILL_BOTH));
134                 composite.setFont(parent.getFont());
135                 Composite group = composite;
136
137                 // Checkbox
138                 fEnableUserDefinedPatterns = new Button(group, SWT.CHECK);
139                 fEnableUserDefinedPatterns.setFocus();
140                 fEnableUserDefinedPatterns.setText(FilterMessages
141                                 .getString("CustomFiltersDialog.enableUserDefinedPattern")); //$NON-NLS-1$
142
143                 // Pattern field
144                 fUserDefinedPatterns = new Text(group, SWT.SINGLE | SWT.BORDER);
145                 GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL
146                                 | GridData.GRAB_HORIZONTAL);
147                 data.widthHint = convertWidthInCharsToPixels(59);
148                 fUserDefinedPatterns.setLayoutData(data);
149                 String patterns = convertToString(fPatterns, SEPARATOR);
150                 fUserDefinedPatterns.setText(patterns);
151
152                 // Info text
153                 final Label info = new Label(group, SWT.LEFT);
154                 info.setText(FilterMessages
155                                 .getString("CustomFiltersDialog.patternInfo")); //$NON-NLS-1$
156
157                 // Enabling / disabling of pattern group
158                 fEnableUserDefinedPatterns.setSelection(fEnablePatterns);
159                 fUserDefinedPatterns.setEnabled(fEnablePatterns);
160                 info.setEnabled(fEnablePatterns);
161                 fEnableUserDefinedPatterns.addSelectionListener(new SelectionAdapter() {
162                         public void widgetSelected(SelectionEvent e) {
163                                 boolean state = fEnableUserDefinedPatterns.getSelection();
164                                 fUserDefinedPatterns.setEnabled(state);
165                                 info.setEnabled(fEnableUserDefinedPatterns.getSelection());
166                                 if (state)
167                                         fUserDefinedPatterns.setFocus();
168                         }
169                 });
170
171                 // Filters provided by extension point
172                 if (fBuiltInFilters.length > 0)
173                         createCheckBoxList(group);
174
175                 applyDialogFont(parent);
176                 return parent;
177         }
178
179         private void createCheckBoxList(Composite parent) {
180                 // Filler
181                 new Label(parent, SWT.NONE);
182
183                 Label info = new Label(parent, SWT.LEFT);
184                 info.setText(FilterMessages
185                                 .getString("CustomFiltersDialog.filterList.label")); //$NON-NLS-1$
186
187                 fCheckBoxList = CheckboxTableViewer.newCheckList(parent, SWT.BORDER);
188                 GridData data = new GridData(GridData.FILL_BOTH);
189                 data.heightHint = fCheckBoxList.getTable().getItemHeight() * 10;
190                 fCheckBoxList.getTable().setLayoutData(data);
191
192                 fCheckBoxList.setLabelProvider(createLabelPrivder());
193                 fCheckBoxList.setContentProvider(new ArrayContentProvider());
194
195                 fCheckBoxList.setInput(fBuiltInFilters);
196                 setInitialSelections(getEnabledFilterDescriptors());
197
198                 List initialSelection = getInitialElementSelections();
199                 if (initialSelection != null && !initialSelection.isEmpty())
200                         checkInitialSelections();
201
202                 // Description
203                 info = new Label(parent, SWT.LEFT);
204                 info.setText(FilterMessages
205                                 .getString("CustomFiltersDialog.description.label")); //$NON-NLS-1$
206                 final Text description = new Text(parent, SWT.LEFT | SWT.WRAP
207                                 | SWT.MULTI | SWT.READ_ONLY | SWT.BORDER | SWT.V_SCROLL);
208                 data = new GridData(GridData.FILL_HORIZONTAL);
209                 data.heightHint = convertHeightInCharsToPixels(3);
210                 description.setLayoutData(data);
211                 fCheckBoxList
212                                 .addSelectionChangedListener(new ISelectionChangedListener() {
213                                         public void selectionChanged(SelectionChangedEvent event) {
214                                                 ISelection selection = event.getSelection();
215                                                 if (selection instanceof IStructuredSelection) {
216                                                         Object selectedElement = ((IStructuredSelection) selection)
217                                                                         .getFirstElement();
218                                                         if (selectedElement instanceof FilterDescriptor)
219                                                                 description
220                                                                                 .setText(((FilterDescriptor) selectedElement)
221                                                                                                 .getDescription());
222                                                 }
223                                         }
224                                 });
225                 fCheckBoxList.addCheckStateListener(new ICheckStateListener() {
226                         /*
227                          * @see org.eclipse.jface.viewers.ICheckStateListener#checkStateChanged(org.eclipse.jface.viewers.CheckStateChangedEvent)
228                          */
229                         public void checkStateChanged(CheckStateChangedEvent event) {
230                                 Object element = event.getElement();
231                                 if (element instanceof FilterDescriptor) {
232                                         // renew if already touched
233                                         if (fFilterDescriptorChangeHistory.contains(element))
234                                                 fFilterDescriptorChangeHistory.remove(element);
235                                         fFilterDescriptorChangeHistory.push(element);
236                                 }
237                         }
238                 });
239
240                 addSelectionButtons(parent);
241         }
242
243         private void addSelectionButtons(Composite composite) {
244                 Composite buttonComposite = new Composite(composite, SWT.RIGHT);
245                 GridLayout layout = new GridLayout();
246                 layout.numColumns = 2;
247                 buttonComposite.setLayout(layout);
248                 GridData data = new GridData(GridData.HORIZONTAL_ALIGN_END
249                                 | GridData.GRAB_HORIZONTAL);
250                 data.grabExcessHorizontalSpace = true;
251                 composite.setData(data);
252
253                 // Select All button
254                 String label = FilterMessages
255                                 .getString("CustomFiltersDialog.SelectAllButton.label"); //$NON-NLS-1$
256                 Button selectButton = createButton(buttonComposite,
257                                 IDialogConstants.SELECT_ALL_ID, label, false);
258                 SWTUtil.setButtonDimensionHint(selectButton);
259                 SelectionListener listener = new SelectionAdapter() {
260                         public void widgetSelected(SelectionEvent e) {
261                                 fCheckBoxList.setAllChecked(true);
262                                 fFilterDescriptorChangeHistory.clear();
263                                 for (int i = 0; i < fBuiltInFilters.length; i++)
264                                         fFilterDescriptorChangeHistory.push(fBuiltInFilters[i]);
265                         }
266                 };
267                 selectButton.addSelectionListener(listener);
268
269                 // De-select All button
270                 label = FilterMessages
271                                 .getString("CustomFiltersDialog.DeselectAllButton.label"); //$NON-NLS-1$
272                 Button deselectButton = createButton(buttonComposite,
273                                 IDialogConstants.DESELECT_ALL_ID, label, false);
274                 SWTUtil.setButtonDimensionHint(deselectButton);
275                 listener = new SelectionAdapter() {
276                         public void widgetSelected(SelectionEvent e) {
277                                 fCheckBoxList.setAllChecked(false);
278                                 fFilterDescriptorChangeHistory.clear();
279                                 for (int i = 0; i < fBuiltInFilters.length; i++)
280                                         fFilterDescriptorChangeHistory.push(fBuiltInFilters[i]);
281                         }
282                 };
283                 deselectButton.addSelectionListener(listener);
284         }
285
286         private void checkInitialSelections() {
287                 Iterator itemsToCheck = getInitialElementSelections().iterator();
288                 while (itemsToCheck.hasNext())
289                         fCheckBoxList.setChecked(itemsToCheck.next(), true);
290         }
291
292         protected void okPressed() {
293                 if (fBuiltInFilters != null) {
294                         ArrayList result = new ArrayList();
295                         for (int i = 0; i < fBuiltInFilters.length; ++i) {
296                                 if (fCheckBoxList.getChecked(fBuiltInFilters[i]))
297                                         result.add(fBuiltInFilters[i]);
298                         }
299                         setResult(result);
300                 }
301                 super.okPressed();
302         }
303
304         private ILabelProvider createLabelPrivder() {
305                 return new LabelProvider() {
306                         public Image getImage(Object element) {
307                                 return null;
308                         }
309
310                         public String getText(Object element) {
311                                 if (element instanceof FilterDescriptor)
312                                         return ((FilterDescriptor) element).getName();
313                                 else
314                                         return null;
315                         }
316                 };
317         }
318
319         // ---------- result handling ----------
320
321         protected void setResult(List newResult) {
322                 super.setResult(newResult);
323                 if (fUserDefinedPatterns.getText().length() > 0) {
324                         fEnablePatterns = fEnableUserDefinedPatterns.getSelection();
325                         fPatterns = convertFromString(fUserDefinedPatterns.getText(),
326                                         SEPARATOR);
327                 } else {
328                         fEnablePatterns = false;
329                         fPatterns = new String[0];
330                 }
331         }
332
333         /**
334          * @return the patterns which have been entered by the user
335          */
336         public String[] getUserDefinedPatterns() {
337                 return fPatterns;
338         }
339
340         /**
341          * @return the Ids of the enabled built-in filters
342          */
343         public String[] getEnabledFilterIds() {
344                 Object[] result = getResult();
345                 Set enabledIds = new HashSet(result.length);
346                 for (int i = 0; i < result.length; i++)
347                         enabledIds.add(((FilterDescriptor) result[i]).getId());
348                 return (String[]) enabledIds.toArray(new String[enabledIds.size()]);
349         }
350
351         /**
352          * @return <code>true</code> if the user-defined patterns are disabled
353          */
354         public boolean areUserDefinedPatternsEnabled() {
355                 return fEnablePatterns;
356         }
357
358         /**
359          * @return a stack with the filter descriptor check history
360          * @since 3.0
361          */
362         public Stack getFilterDescriptorChangeHistory() {
363                 return fFilterDescriptorChangeHistory;
364         }
365
366         private FilterDescriptor[] getEnabledFilterDescriptors() {
367                 FilterDescriptor[] filterDescs = fBuiltInFilters;
368                 List result = new ArrayList(filterDescs.length);
369                 List enabledFilterIds = Arrays.asList(fEnabledFilterIds);
370                 for (int i = 0; i < filterDescs.length; i++) {
371                         String id = filterDescs[i].getId();
372                         if (enabledFilterIds.contains(id))
373                                 result.add(filterDescs[i]);
374                 }
375                 return (FilterDescriptor[]) result.toArray(new FilterDescriptor[result
376                                 .size()]);
377         }
378
379         public static String[] convertFromString(String patterns, String separator) {
380                 StringTokenizer tokenizer = new StringTokenizer(patterns, separator,
381                                 true);
382                 int tokenCount = tokenizer.countTokens();
383                 List result = new ArrayList(tokenCount);
384                 boolean escape = false;
385                 boolean append = false;
386                 while (tokenizer.hasMoreTokens()) {
387                         String token = tokenizer.nextToken().trim();
388                         if (separator.equals(token)) {
389                                 if (!escape)
390                                         escape = true;
391                                 else {
392                                         addPattern(result, separator);
393                                         append = true;
394                                 }
395                         } else {
396                                 if (!append)
397                                         result.add(token);
398                                 else
399                                         addPattern(result, token);
400                                 append = false;
401                                 escape = false;
402                         }
403                 }
404                 return (String[]) result.toArray(new String[result.size()]);
405         }
406
407         private static void addPattern(List list, String pattern) {
408                 if (list.isEmpty())
409                         list.add(pattern);
410                 else {
411                         int index = list.size() - 1;
412                         list.set(index, ((String) list.get(index)) + pattern);
413                 }
414         }
415
416         public static String convertToString(String[] patterns, String separator) {
417                 int length = patterns.length;
418                 StringBuffer strBuf = new StringBuffer();
419                 if (length > 0)
420                         strBuf.append(escapeSeparator(patterns[0], separator));
421                 else
422                         return ""; //$NON-NLS-1$
423                 int i = 1;
424                 while (i < length) {
425                         strBuf.append(separator);
426                         strBuf.append(" "); //$NON-NLS-1$
427                         strBuf.append(escapeSeparator(patterns[i++], separator));
428                 }
429                 return strBuf.toString();
430         }
431
432         private static String escapeSeparator(String pattern, String separator) {
433                 int length = pattern.length();
434                 StringBuffer buf = new StringBuffer(length);
435                 for (int i = 0; i < length; i++) {
436                         char ch = pattern.charAt(i); //$NON-NLS-1$
437                         if (separator.equals(String.valueOf(ch)))
438                                 buf.append(ch);
439                         buf.append(ch);
440                 }
441                 return buf.toString();
442
443         }
444 }