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