a45c2a37c2e97bcee1b2e02e1173418f6832046a
[phpeclipse.git] / archive / net.sourceforge.phpeclipse.wiki / src / net / sourceforge / phpeclipse / wiki / actions / mediawiki / DownloadWikiLinkEditorAction.java
1 package net.sourceforge.phpeclipse.wiki.actions.mediawiki;
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 DownloadWikiLinkEditorAction implements IEditorActionDelegate {
35
36   private IWorkbenchWindow window; 
37
38   private AbstractTextEditor fEditor;
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 (fEditor == null) {
62       IEditorPart targetEditor = window.getActivePage().getActiveEditor();
63       if (targetEditor != null && (targetEditor instanceof AbstractTextEditor)) {
64         fEditor = (AbstractTextEditor) targetEditor;
65       }
66     }
67     if (fEditor != null) {
68       openWikiLinkOnSelection();
69     }
70   }
71
72   public void setActiveEditor(IAction action, IEditorPart targetEditor) {
73     if (targetEditor != null && (targetEditor instanceof AbstractTextEditor)) {
74       fEditor = (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 = fEditor.getDocumentProvider().getDocument(fEditor.getEditorInput());
136     return doc;
137   }
138
139   public void openWikiLinkOnSelection() {
140     IDocument doc = getDocument();
141     ITextSelection selection = (ITextSelection) fEditor.getSelectionProvider().getSelection();
142     int pos = selection.getOffset();
143     String textRegion = getWikiString(fEditor, doc, pos);
144     IFileEditorInput ei = (IFileEditorInput) fEditor.getEditorInput();
145     openWikiFile(ei.getFile(), textRegion);
146   }
147
148   void openWikiFile(IFile cfile, String word) {
149     if (word != null && !word.equals("")) {
150       IFile file = getWikiFile(cfile, word);
151       try {
152         createNewFileIfNeeded(file, word);
153         
154         //                              if (WikiEditorPlugin.getDefault().getPreferenceStore().getBoolean(WikiConstants.REUSE_EDITOR)) {
155         //                                      saveIfNeeded();
156         //                                      getActivePage().reuseEditor(reusableEditor, new FileEditorInput(file));
157         //                              } else {
158         IEditorPart part = IDE.openEditor(WikiEditorPlugin.getDefault().getActivePage(), file, true);
159         if (part != null && (part instanceof AbstractTextEditor)) {
160           AbstractTextEditor newEditor = (AbstractTextEditor) part;
161           word = Util.titleToDB(word);
162           String wikiText = MediaWikiConnector.getWikiRawText(word, "http://en.wikibooks.org/w/wiki.phtml");
163           if (wikiText!=null) {
164             IDocument doc = newEditor.getDocumentProvider().getDocument(newEditor.getEditorInput());
165             doc.set(wikiText);
166           }
167         }
168         
169         
170         //                                      redrawText();
171         //                              }
172       } catch (Exception e) {
173         //                        WikiEditorPlugin.getDefault().logAndReport(WikiEditorPlugin.getResourceString(WikiConstants.RESOURCE_WIKI_ERROR_DIALOGUE_OPEN_WIKI_FILE_TITLE),
174         // WikiPlugin.getResourceString(WikiConstants.RESOURCE_WIKI_ERROR_DIALOGUE_OPEN_WIKI_FILE_TEXT), e);
175       }
176     } 
177   }
178
179   private void createNewFileIfNeeded(IFile file, String word) throws CoreException {
180     if (!file.exists()) {
181       createWikiFile(file, word);
182     }
183   }
184
185   private IFile getWikiFile(IFile file, String word) {
186     String wikiFileName = Util.getWikiFileName(word, file, WikiEditorPlugin.HTML_OUTPUT_PATH);
187     IPath path = new Path(wikiFileName);
188     return ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(path);
189   }
190
191   /**
192    * Creates a folder resource handle for the folder with the given workspace path. This method does not create the folder resource;
193    * this is the responsibility of <code>createFolder</code>.
194    * 
195    * @param folderPath
196    *          the path of the folder resource to create a handle for
197    * @return the new folder resource handle
198    * @see #createFolder
199    */
200   private IFolder createFolderHandle(IPath folderPath) {
201     return IDEWorkbenchPlugin.getPluginWorkspace().getRoot().getFolder(folderPath);
202   }
203
204   private void createFolder(IFolder folderHandle, IProgressMonitor monitor) throws CoreException {
205     try {
206       // Create the folder resource in the workspace
207       // Recursive to create any folders which do not exist already
208       if (!folderHandle.exists()) {
209         IContainer parent = folderHandle.getParent();
210         if (parent instanceof IFolder && (!((IFolder) parent).exists())) {
211           createFolder((IFolder) parent, monitor);
212         }
213         //                  if (linkTargetPath != null)
214         //                              folderHandle.createLink(linkTargetPath, IResource.ALLOW_MISSING_LOCAL, monitor);
215         //                  else
216         folderHandle.create(false, true, monitor);
217       }
218     } catch (CoreException e) {
219       // If the folder already existed locally, just refresh to get contents
220       if (e.getStatus().getCode() == IResourceStatus.PATH_OCCUPIED)
221         folderHandle.refreshLocal(IResource.DEPTH_INFINITE, new SubProgressMonitor(monitor, 500));
222       else
223         throw e;
224     }
225   }
226
227   private void createWikiFile(IFile file, String word) throws CoreException {
228     IContainer parent = file.getParent();
229     if (parent instanceof IFolder && (!((IFolder) parent).exists())) {
230       createFolder((IFolder) parent, null);
231     }
232     String newText = "<!--" + word + "-->";
233     byte[] buffer = newText.getBytes();
234     ByteArrayInputStream source = new ByteArrayInputStream(buffer);
235     file.create(source, true, null);
236   }
237
238 }