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