View Javadoc

1   package com.explosion.expfmodules.search.dialogs;
2   
3   /* =============================================================================
4    *       
5    *     Copyright 2004 Stephen Cowx
6    *
7    *     Licensed under the Apache License, Version 2.0 (the "License");
8    *     you may not use this file except in compliance with the License.
9    *     You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   *     Unless required by applicable law or agreed to in writing, software
14   *     distributed under the License is distributed on an "AS IS" BASIS,
15   *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   *     See the License for the specific language governing permissions and
17   *     limitations under the License.
18   * 
19   * =============================================================================
20   */
21  
22  import java.awt.BorderLayout;
23  import java.awt.Dimension;
24  import java.awt.GridBagConstraints;
25  import java.awt.GridBagLayout;
26  import java.awt.Insets;
27  import java.awt.event.ActionEvent;
28  import java.awt.event.ActionListener;
29  import java.awt.event.MouseAdapter;
30  import java.awt.event.MouseEvent;
31  import java.awt.event.MouseListener;
32  import java.io.File;
33  import java.util.Vector;
34  
35  import javax.swing.JButton;
36  import javax.swing.JInternalFrame;
37  import javax.swing.JLabel;
38  import javax.swing.JPanel;
39  import javax.swing.JScrollPane;
40  import javax.swing.JTextField;
41  import javax.swing.JTree;
42  import javax.swing.tree.TreePath;
43  
44  import com.explosion.datastream.exql.gui.ExqlTreeNode;
45  import com.explosion.expf.Application;
46  import com.explosion.expf.Closeable;
47  import com.explosion.expf.ExpComponent;
48  import com.explosion.expf.ExpFrame;
49  import com.explosion.expfmodules.search.FileSearchResultCollection;
50  import com.explosion.expfmodules.search.LineReplacer;
51  import com.explosion.expfmodules.search.LineSearcher;
52  import com.explosion.expfmodules.search.SearchConstants;
53  import com.explosion.expfmodules.search.SearchModuleManager;
54  import com.explosion.expfmodules.search.SearchResult;
55  import com.explosion.expfmodules.texteditor.ExpfTextField;
56  import com.explosion.expfmodules.texteditor.TextEditor;
57  import com.explosion.utilities.FileSystemUtils;
58  import com.explosion.utilities.exception.ExceptionManagerFactory;
59  import com.explosion.utilities.preferences.Preference;
60  import com.explosion.utilities.process.MultiFileLineByLineParser;
61  import com.explosion.utilities.process.MultiFileLineByLineReplacer;
62  import com.explosion.utilities.process.ProcessMonitoringStatusBar;
63  import com.explosion.utilities.process.threads.Finishable;
64  
65  
66  /***
67   * @author Stephen Cowx
68   * @version
69   */
70  
71  public class SearchJPanel extends JPanel implements ExpComponent, Finishable, Closeable
72  {
73    private static int stateofit = 0;
74    private JPanel controlsPanel = new JPanel();
75    
76    private JTextField searchStringTextField;
77    private JTextField filenamePatternTextField;
78    private JTextField replaceWithTextField;
79    private JTextField searchInWhichFilesTextField;
80    private JLabel searchForLabel = new JLabel();
81    private JLabel replaceWithLabel = new JLabel();
82    private JLabel filenamePatternLabel = new JLabel();
83    private JLabel searchInWhichFilesLabel = new JLabel();
84  
85    private JButton goButton = new JButton();
86    private JButton clearResultsButton = new JButton();
87    private JButton closeButton = new JButton();
88    private JButton selectDirButton = new JButton();
89    
90    private String lastSearch= "";
91    private String lastReplaceWith = "";
92    private String lastFilenamePatternSearch= "";
93    private File lastDir = null;
94    private boolean replaceMode = false;
95    
96    private ProcessMonitoringStatusBar processMonitoringStatusBar;
97    private LineSearcher lineSearcher;
98    private MultiFileLineByLineParser parser;
99    private LineReplacer lineReplacer;
100   private MultiFileLineByLineReplacer replacer;
101   
102   private JScrollPane pane;
103   private JTree tree;
104   
105   public SearchJPanel(boolean replaceModeOn)
106   {
107     try
108     {
109       this.replaceMode = replaceModeOn;
110       init();
111     }
112     catch (Exception e)
113     {
114      e.printStackTrace();
115     }
116   }
117 
118   private void init() throws Exception
119   {
120     processMonitoringStatusBar = new ProcessMonitoringStatusBar(Application.getApplicationFrame());
121     lastSearch = (String) SearchModuleManager.instance().getPreference(SearchConstants.LAST_SEARCH_IN_FILES).getValue();
122     lastReplaceWith = (String) SearchModuleManager.instance().getPreference(SearchConstants.LAST_REPLACE_IN_FILES).getValue();
123     lastDir = (File) SearchModuleManager.instance().getPreference(SearchConstants.LAST_DIRECTORY_SEARCHED).getValue();
124     lastFilenamePatternSearch = (String) SearchModuleManager.instance().getPreference(SearchConstants.LAST_FILENAMEPATTERN_SEARCHED).getValue();
125     
126     searchStringTextField = new ExpfTextField(this);
127     filenamePatternTextField = new ExpfTextField(this);
128     replaceWithTextField = new ExpfTextField(this);
129     searchInWhichFilesTextField = new ExpfTextField(this);
130     
131     searchForLabel.setText("Search for:");
132     filenamePatternLabel.setText("Filename pattern:");
133     searchInWhichFilesLabel.setText("In directory:");
134     replaceWithLabel.setText("Replace with:");
135         
136     searchStringTextField.setText(lastSearch);
137     filenamePatternTextField.setText(lastFilenamePatternSearch);
138     searchInWhichFilesTextField.setText(lastDir.getAbsolutePath());
139     replaceWithTextField.setText(lastReplaceWith);
140     
141     goButton.setText("Search");
142     clearResultsButton.setText("Clear results");
143     closeButton.setText("Close");
144     selectDirButton.setText("...");
145     
146     goButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) {goButton_actionPerformed(e); }});
147     closeButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) {closeButton_actionPerformed(e); }}); 
148     clearResultsButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) {clearResultsButton_actionPerformed(e); }}); 
149     
150     selectDirButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) {selectDirButton_actionPerformed(e); }});
151     
152     JPanel buttonPanel = new JPanel();
153     buttonPanel.add(clearResultsButton);
154     buttonPanel.add(goButton);
155     buttonPanel.add(closeButton);
156     
157     clearResultsButton.setEnabled(false);
158     
159     controlsPanel.setLayout(new GridBagLayout());
160         
161     controlsPanel.add(searchForLabel,              new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 ,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(2, 5, 2, 0), 0, 0));
162 	controlsPanel.add(searchStringTextField,       new GridBagConstraints(1, 0, 2, 1, 1.0, 0.0 ,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(2, 0, 2, 5), 0, 0));
163 	if (replaceMode)
164 	{
165 	  controlsPanel.add(replaceWithLabel,            new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 ,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(2, 5, 2, 0), 0, 0));
166 	  controlsPanel.add(replaceWithTextField,        new GridBagConstraints(1, 1, 2, 1, 1.0, 0.0 ,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(2, 0, 2, 5), 0, 0));
167 	}
168 	controlsPanel.add(filenamePatternLabel,        new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 ,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(2, 5, 2, 0), 0, 0));
169 	controlsPanel.add(filenamePatternTextField,    new GridBagConstraints(1, 2, 2, 1, 1.0, 0.0 ,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(2, 0, 2, 5), 0, 0));
170 	controlsPanel.add(searchInWhichFilesLabel,     new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0 ,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(2, 5, 2, 2), 0, 0));
171 	controlsPanel.add(searchInWhichFilesTextField, new GridBagConstraints(1, 3, 1, 1, 1.0, 0.0 ,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(2, 0, 2, 2), 0, 0));
172 	controlsPanel.add(selectDirButton,             new GridBagConstraints(2, 3, 1, 1, 0.0, 0.0 ,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(2, 0, 2, 5), 0, 0));
173 	controlsPanel.add(buttonPanel,                 new GridBagConstraints(0, 4, 3, 1, 1.0, 0.0 ,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(2, 5, 2, 5), 0, 0));
174 	
175 	this.setPreferredSize(new Dimension(400,125));
176     this.setLayout(new BorderLayout());
177     this.add(controlsPanel,BorderLayout.NORTH);
178 	
179     searchStringTextField.requestFocus();
180     
181   }
182 
183   void closeButton_actionPerformed(ActionEvent e)
184   {
185   	try
186     {
187       ((ExpFrame) Application.getApplicationFrame()).closeFrameWithComponent(this, ExpFrame.PALETTE_LAYER);
188     }
189     catch (Exception ex)
190     {
191       ExceptionManagerFactory.getExceptionManager().manageException(ex,null);
192     }
193   }
194   
195   public String getCloseCommand()
196   {
197 	return SearchConstants.MENU_CLOSE_SEARCH;
198   }
199   
200   void clearResultsButton_actionPerformed(ActionEvent e)
201   {
202   	try
203     {
204       this.remove(pane);
205       this.setPreferredSize(new Dimension(400,125));
206       clearResultsButton.setEnabled(false);
207       tree = null;
208       pane = null;
209       ((ExpFrame) Application.getApplicationFrame()).getFrameWithComponent(this, ExpFrame.PALETTE_LAYER.intValue()).pack();
210     }
211     catch (Exception ex)
212     {
213       ExceptionManagerFactory.getExceptionManager().manageException(ex,null);
214     }
215   }
216   
217   void goButton_actionPerformed(ActionEvent e)
218   {
219   	try
220     {
221       
222       if (!updateText())
223 	    return;
224 	       
225 	  File directory = (File) SearchModuleManager.instance().getPreference(SearchConstants.LAST_DIRECTORY_SEARCHED).getValue();
226 	  String filenamePattern = (String) SearchModuleManager.instance().getPreference(SearchConstants.LAST_FILENAMEPATTERN_SEARCHED).getValue();
227 	  lastSearch = (String) SearchModuleManager.instance().getPreference(SearchConstants.LAST_SEARCH_IN_FILES).getValue();
228 	  lastReplaceWith = (String) SearchModuleManager.instance().getPreference(SearchConstants.LAST_REPLACE_IN_FILES).getValue();
229 	     
230 	  JInternalFrame frame = ((ExpFrame) Application.getApplicationFrame()).getFrameWithComponent(this, ExpFrame.PALETTE_LAYER.intValue());
231       frame.getContentPane().add(processMonitoringStatusBar,BorderLayout.SOUTH);
232       frame.setDefaultCloseOperation(JInternalFrame.DO_NOTHING_ON_CLOSE);
233       frame.pack();
234 
235       if (replaceMode)
236       {
237           lineReplacer = new LineReplacer(lastSearch, lastReplaceWith);
238           replacer = new MultiFileLineByLineReplacer(this,directory.getAbsolutePath(),true,filenamePattern,lineReplacer, true);
239           stateofit++;
240           processMonitoringStatusBar.setProcessToMonitor(replacer);
241       }
242       else
243       {
244 	    lineSearcher = new LineSearcher(lastSearch);
245         parser = new MultiFileLineByLineParser(this,directory.getAbsolutePath(),true,filenamePattern,lineSearcher);
246         stateofit++;
247         processMonitoringStatusBar.setProcessToMonitor(parser);
248       }
249       
250       processMonitoringStatusBar.setProgressBarEnabled(false);//stateofit % 2== 0);
251       processMonitoringStatusBar.startProcess();      
252 	  setAllEnabled(false);
253     }
254     catch (Exception ex)
255     {
256       ExceptionManagerFactory.getExceptionManager().manageException(ex,null);
257 	  setAllEnabled(true);
258     }
259   }
260   
261   private void setAllEnabled(boolean truth)
262   {
263 	  searchStringTextField.setEnabled(truth);
264 	  filenamePatternTextField.setEnabled(truth);
265 	  searchInWhichFilesTextField.setEnabled(truth);
266 	  selectDirButton.setEnabled(truth);
267 	  goButton.setEnabled(truth);
268 	  closeButton.setEnabled(truth);
269 	  clearResultsButton.setEnabled(truth);
270   }
271   
272   public void finish()
273   {
274     try
275     {   
276        Vector searchresults = null;
277         
278        if (parser != null)
279        {
280            if (parser.getProcessControl().wasKilled())
281            {
282                searchresults = lineSearcher.getFileSearchResults();
283            }
284        }
285        else if (replacer != null)
286        {
287            if (replacer.getProcessControl().wasKilled())
288            {
289                searchresults = lineReplacer.getFileSearchResults();
290            }
291        }
292         
293        if (searchresults != null )
294        {
295 	       
296 	       ExqlTreeNode resultsNode = resultsNode = new ExqlTreeNode(lastSearch);
297 	       
298 	       int matchingLines = 0;
299 	       if (searchresults.size() < 1)
300 	         resultsNode.add(new ExqlTreeNode("No matches."));	         
301 	       
302 	       for (int i=0;i<searchresults.size();i++)
303 	       {
304 	          FileSearchResultCollection resultsCollection = (FileSearchResultCollection) searchresults.elementAt(i);
305 	          ShortCutFile file = new ShortCutFile(resultsCollection.getFileName());
306 	          ExqlTreeNode fileNode  = new ExqlTreeNode(file);
307 	          fileNode.setUserObject(file);
308 	          resultsNode.add(fileNode);
309 	          
310 	          Vector fileResults = resultsCollection.getSearchResults();
311 	          for (int j=0;j<fileResults.size();j++)
312 	          {
313 	          	SearchResult result = (SearchResult) fileResults.elementAt(j); 
314 	          	ExqlTreeNode lineNode  = new ExqlTreeNode(result.getLineNumber() + ": " + result.getMatchedLine());
315 	          	fileNode.add(lineNode);
316 	          	matchingLines++;
317 	          }
318 	       } 
319 	       
320 	       if (pane == null)
321 	       {
322 	         pane = new JScrollPane();
323 	         this.setPreferredSize(new Dimension(400,350));
324    	         this.add(pane,BorderLayout.CENTER);
325 	       }  
326            
327            if (tree == null)
328            {
329               ExqlTreeNode rootNode = new ExqlTreeNode("Results");
330               rootNode.add(resultsNode);
331               tree = new JTree(rootNode);
332               pane.getViewport().add(tree);
333               
334                MouseListener ml = new MouseAdapter() 
335 		       {
336 		       	    public void mousePressed(MouseEvent e) 
337 		       	    {
338 		               int selRow = tree.getRowForLocation(e.getX(), e.getY());
339 		               TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
340 		               if(selRow != -1) 
341 		               {
342 		                  if(e.getClickCount() == 2) 
343 					        {
344 					          Object parent = selPath.getParentPath().getLastPathComponent();
345 					          if (parent != null )
346 					          {
347 					            
348 					            try
349 					            {
350 					              if (((ExqlTreeNode)parent).getUserObject() != null && ((ExqlTreeNode)parent).getUserObject() instanceof File)
351 					              {
352 					                TextEditor editor = new TextEditor((File)((ExqlTreeNode)parent).getUserObject());
353 					                ((ExpFrame) Application.getApplicationFrame()).createDocumentFrame(editor, new Dimension(500,500), editor.getDocument().getDocumentName(),true);
354 					              }  
355 					            }
356 					            catch (Exception ex)
357 					            {
358 					              ExceptionManagerFactory.getExceptionManager().manageException(ex,"Exception caught while opening search document.");
359 					            }
360 					          }  
361 					        }
362 		               }
363 		            }
364 		      };
365 		      tree.addMouseListener(ml);
366            }  
367            else
368            {
369            	  ExqlTreeNode rootNode = (ExqlTreeNode)tree.getModel().getRoot();
370            	  rootNode.add(resultsNode);
371            	  //tree = new JTree(rootNode);
372            	  tree.updateUI();
373            }
374            clearResultsButton.setEnabled(true);
375       }
376       
377 	  setAllEnabled(true);
378 	  
379 	  JInternalFrame frame = ((ExpFrame) Application.getApplicationFrame()).getFrameWithComponent(this, ExpFrame.PALETTE_LAYER.intValue());
380       frame.setDefaultCloseOperation(JInternalFrame.DISPOSE_ON_CLOSE);
381       frame.getContentPane().remove(processMonitoringStatusBar);
382       frame.pack();
383     }
384     catch (Exception ex)
385     {
386       ExceptionManagerFactory.getExceptionManager().manageException(ex,null);
387 	  setAllEnabled(true);
388     }
389   }
390 
391 
392   void selectDirButton_actionPerformed(ActionEvent e)
393   {
394   	try
395     {
396       Preference preference = SearchModuleManager.instance().getPreference(SearchConstants.LAST_DIRECTORY_SEARCHED);
397       File[] file = FileSystemUtils.chooseFiles(Application.getApplicationFrame(), FileSystemUtils.OPENTYPE, false, (File) preference.getValue(), FileSystemUtils.DIRECTORIES_ONLY,"Select the directory containing the files you want to search.");
398       
399       if (file != null && file[0] != null)
400       {
401         preference.setValue(file[0]);
402         preference.save();
403         this.searchInWhichFilesTextField.setText(file[0].getAbsolutePath());
404       }  
405          
406     }
407     catch (Exception ex)
408     {
409       ExceptionManagerFactory.getExceptionManager().manageException(ex,null);
410     }
411        
412   }
413   
414   public boolean updateText()
415   {
416   	try
417     {
418       SearchModuleManager.instance().getPreference(SearchConstants.LAST_FILENAMEPATTERN_SEARCHED).setValue(filenamePatternTextField.getText());
419       SearchModuleManager.instance().getPreference(SearchConstants.LAST_FILENAMEPATTERN_SEARCHED).save();
420       SearchModuleManager.instance().getPreference(SearchConstants.LAST_SEARCH_IN_FILES).setValue(searchStringTextField.getText());
421       SearchModuleManager.instance().getPreference(SearchConstants.LAST_SEARCH_IN_FILES).save();
422       SearchModuleManager.instance().getPreference(SearchConstants.LAST_REPLACE_IN_FILES).setValue(replaceWithTextField.getText());
423       SearchModuleManager.instance().getPreference(SearchConstants.LAST_REPLACE_IN_FILES).save();
424       SearchModuleManager.instance().getPreference(SearchConstants.LAST_DIRECTORY_SEARCHED).setValue(new File(searchInWhichFilesTextField.getText()));
425       SearchModuleManager.instance().getPreference(SearchConstants.LAST_DIRECTORY_SEARCHED).save();
426     }
427     catch (Exception ex)
428     {
429       ExceptionManagerFactory.getExceptionManager().manageException(ex,null);
430       return false;
431     }
432     return true;
433   }
434   
435   public void applyPreferences()
436   {
437   }
438   
439   public ActionListener getGlobalListener()
440   {
441   	return null;
442   } 
443 
444 }
445