638ca71246c7ad38ec7c5d0848a53e59f83a1322
[phpeclipse.git] / net.sourceforge.phpeclipse / src / net / sourceforge / phpeclipse / views / PHPConsole.java
1 package net.sourceforge.phpeclipse.views;
2
3 /**********************************************************************
4 Copyright (c) 2000, 2002 IBM Corp. and others.
5 All rights reserved. This program and the accompanying materials
6 are made available under the terms of the Common Public License v1.0
7 which accompanies this distribution, and is available at
8 http://www.eclipse.org/legal/cpl-v10.html
9
10 Contributors:
11     IBM Corporation - Initial implementation
12     Klaus Hartlage - www.eclipseproject.de
13 **********************************************************************/
14
15 import java.io.BufferedReader;
16 import java.io.IOException;
17 import java.io.InputStream;
18 import java.io.InputStreamReader;
19
20 import net.sourceforge.phpdt.internal.ui.PHPUiImages;
21 import net.sourceforge.phpeclipse.PHPeclipsePlugin;
22 import net.sourceforge.phpeclipse.actions.PHPActionMessages;
23
24 import org.eclipse.core.runtime.IStatus;
25 import org.eclipse.core.runtime.Status;
26 import org.eclipse.jface.action.Action;
27 import org.eclipse.jface.action.IMenuListener;
28 import org.eclipse.jface.action.IMenuManager;
29 import org.eclipse.jface.action.IToolBarManager;
30 import org.eclipse.jface.action.MenuManager;
31 import org.eclipse.jface.action.Separator;
32 import org.eclipse.jface.resource.JFaceResources;
33 import org.eclipse.jface.text.BadLocationException;
34 import org.eclipse.jface.text.Document;
35 import org.eclipse.jface.text.TextViewer;
36 import org.eclipse.swt.SWT;
37 import org.eclipse.swt.custom.StyledText;
38 import org.eclipse.swt.layout.GridData;
39 import org.eclipse.swt.layout.GridLayout;
40 import org.eclipse.swt.widgets.Composite;
41 import org.eclipse.swt.widgets.Label;
42 import org.eclipse.swt.widgets.Menu;
43 import org.eclipse.ui.IActionBars;
44 import org.eclipse.ui.IWorkbenchActionConstants;
45 import org.eclipse.ui.IWorkbenchPage;
46 import org.eclipse.ui.PartInitException;
47 import org.eclipse.ui.PlatformUI;
48 import org.eclipse.ui.part.ViewPart;
49
50 /**
51  * The PHPConsole is used to display the output if you start MySQL/Apache
52  * @see ViewPart
53  */
54 public class PHPConsole extends ViewPart {
55
56   public static final String CONSOLE_ID = "net.sourceforge.phpeclipse.views.phpconsoleview";
57   private int COMMAND_COMBO_SIZE = 10;
58
59   private TextViewer fViewer = null;
60   private Document fDocument = null;
61   private StyledText fStyledText;
62   // private Combo fCommandCombo;
63 //  private ProcessOutputWriter consoleOut;
64 //  private ProcessOutputWriter consoleErr;
65
66   // private Action goAction;
67
68   private Action cutAction = new Action() {
69     public void run() {
70       fViewer.getTextWidget().cut();
71     }
72   };
73   private Action copyAction = new Action() {
74     public void run() {
75       fStyledText.copy();
76     }
77   };
78   //  private Action pasteAction = new Action() {
79   //    public void run() {
80   //      fViewer.getTextWidget().paste();
81   //    }
82   //  };
83   private Action selectAllAction = new Action() {
84     public void run() {
85       fStyledText.selectAll();
86     }
87   };
88   private Action clearAction = new Action() {
89     public void run() {
90       fStyledText.setText("");
91     }
92   };
93   /**
94    * The constructor.
95    */
96   public PHPConsole() {
97   }
98
99   /**
100    * Insert the method's description here.
101    * @see ViewPart#createPartControl
102    */
103   public void createPartControl(Composite parent) {
104 //    Composite container = new Composite(parent, SWT.NULL);
105 //    //   control = container;
106 //    GridLayout layout = new GridLayout();
107 //    layout.marginWidth = 0;
108 //    layout.marginHeight = 0;
109 //    layout.verticalSpacing = 0;
110 //    container.setLayout(layout);
111 //    Composite navContainer = new Composite(container, SWT.NONE);
112 //    layout = new GridLayout();
113 //    layout.numColumns = 2;
114 //    layout.marginHeight = 1;
115 //    navContainer.setLayout(layout);
116 //    createCommandBar(navContainer);
117 //    navContainer.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
118
119     fViewer = new TextViewer(parent, SWT.WRAP | SWT.V_SCROLL | SWT.H_SCROLL);
120     GridData viewerData = new GridData(GridData.FILL_BOTH);
121     fViewer.getControl().setLayoutData(viewerData);
122     fViewer.setEditable(false);
123
124     fStyledText = fViewer.getTextWidget();
125     fStyledText.setFont(JFaceResources.getFontRegistry().get(JFaceResources.TEXT_FONT));
126
127     cutAction.setText("Cut");
128     copyAction.setText("Copy");
129     //   pasteAction.setText("Paste");
130     selectAllAction.setText("Select All");
131     clearAction.setText("Clear PHP Console");
132     clearAction.setImageDescriptor(PHPUiImages.DESC_CLEAR);
133     clearAction.setToolTipText("Clear PHP Console");
134
135     IActionBars bars = this.getViewSite().getActionBars();
136     bars.setGlobalActionHandler(IWorkbenchActionConstants.CUT, cutAction);
137     bars.setGlobalActionHandler(IWorkbenchActionConstants.COPY, copyAction);
138     //  bars.setGlobalActionHandler(IWorkbenchActionConstants.PASTE, pasteAction);
139
140     hookContextMenu();
141     //  hookDoubleClickAction();
142     contributeToActionBars();
143
144     //    appendOutputText("This is the PHP console.\n");
145     //    appendOutputText("Type: \"php $f\" to run the current editor file.\n");
146
147   }
148
149   private void createCommandBar(Composite parent) {
150 //    Label addressLabel = new Label(parent, SWT.NONE);
151 //    addressLabel.setText("Command:");
152
153     //    fCommandCombo = new Combo(parent, SWT.DROP_DOWN | SWT.BORDER);
154     //    fCommandCombo.addModifyListener(new ModifyListener() {
155     //      public void modifyText(ModifyEvent e) {
156     //        String text = fCommandCombo.getText();
157     //        //       goAction.setEnabled(text.length() > 0);
158     //      }
159     //    });
160     //    fCommandCombo.addSelectionListener(new SelectionListener() {
161     //      public void widgetSelected(SelectionEvent e) {
162     //        String text = fCommandCombo.getItem(fCommandCombo.getSelectionIndex());
163     //        if (text.length() > 0) {
164     //          fCommandCombo.setText(text);
165     //          //    executeCommand(text);
166     //        }
167     //      }
168     //      public void widgetDefaultSelected(SelectionEvent e) {
169     //        executeCommand(fCommandCombo.getText());
170     //      }
171     //    });
172     GridData gd = new GridData(GridData.FILL_HORIZONTAL);
173     //  fCommandCombo.setLayoutData(gd);
174   }
175
176   //  private void executeCommand(String command) {
177   //    command.trim();
178   //    if (command.equals("")) {
179   //      fCommandCombo.forceFocus();
180   //      return;
181   //    }
182   //    execute(command);
183   //
184   //    fCommandCombo.forceFocus();
185   //    // add to Combo history
186   //    String[] items = fCommandCombo.getItems();
187   //    int loc = -1;
188   //    String normURL = command;
189   //    for (int i = 0; i < items.length; i++) {
190   //      String normItem = items[i];
191   //      if (normURL.equals(normItem)) {
192   //        // match 
193   //        loc = i;
194   //        break;
195   //      }
196   //    }
197   //    if (loc != -1) {
198   //      fCommandCombo.remove(loc);
199   //    }
200   //    fCommandCombo.add(command, 0);
201   //    if (fCommandCombo.getItemCount() > COMMAND_COMBO_SIZE) {
202   //      fCommandCombo.remove(fCommandCombo.getItemCount() - 1);
203   //    }
204   //    fCommandCombo.getParent().layout(true);
205   //  }
206
207   //  private void execute(String command) {  
208   //    
209   //    ArrayList args = new ArrayList();
210   //
211   //    command = command.replace('\\', '§');
212   //
213   //    StreamTokenizer tokenizer = new StreamTokenizer(new StringReader(command));
214   //    tokenizer.resetSyntax();
215   //
216   //    tokenizer.whitespaceChars(0, ' ');
217   //    tokenizer.wordChars('!', 255);
218   //
219   //    tokenizer.quoteChar('"');
220   //    tokenizer.quoteChar('\'');
221   //
222   //    int token;
223   //    try {
224   //      while ((token = tokenizer.nextToken()) != StreamTokenizer.TT_EOF) {
225   //        if (token == StreamTokenizer.TT_WORD) {
226   //          args.add(tokenizer.sval);
227   //        }
228   //      }
229   //    } catch (IOException e) {
230   //      // 
231   //    }
232   //    String arg = "";
233   //    // replace variables in arguments
234   //
235   ////    IFile file = getFile();
236   //    IFile file = PHPeclipsePlugin.getDefault().getLastEditorFile();
237   //    if (file != null) {
238   //      String fileLocation = file.getLocation().toString();
239   //      for (int i = 0; i < args.size(); i++) {
240   //        arg = args.get(i).toString();
241   //        if (arg.equals("$f")) {
242   //          //current php editor file
243   //          if (File.separatorChar == '\\') {
244   //            fileLocation = fileLocation.replace('/', '\\');
245   //          }
246   //          args.set(i, fileLocation);
247   //        }
248   //      }
249   //    }
250   //
251   //    final IPreferenceStore store = PHPeclipsePlugin.getDefault().getPreferenceStore();
252   //
253   //    String arg0 = "";
254   //    String temp;
255   //    StringBuffer commandBuffer = new StringBuffer(1024);
256   //    //    Program.launch(command);
257   //    if (args.size() > 0) {
258   //      arg0 = (String) args.get(0);
259   //      arg0 = arg0.replace('§', '\\');
260   //      args.remove(0);
261   //      if (arg0.equals("php")) {
262   //        temp = store.getString(PHPeclipsePlugin.PHP_RUN_PREF);
263   //        if (temp != null) {
264   //          arg0 = temp;
265   //        }
266   //      }
267   //      commandBuffer.append(arg0 + " ");
268   //    }
269   //    String[] stringArgs = new String[args.size()];
270   //    for (int i = 0; i < args.size(); i++) {
271   //      arg = (String) args.get(i);
272   //      arg = arg.replace('§', '\\');
273   //      stringArgs[i] = arg;
274   //      commandBuffer.append(arg + " ");
275   //    }
276   //    commandBuffer.append("\n");
277   //
278   //    try {
279   //      command = commandBuffer.toString();
280   //      write(command+"\n");
281   //      Runtime runtime = Runtime.getRuntime();
282   //
283   //      // runs the command
284   //      Process process = runtime.exec(command);
285   //      
286   //      consoleOut = new ProcessOutputWriter(process.getInputStream());
287   //      consoleOut.start();
288   //      consoleErr = new ProcessOutputWriter(process.getErrorStream());
289   //      consoleErr.start();
290   //            
291   //      //process.waitFor();
292   ////      InputStream in = process.getInputStream();
293   ////      String output = getStringFromStream(in);
294   ////      write(output);
295   ////      in.close();
296   ////    } catch (InterruptedException e) {
297   ////      write(e.toString());
298   //    } catch (IOException e) {
299   //      write(e.toString());
300   //    }
301   //  }
302
303   private void hookContextMenu() {
304     MenuManager menuMgr = new MenuManager("#PopupMenu");
305     menuMgr.setRemoveAllWhenShown(true);
306     menuMgr.addMenuListener(new IMenuListener() {
307       public void menuAboutToShow(IMenuManager manager) {
308         PHPConsole.this.fillContextMenu(manager);
309       }
310     });
311     Menu menu = menuMgr.createContextMenu(fViewer.getControl());
312     fViewer.getControl().setMenu(menu);
313     getSite().registerContextMenu(menuMgr, fViewer);
314   }
315
316   private void contributeToActionBars() {
317     IActionBars bars = getViewSite().getActionBars();
318     fillLocalPullDown(bars.getMenuManager());
319     fillLocalToolBar(bars.getToolBarManager());
320   }
321
322   private void fillLocalPullDown(IMenuManager manager) {
323     manager.add(cutAction);
324     manager.add(copyAction);
325     //   manager.add(pasteAction);
326     manager.add(selectAllAction);
327   }
328
329   private void fillContextMenu(IMenuManager manager) {
330     manager.add(cutAction);
331     manager.add(copyAction);
332     //  manager.add(pasteAction);
333     manager.add(selectAllAction);
334     // Other plug-ins can contribute there actions here
335     manager.add(new Separator("Additions"));
336   }
337
338   private void fillLocalToolBar(IToolBarManager manager) {
339     manager.add(clearAction);
340   }
341   /**
342    * Insert the method's description here.
343    * @see ViewPart#setFocus
344    */
345   public void setFocus() {
346     //   fCommandCombo.forceFocus();
347   }
348
349   /**
350    * Set the text for the viewer
351    */
352   public void setOutputText(String text) {
353     fDocument = new Document(text);
354     fViewer.setDocument(fDocument);
355   }
356
357   public void appendOutputText(String text) {
358     try {
359       if (fDocument == null) {
360         fDocument = new Document(text);
361         fViewer.setDocument(fDocument);
362       } else {
363         fDocument.replace(fDocument.getLength(), 0, text);
364       }
365     } catch (BadLocationException e) {
366     }
367     //  viewer.setDocument(document);
368   }
369
370   public static PHPConsole getInstance() {
371     IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
372     PHPConsole console = (PHPConsole) page.findView(PHPConsole.CONSOLE_ID);
373
374     if (PHPeclipsePlugin.getDefault().getPreferenceStore().getBoolean(PHPeclipsePlugin.SHOW_OUTPUT_IN_CONSOLE) == true) {
375       try {
376         page.showView(PHPConsole.CONSOLE_ID);
377         if (console == null) {
378           console = (PHPConsole) page.findView(PHPConsole.CONSOLE_ID);
379         }
380       } catch (PartInitException e) {
381         PHPeclipsePlugin.getDefault().getLog().log(
382           new Status(
383             IStatus.ERROR,
384             PHPeclipsePlugin.getPluginId(),
385             0,
386             PHPActionMessages.getString("PHPStartApacheAction.consoleViewOpeningProblem"),
387             e));
388       }
389     }
390     return console;
391   }
392
393   /**
394    * Prints out the string represented by the string 
395    */
396   public synchronized void write(String output) {
397     appendOutputText(output);
398   }
399
400   /**
401    * Creates a string buffer from the given input stream
402    */
403   public static String getStringFromStream(InputStream stream) throws IOException {
404     StringBuffer buffer = new StringBuffer();
405     byte[] b = new byte[100];
406     int finished = 0;
407     while (finished != -1) {
408       finished = stream.read(b);
409       if (finished != -1) {
410         String current = new String(b, 0, finished);
411         buffer.append(current);
412       }
413     }
414     return buffer.toString();
415   }
416
417   /**
418    * Finds the file that's currently opened in the PHP Text Editor
419    */
420   //  protected IFile getFile() {
421   //    ITextEditor editor = PHPeclipsePlugin.getDefault().getLastEditorFile();
422   //
423   //    IEditorInput editorInput = null;
424   //    if (editor != null) {
425   //      editorInput = editor.getEditorInput();
426   //    }
427   //
428   //    if (editorInput instanceof IFileEditorInput)
429   //      return ((IFileEditorInput) editorInput).getFile();
430   //
431   //    // if nothing was found, which should never happen
432   //    return null;
433   //  }
434
435   class ProcessOutputWriter extends Thread {
436     boolean fStreamClosed;
437     InputStream fInputStream;
438
439     ProcessOutputWriter(InputStream inputStream) {
440       fInputStream = inputStream;
441       fStreamClosed = false;
442     }
443
444     public void closeStream() {
445       fStreamClosed = true;
446       try {
447         fInputStream.close();
448       } catch (IOException io) {
449       }
450     }
451
452     public void run() {
453       try {
454         BufferedReader in = new BufferedReader(new InputStreamReader(fInputStream));
455
456         String line;
457         while ((line = in.readLine()) != null) {
458           write(line);
459         }
460         in.close();
461       } catch (Exception e) {
462         e.printStackTrace(System.out);
463         if (!fStreamClosed) {
464           //  write("\nPHP Console Exception: "+ e.toString() );
465         }
466       } finally {
467       }
468     }
469   }
470
471 }