initial contribution
[phpeclipse.git] / archive / net.sourceforge.phpeclipse.wiki / src / net / sourceforge / phpeclipse / wiki / actions / OpenWikiLinkEditorAction.java
1 package net.sourceforge.phpeclipse.wiki.actions;
2
3 import java.io.ByteArrayInputStream;
4
5 import net.sourceforge.phpeclipse.wiki.editor.WikiEditor;
6 import net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin;
7 import net.sourceforge.phpeclipse.wiki.preferences.Util;
8
9 import org.eclipse.core.resources.IContainer;
10 import org.eclipse.core.resources.IFile;
11 import org.eclipse.core.resources.IFolder;
12 import org.eclipse.core.resources.IResource;
13 import org.eclipse.core.resources.IResourceStatus;
14 import org.eclipse.core.resources.ResourcesPlugin;
15 import org.eclipse.core.runtime.CoreException;
16 import org.eclipse.core.runtime.IPath;
17 import org.eclipse.core.runtime.IProgressMonitor;
18 import org.eclipse.core.runtime.Path;
19 import org.eclipse.core.runtime.SubProgressMonitor;
20 import org.eclipse.jface.action.IAction;
21 import org.eclipse.jface.text.BadLocationException;
22 import org.eclipse.jface.text.IDocument;
23 import org.eclipse.jface.text.ITextSelection;
24 import org.eclipse.jface.text.TextSelection;
25 import org.eclipse.jface.viewers.ISelection;
26 import org.eclipse.ui.IEditorActionDelegate;
27 import org.eclipse.ui.IEditorPart;
28 import org.eclipse.ui.IFileEditorInput;
29 import org.eclipse.ui.IWorkbenchWindow;
30 import org.eclipse.ui.ide.IDE;
31 import org.eclipse.ui.internal.ide.IDEWorkbenchPlugin;
32 import org.eclipse.ui.texteditor.AbstractTextEditor;
33
34 public final class OpenWikiLinkEditorAction implements IEditorActionDelegate {
35
36   private IWorkbenchWindow window;
37
38   private AbstractTextEditor editor;
39
40   public void dispose() {
41   }
42
43   public void init(IWorkbenchWindow window) {
44     this.window = window;
45   }
46
47   public void selectionChanged(IAction action, ISelection selection) {
48     if (selection.isEmpty()) {
49       return;
50     }
51     if (selection instanceof TextSelection) {
52       action.setEnabled(true);
53       return;
54     }
55     if (window.getActivePage() != null && window.getActivePage().getActivePart() != null) {
56       action.setEnabled(window.getActivePage().getActivePart().getClass().equals(WikiEditor.class));
57     }
58   }
59
60   public void run(IAction action) {
61     if (editor == null) {
62       IEditorPart targetEditor = window.getActivePage().getActiveEditor();
63       if (targetEditor != null && (targetEditor instanceof AbstractTextEditor)) {
64         editor = (AbstractTextEditor) targetEditor;
65       }
66     }
67     if (editor != null) {
68       openWikiLinkOnSelection();
69     }
70   }
71
72   public void setActiveEditor(IAction action, IEditorPart targetEditor) {
73     if (targetEditor != null && (targetEditor instanceof AbstractTextEditor)) {
74       editor = (AbstractTextEditor) targetEditor;
75     }
76   }
77
78   public static String getWikiString(AbstractTextEditor editor, IDocument document, int initialPos) {
79     try {
80       int pos = initialPos;
81       int line = document.getLineOfOffset(pos);
82       int start = document.getLineOffset(line);
83       int end = start + document.getLineInformation(line).getLength();
84
85       /*
86        * The line does not include \n or \r so pos can be > end. Making pos = end in this case is safe for the purposes of
87        * determining the TextRegion at the cursor position
88        */
89       if (pos > end) {
90         pos = end;
91       }
92
93       int offsetInLine = pos - start;
94       String word = document.get(start, end - start);
95       int wordlen = word.length();
96       int wikiLinkStart = -1;
97       int wikiLinkEnd = -1;
98
99       for (int i = offsetInLine; i < wordlen; i++) {
100         if (word.charAt(i) == ']' && i < wordlen - 1 && word.charAt(i + 1) == ']') {
101           wikiLinkEnd = i;
102           break;
103         }
104         if (word.charAt(i) == '|') {
105           wikiLinkEnd = i;
106           break;
107         }
108         if (word.charAt(i) == '#') {
109           wikiLinkEnd = i;
110           break;
111         }
112       }
113       for (int i = offsetInLine; i >= 0; i--) {
114         if (word.charAt(i) == '[' && i > 0 && word.charAt(i - 1) == '[') {
115           wikiLinkStart = i + 1;
116           break;
117         }
118         if (word.charAt(i) == '|') { // links wih different description
119           wikiLinkEnd = i;
120         }
121         if (word.charAt(i) == '#') { // for links with anchors
122           wikiLinkEnd = i;
123         }
124       }
125       if (wikiLinkStart != (-1) && wikiLinkEnd != (-1) && wikiLinkStart < wikiLinkEnd) {
126         return new String(word.toCharArray(), wikiLinkStart, wikiLinkEnd - wikiLinkStart);
127       }
128     } catch (BadLocationException e) {
129
130     }
131     return "";
132   }
133
134   public IDocument getDocument() {
135     IDocument doc = editor.getDocumentProvider().getDocument(editor.getEditorInput());
136     return doc;
137   }
138
139   public void openWikiLinkOnSelection() {
140     IDocument doc = getDocument();
141     ITextSelection selection = (ITextSelection) editor.getSelectionProvider().getSelection();
142     int pos = selection.getOffset();
143     
144     String textRegion = getWikiString(editor, doc, pos);
145     IFileEditorInput ei = (IFileEditorInput) editor.getEditorInput();
146     openWikiFile(ei.getFile(), textRegion);
147   }
148
149   void openWikiFile(IFile cfile, String word) {
150     if (word != null && !word.equals("")) {
151       IFile file = getWikiFile(cfile, word);
152       try {
153         createNewFileIfNeeded(file, word);
154         //                              if (WikiEditorPlugin.getDefault().getPreferenceStore().getBoolean(WikiConstants.REUSE_EDITOR)) {
155         //                                      saveIfNeeded();
156         //                                      getActivePage().reuseEditor(reusableEditor, new FileEditorInput(file));
157         //                              } else {
158         IDE.openEditor(WikiEditorPlugin.getDefault().getActivePage(), file, true);
159         //                                      redrawText();
160         //                              }
161       } catch (Exception e) {
162         //                        WikiEditorPlugin.getDefault().logAndReport(WikiEditorPlugin.getResourceString(WikiConstants.RESOURCE_WIKI_ERROR_DIALOGUE_OPEN_WIKI_FILE_TITLE),
163         // WikiPlugin.getResourceString(WikiConstants.RESOURCE_WIKI_ERROR_DIALOGUE_OPEN_WIKI_FILE_TEXT), e);
164       }
165     } 
166   }
167
168   private void createNewFileIfNeeded(IFile file, String word) throws CoreException {
169     if (!file.exists()) {
170       createWikiFile(file, word);
171     }
172   }
173
174   private IFile getWikiFile(IFile file, String word) {
175     String wikiFileName = Util.getWikiFileName(word, file, WikiEditorPlugin.HTML_OUTPUT_PATH);
176     IPath path = new Path(wikiFileName);
177     return ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(path);
178   }
179
180   /**
181    * Creates a folder resource handle for the folder with the given workspace path. This method does not create the folder resource;
182    * this is the responsibility of <code>createFolder</code>.
183    * 
184    * @param folderPath
185    *          the path of the folder resource to create a handle for
186    * @return the new folder resource handle
187    * @see #createFolder
188    */
189   private IFolder createFolderHandle(IPath folderPath) {
190     return IDEWorkbenchPlugin.getPluginWorkspace().getRoot().getFolder(folderPath);
191   }
192
193   private void createFolder(IFolder folderHandle, IProgressMonitor monitor) throws CoreException {
194     try {
195       // Create the folder resource in the workspace
196       // Recursive to create any folders which do not exist already
197       if (!folderHandle.exists()) {
198         IContainer parent = folderHandle.getParent();
199         if (parent instanceof IFolder && (!((IFolder) parent).exists())) {
200           createFolder((IFolder) parent, monitor);
201         }
202         //                  if (linkTargetPath != null)
203         //                              folderHandle.createLink(linkTargetPath, IResource.ALLOW_MISSING_LOCAL, monitor);
204         //                  else
205         folderHandle.create(false, true, monitor);
206       }
207     } catch (CoreException e) {
208       // If the folder already existed locally, just refresh to get contents
209       if (e.getStatus().getCode() == IResourceStatus.PATH_OCCUPIED)
210         folderHandle.refreshLocal(IResource.DEPTH_INFINITE, new SubProgressMonitor(monitor, 500));
211       else
212         throw e;
213     }
214   }
215
216   private void createWikiFile(IFile file, String word) throws CoreException {
217     IContainer parent = file.getParent();
218     if (parent instanceof IFolder && (!((IFolder) parent).exists())) {
219       createFolder((IFolder) parent, null);
220     }
221     String newText = "<!--" + word + "-->";
222     byte[] buffer = newText.getBytes();
223     ByteArrayInputStream source = new ByteArrayInputStream(buffer);
224     file.create(source, true, null);
225   }
226
227 }