1 package net.sourceforge.phpeclipse.wiki.actions.httpquery;
4 import java.text.BreakIterator;
6 import net.sourceforge.phpeclipse.webbrowser.views.BrowserView;
8 import org.eclipse.jface.action.IAction;
9 import org.eclipse.jface.text.IDocument;
10 import org.eclipse.jface.text.IRegion;
11 import org.eclipse.jface.text.ITextSelection;
12 import org.eclipse.jface.viewers.ISelection;
13 import org.eclipse.ui.IEditorActionDelegate;
14 import org.eclipse.ui.IEditorPart;
15 import org.eclipse.ui.IViewPart;
16 import org.eclipse.ui.IWorkbenchPage;
17 import org.eclipse.ui.IWorkbenchWindow;
18 import org.eclipse.ui.PlatformUI;
19 import org.eclipse.ui.texteditor.IDocumentProvider;
20 import org.eclipse.ui.texteditor.ITextEditor;
22 public abstract class AbstractHTTPQueryAction implements IEditorActionDelegate {
24 private IEditorPart targetEditor;
26 public AbstractHTTPQueryAction() {
30 public void setActiveEditor(IAction action, IEditorPart targetEditor) {
31 this.targetEditor = targetEditor;
34 abstract protected String getUrl(String selection);
36 public void run(IAction action) {
37 String selection = findSelectedText();
38 if (selection != null && selection.trim().length() > 0) {
40 IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
42 IWorkbenchPage page = window.getActivePage();
44 IViewPart part = page.findView(BrowserView.ID_BROWSER);
46 part = page.showView(BrowserView.ID_BROWSER);
48 page.bringToTop(part);
50 String urlStr = getUrl(selection);
51 if (urlStr != null && !urlStr.equals("")) {
52 ((BrowserView) part).setUrl(urlStr);
54 } catch (Exception e) {
60 public void selectionChanged(IAction action, ISelection selection) {
63 protected String findSelectedText() {
64 String selectedText = null;
65 ITextSelection textSelection = (ITextSelection) targetEditor.getEditorSite().getSelectionProvider().getSelection();
67 selectedText = textSelection.getText();
68 if (selectedText == null || selectedText.trim().length() == 0) {
69 selectedText = findWord(textSelection);
74 private String findWord(ITextSelection textSelection) {
75 IDocumentProvider documentProvider = ((ITextEditor) targetEditor).getDocumentProvider();
76 IDocument document = documentProvider.getDocument(targetEditor.getEditorInput());
77 int caretPosition = textSelection.getOffset();
79 IRegion line = document.getLineInformation(document.getLineOfOffset(caretPosition));
80 String currentLine = document.get(line.getOffset(), line.getLength());
81 int positionInLine = caretPosition - line.getOffset();
82 return findWordAt(positionInLine, currentLine);
83 } catch (Exception e) {
88 private String findWordAt(int pos, String source) {
89 BreakIterator boundary = BreakIterator.getWordInstance();
90 boundary.setText(source);
91 int end = boundary.following(pos);
92 int start = boundary.previous();
93 return source.substring(start, end);