From: axelcl Date: Wed, 8 Dec 2004 22:01:51 +0000 (+0000) Subject: initial contribution X-Git-Url: http://git.phpeclipse.com initial contribution --- diff --git a/archive/net.sourceforge.phpeclipse.wiki/.classpath b/archive/net.sourceforge.phpeclipse.wiki/.classpath new file mode 100644 index 0000000..8f4f2e9 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/.classpath @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/archive/net.sourceforge.phpeclipse.wiki/.project b/archive/net.sourceforge.phpeclipse.wiki/.project new file mode 100644 index 0000000..1739d16 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/.project @@ -0,0 +1,28 @@ + + + net.sourceforge.phpeclipse.wiki + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + + org.eclipse.pde.PluginNature + org.eclipse.jdt.core.javanature + + diff --git a/archive/net.sourceforge.phpeclipse.wiki/build.properties b/archive/net.sourceforge.phpeclipse.wiki/build.properties new file mode 100644 index 0000000..202752c --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/build.properties @@ -0,0 +1,13 @@ +source.wiki.jar = src/ +output.wiki.jar = bin/ +bin.includes = plugin.xml,\ + wiki.jar,\ + icons/,\ + commons-httpclient-2.0.2.jar,\ + commons-logging.jar,\ + radeox.jar,\ + templates/ +src.includes = .classpath,\ + .project,\ + build.properties,\ + src/ diff --git a/archive/net.sourceforge.phpeclipse.wiki/build.xml b/archive/net.sourceforge.phpeclipse.wiki/build.xml new file mode 100644 index 0000000..4ad0f51 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/build.xml @@ -0,0 +1,182 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/archive/net.sourceforge.phpeclipse.wiki/icons/full/glyphs/glyph1.gif b/archive/net.sourceforge.phpeclipse.wiki/icons/full/glyphs/glyph1.gif new file mode 100644 index 0000000..28466aa Binary files /dev/null and b/archive/net.sourceforge.phpeclipse.wiki/icons/full/glyphs/glyph1.gif differ diff --git a/archive/net.sourceforge.phpeclipse.wiki/icons/full/glyphs/glyph2.gif b/archive/net.sourceforge.phpeclipse.wiki/icons/full/glyphs/glyph2.gif new file mode 100644 index 0000000..ef51bd5 Binary files /dev/null and b/archive/net.sourceforge.phpeclipse.wiki/icons/full/glyphs/glyph2.gif differ diff --git a/archive/net.sourceforge.phpeclipse.wiki/icons/full/glyphs/glyph3.gif b/archive/net.sourceforge.phpeclipse.wiki/icons/full/glyphs/glyph3.gif new file mode 100644 index 0000000..f53f01b Binary files /dev/null and b/archive/net.sourceforge.phpeclipse.wiki/icons/full/glyphs/glyph3.gif differ diff --git a/archive/net.sourceforge.phpeclipse.wiki/icons/full/glyphs/glyph4.gif b/archive/net.sourceforge.phpeclipse.wiki/icons/full/glyphs/glyph4.gif new file mode 100644 index 0000000..27506f6 Binary files /dev/null and b/archive/net.sourceforge.phpeclipse.wiki/icons/full/glyphs/glyph4.gif differ diff --git a/archive/net.sourceforge.phpeclipse.wiki/icons/full/glyphs/glyph5.gif b/archive/net.sourceforge.phpeclipse.wiki/icons/full/glyphs/glyph5.gif new file mode 100644 index 0000000..1bccaf8 Binary files /dev/null and b/archive/net.sourceforge.phpeclipse.wiki/icons/full/glyphs/glyph5.gif differ diff --git a/archive/net.sourceforge.phpeclipse.wiki/icons/full/glyphs/glyph6.gif b/archive/net.sourceforge.phpeclipse.wiki/icons/full/glyphs/glyph6.gif new file mode 100644 index 0000000..0716475 Binary files /dev/null and b/archive/net.sourceforge.phpeclipse.wiki/icons/full/glyphs/glyph6.gif differ diff --git a/archive/net.sourceforge.phpeclipse.wiki/icons/full/glyphs/glyph7.gif b/archive/net.sourceforge.phpeclipse.wiki/icons/full/glyphs/glyph7.gif new file mode 100644 index 0000000..32b655e Binary files /dev/null and b/archive/net.sourceforge.phpeclipse.wiki/icons/full/glyphs/glyph7.gif differ diff --git a/archive/net.sourceforge.phpeclipse.wiki/icons/full/glyphs/glyph8.gif b/archive/net.sourceforge.phpeclipse.wiki/icons/full/glyphs/glyph8.gif new file mode 100644 index 0000000..5952ed9 Binary files /dev/null and b/archive/net.sourceforge.phpeclipse.wiki/icons/full/glyphs/glyph8.gif differ diff --git a/archive/net.sourceforge.phpeclipse.wiki/icons/full/wizban/keylock.gif b/archive/net.sourceforge.phpeclipse.wiki/icons/full/wizban/keylock.gif new file mode 100644 index 0000000..2efb6ff Binary files /dev/null and b/archive/net.sourceforge.phpeclipse.wiki/icons/full/wizban/keylock.gif differ diff --git a/archive/net.sourceforge.phpeclipse.wiki/icons/monitorOff.gif b/archive/net.sourceforge.phpeclipse.wiki/icons/monitorOff.gif new file mode 100644 index 0000000..42e5f31 Binary files /dev/null and b/archive/net.sourceforge.phpeclipse.wiki/icons/monitorOff.gif differ diff --git a/archive/net.sourceforge.phpeclipse.wiki/icons/monitorOn.gif b/archive/net.sourceforge.phpeclipse.wiki/icons/monitorOn.gif new file mode 100644 index 0000000..2ff3974 Binary files /dev/null and b/archive/net.sourceforge.phpeclipse.wiki/icons/monitorOn.gif differ diff --git a/archive/net.sourceforge.phpeclipse.wiki/icons/occurrence.gif b/archive/net.sourceforge.phpeclipse.wiki/icons/occurrence.gif new file mode 100644 index 0000000..7b1efa5 Binary files /dev/null and b/archive/net.sourceforge.phpeclipse.wiki/icons/occurrence.gif differ diff --git a/archive/net.sourceforge.phpeclipse.wiki/icons/preparation.gif b/archive/net.sourceforge.phpeclipse.wiki/icons/preparation.gif new file mode 100644 index 0000000..f1e585b Binary files /dev/null and b/archive/net.sourceforge.phpeclipse.wiki/icons/preparation.gif differ diff --git a/archive/net.sourceforge.phpeclipse.wiki/icons/step.gif b/archive/net.sourceforge.phpeclipse.wiki/icons/step.gif new file mode 100644 index 0000000..25c66a1 Binary files /dev/null and b/archive/net.sourceforge.phpeclipse.wiki/icons/step.gif differ diff --git a/archive/net.sourceforge.phpeclipse.wiki/icons/template.gif b/archive/net.sourceforge.phpeclipse.wiki/icons/template.gif new file mode 100644 index 0000000..65c2632 Binary files /dev/null and b/archive/net.sourceforge.phpeclipse.wiki/icons/template.gif differ diff --git a/archive/net.sourceforge.phpeclipse.wiki/icons/text.gif b/archive/net.sourceforge.phpeclipse.wiki/icons/text.gif new file mode 100644 index 0000000..9312d7e Binary files /dev/null and b/archive/net.sourceforge.phpeclipse.wiki/icons/text.gif differ diff --git a/archive/net.sourceforge.phpeclipse.wiki/lib/commons-httpclient-2.0.2.jar b/archive/net.sourceforge.phpeclipse.wiki/lib/commons-httpclient-2.0.2.jar new file mode 100644 index 0000000..c5c52ad Binary files /dev/null and b/archive/net.sourceforge.phpeclipse.wiki/lib/commons-httpclient-2.0.2.jar differ diff --git a/archive/net.sourceforge.phpeclipse.wiki/lib/commons-logging.jar b/archive/net.sourceforge.phpeclipse.wiki/lib/commons-logging.jar new file mode 100644 index 0000000..b99c937 Binary files /dev/null and b/archive/net.sourceforge.phpeclipse.wiki/lib/commons-logging.jar differ diff --git a/archive/net.sourceforge.phpeclipse.wiki/lib/java2html_4.1.jar b/archive/net.sourceforge.phpeclipse.wiki/lib/java2html_4.1.jar new file mode 100644 index 0000000..f35dd46 Binary files /dev/null and b/archive/net.sourceforge.phpeclipse.wiki/lib/java2html_4.1.jar differ diff --git a/archive/net.sourceforge.phpeclipse.wiki/lib/plog4u.jar b/archive/net.sourceforge.phpeclipse.wiki/lib/plog4u.jar new file mode 100644 index 0000000..abe7273 Binary files /dev/null and b/archive/net.sourceforge.phpeclipse.wiki/lib/plog4u.jar differ diff --git a/archive/net.sourceforge.phpeclipse.wiki/lib/radeox.jar b/archive/net.sourceforge.phpeclipse.wiki/lib/radeox.jar new file mode 100644 index 0000000..5960bf6 Binary files /dev/null and b/archive/net.sourceforge.phpeclipse.wiki/lib/radeox.jar differ diff --git a/archive/net.sourceforge.phpeclipse.wiki/lib/xmlrpc-1.1.jar b/archive/net.sourceforge.phpeclipse.wiki/lib/xmlrpc-1.1.jar new file mode 100644 index 0000000..b360b03 Binary files /dev/null and b/archive/net.sourceforge.phpeclipse.wiki/lib/xmlrpc-1.1.jar differ diff --git a/archive/net.sourceforge.phpeclipse.wiki/plugin.properties b/archive/net.sourceforge.phpeclipse.wiki/plugin.properties new file mode 100644 index 0000000..e3fe00c --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/plugin.properties @@ -0,0 +1,26 @@ +MediaWiki.label=Wikipedia +HTTPQuery.label=HTTP Query + +# --------------- General UI --------------- +preferenceDescription=Configure HTTP Actions for your Wiki texts. +configurationsList=Configurations +columnUser=User Name +columnURL=URL +columnType=Type +columnStatus=Active +add=Add... +edit=Edit... +remove=Remove +start=Activate +stop=Deactivate +started=True +stopped=False + +newConfig=New Configuration +editConfig=Edit Configuration + +user=User: +remoteGroup=Configuration +url=URL: +password=Password: +parseType=Type: diff --git a/archive/net.sourceforge.phpeclipse.wiki/plugin.xml b/archive/net.sourceforge.phpeclipse.wiki/plugin.xml new file mode 100644 index 0000000..9cce801 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/plugin.xml @@ -0,0 +1,384 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/actions/NewPostBlogEditorAction.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/actions/NewPostBlogEditorAction.java new file mode 100644 index 0000000..c402bed --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/actions/NewPostBlogEditorAction.java @@ -0,0 +1,136 @@ +package net.sourceforge.phpeclipse.wiki.actions; + +import java.util.ArrayList; +import java.util.List; + +import net.sourceforge.phpeclipse.wiki.blog.Configuration; +import net.sourceforge.phpeclipse.wiki.blog.MetaWeblog; +import net.sourceforge.phpeclipse.wiki.builder.CreatePageAction; +import net.sourceforge.phpeclipse.wiki.editor.WikiEditor; +import net.sourceforge.phpeclipse.wiki.preferences.Util; +import net.sourceforge.phpeclipse.wiki.renderer.IContentRenderer; +import net.sourceforge.phpeclipse.wiki.renderer.RendererFactory; + +import org.eclipse.core.resources.IFile; +import org.eclipse.jface.action.IAction; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.text.TextSelection; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.ui.IEditorActionDelegate; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.IFileEditorInput; +import org.eclipse.ui.IWorkbenchWindow; +import org.eclipse.ui.texteditor.AbstractTextEditor; + +public final class NewPostBlogEditorAction implements IEditorActionDelegate { + // public static String APPKEY = + // "1c0c75ffffffb512ffffff9575ffffff97ffffffd2ffffff87ffffff91ffffffe41dffffffc5320cffffffab544effffffc0546459ffffff83"; + + private IWorkbenchWindow window; + + private AbstractTextEditor fEditor; + + public void dispose() { + } + + public void init(IWorkbenchWindow window) { + this.window = window; + } + + public void selectionChanged(IAction action, ISelection selection) { + if (selection.isEmpty()) { + return; + } + if (selection instanceof TextSelection) { + action.setEnabled(true); + return; + } + if (window.getActivePage() != null && window.getActivePage().getActivePart() != null) { + action.setEnabled(window.getActivePage().getActivePart().getClass().equals(WikiEditor.class)); + } + } + + public void run(IAction action) { + if (fEditor == null) { + IEditorPart targetEditor = window.getActivePage().getActiveEditor(); + if (targetEditor != null && (targetEditor instanceof AbstractTextEditor)) { + fEditor = (AbstractTextEditor) targetEditor; + } + } + if (fEditor != null) { + try { + Configuration config = new Configuration("http://localhost:8080/snip/RPC2", "1", "admin", "admin"); + IFileEditorInput ei = (IFileEditorInput) fEditor.getEditorInput(); + IFile file = ei.getFile(); + StringBuffer htmlBuffer = new StringBuffer(); + CreatePageAction.getWikiBuffer(htmlBuffer,file); + + ArrayList images = new ArrayList(); + getImages(htmlBuffer, images); + + String[] result = new String[2]; + boolean cache = config.promptForPassword(config.getUser(), "Insert Config", true, result); + if (result[0] == null || result[1] == null) { + return; + } + if (result[0].equals("") || result[1].equals("")) { + return; + } + + String title = Util.getWikiTitle(file); + if (title != null) { + MetaWeblog metaWebLog = new MetaWeblog(config); + String guid = metaWebLog.newPost(file, title, htmlBuffer, true); + System.out.println(guid); + + if (images.size() > 0) { + String fullImagePath; + String filePath = file.getLocation().toString(); + int index = filePath.lastIndexOf('/'); + if (index>=0) { + filePath = filePath.substring(0,index+1); + } + for (int i = 0; i < images.size(); i++) { + fullImagePath = filePath+"Image/"+images.get(i).toString(); + metaWebLog.publishAttachement(guid, fullImagePath, false); + } + } + } else { + MessageDialog.openError(null, "Undefined Blog Title: ", "Blog file name must end with *.wp"); + } + } catch (Exception e) { + MessageDialog.openError(null, "Exception: ", e.toString()); + e.printStackTrace(); + } + } + } + + /** + * @param content the wikitext + * @param images result List of image names + */ + private void getImages(StringBuffer content, List images) { + int startIndex = 0; + int endIndex = 0; + String imageName; + while (startIndex >= 0) { + startIndex = content.indexOf("[[Image:", startIndex); + if (startIndex >= 0) { + endIndex = content.indexOf("]]", startIndex + 8); + if (endIndex < 0) { + return; + } + imageName = content.substring(startIndex + 8, endIndex); + images.add(imageName); + startIndex += 8; + } + } + } + + public void setActiveEditor(IAction action, IEditorPart targetEditor) { + if (targetEditor != null && (targetEditor instanceof AbstractTextEditor)) { + fEditor = (AbstractTextEditor) targetEditor; + } + } + +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/actions/NewPostBlogHTMLAction.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/actions/NewPostBlogHTMLAction.java new file mode 100644 index 0000000..510eba4 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/actions/NewPostBlogHTMLAction.java @@ -0,0 +1,118 @@ +package net.sourceforge.phpeclipse.wiki.actions; + +import net.sourceforge.phpeclipse.wiki.blog.Configuration; +import net.sourceforge.phpeclipse.wiki.blog.MetaWeblog; +import net.sourceforge.phpeclipse.wiki.builder.CreatePageAction; +import net.sourceforge.phpeclipse.wiki.editor.WikiEditor; +import net.sourceforge.phpeclipse.wiki.preferences.Util; +import net.sourceforge.phpeclipse.wiki.renderer.IContentRenderer; +import net.sourceforge.phpeclipse.wiki.renderer.RendererFactory; + +import org.eclipse.core.resources.IFile; +import org.eclipse.jface.action.IAction; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.text.TextSelection; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.ui.IEditorActionDelegate; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.IFileEditorInput; +import org.eclipse.ui.IWorkbenchWindow; +import org.eclipse.ui.texteditor.AbstractTextEditor; + +public final class NewPostBlogHTMLAction implements IEditorActionDelegate { + // public static String APPKEY = + // "1c0c75ffffffb512ffffff9575ffffff97ffffffd2ffffff87ffffff91ffffffe41dffffffc5320cffffffab544effffffc0546459ffffff83"; + + private IWorkbenchWindow window; + + private AbstractTextEditor fEditor; + + public void dispose() { + } + + public void init(IWorkbenchWindow window) { + this.window = window; + } + + public void selectionChanged(IAction action, ISelection selection) { + if (selection.isEmpty()) { + return; + } + if (selection instanceof TextSelection) { + action.setEnabled(true); + return; + } + if (window.getActivePage() != null && window.getActivePage().getActivePart() != null) { + action.setEnabled(window.getActivePage().getActivePart().getClass().equals(WikiEditor.class)); + } + } + + public void run(IAction action) { + if (fEditor == null) { + IEditorPart targetEditor = window.getActivePage().getActiveEditor(); + if (targetEditor != null && (targetEditor instanceof AbstractTextEditor)) { + fEditor = (AbstractTextEditor) targetEditor; + } + } + if (fEditor != null) { + try { + Configuration config = new Configuration("http://localhost:8080/blog/default", "1", "root", "******"); + IFileEditorInput ei = (IFileEditorInput) fEditor.getEditorInput(); + IFile file = ei.getFile(); + IContentRenderer renderer = RendererFactory.createContentRenderer(file.getProject()); + StringBuffer htmlBuffer = new StringBuffer(); + CreatePageAction.convertWikiBuffer(htmlBuffer, file, renderer, false); + + String[] result = new String[2]; + boolean cache = config.promptForPassword(config.getUser(), "Insert Config", true, result); + if (result[0] == null || result[1] == null) { + return; + } + if (result[0].equals("") || result[1].equals("") ) { + return; + } + + String title = Util.getWikiTitle(file); + if (title != null) { + MetaWeblog metaWebLog = new MetaWeblog(config); + String guid = metaWebLog.newPost(file, title, htmlBuffer, true); + System.out.println(guid); + } else { + MessageDialog.openError(null, "Undefined Blog Title: ", "Blog file name must end with *.wp"); + } + } catch (Exception e) { + MessageDialog.openError(null, "Exception: ", e.toString()); + e.printStackTrace(); + } + // try { + // IFileEditorInput ei = (IFileEditorInput) fEditor.getEditorInput(); + // IFile file = ei.getFile(); + // IContentRenderer renderer = RendererFactory.createContentRenderer(file.getProject()); + // StringBuffer htmlBuffer = new StringBuffer(); + // CreatePageAction.convertWikiBuffer(htmlBuffer, file, renderer, false); + // XmlRpcClientLite xmlrpc = new XmlRpcClientLite("http://www.plog4u.de/xmlrpc.php"); + // Vector rpcParams = new Vector(); + // rpcParams.add(APPKEY); + // rpcParams.add("1"); // blog.getBlogId()); + // rpcParams.add("admin"); + // rpcParams.add("******"); // fPassword + // rpcParams.add(htmlBuffer.toString()); //getContent()); + // rpcParams.add(Boolean.TRUE); // publish == yes + // + // String postId = (String) xmlrpc.execute("blogger.newPost", rpcParams); + // + // // return postId; + // } catch (Exception e) { + // e.printStackTrace(); + // // return null; + // } + } + } + + public void setActiveEditor(IAction action, IEditorPart targetEditor) { + if (targetEditor != null && (targetEditor instanceof AbstractTextEditor)) { + fEditor = (AbstractTextEditor) targetEditor; + } + } + +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/actions/OpenWikiLinkEditorAction.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/actions/OpenWikiLinkEditorAction.java new file mode 100644 index 0000000..de7a91f --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/actions/OpenWikiLinkEditorAction.java @@ -0,0 +1,227 @@ +package net.sourceforge.phpeclipse.wiki.actions; + +import java.io.ByteArrayInputStream; + +import net.sourceforge.phpeclipse.wiki.editor.WikiEditor; +import net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin; +import net.sourceforge.phpeclipse.wiki.preferences.Util; + +import org.eclipse.core.resources.IContainer; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IFolder; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IResourceStatus; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.Path; +import org.eclipse.core.runtime.SubProgressMonitor; +import org.eclipse.jface.action.IAction; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.ITextSelection; +import org.eclipse.jface.text.TextSelection; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.ui.IEditorActionDelegate; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.IFileEditorInput; +import org.eclipse.ui.IWorkbenchWindow; +import org.eclipse.ui.ide.IDE; +import org.eclipse.ui.internal.ide.IDEWorkbenchPlugin; +import org.eclipse.ui.texteditor.AbstractTextEditor; + +public final class OpenWikiLinkEditorAction implements IEditorActionDelegate { + + private IWorkbenchWindow window; + + private AbstractTextEditor editor; + + public void dispose() { + } + + public void init(IWorkbenchWindow window) { + this.window = window; + } + + public void selectionChanged(IAction action, ISelection selection) { + if (selection.isEmpty()) { + return; + } + if (selection instanceof TextSelection) { + action.setEnabled(true); + return; + } + if (window.getActivePage() != null && window.getActivePage().getActivePart() != null) { + action.setEnabled(window.getActivePage().getActivePart().getClass().equals(WikiEditor.class)); + } + } + + public void run(IAction action) { + if (editor == null) { + IEditorPart targetEditor = window.getActivePage().getActiveEditor(); + if (targetEditor != null && (targetEditor instanceof AbstractTextEditor)) { + editor = (AbstractTextEditor) targetEditor; + } + } + if (editor != null) { + openWikiLinkOnSelection(); + } + } + + public void setActiveEditor(IAction action, IEditorPart targetEditor) { + if (targetEditor != null && (targetEditor instanceof AbstractTextEditor)) { + editor = (AbstractTextEditor) targetEditor; + } + } + + public static String getWikiString(AbstractTextEditor editor, IDocument document, int initialPos) { + try { + int pos = initialPos; + int line = document.getLineOfOffset(pos); + int start = document.getLineOffset(line); + int end = start + document.getLineInformation(line).getLength(); + + /* + * 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 + * determining the TextRegion at the cursor position + */ + if (pos > end) { + pos = end; + } + + int offsetInLine = pos - start; + String word = document.get(start, end - start); + int wordlen = word.length(); + int wikiLinkStart = -1; + int wikiLinkEnd = -1; + + for (int i = offsetInLine; i < wordlen; i++) { + if (word.charAt(i) == ']' && i < wordlen - 1 && word.charAt(i + 1) == ']') { + wikiLinkEnd = i; + break; + } + if (word.charAt(i) == '|') { + wikiLinkEnd = i; + break; + } + if (word.charAt(i) == '#') { + wikiLinkEnd = i; + break; + } + } + for (int i = offsetInLine; i >= 0; i--) { + if (word.charAt(i) == '[' && i > 0 && word.charAt(i - 1) == '[') { + wikiLinkStart = i + 1; + break; + } + if (word.charAt(i) == '|') { // links wih different description + wikiLinkEnd = i; + } + if (word.charAt(i) == '#') { // for links with anchors + wikiLinkEnd = i; + } + } + if (wikiLinkStart != (-1) && wikiLinkEnd != (-1) && wikiLinkStart < wikiLinkEnd) { + return new String(word.toCharArray(), wikiLinkStart, wikiLinkEnd - wikiLinkStart); + } + } catch (BadLocationException e) { + + } + return ""; + } + + public IDocument getDocument() { + IDocument doc = editor.getDocumentProvider().getDocument(editor.getEditorInput()); + return doc; + } + + public void openWikiLinkOnSelection() { + IDocument doc = getDocument(); + ITextSelection selection = (ITextSelection) editor.getSelectionProvider().getSelection(); + int pos = selection.getOffset(); + + String textRegion = getWikiString(editor, doc, pos); + IFileEditorInput ei = (IFileEditorInput) editor.getEditorInput(); + openWikiFile(ei.getFile(), textRegion); + } + + void openWikiFile(IFile cfile, String word) { + if (word != null && !word.equals("")) { + IFile file = getWikiFile(cfile, word); + try { + createNewFileIfNeeded(file, word); + // if (WikiEditorPlugin.getDefault().getPreferenceStore().getBoolean(WikiConstants.REUSE_EDITOR)) { + // saveIfNeeded(); + // getActivePage().reuseEditor(reusableEditor, new FileEditorInput(file)); + // } else { + IDE.openEditor(WikiEditorPlugin.getDefault().getActivePage(), file, true); + // redrawText(); + // } + } catch (Exception e) { + // WikiEditorPlugin.getDefault().logAndReport(WikiEditorPlugin.getResourceString(WikiConstants.RESOURCE_WIKI_ERROR_DIALOGUE_OPEN_WIKI_FILE_TITLE), + // WikiPlugin.getResourceString(WikiConstants.RESOURCE_WIKI_ERROR_DIALOGUE_OPEN_WIKI_FILE_TEXT), e); + } + } + } + + private void createNewFileIfNeeded(IFile file, String word) throws CoreException { + if (!file.exists()) { + createWikiFile(file, word); + } + } + + private IFile getWikiFile(IFile file, String word) { + String wikiFileName = Util.getWikiFileName(word, file, WikiEditorPlugin.HTML_OUTPUT_PATH); + IPath path = new Path(wikiFileName); + return ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(path); + } + + /** + * Creates a folder resource handle for the folder with the given workspace path. This method does not create the folder resource; + * this is the responsibility of createFolder. + * + * @param folderPath + * the path of the folder resource to create a handle for + * @return the new folder resource handle + * @see #createFolder + */ + private IFolder createFolderHandle(IPath folderPath) { + return IDEWorkbenchPlugin.getPluginWorkspace().getRoot().getFolder(folderPath); + } + + private void createFolder(IFolder folderHandle, IProgressMonitor monitor) throws CoreException { + try { + // Create the folder resource in the workspace + // Recursive to create any folders which do not exist already + if (!folderHandle.exists()) { + IContainer parent = folderHandle.getParent(); + if (parent instanceof IFolder && (!((IFolder) parent).exists())) { + createFolder((IFolder) parent, monitor); + } + // if (linkTargetPath != null) + // folderHandle.createLink(linkTargetPath, IResource.ALLOW_MISSING_LOCAL, monitor); + // else + folderHandle.create(false, true, monitor); + } + } catch (CoreException e) { + // If the folder already existed locally, just refresh to get contents + if (e.getStatus().getCode() == IResourceStatus.PATH_OCCUPIED) + folderHandle.refreshLocal(IResource.DEPTH_INFINITE, new SubProgressMonitor(monitor, 500)); + else + throw e; + } + } + + private void createWikiFile(IFile file, String word) throws CoreException { + IContainer parent = file.getParent(); + if (parent instanceof IFolder && (!((IFolder) parent).exists())) { + createFolder((IFolder) parent, null); + } + String newText = ""; + byte[] buffer = newText.getBytes(); + ByteArrayInputStream source = new ByteArrayInputStream(buffer); + file.create(source, true, null); + } + +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/actions/httpquery/AbstractHTTPQueryAction.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/actions/httpquery/AbstractHTTPQueryAction.java new file mode 100644 index 0000000..32e155c --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/actions/httpquery/AbstractHTTPQueryAction.java @@ -0,0 +1,96 @@ +package net.sourceforge.phpeclipse.wiki.actions.httpquery; + +import java.net.URL; +import java.text.BreakIterator; + +import net.sourceforge.phpeclipse.webbrowser.views.BrowserView; + +import org.eclipse.jface.action.IAction; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.ITextSelection; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.ui.IEditorActionDelegate; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.IViewPart; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.IWorkbenchWindow; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.texteditor.IDocumentProvider; +import org.eclipse.ui.texteditor.ITextEditor; + +public abstract class AbstractHTTPQueryAction implements IEditorActionDelegate { + + private IEditorPart targetEditor; + + public AbstractHTTPQueryAction() { + super(); + } + + public void setActiveEditor(IAction action, IEditorPart targetEditor) { + this.targetEditor = targetEditor; + } + + abstract protected String getUrl(String selection); + + public void run(IAction action) { + String selection = findSelectedText(); + if (selection != null && selection.trim().length() > 0) { + URL url; + IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); + if (window != null) { + IWorkbenchPage page = window.getActivePage(); + try { + IViewPart part = page.findView(BrowserView.ID_BROWSER); + if (part == null) { + part = page.showView(BrowserView.ID_BROWSER); + } else { + page.bringToTop(part); + } + String urlStr = getUrl(selection); + if (urlStr != null && !urlStr.equals("")) { + ((BrowserView) part).setUrl(urlStr); + } + } catch (Exception e) { + } + } + } + } + + public void selectionChanged(IAction action, ISelection selection) { + } + + protected String findSelectedText() { + String selectedText = null; + ITextSelection textSelection = (ITextSelection) targetEditor.getEditorSite().getSelectionProvider().getSelection(); + + selectedText = textSelection.getText(); + if (selectedText == null || selectedText.trim().length() == 0) { + selectedText = findWord(textSelection); + } + return selectedText; + } + + private String findWord(ITextSelection textSelection) { + IDocumentProvider documentProvider = ((ITextEditor) targetEditor).getDocumentProvider(); + IDocument document = documentProvider.getDocument(targetEditor.getEditorInput()); + int caretPosition = textSelection.getOffset(); + try { + IRegion line = document.getLineInformation(document.getLineOfOffset(caretPosition)); + String currentLine = document.get(line.getOffset(), line.getLength()); + int positionInLine = caretPosition - line.getOffset(); + return findWordAt(positionInLine, currentLine); + } catch (Exception e) { + } + return null; + } + + private String findWordAt(int pos, String source) { + BreakIterator boundary = BreakIterator.getWordInstance(); + boundary.setText(source); + int end = boundary.following(pos); + int start = boundary.previous(); + return source.substring(start, end); + } + +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/actions/httpquery/GoogleAction.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/actions/httpquery/GoogleAction.java new file mode 100644 index 0000000..0b293c4 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/actions/httpquery/GoogleAction.java @@ -0,0 +1,14 @@ +package net.sourceforge.phpeclipse.wiki.actions.httpquery; + + +public class GoogleAction extends AbstractHTTPQueryAction { + + public GoogleAction() { + super(); + } + + protected String getUrl(String selection) { + return "http://www.google.com/search?q=" + selection; + } + +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/actions/httpquery/HTTPQueryAction.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/actions/httpquery/HTTPQueryAction.java new file mode 100644 index 0000000..0cdfd38 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/actions/httpquery/HTTPQueryAction.java @@ -0,0 +1,51 @@ +package net.sourceforge.phpeclipse.wiki.actions.httpquery; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin; +import net.sourceforge.phpeclipse.wiki.internal.ConfigurationManager; +import net.sourceforge.phpeclipse.wiki.internal.IConfiguration; + +import org.eclipse.jface.viewers.LabelProvider; +import org.eclipse.jface.window.Window; +import org.eclipse.ui.dialogs.ListSelectionDialog; +import org.eclipse.ui.internal.dialogs.ListContentProvider; + +public class HTTPQueryAction extends AbstractHTTPQueryAction { + + public HTTPQueryAction() { + super(); + } + + protected String getUrl(String selection) { + String selectedURL = null; + + List allConfigsList = ConfigurationManager.getInstance().getConfigurations(); + ArrayList configsList = new ArrayList(); + for (int i=0;icreateFolder. + * + * @param folderPath + * the path of the folder resource to create a handle for + * @return the new folder resource handle + * @see #createFolder + */ + private IFolder createFolderHandle(IPath folderPath) { + return IDEWorkbenchPlugin.getPluginWorkspace().getRoot().getFolder(folderPath); + } + + private void createFolder(IFolder folderHandle, IProgressMonitor monitor) throws CoreException { + try { + // Create the folder resource in the workspace + // Recursive to create any folders which do not exist already + if (!folderHandle.exists()) { + IContainer parent = folderHandle.getParent(); + if (parent instanceof IFolder && (!((IFolder) parent).exists())) { + createFolder((IFolder) parent, monitor); + } + // if (linkTargetPath != null) + // folderHandle.createLink(linkTargetPath, IResource.ALLOW_MISSING_LOCAL, monitor); + // else + folderHandle.create(false, true, monitor); + } + } catch (CoreException e) { + // If the folder already existed locally, just refresh to get contents + if (e.getStatus().getCode() == IResourceStatus.PATH_OCCUPIED) + folderHandle.refreshLocal(IResource.DEPTH_INFINITE, new SubProgressMonitor(monitor, 500)); + else + throw e; + } + } + + private void createWikiFile(IFile file, String word) throws CoreException { + IContainer parent = file.getParent(); + if (parent instanceof IFolder && (!((IFolder) parent).exists())) { + createFolder((IFolder) parent, null); + } + String newText = ""; + byte[] buffer = newText.getBytes(); + ByteArrayInputStream source = new ByteArrayInputStream(buffer); + file.create(source, true, null); + } + +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/actions/mediawiki/MediaWikiConnector.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/actions/mediawiki/MediaWikiConnector.java new file mode 100644 index 0000000..c9d2bda --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/actions/mediawiki/MediaWikiConnector.java @@ -0,0 +1,111 @@ +package net.sourceforge.phpeclipse.wiki.actions.mediawiki; + +import java.io.IOException; +import java.io.InputStream; +import java.io.StringReader; + +import net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin; + +import org.apache.commons.httpclient.ConnectMethod; +import org.apache.commons.httpclient.HttpConnection; +import org.apache.commons.httpclient.HttpMethod; +import org.apache.commons.httpclient.HttpState; +import org.apache.commons.httpclient.HttpStatus; +import org.apache.commons.httpclient.URI; +import org.apache.commons.httpclient.UsernamePasswordCredentials; +import org.apache.commons.httpclient.methods.GetMethod; +import org.apache.commons.httpclient.protocol.Protocol; + +/** + * This class gets the wikitext from a wikipedia edit page + * + * The basic coding was copied from the commons-httpclient example MediaWikiConnector.java + */ +public class MediaWikiConnector { + + /** + * Get the text of a wikimedia Wiki-Description from en.wikipedia.org + * + */ + public static String getWikiText(String wikiDescriptor) { + return getWikiText(wikiDescriptor, null); + } + + /** + * Get the text of a wikimedia Wiki-Description + * + */ + public static String getWikiText(String wikiDescriptor, String urlStr) { + // examples + // http://en.wikipedia.org/w/wiki.phtml?title=Main_Page&action=edit + // http://en.wikibooks.org/w/wiki.phtml?title=Programming:PHP:SQL_Injection&action=edit + // http://en.wikipedia.org/w/wiki.phtml?title=Talk:Division_by_zero&action=edit + HttpMethod method = null; + try { + if (urlStr == null) { + urlStr = "http://en.wikipedia.org/w/wiki.phtml?title=" + wikiDescriptor + "&action=edit"; + } else { + urlStr = urlStr + "?title=" + wikiDescriptor + "&action=edit"; + } + URI uri = new URI(urlStr.toCharArray()); + + String schema = uri.getScheme(); + if ((schema == null) || (schema.equals(""))) { + schema = "http"; + } + Protocol protocol = Protocol.getProtocol(schema); + + HttpState state = new HttpState(); + + method = new GetMethod(uri.toString()); + String host = uri.getHost(); + int port = uri.getPort(); + + HttpConnection connection = new HttpConnection(host, port, protocol); + + connection.setProxyHost(System.getProperty("http.proxyHost")); + connection.setProxyPort(Integer.parseInt(System.getProperty("http.proxyPort", "80"))); + + if (System.getProperty("http.proxyUserName") != null) { + state.setProxyCredentials(null, null, new UsernamePasswordCredentials(System.getProperty("http.proxyUserName"), System + .getProperty("http.proxyPassword"))); + } + + if (connection.isProxied() && connection.isSecure()) { + method = new ConnectMethod(method); + } + + method.execute(state, connection); + + if (method.getStatusCode() == HttpStatus.SC_OK) { + // get the textareas wiki text now: + InputStream stream = method.getResponseBodyAsStream(); + int byteLen = stream.available(); + int count = 1; + byte[] buffer = new byte[byteLen]; + stream.read(buffer, 0, byteLen); + String wikiText = new String(buffer); +// String wikiText = method.getResponseBodyAsString(); + int start = wikiText.indexOf("", start + 1); + if (start != (-1)) { + int end = wikiText.indexOf(""); + wikiText = wikiText.substring(start + 1, end); + } + } + return wikiText; + // System.out.println(wikiText); + + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (method != null) { + method.releaseConnection(); + } + } + return null; // no success in getting wiki text + } +} + diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/actions/mediawiki/RefreshWikiTextEditorAction.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/actions/mediawiki/RefreshWikiTextEditorAction.java new file mode 100644 index 0000000..f00d446 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/actions/mediawiki/RefreshWikiTextEditorAction.java @@ -0,0 +1,195 @@ +package net.sourceforge.phpeclipse.wiki.actions.mediawiki; + +import java.io.ByteArrayInputStream; +import java.util.ArrayList; +import java.util.Collections; + +import net.sourceforge.phpeclipse.wiki.editor.WikiEditor; +import net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin; +import net.sourceforge.phpeclipse.wiki.preferences.Util; + +import org.eclipse.core.resources.IContainer; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IFolder; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IResourceStatus; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.SubProgressMonitor; +import org.eclipse.jface.action.IAction; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.ITextSelection; +import org.eclipse.jface.text.TextSelection; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.LabelProvider; +import org.eclipse.jface.window.Window; +import org.eclipse.ui.IEditorActionDelegate; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.IFileEditorInput; +import org.eclipse.ui.IWorkbenchWindow; +import org.eclipse.ui.dialogs.ListSelectionDialog; +import org.eclipse.ui.internal.dialogs.ListContentProvider; +import org.eclipse.ui.internal.ide.IDEWorkbenchPlugin; +import org.eclipse.ui.texteditor.AbstractTextEditor; + +public final class RefreshWikiTextEditorAction implements IEditorActionDelegate { + + private IWorkbenchWindow window; + + private AbstractTextEditor fEditor; + + public void dispose() { + } + + public void init(IWorkbenchWindow window) { + this.window = window; + } + + public void selectionChanged(IAction action, ISelection selection) { + if (selection.isEmpty()) { + return; + } + if (selection instanceof TextSelection) { + action.setEnabled(true); + return; + } + if (window.getActivePage() != null && window.getActivePage().getActivePart() != null) { + action.setEnabled(window.getActivePage().getActivePart().getClass().equals(WikiEditor.class)); + } + } + + public void run(IAction action) { + if (fEditor == null) { + IEditorPart targetEditor = window.getActivePage().getActiveEditor(); + if (targetEditor != null && (targetEditor instanceof AbstractTextEditor)) { + fEditor = (AbstractTextEditor) targetEditor; + } + } + if (fEditor != null) { + openWikiLinkOnSelection(); + } + } + + public void setActiveEditor(IAction action, IEditorPart targetEditor) { + if (targetEditor != null && (targetEditor instanceof AbstractTextEditor)) { + fEditor = (AbstractTextEditor) targetEditor; + } + } + + public IDocument getDocument() { + IDocument doc = fEditor.getDocumentProvider().getDocument(fEditor.getEditorInput()); + return doc; + } + + public void openWikiLinkOnSelection() { + IDocument doc = getDocument(); + ITextSelection selection = (ITextSelection) fEditor.getSelectionProvider().getSelection(); + int pos = selection.getOffset(); + // String textRegion = getWikiString(fEditor, doc, pos); + IFileEditorInput ei = (IFileEditorInput) fEditor.getEditorInput(); + openWikiFile(ei.getFile()); + } + + void openWikiFile(IFile cfile) { + String wikiName = getWikiFile(cfile); + try { + if (fEditor != null) { + selectWiki(wikiName); + } + } catch (Exception e) { + } + + } + + private void selectWiki(String wikiName) { + String exampleWikiURL = "http://en.wikibooks.org/w/wiki.phtml"; + String selectedWikiURL = null; + ArrayList locationsList = new ArrayList(); + locationsList.add(exampleWikiURL); + + Collections.sort(locationsList); + + ListSelectionDialog listSelectionDialog = new ListSelectionDialog(WikiEditorPlugin.getDefault().getWorkbench() + .getActiveWorkbenchWindow().getShell(), locationsList, new ListContentProvider(), new LabelProvider(), + "Select the refresh URL."); + listSelectionDialog.setTitle("Multiple active configuration found"); + if (listSelectionDialog.open() == Window.OK) { + Object[] locations = listSelectionDialog.getResult(); + if (locations != null) { + for (int i = 0; i < locations.length; i++) { + selectedWikiURL = (String) locations[i]; + break; + } + } + } + + if (selectedWikiURL != null && !selectedWikiURL.equals("")) { + String wikiContent = MediaWikiConnector.getWikiText(wikiName, selectedWikiURL); + if (wikiContent != null) { + IDocument doc = fEditor.getDocumentProvider().getDocument(fEditor.getEditorInput()); + doc.set(wikiContent); + } + } + } + + private void createNewFileIfNeeded(IFile file, String word) throws CoreException { + if (!file.exists()) { + createWikiFile(file, word); + } + } + + private String getWikiFile(IFile file) { + return Util.getFileWikiName(file, WikiEditorPlugin.HTML_OUTPUT_PATH); + // IPath path = new Path(wikiFileName); + // return ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(path); + } + + /** + * Creates a folder resource handle for the folder with the given workspace path. This method does not create the folder resource; + * this is the responsibility of createFolder. + * + * @param folderPath + * the path of the folder resource to create a handle for + * @return the new folder resource handle + * @see #createFolder + */ + private IFolder createFolderHandle(IPath folderPath) { + return IDEWorkbenchPlugin.getPluginWorkspace().getRoot().getFolder(folderPath); + } + + private void createFolder(IFolder folderHandle, IProgressMonitor monitor) throws CoreException { + try { + // Create the folder resource in the workspace + // Recursive to create any folders which do not exist already + if (!folderHandle.exists()) { + IContainer parent = folderHandle.getParent(); + if (parent instanceof IFolder && (!((IFolder) parent).exists())) { + createFolder((IFolder) parent, monitor); + } + // if (linkTargetPath != null) + // folderHandle.createLink(linkTargetPath, IResource.ALLOW_MISSING_LOCAL, monitor); + // else + folderHandle.create(false, true, monitor); + } + } catch (CoreException e) { + // If the folder already existed locally, just refresh to get contents + if (e.getStatus().getCode() == IResourceStatus.PATH_OCCUPIED) + folderHandle.refreshLocal(IResource.DEPTH_INFINITE, new SubProgressMonitor(monitor, 500)); + else + throw e; + } + } + + private void createWikiFile(IFile file, String word) throws CoreException { + IContainer parent = file.getParent(); + if (parent instanceof IFolder && (!((IFolder) parent).exists())) { + createFolder((IFolder) parent, null); + } + String newText = ""; + byte[] buffer = newText.getBytes(); + ByteArrayInputStream source = new ByteArrayInputStream(buffer); + file.create(source, true, null); + } + +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/actions/mediawiki/main.css b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/actions/mediawiki/main.css new file mode 100644 index 0000000..ca8e627 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/actions/mediawiki/main.css @@ -0,0 +1,908 @@ +/* +** Mediawiki 'monobook' style sheet for CSS2-capable browsers. +** Copyright Gabriel Wicke - http://wikidev.net/ +** License: GPL +** +** Loosely based on http://www.positioniseverything.net/ordered-floats.html by Big John +** and the Plone 2.0 styles, see http://plone.org/ (Alexander Limi,Joe Geldart & Tom Croucher, +** Michael Zeltner and Geir Bækholt) +** All you guys rock :) +*/ + +#column-content { + width: 100%; + float: right; + margin: 0 0 0.6em -12.2em; + padding:0; +} +#content { + margin: 2.8em 0 0 12.2em; + padding: 0em 1em 1.5em 1em; + background: White; + border: 1px solid #aaaaaa; + border-right: none; + line-height: 1.5em; + position: relative; + z-index: 2; +} +#column-one { padding-top: 160px; } +/* the left column width is specified in class .portlet */ + +/* Font size: +** We take advantage of keyword scaling- browsers won't go below 9px +** More at http://www.w3.org/2003/07/30-font-size +** http://style.cleverchimp.com/font_size_intervals/altintervals.html +*/ + +body { + font: x-small sans-serif; + background: #f9f9f9 url("headbg.jpg") 0px 0px no-repeat; + color: Black; + margin: 0; + padding: 0; +} + +/* scale back up to a sane default */ +#globalWrapper { + font-size:127%; + width: 100%; + margin: 0; + padding: 0; +} +.visualClear { clear: both; } + +/* general styles */ + +table { + font-size: 100%; + background: White; +} +a { + text-decoration: none; + color: #002bb8; + background: none; +} +a:visited { color: #5a3696; } +a:active { color: Orange; } +a:hover { text-decoration: underline; } +a.stub { color: #772233; } +a.new, +#p-personal a.new { color:#ba0000; } +a.new:visited, +#p-personal a.new:visited { color:#a55858; } + +img { + border: none; + vertical-align: middle; +} +p { + margin: 0.4em 0em 0.5em 0em; + line-height: 1.5em; +} + +p img { margin: 0; } + +hr { + height: 1px; + color: #aaaaaa; + background-color: #aaaaaa; + border: 0; + margin: 0.2em 0 0.2em 0; +} + +h1, h2, h3, h4, h5, h6 { + color: Black; + background: none; + font-weight: normal; + margin: 0; + padding-top: 0.5em; + padding-bottom: 0.17em; + border-bottom: 1px solid #aaaaaa; +} +h1 { font-size: 188%; } +h2 { font-size: 150%; } +h3, h4, h5, h6 { + border-bottom: none; + font-weight: bold; +} +h3 { font-size: 132%; } +h4 { font-size: 116%; } +h5 { font-size: 100%; } +h6 { font-size: 80%; } + +ul { + line-height: 1.5em; + list-style-type: square; + margin: 0.3em 0 0 1.5em; + padding:0; + list-style-image: url("bullet.gif"); +} +ol { + line-height: 1.5em; + margin: 0.3em 0 0 3.2em; + padding:0; + list-style-image: none; +} +li { margin-bottom: 0.1em; } +dt { + font-weight: bold; + margin-bottom: 0.1em; +} +dl{ + margin-top: 0.2em; + margin-bottom: 0.5em; +} +dd { + line-height: 1.5em; + margin-left: 2em; + margin-bottom: 0.1em; +} + +fieldset { + border: 1px solid #2f6fab; + margin: 1em 0em 1em 0em; + padding: 0em 1em 1em 1em; + line-height: 1.5em; +} +legend { + background: White; + padding: 0.5em; + font-size: 95%; +} +form { + border: none; + margin: 0; +} + +textarea { + border: 1px solid #2f6fab; + color: Black; + background-color: white; + width: 100%; + padding: 0.1em; + overflow: auto; +} +/* hide this from ie/mac and konq2.2 */ +@media All { + head:first-child+body input { + visibility: visible; + border: 1px solid #2f6fab; + color: Black; + background-color: white; + vertical-align: middle; + padding: 0.2em; + } +} +input.historysubmit { + padding: 0 0.3em 0.3em 0.3em !important; + font-size: 94%; + cursor: pointer; + height: 1.7em !important; + margin-left: 1.6em; +} +input[type="radio"], +input[type="checkbox"] { border:none; } +select { + border: 1px solid #2f6fab; + color: Black; + vertical-align: top; +} +abbr, acronym, .explain { + border-bottom: 1px dotted Black; + color: Black; + background: none; + cursor: help; +} +q { + font-family: Times, "Times New Roman", serif; + font-style: italic; +} +/* disabled for now +blockquote { + font-family: Times, "Times New Roman", serif; + font-style: italic; +}*/ +code { background-color: #f9f9f9; } +pre { + padding: 1em; + border: 1px dashed #2f6fab; + color: Black; + background-color: #f9f9f9; + line-height: 1.1em; +} + + +/* +** the main content area +*/ + +#siteSub { display: none; } +#contentSub { + font-size: 84%; + line-height: 1.2em; + margin: 0 0 1.4em 1em; + color: #7d7d7d; + width: auto; +} +span.subpages { display: block; } + +/* Some space under the headers in the content area */ +#bodyContent h1, #bodyContent h2 { margin-bottom:0.6em; } +#bodyContent h3, +#bodyContent h4, +#bodyContent h5 { + margin-bottom: 0.3em; +} +.firstHeading { margin-bottom:0.1em; } + +/* user notification thing */ +.usermessage { + background-color: #ffce7b; + border: 1px solid #ffa500; + color: Black; + font-weight: bold; + margin: 2em 0em 1em 0em; + padding: 0.5em 1em; + vertical-align: middle; +} +#siteNotice { + text-align: center; + font-size: 95%; + padding: 0 0.9em 0 0.9em; +} +#siteNotice p { margin: none; padding: none; } +.error { + color: red; + font-size: larger; +} +#catlinks { + border:1px solid #aaaaaa; + background-color:#f9f9f9; + padding:5px; + margin-top: 1em; + clear: both; +} +/* currently unused, intended to be used by a metadata box +in the bottom-right corner of the content area */ +.documentDescription { + /* The summary text describing the document */ + font-weight: bold; + display: block; + margin: 1em 0em; + line-height: 1.5em; +} +.documentByLine { + text-align: right; + font-size: 90%; + clear: both; + font-weight: normal; + color: #76797c; +} + +/* emulate center */ +.center { + width: 100%; + text-align: center; +} +*.center * { + margin-left: auto; + margin-right: auto; +} +/* small for tables and similar */ +.small, .small * { font-size: 94%; } +table.small { font-size: 100% } + +/* +** content styles +*/ + +#toc { + /*border:1px solid #2f6fab;*/ + border:1px solid #aaaaaa; + background-color:#f9f9f9; + padding:5px; + font-size: 95%; +} +#toc .tocindent { margin-left: 2em; } +#toc .tocline { margin-bottom: 0px; } +#toc p { margin: 0 } +#toc .toctoggle { font-size: 94%; } +#toc .editsection { + margin-top: 0.7em; + font-size: 94%; +} + +/* images */ +div.floatright, table.floatright { + clear: right; + float: right; + margin: 0; + position: relative; + border: 0.5em solid White; + border-width: 0.5em 0 0.8em 1.4em; +} +div.floatright p { font-style: italic; } +div.floatleft, table.floatleft { + float: left; + margin: 0.3em 0.5em 0.5em 0; + position: relative; + border: 0.5em solid White; + border-width: 0.5em 1.4em 0.8em 0; +} +div.floatleft p { font-style: italic; } +/* thumbnails */ +div.thumb { + margin-bottom: 0.5em; + border-style: solid; border-color: White; + width: auto; +} +div.thumb div { + border:1px solid #cccccc; + padding: 3px !important; + background-color:#f9f9f9; + font-size: 94%; + text-align: center; + overflow: hidden; +} +div.thumb div a img { + border:1px solid #cccccc; +} +div.thumb div div.thumbcaption { + border: none; + text-align: left; + line-height: 1.4; + padding: 0.3em 0 0.1em 0; +} +div.magnify { + float: right; + border: none !important; + background: none !important; +} +div.magnify a, div.magnify img { + display: block; + border: none !important; + background: none !important; +} +div.tright { + clear: right; + float: right; + border-width: 0.5em 0 0.8em 1.4em; +} +div.tleft { + float: left; + margin-right:0.5em; + border-width: 0.5em 1.4em 0.8em 0; +} +.urlexpansion, +.hiddenStructure { + display: none; +} +img.tex { vertical-align: middle; } +span.texhtml { font-family: serif; } + +/* +** classes for special content elements like town boxes +** intended to be referenced directly from the wiki src +*/ + +/* +** User styles +*/ +/* table standards */ +table.rimage { + float:right; + position:relative; + margin-left:1em; + margin-bottom:1em; + text-align:center; +} +.toccolours { + border:1px solid #aaaaaa; + background-color:#f9f9f9; + padding:5px; + font-size: 95%; +} +div.townBox { + position:relative; + float:right; + background:White; + margin-left:1em; + border: 1px solid Grey; + padding:0.3em; + width: 200px; + overflow: hidden; + clear: right; +} +div.townBox dl { + padding: 0; + margin: 0 0 0.3em 0; + font-size: 96%; +} +div.townBox dl dt { + background: none; + margin: 0.4em 0 0 0; +} +div.townBox dl dd { + margin: 0.1em 0 0 1.1em; + background-color: #f3f3f3; +} + +/* +** edit views etc +*/ +.special li { + line-height: 1.4em; + margin: 0; + padding: 0; +} + +/* Page history styling */ +/* the auto-generated edit comments */ +.autocomment { color: gray; } +#pagehistory span.user { + margin-left: 1.4em; + margin-right: 0.4em; +} +#pagehistory span.minor { font-weight: bold; } +#pagehistory li { border: 1px solid White; } +#pagehistory li.selected { + background-color:#f9f9f9; + border:1px dashed #aaaaaa; +} +/* +** Diff rendering +*/ +table.diff { background:white; } +td.diff-otitle { background:#ffffff; } +td.diff-ntitle { background:#ffffff; } +td.diff-addedline { + background:#ccffcc; + font-size: smaller; +} +td.diff-deletedline { + background:#ffffaa; + font-size: smaller; +} +td.diff-context { + background:#eeeeee; + font-size: smaller; +} +span.diffchange { color: red; } + +/* +** keep the whitespace in front of the ^=, hides rule from konqueror +** this is css3, the validator doesn't like it when validating as css2 +*/ +#bodyContent a[href ^="http://"], +#bodyContent a[href ^="gopher://"] { + background: url(external.png) center right no-repeat; + padding-right: 13px; +} +#bodyContent a[href ^="https://"], +.link-https { + background: url("lock_icon.gif") center right no-repeat; + padding-right: 16px; +} +#bodyContent a[href ^="mailto:"], +.link-mailto { + background: url("mail_icon.gif") center right no-repeat; + padding-right: 18px; +} +#bodyContent a[href ^="news://"] { + background: url("news_icon.png") center right no-repeat; + padding-right: 18px; +} +#bodyContent a[href ^="ftp://"], +.link-ftp { + background: url("file_icon.gif") center right no-repeat; + padding-right: 18px; +} +#bodyContent a[href ^="irc://"], +.link-irc { + background: url("discussionitem_icon.gif") center right no-repeat; + padding-right: 18px; +} +/* disable interwiki styling */ +#bodyContent a.extiw, +#bodyContent a.extiw:active { + color: #3366bb; + background: none; + padding: 0; +} +#bodyContent a.external { color: #3366bb; } +/* this can be used in the content area to switch off +special external link styling */ +#bodyContent .plainlinks a { + background: none !important; + padding: 0; +} +/* +** Structural Elements +*/ + +/* +** general portlet styles (elements in the quickbar) +*/ +.portlet { + border: none; + margin: 0 0 0.5em 0em; + float: none; + padding: 0; + width: 11.6em; + overflow: hidden; +} +.portlet h4 { + font-size: 95%; + font-weight: normal; + white-space: nowrap; +} +.portlet h5 { + background: transparent; + padding: 0em 1em 0em 0.5em; + text-transform: lowercase; + display: inline; + font-size: 91%; + height: 1em; + font-weight: normal; + white-space: nowrap; +} +.portlet h6 { + background: #ffae2e; + border: 1px solid #2f6fab; + border-style: solid solid none solid; + padding: 0em 1em 0em 1em; + text-transform: lowercase; + display: block; + font-size: 1em; + height: 1.2em; + font-weight: normal; + white-space: nowrap; +} +.pBody { + font-size: 95%; + background: White; + border-collapse: collapse; + border: 1px solid #aaaaaa; + padding: 0 0.8em 0.3em 0.5em; +} +.portlet h1, +.portlet h2, +.portlet h3, +.portlet h4 { + margin: 0; + padding: 0; +} +.portlet ul { + line-height: 1.5em; + list-style-type: square; + list-style-image: url("bullet.gif"); + font-size:95%; +} +.portlet li { + padding:0; + margin: 0 0 0 0; + margin-bottom: 0; +} + +/* +** Logo properties +*/ + +#p-logo { + z-index: 3; + position:absolute; /*needed to use z-index */ + top: 0; + left: 0; + height: 155px; + width: 12em; + overflow: visible; +} +#p-logo h5 { display: none; } +#p-logo a, +#p-logo a:hover { + display: block; + height: 155px; + width: 12.2em; + background-repeat: no-repeat; + background-position: 35% 50% !important; + text-decoration: none; +} + +/* +** the navigation portlet +*/ + +#p-nav { + position:relative; + z-index:3; +} + +/* +** Search portlet +*/ +#p-search { + position:relative; + z-index:3; +} +#p-search .pBody { + text-align: center; +} +input.searchButton { + margin-top:1px; + padding: 0 0.4em !important; + font-size: 95%; + cursor: pointer; + background-color: White; + border: 1px solid #2f6fab; +} +#searchInput { + border: 1px solid #2f6fab; + width:10.9em; + margin: 0 0 0 0; + font-size: 95%; +} +#p-search .pBody { + padding: 0.5em 0.4em 0.4em 0.4em; +} + +/* +** the personal toolbar +*/ + +#p-personal { + width:100%; + white-space:nowrap; + padding:0 0 0 0; + margin:0; + position:absolute; + left:0px; + top:0px; + z-index: 0; + border: none; + background: none; + overflow: visible; + line-height: 1.2em; +} + +#p-personal h5 { + display:none; +} +#p-personal .portlet, +#p-personal .pBody { + padding:0; + margin:0; + border: none; + z-index:0; + overflow: visible; + background: none; +} +/* this is the ul contained in the portlet */ +#p-personal ul { + border: none; + line-height: 1.4em; + color: #2f6fab; + padding: 0em 2em 0 3em; + margin: 0; + text-align: right; + text-transform: lowercase; + list-style: none; + z-index:0; + background: none; +} +#p-personal li { + z-index:0; + border:none; + padding:0; + display: inline; + color: #2f6fab; + margin-left: 1em; + line-height: 1.2em; + background: none; +} +#p-personal li a { + text-decoration: none; + color: #005896; + padding-bottom: 0.2em; + background: none; +} +#p-personal li a:hover { + background-color: White; + padding-bottom: 0.2em; + text-decoration: none; +} + +/* the icon in front of the user name, single quotes +in bg url to hide it from iemac */ +li#pt-userpage, +li#pt-anonuserpage, +li#pt-login { + background: url('user.gif') top left no-repeat; + background-repeat: no-repeat; + padding-left: 20px; + text-transform: none; +} + +/* +** the page-related actions- page/talk, edit etc +*/ +#p-cactions { + position:absolute; + top: 1.3em; + left: 11.5em; + margin: 0; + white-space:nowrap; + width: 76%; + line-height: 1.1em; + overflow: visible; + background: none; + border-collapse: collapse; + padding-left: 1em; + list-style: none; + font-size: 95%; +} +#p-cactions .hiddenStructure { display: none; } +#p-cactions ul { + list-style: none; +} +#p-cactions li { + display: inline; + border: 1px solid #aaaaaa; + border-bottom: none; + padding: 0 0 0.1em 0; + margin: 0 0.3em 0 0; + overflow: visible; + background: White; +} +#p-cactions li.selected { + border-color: #fabd23; + padding: 0 0 0.2em 0; +} +#p-cactions li a { + background-color: White; + color: #002bb8; + border: none; + padding: 0 0.8em 0.3em 0.8em; + text-decoration: none; + text-transform: lowercase; + position: relative; + z-index: 0; + margin: 0; +} +#p-cactions .selected a { z-index: 3; } +#p-cactions .new a { color:#ba0000; } +#p-cactions li a:hover { + z-index: 3; + text-decoration: none; +} +#p-cactions h5 { display: none; } +#p-cactions li.istalk { margin-right: 0; } +#p-cactions li.istalk a { padding-right: 0.5em; } +#p-cactions #ca-addsection a { + padding-left: 0.4em; + padding-right: 0.4em; +} +/* offsets to distinguish the tab groups */ +li#ca-talk { margin-right: 1.6em; } +li#ca-watch, li#ca-watch { margin-left: 1.6em; } + + +/* +** the remaining portlets +*/ +#p-tbx, +#p-lang { + position:relative; + z-index:3; +} + +/* +** footer +*/ +#footer { + background-color: White; + border-top: 1px solid #fabd23; + border-bottom: 1px solid #fabd23; + margin: 0.6em 0em 1em 0em; + padding: 0.4em 0em 1.2em 0em; + text-align: center; + font-size: 90%; +} +#footer li { + display: inline; + margin: 0 1.3em; +} +/* hide from incapable browsers */ +head:first-child+body #footer li { white-space: nowrap; } +#f-poweredbyico, #f-copyrightico { + margin: 0 8px; + position: relative; + top: -2px; /* Bump it up just a tad */ +} +#f-poweredbyico { + float: right; + height: 1%; +} +#f-copyrightico { + float: left; + height: 1%; +} + +/* js pref toc */ +#preftoc { + float: left; + margin: 1em 1em 1em 1em; + width: 13em; +} +#preftoc li { border: 1px solid White; } +#preftoc li.selected { + background-color:#f9f9f9; + border:1px dashed #aaaaaa; +} +#preftoc a, +#preftoc a:active { + display: block; + color: #0014a6; +} +#prefcontrol { + clear: both; + float: left; + margin-top: 1em; +} +div.prefsectiontip { + font-size: 95%; + margin-top: 1em; +} +fieldset.operaprefsection { margin-left: 15em } + +/* +** IE/Mac fixes, hope to find a validating way to move this +** to a separate stylesheet. This would work but doesn't validate: +** @import("IEMacFixes.css"); +*/ +/* tabs: border on the a, not the div */ +* > html #p-cactions li { border:none; } +* > html #p-cactions li a { + border: 1px solid #aaaaaa; + border-bottom: none; +} +* > html #p-cactions li.selected a { border-color: #fabd23; } +/* footer icons need a fixed width */ +* > html #f-poweredbyico, +* > html #f-copyrightico { width: 88px; } +* > html #bodyContent, +* > html #bodyContent pre { + overflow-x: auto; + width: 100%; + padding-bottom: 25px; +} + +/* more IE fixes */ +/* float/negative margin brokenness */ +* html #footer {margin-top: 0;} +* html #column-content { + display: inline; + margin-bottom: 0; +} +* html div.editsection { font-size: smaller; } +#pagehistory li.selected { position: relative; } + +/* Mac IE 5.0 fix; floated content turns invisible */ +* > html #column-content { + float: none; +} +* > html #column-one { + position: absolute; + left: 0; + top: 0; +} +* > html #footer { + margin-left: 13.2em; +} + +.printfooter { + display: none; +} + +.sharedUploadNotice { + font-style: italic; +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/blog/BlogEntry.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/blog/BlogEntry.java new file mode 100644 index 0000000..4d0d7b8 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/blog/BlogEntry.java @@ -0,0 +1,17 @@ + +package net.sourceforge.phpeclipse.wiki.blog; + +public class BlogEntry { + String fGuid; + long fDate; + public BlogEntry(String guid, long date) { + fGuid = guid; + fDate = date; + } + public String getGuid() { + return fGuid; + } + public long getTime() { + return fDate; + } +} diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/blog/Configuration.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/blog/Configuration.java new file mode 100644 index 0000000..8d8843b --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/blog/Configuration.java @@ -0,0 +1,149 @@ +package net.sourceforge.phpeclipse.wiki.blog; + +import net.sourceforge.phpeclipse.wiki.preferences.AlternateUserValidationDialog; +import net.sourceforge.phpeclipse.wiki.preferences.UserValidationDialog; +import net.sourceforge.phpeclipse.wiki.preferences.Util; + +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.swt.widgets.Shell; + +public class Configuration { + String fUrl; + + String fBlogID; + + String fUser; + + String fPassword; + + public Configuration(String url, String blogId, String user, String password) { + fUrl = url; + fBlogID = blogId; + fUser = user; + fPassword = password; + } + + /** + * @return Returns the blogID. + */ + public String getBlogID() { + return fBlogID; + } + + /** + * @param blogID + * The blogID to set. + */ + public void setBlogID(String blogID) { + fBlogID = blogID; + } + + /** + * @return Returns the fPassword. + */ + public String getPassword() { + return fPassword; + } + + /** + * @param fPassword + * The fPassword to set. + */ + public void setPassword(String password) { + fPassword = password; + } + + /** + * @return Returns the url. + */ + public String getUrl() { + return fUrl; + } + + /** + * @param url + * The url to set. + */ + public void setUrl(String url) { + fUrl = url; + } + + /** + * @return Returns the fUser. + */ + public String getUser() { + return fUser; + } + + /** + * @param fUser + * The fUser to set. + */ + public void setUser(String user) { + fUser = user; + } + + public boolean isUserComplete() { + if (fUser==null || fUser.equals("")) { + return false; + } + if (fPassword==null || fPassword.equals("")) { + return false; + } + return true; + } + /** + * Special alternate prompting. Returns the fPassword. Username must be fixed. + * + * + * String passWord = Configuration.alternatePromptForPassword(config.getUser()); + * if (passWord==null||passWord.equals("")) { + * return; + * } + * config.setPassword(passWord); + */ + public String alternatePromptForPassword(final String username) { + Shell shell = Util.findShell(); + AlternateUserValidationDialog dialog = new AlternateUserValidationDialog(shell, (username == null) ? "" : username); //$NON-NLS-1$ + dialog.setUsername(username); + int result = dialog.open(); + if (result == Dialog.CANCEL) + return null; + return dialog.getPassword(); + } + + /** + * Asks the User to enter a Password. Places the results in the supplied string[]. result[0] must contain the username, result[1] + * must contain the fPassword. If the fUser canceled, both values must be zero. + * + * @param location + * the location to obtain the fPassword for + * @param username + * the username + * @param message + * a message to display to the fUser + * @param userMutable + * whether the fUser can be changed in the dialog + * @param result + * a String array of length two in which to put the result + */ + public boolean promptForPassword(final String username, final String message, final boolean userMutable, final String[] result) { + if (isUserComplete()) { + result[0] = fUser; + result[1] = fPassword; + return false; + } + Shell shell = Util.findShell(); + if (shell == null) { + return false; + } + String domain = ""; //location == null ? null : location.getLocation(); + UserValidationDialog dialog = new UserValidationDialog(shell, domain, (username == null) ? "" : username, message);//$NON-NLS-1$ + dialog.setUsernameMutable(userMutable); + dialog.open(); + result[0] = dialog.getUsername(); + result[1] = dialog.getPassword(); + return dialog.getAllowCaching(); + } + +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/blog/MetaWeblog.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/blog/MetaWeblog.java new file mode 100644 index 0000000..07de445 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/blog/MetaWeblog.java @@ -0,0 +1,189 @@ +package net.sourceforge.phpeclipse.wiki.blog; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.util.Date; +import java.util.Hashtable; +import java.util.Vector; + +import org.apache.xmlrpc.XmlRpcClient; +import org.apache.xmlrpc.XmlRpcException; +import org.eclipse.core.resources.IFile; +import org.eclipse.jface.dialogs.MessageDialog; + +public class MetaWeblog { + + XmlRpcClient xmlrpc; + + Configuration config; + + public MetaWeblog(Configuration conf) throws MalformedURLException { + config = conf; + xmlrpc = new XmlRpcClient(config.getUrl()); + } + + public String newPost(Configuration config, IFile file, String title, StringBuffer htmlBuffer) { + return newPost(config, file, title, htmlBuffer); + } + + public String newPost(IFile file, String title, StringBuffer htmlBuffer, boolean publish) { + try { + // XmlRpcClient xmlrpc = new XmlRpcClient(config.getUrl()); + + Hashtable message = new Hashtable(); + message.put("title", "title"); + message.put("description", htmlBuffer.toString()); + + Vector params = new Vector(); + String guid = null; + + params.add(config.getBlogID()); + params.add(config.getUser()); + params.add(config.getPassword()); + params.add(message); + if (publish) { + params.add(Boolean.TRUE); //publish=true + } else { + params.add(Boolean.FALSE); //publish=false + } + return (String) xmlrpc.execute("metaWeblog.newPost", params); + } catch (MalformedURLException e) { + MessageDialog.openError(null, "MalformedURLException: ", e.toString()); + } catch (Exception e) { + MessageDialog.openError(null, "Exception: ", e.toString()); + // e.printStackTrace(); + } + return null; + } + + /** + * Publish (or delete) the attachement. + * + * @param snipId + * the id of the snip to which the attachment belongs + * @param attachementFilename + * The blog attachement. If the publication is successful this will be updated to contain a reference to the publication + * location. + * @param delete + * true if the attachment is in fact to be deleted + * @return the attachment info + * @throws TransferFilesException + */ + public void publishAttachement(String snipId, String attachementFilename, boolean delete) throws TransferFilesException { + Vector params = new Vector(); + + params.add(config.getBlogID()); + params.add(config.getUser()); + params.add(config.getPassword()); + Hashtable message = new Hashtable(); + File attf = new File(attachementFilename); + try { + if (attf.length() > 2 * 1000 * 1000) { + throw new TransferFilesException("File should not be close to 2MB. Currently it is " + attf.length() + " bytes."); + } + byte[] data; + if (delete) { + data = new byte[0]; + } else { + data = new byte[(int) attf.length()]; + InputStream in = new FileInputStream(attf); + int total = 0; + for (int read = 0; total + read < data.length && (read = in.read(data, read, data.length - read)) >= 0; total += read) { + } //read file into data + if (total != data.length) { + throw new TransferFilesException("Could not read all of " + attf); + } + } + message.put("bits", data); + message.put("name", attf.getName()); + int index = attachementFilename.lastIndexOf('.'); + if (index != (-1)) { + message.put("key", attachementFilename.substring(index+1, attachementFilename.length()).toLowerCase()); + } else { + // assume png as default + message.put("key", "png"); + } + message.put("postid", snipId); //required for snipsnap. + } catch (FileNotFoundException e) { + throw new TransferFilesException("Could not find image " + attf, e); + } catch (IOException e) { + throw new TransferFilesException("Could not read data from file " + attf, e); + } + params.add(message); + String attURL; + try { + Hashtable res = (Hashtable) xmlrpc.execute("metaWeblog.newMediaObject", params); + attURL = (String) res.get("url"); + } catch (XmlRpcException e) { + throw new TransferFilesException("problem in communication with server", e); + } catch (IOException e) { + throw new TransferFilesException("IO problem trying to communicate with server", e); + } + // return att.setUrl(attURL); + } + + /** + * delete the entry from the blog server + * + * @param entry + * @return + */ + boolean deleteEntry(BlogEntry entry) throws TransferFilesException { + Vector params = new Vector(5); + // params.add(props.getProperty("blogid", "none")); //Should be the appkey, but what use is that? + params.add(config.getBlogID()); + params.add(entry.getGuid()); + params.add(config.getUser()); + params.add(config.getPassword()); + params.add(Boolean.TRUE); + + Boolean result; + try { + result = (Boolean) xmlrpc.execute("blogger.deletePost", params); + } catch (XmlRpcException e) { + throw new TransferFilesException("problem in communication with server", e); + } catch (IOException e) { + throw new TransferFilesException("IO problem trying to communicate with server", e); + } + + return result.booleanValue(); + } + + /** + * + * @param entry + * the entry that requires updating + * @return true if successful. + */ + boolean updateEntry(BlogEntry entry, String title, StringBuffer htmlBuffer) throws TransferFilesException { + Vector params = new Vector(5); + Boolean result = null; + + params.add(entry.getGuid()); + params.add(config.getUser()); + params.add(config.getPassword()); + + Hashtable message = new Hashtable(5); + message.put("title", title); + message.put("description", htmlBuffer.toString()); + message.put("dateCreated", new Date(entry.getTime())); + params.add(message); + + params.add(Boolean.TRUE); + + try { + result = (Boolean) xmlrpc.execute("metaWeblog.editPost", params); + } catch (XmlRpcException e) { + throw new TransferFilesException("problem in communication with server", e); + } catch (IOException e) { + throw new TransferFilesException("IO problem trying to communicate with server", e); + } + return (result == null) ? false : result.booleanValue(); + + } + +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/blog/TransferFilesException.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/blog/TransferFilesException.java new file mode 100644 index 0000000..eb415a3 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/blog/TransferFilesException.java @@ -0,0 +1,21 @@ +package net.sourceforge.phpeclipse.wiki.blog; + +public class TransferFilesException extends Exception { + + public TransferFilesException() { + super(); + } + + public TransferFilesException(String message) { + super(message); + } + + public TransferFilesException(String message, Throwable cause) { + super(message, cause); + } + + public TransferFilesException(Throwable cause) { + super(cause); + } + +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/builder/AddBuilderAction.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/builder/AddBuilderAction.java new file mode 100644 index 0000000..ef06dc8 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/builder/AddBuilderAction.java @@ -0,0 +1,104 @@ +package net.sourceforge.phpeclipse.wiki.builder; + +import java.util.Iterator; + +import net.sourceforge.phpeclipse.wiki.preferences.Util; + +import org.eclipse.core.resources.ICommand; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IProjectDescription; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.jface.action.IAction; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.ISelectionProvider; +import org.eclipse.jface.viewers.StructuredSelection; +import org.eclipse.ui.IActionDelegate; +import org.eclipse.ui.IObjectActionDelegate; +import org.eclipse.ui.IWorkbenchPart; + +public class AddBuilderAction implements IObjectActionDelegate { + private IWorkbenchPart workbenchPart; + + /** + * + */ + public AddBuilderAction() { + super(); + } + + /** + * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart) + */ + public void setActivePart(IAction action, IWorkbenchPart targetPart) { + workbenchPart = targetPart; + } + + public void run(IAction action) { + ISelectionProvider selectionProvider = null; + selectionProvider = workbenchPart.getSite().getSelectionProvider(); + + StructuredSelection selection = null; + selection = (StructuredSelection) selectionProvider.getSelection(); + + //Shell shell = null; + Iterator iterator = null; + iterator = selection.iterator(); + while (iterator.hasNext()) { + // obj => selected object in the view + Object obj = iterator.next(); + + // is it a resource + if (obj instanceof IResource) { + IResource resource = (IResource) obj; + + // check if it's a project resource + switch (resource.getType()) { + + case IResource.PROJECT: + addBuilder((IProject) resource); + } + } + } + } + + /** + * @see IActionDelegate#selectionChanged(IAction, ISelection) + */ + public void selectionChanged(IAction action, ISelection selection) { + } + + private void addBuilder(IProject project) { + IProjectDescription desc; + try { + desc = project.getDescription(); + + ICommand[] commands = desc.getBuildSpec(); + boolean found = false; + + for (int i = 0; i < commands.length; ++i) { + if (commands[i].getBuilderName().equals(WikiBuilder.BUILDER_ID)) { + found = true; + break; + } + } + if (!found) { + //add builder to project + ICommand command = desc.newCommand(); + command.setBuilderName(WikiBuilder.BUILDER_ID); + ICommand[] newCommands = new ICommand[commands.length + 1]; + + // Add it before other builders. + System.arraycopy(commands, 0, newCommands, 1, commands.length); + newCommands[0] = command; + desc.setBuildSpec(newCommands); + project.setDescription(desc, null); + // add some default wiki project settings + Util.setWikiTextsPath(project); + + } + } catch (CoreException e) { + e.printStackTrace(); + } + } +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/builder/BuilderRenderEngine.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/builder/BuilderRenderEngine.java new file mode 100644 index 0000000..56555fa --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/builder/BuilderRenderEngine.java @@ -0,0 +1,96 @@ +package net.sourceforge.phpeclipse.wiki.builder; + +import net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin; +import net.sourceforge.phpeclipse.wiki.preferences.Util; + +import org.eclipse.core.resources.IProject; +import org.eclipse.core.runtime.IPath; +import org.radeox.api.engine.WikiRenderEngine; +import org.radeox.api.engine.context.InitialRenderContext; +import org.radeox.api.engine.context.RenderContext; +import org.radeox.engine.BaseRenderEngine; +import org.plog4u.wiki.filter.FilterUtil; + +public class BuilderRenderEngine extends BaseRenderEngine implements WikiRenderEngine { + IProject fProject; + + IPath fPath; + + int fLevel; + + public BuilderRenderEngine(IProject project, InitialRenderContext context) { + super(context); + fProject = project; + fPath = fProject.getFullPath(); + fLevel = 0; + } + + /** + * + * @param location - + * the absolute basepath or null + * @param name - + * the name of the wiki link + * @param extension - + * the file extension of the wiki text ( *.wp prefered ) + * @param createHTMLLevel - + * if true prepend the directory level before the link i.e. ../../ + * @return + */ + public String createHTMLLink(String location, String name, String extension, boolean createHTMLLevel) { + return FilterUtil.createHTMLLink(location, name, extension, createHTMLLevel, fLevel); + } + + public boolean exists(String name) { + + java.io.File file = new java.io.File(createHTMLLink(Util.getWikiTextsPath(fProject), name, "wp", false)); + return file.exists(); + // return name.equals("SnipSnap") || name.equals("stephan"); + } + + public boolean showCreate() { + return true; + } + + public void appendLink(StringBuffer buffer, String name, String view, String anchor) { + String basePath = Util.getProjectsWikiOutputPath(fProject, WikiEditorPlugin.HTML_OUTPUT_PATH); + // String basePath = WikiEditorPlugin.getDefault().getPreferenceStore().getString(WikiConstants.HTML_OUTPUT_PATH); + buffer.append(""); + buffer.append(view); + buffer.append(""); + //buffer.append("link:"+name+"|"+view+"#"+anchor); + } + + public void appendLink(StringBuffer buffer, String name, String view) { + String basePath = Util.getProjectsWikiOutputPath(fProject, WikiEditorPlugin.HTML_OUTPUT_PATH); + // String basePath = WikiEditorPlugin.getDefault().getPreferenceStore().getString(WikiConstants.HTML_OUTPUT_PATH); + buffer.append(""); + buffer.append(view); + buffer.append(""); + // buffer.append("link:" + name + "|" +view); + } + + public void appendCreateLink(StringBuffer buffer, String name, String view) { + // if showCreate is true this method will be used to create a link to a + // "Wiki creationpage" + buffer.append(view); + + // buffer.append("'").append(name).append("' - "); + // buffer.append("'").append(Encoder.escape(name)).append("'"); + } + + public String getName() { + return "BuilderRenderEngine"; + } + + public void setLevel(int level) { + fLevel = level; + } + +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/builder/CreatePageAction.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/builder/CreatePageAction.java new file mode 100644 index 0000000..9fc589c --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/builder/CreatePageAction.java @@ -0,0 +1,313 @@ +package net.sourceforge.phpeclipse.wiki.builder; + +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.Iterator; + +import net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin; +import net.sourceforge.phpeclipse.wiki.preferences.Util; +import net.sourceforge.phpeclipse.wiki.renderer.IContentRenderer; +import net.sourceforge.phpeclipse.wiki.renderer.RendererFactory; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.jface.action.IAction; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.ISelectionProvider; +import org.eclipse.jface.viewers.StructuredSelection; +import org.eclipse.ui.IActionDelegate; +import org.eclipse.ui.IObjectActionDelegate; +import org.eclipse.ui.IWorkbenchPart; + +/** + * Create a static HTML page + */ +public class CreatePageAction implements IObjectActionDelegate { + /** + * Constant for an empty char array + */ + public static final char[] NO_CHAR = new char[0]; + + private static final int DEFAULT_READING_SIZE = 8192; + + private IWorkbenchPart workbenchPart; + + /** + * + */ + public CreatePageAction() { + super(); + } + + /** + * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart) + */ + public void setActivePart(IAction action, IWorkbenchPart targetPart) { + workbenchPart = targetPart; + } + + public void run(IAction action) { + ISelectionProvider selectionProvider = null; + selectionProvider = workbenchPart.getSite().getSelectionProvider(); + + StructuredSelection selection = null; + selection = (StructuredSelection) selectionProvider.getSelection(); + + //Shell shell = null; + Iterator iterator = null; + iterator = selection.iterator(); + while (iterator.hasNext()) { + // obj => selected object in the view + Object obj = iterator.next(); + + // is it a resource + if (obj instanceof IResource) { + IResource resource = (IResource) obj; + + // check if it's a file resource + switch (resource.getType()) { + + case IResource.FILE: + createPage((IFile) resource); + } + } + } + } + + /** + * @see IActionDelegate#selectionChanged(IAction, ISelection) + */ + public void selectionChanged(IAction action, ISelection selection) { + } + + public static void createPage(IFile file) { + String srcBasePath = Util.getWikiTextsPath(file); + String binBasePath = Util.getProjectsWikiOutputPath(file.getProject(), WikiEditorPlugin.HTML_OUTPUT_PATH); + createPage(file, binBasePath, srcBasePath); + } + + public static void createPage(IFile file, String binBasepath, String srcBasePath) { + // only interested in files with the "wp" extension + if ("wp".equalsIgnoreCase(file.getFileExtension())) { + try { + IContentRenderer renderer = RendererFactory.createContentRenderer(file.getProject()); + convertWikiFile(file, binBasepath, srcBasePath, renderer); + } catch (InstantiationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (ClassNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (CoreException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + } else { + String fname = file.getName().toLowerCase(); + if ((fname.charAt(0) == '.') || "project.index".equals(fname) || "cvs".equals(fname) || "entries".equals(fname) + || "repository".equals(fname) || "root".equals(fname)) { + // ignore meta information + return; + } + // copy the file + FileOutputStream output = null; + InputStream contentStream = null; + + try { + String filename = Util.getHTMLFileName(file, binBasepath, srcBasePath); + if (filename != null) { + int index = filename.lastIndexOf('/'); + if (index >= 0) { + File ioFile = new File(filename.substring(0, index)); + if (!ioFile.isDirectory()) { + ioFile.mkdirs(); + } + } + output = new FileOutputStream(filename); + + contentStream = file.getContents(false); + int chunkSize = contentStream.available(); + byte[] readBuffer = new byte[chunkSize]; + int n = contentStream.read(readBuffer); + + while (n > 0) { + output.write(readBuffer); + n = contentStream.read(readBuffer); + } + } + } catch (Exception e) { + + } finally { + try { + if (output != null) + output.close(); + if (contentStream != null) + contentStream.close(); + } catch (IOException e1) { + } + } + } + } + + public static void convertWikiFile(IFile file, String binBasePath, String srcBasePath, IContentRenderer renderer) + throws CoreException { + StringBuffer htmlBuffer = new StringBuffer(); + convertWikiBuffer(htmlBuffer, file, renderer, true); + String htmlName = Util.getHTMLFileName(file, binBasePath, srcBasePath); + if (htmlName != null) { + writeHTMLFile(htmlBuffer, htmlName); + } + } + + public static void getWikiBuffer(StringBuffer htmlBuffer, IFile file) throws CoreException { + BufferedInputStream stream = new BufferedInputStream(file.getContents()); + try { + htmlBuffer.append(getInputStreamAsCharArray(stream, -1, null)); + return; + //new String(getInputStreamAsCharArray(stream, -1, null)); + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + if (stream != null) { + stream.close(); + } + } catch (IOException e) { + } + } + return; + } + + public static void convertWikiBuffer(StringBuffer htmlBuffer, IFile file, IContentRenderer renderer, boolean completeHTML) + throws CoreException { + BufferedInputStream stream = new BufferedInputStream(file.getContents()); + try { + String content = new String(getInputStreamAsCharArray(stream, -1, null)); + String srcPath = Util.getWikiTextsPath(file); + String filePath = file.getLocation().toString(); // file.getProjectRelativePath().toString() + if (filePath.startsWith(srcPath)) { + filePath = filePath.substring(srcPath.length()+1); + } + createWikiBuffer(htmlBuffer, filePath, content, renderer, completeHTML); + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + if (stream != null) { + stream.close(); + } + } catch (IOException e) { + } + } + } + + /** + * @param htmlBuffer + * @param fileName + * @param content + * @param renderer + */ + public static void createWikiBuffer(StringBuffer htmlBuffer, String fileName, String content, IContentRenderer renderer, + boolean completeHTML) { + // calculate the depth of the file (i.e. ../../../ as much as needed) + int index = 0; + int level = 0; + while (index >= 0) { + index = fileName.indexOf('/', index); + if (index >= 0) { + level++; + index++; + } + } + renderer.render(content, htmlBuffer, level, completeHTML); + } + + public static void writeHTMLFile(StringBuffer buffer, String filename) { + int index = filename.lastIndexOf('/'); + if (index >= 0) { + File file = new File(filename.substring(0, index)); + if (!file.isDirectory()) { + file.mkdirs(); + } + } + FileWriter fileWriter; + try { + fileWriter = new FileWriter(filename); + fileWriter.write(buffer.toString()); + fileWriter.close(); + } catch (FileNotFoundException e) { + // ignore exception; project is deleted by fUser + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + /** + * Returns the given input stream's contents as a character array. If a length is specified (ie. if length != -1), only length + * chars are returned. Otherwise all chars in the stream are returned. Note this doesn't close the stream. + * + * @throws IOException + * if a problem occured reading the stream. + */ + public static char[] getInputStreamAsCharArray(InputStream stream, int length, String encoding) throws IOException { + InputStreamReader reader = null; + reader = encoding == null ? new InputStreamReader(stream) : new InputStreamReader(stream, encoding); + char[] contents; + if (length == -1) { + contents = NO_CHAR; + int contentsLength = 0; + int amountRead = -1; + do { + int amountRequested = Math.max(stream.available(), DEFAULT_READING_SIZE); // read at least 8K + + // resize contents if needed + if (contentsLength + amountRequested > contents.length) { + System.arraycopy(contents, 0, contents = new char[contentsLength + amountRequested], 0, contentsLength); + } + + // read as many chars as possible + amountRead = reader.read(contents, contentsLength, amountRequested); + + if (amountRead > 0) { + // remember length of contents + contentsLength += amountRead; + } + } while (amountRead != -1); + + // resize contents if necessary + if (contentsLength < contents.length) { + System.arraycopy(contents, 0, contents = new char[contentsLength], 0, contentsLength); + } + } else { + contents = new char[length]; + int len = 0; + int readSize = 0; + while ((readSize != -1) && (len != length)) { + // See PR 1FMS89U + // We record first the read size. In this case len is the actual + // read size. + len += readSize; + readSize = reader.read(contents, len, length - len); + } + // See PR 1FMS89U + // Now we need to resize in case the default encoding used more than + // one byte for each + // character + if (len != length) + System.arraycopy(contents, 0, (contents = new char[len]), 0, len); + } + + return contents; + } +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/builder/WikiBuilder.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/builder/WikiBuilder.java new file mode 100644 index 0000000..f20fddb --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/builder/WikiBuilder.java @@ -0,0 +1,156 @@ +package net.sourceforge.phpeclipse.wiki.builder; + +import java.io.IOException; +import java.util.Map; + +import net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin; +import net.sourceforge.phpeclipse.wiki.export.WikiExporter; +import net.sourceforge.phpeclipse.wiki.preferences.Util; + +import org.eclipse.core.internal.resources.Folder; +import org.eclipse.core.resources.ICommand; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IFolder; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IResourceDelta; +import org.eclipse.core.resources.IResourceDeltaVisitor; +import org.eclipse.core.resources.IncrementalProjectBuilder; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.core.runtime.Path; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.PlatformUI; + +public class WikiBuilder extends IncrementalProjectBuilder { + + class WikiVisitor implements IResourceDeltaVisitor { + String fBinBasePath; + + String fSrcBasePath; + + public WikiVisitor(String binBasePath, String srcBasePath) { + fBinBasePath = binBasePath; + fSrcBasePath = srcBasePath; + } + + public boolean visit(IResourceDelta delta) { + IResource resource = delta.getResource(); + if (DEBUG) { + System.out.println(resource.toString()); + } + if (delta.getKind() == IResourceDelta.REMOVED && resource.getType() == IResource.FILE) { + // remove this file from the wiki publishing directory + String htmlName = Util.getHTMLFileName((IFile) resource, fBinBasePath, fSrcBasePath); + if (htmlName != null) { + java.io.File file = new java.io.File(htmlName); + if (file.exists()) { + file.delete(); + } + } + return true; + } + //only interested in changed resources at this point (not added or removed) + if (delta.getKind() != IResourceDelta.CHANGED) + return true; + //only interested in content changes + if ((delta.getFlags() & IResourceDelta.CONTENT) == 0) + return true; + if (resource.getType() == IResource.FILE) { + CreatePageAction.createPage((IFile) resource); + } + return true; + } + } + + public static final String BUILDER_ID = "net.sourceforge.phpeclipse.wiki.wikibuilder"; + + private static final boolean DEBUG = false; + + private IProject fProject; + + private IWorkbench workbench; + + public WikiBuilder() { + workbench = PlatformUI.getWorkbench(); + fProject = null; + } + + protected IProject[] build(int kind, Map args, IProgressMonitor _monitor) { + try { + fProject = getProject(); + ICommand[] commands = fProject.getDescription().getBuildSpec(); + boolean found = false; + for (int i = 0; i < commands.length; i++) { + if (commands[i].getBuilderName().equals(BUILDER_ID)) { + found = true; + break; + } + } + // fProject.hasNature() + if (found && fProject != null && fProject.isAccessible()) { + + if (_monitor == null) + _monitor = new NullProgressMonitor(); + switch (kind) { + case INCREMENTAL_BUILD: + if (DEBUG) { + System.out.println("INCREMENTAL_BUILD requested"); + } + incrementalBuild(); + break; + // we don't need auto build, because on every save we create a new *.html file ? + case AUTO_BUILD: + if (DEBUG) { + System.out.println("AUTO_BUILD requested"); + } + incrementalBuild(); + break; + case FULL_BUILD: + if (DEBUG) { + System.out.println("FULL_BUILD requested"); + } + fullBuild(_monitor); + break; + default: + // unknown build kind requested; + } + // fProject.refreshLocal(1,_monitor); + } + } catch (Exception x) { + + } + return new IProject[0]; + } + + private void fullBuild(IProgressMonitor monitor) throws CoreException, IOException { + try { + WikiExporter wikiExporter = new WikiExporter(); + String srcBasePath = Util.getProjectsWikiTextsPath(fProject); + String basePath = Util.getProjectsWikiOutputPath(fProject, WikiEditorPlugin.HTML_OUTPUT_PATH); + wikiExporter.export(fProject, basePath, srcBasePath, monitor); + } catch (IOException e) { + e.printStackTrace(); + } catch (CoreException e) { + e.printStackTrace(); + } catch (InstantiationException e) { + e.printStackTrace(); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + } + + private void incrementalBuild() throws CoreException, IOException { + IResourceDelta delta = getDelta(fProject); + String srcBasePath = Util.getProjectsWikiTextsPath(fProject); + String basePath = Util.getProjectsWikiOutputPath(fProject, WikiEditorPlugin.HTML_OUTPUT_PATH); + IResourceDeltaVisitor visitor = new WikiVisitor(basePath, srcBasePath); + if (delta != null) + delta.accept(visitor); + } + +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/ExternalEditorInput.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/ExternalEditorInput.java new file mode 100644 index 0000000..5ccc464 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/ExternalEditorInput.java @@ -0,0 +1,98 @@ +package net.sourceforge.phpeclipse.wiki.editor; + +import org.eclipse.core.resources.IStorage; +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.ui.IEditorRegistry; +import org.eclipse.ui.IPersistableElement; +import org.eclipse.ui.IStorageEditorInput; +import org.eclipse.ui.PlatformUI; + +/** + * An EditorInput for an external file. + */ +public class ExternalEditorInput implements IStorageEditorInput { + + IStorage externalFile; + + /** + * Two ExternalEditorInputs are equal if their IStorage's are equal. + * @see java.lang.Object#equals(java.lang.Object) + */ + public boolean equals(Object obj) { + if (this == obj) + return true; + if (!(obj instanceof ExternalEditorInput)) + return false; + ExternalEditorInput other = (ExternalEditorInput) obj; + return externalFile.equals(other.externalFile); + } + + /* + * @see IEditorInput#exists() + */ + public boolean exists() { + // External file can not be deleted + return true; + } + + /* + * @see IAdaptable#getAdapter(Class) + */ + public Object getAdapter(Class adapter) { + return null; + } + + /* + * @see IEditorInput#getContentType() + */ + public String getContentType() { + return externalFile.getFullPath().getFileExtension(); + } + + /* + * @see IEditorInput#getFullPath() + */ + public String getFullPath() { + return externalFile.getFullPath().toString(); + } + + /* + * @see IEditorInput#getImageDescriptor() + */ + public ImageDescriptor getImageDescriptor() { + IEditorRegistry registry = PlatformUI.getWorkbench().getEditorRegistry(); + return registry.getImageDescriptor(externalFile.getFullPath().getFileExtension()); + } + + /* + * @see IEditorInput#getName() + */ + public String getName() { + return externalFile.getName(); + } + + /* + * @see IEditorInput#getPersistable() + */ + public IPersistableElement getPersistable() { + return null; + } + + /* + * see IStorageEditorInput#getStorage() + */ + public IStorage getStorage() { + return externalFile; + } + + /* + * @see IEditorInput#getToolTipText() + */ + public String getToolTipText() { + return externalFile.getFullPath().toString(); + } + + public ExternalEditorInput(IStorage exFile) { + externalFile = exFile; + } +} diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/WikiCompletionProcessor.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/WikiCompletionProcessor.java new file mode 100644 index 0000000..533e894 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/WikiCompletionProcessor.java @@ -0,0 +1,255 @@ +/*********************************************************************************************************************************** + * Copyright (c) 2000, 2004 IBM Corporation and others. All rights reserved. This program and the accompanying materials are made + * available under the terms of the Common Public License v1.0 which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: IBM Corporation - initial API and implementation + **********************************************************************************************************************************/ +package net.sourceforge.phpeclipse.wiki.editor; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +import net.sourceforge.phpeclipse.wiki.editor.model.WikipediaSection; +import net.sourceforge.phpeclipse.wiki.editor.model.WikipediaText; + +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.jface.resource.ImageRegistry; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.ITextSelection; +import org.eclipse.jface.text.ITextViewer; +import org.eclipse.jface.text.Region; +import org.eclipse.jface.text.TextUtilities; +import org.eclipse.jface.text.contentassist.CompletionProposal; +import org.eclipse.jface.text.contentassist.ICompletionProposal; +import org.eclipse.jface.text.contentassist.IContentAssistProcessor; +import org.eclipse.jface.text.contentassist.IContextInformation; +import org.eclipse.jface.text.contentassist.IContextInformationValidator; +import org.eclipse.jface.text.templates.DocumentTemplateContext; +import org.eclipse.jface.text.templates.Template; +import org.eclipse.jface.text.templates.TemplateContext; +import org.eclipse.jface.text.templates.TemplateContextType; +import org.eclipse.jface.text.templates.TemplateException; +import org.eclipse.jface.text.templates.TemplateProposal; +import org.eclipse.swt.graphics.Image; + +public class WikiCompletionProcessor implements IContentAssistProcessor { + + private static final String TEMPLATE_ICON = "icons/template.gif"; + +// private static final String PREPARATION_TEMPLATE_CTX = "net.sourceforge.phpeclipse.wiki.editor.preparation"; + + private static final String INGREDIENTS_TEMPLATE_CTX = "net.sourceforge.phpeclipse.wiki.editor.templates"; + + private static final class ProposalComparator implements Comparator { + public int compare(Object o1, Object o2) { + return ((TemplateProposal) o2).getRelevance() - ((TemplateProposal) o1).getRelevance(); + } + } + + private static final Comparator fgProposalComparator = new ProposalComparator(); + + private final WikiEditor fEditor; + + public WikiCompletionProcessor(WikiEditor editor) { + fEditor = editor; + } + + public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) { + WikipediaSection section = fEditor.getSection(); + if (section == null) + return null; + + ITextSelection selection = (ITextSelection) viewer.getSelectionProvider().getSelection(); + // adjust offset to start of normalized selection: + if (selection.getOffset() != offset) + offset = selection.getOffset(); + + String prefix = getPrefix(viewer, offset); + Region region = new Region(offset - prefix.length(), prefix.length() + selection.getLength()); + + ICompletionProposal[] templateProposals = computeTemplateProposals(viewer, region, section, prefix); +// ICompletionProposal[] ingredientProposals = computeIngredientsProposals(viewer, region, recipe, prefix); +// ICompletionProposal[] titleProposals = computeTitleProposals(viewer, region, recipe, prefix); + List result = new ArrayList(); +// result.addAll(Arrays.asList(ingredientProposals)); + result.addAll(Arrays.asList(templateProposals)); +// result.addAll(Arrays.asList(titleProposals)); + + return (ICompletionProposal[]) result.toArray(new ICompletionProposal[result.size()]); + } + + private ICompletionProposal[] computeTitleProposals(ITextViewer viewer, IRegion region, WikipediaText recipe, String prefix) { + List props = new ArrayList(2); + // if (recipe.getIngredientsSection() == null) + // props.add(createTitleProposal("Zutaten:", region, viewer)); + // if (recipe.getPreparationSection() == null) + // props.add(createTitleProposal("Zubereitung:", region, viewer)); + return (ICompletionProposal[]) props.toArray(new ICompletionProposal[props.size()]); + } + + private CompletionProposal createTitleProposal(String name, IRegion region, ITextViewer viewer) { + String lineDelimiter = TextUtilities.getDefaultLineDelimiter(viewer.getDocument()); + return new CompletionProposal(name + lineDelimiter, region.getOffset(), region.getLength(), region.getOffset() + name.length() + + lineDelimiter.length(), null, name, null, null); + } + + private ICompletionProposal[] computeIngredientsProposals(ITextViewer viewer, IRegion region, WikipediaText recipe, String prefix) { + return new ICompletionProposal[0]; + // Step[] steps= recipe.getSteps(); + // if (steps == null || steps.length == 0) + // return new ICompletionProposal[0]; + // + // int offset= region.getOffset(); + // Step first= steps[0]; + // if (offset < first.getOffset()) + // return new ICompletionProposal[0]; + // + // Ingredient[] ingredients= recipe.getIngredients(); + // if (ingredients == null) + // return new ICompletionProposal[0]; + // + // prefix= prefix.toLowerCase(); + // + // ArrayList proposals= new ArrayList(); + // for (int i= 0; i < ingredients.length; i++) { + // String ingredient= ingredients[i].getName(); + // if (ingredient.toLowerCase().startsWith(prefix)) + // proposals.add(new CompletionProposal(ingredient, offset, region.getLength(), ingredient.length())); + // } + // return (ICompletionProposal[]) proposals.toArray(new ICompletionProposal[proposals.size()]); + } + + private TemplateContextType getContextType(WikipediaSection section, int offset) { +// if (recipe.getPreparationSection() != null && recipe.getPreparationSection().getOffset() < offset) +// return WikiEditorPlugin.getDefault().getContextTypeRegistry().getContextType(PREPARATION_TEMPLATE_CTX); +// else + return WikiEditorPlugin.getDefault().getContextTypeRegistry().getContextType(INGREDIENTS_TEMPLATE_CTX); + } + + /** + * Creates a concrete template context for the given region in the document. This involves finding out which context fType is valid + * at the given location, and then creating a context of this fType. The default implementation returns a + * DocumentTemplateContext for the context fType at the given location. + * + * @param viewer + * the viewer for which the context is created + * @param region + * the region into document for which the context is created + * @return a template context that can handle template insertion at the given location, or null + */ + private TemplateContext createContext(ITextViewer viewer, IRegion region, WikipediaSection recipe) { + TemplateContextType contextType = getContextType(recipe, region.getOffset()); + if (contextType != null) { + IDocument document = viewer.getDocument(); + return new DocumentTemplateContext(contextType, document, region.getOffset(), region.getLength()); + } + return null; + } + + private ICompletionProposal[] computeTemplateProposals(ITextViewer viewer, IRegion region, WikipediaSection recipe, String prefix) { + TemplateContext context = createContext(viewer, region, recipe); + if (context == null) + return new ICompletionProposal[0]; + + ITextSelection selection = (ITextSelection) viewer.getSelectionProvider().getSelection(); + context.setVariable("selection", selection.getText()); // name of the selection variables {line, word}_selection + + String id = context.getContextType().getId(); + Template[] templates = WikiEditorPlugin.getDefault().getTemplateStore().getTemplates(id); + + List matches = new ArrayList(); + for (int i = 0; i < templates.length; i++) { + Template template = templates[i]; + try { + context.getContextType().validate(template.getPattern()); + } catch (TemplateException e) { + continue; + } + int relevance = getRelevance(template, prefix); + if (relevance > 0) { + matches.add(new TemplateProposal(template, context, region, getImage(template), relevance)); + } + } + + Collections.sort(matches, fgProposalComparator); + + return (ICompletionProposal[]) matches.toArray(new ICompletionProposal[matches.size()]); + } + + /** + * Returns the relevance of a template given a prefix. The default implementation returns a number greater than zero if the + * template name starts with the prefix, and zero otherwise. + * + * @param template + * the template to compute the relevance for + * @param prefix + * the prefix after which content assist was requested + * @return the relevance of template + * @see #getPrefix(ITextViewer, int) + */ + private int getRelevance(Template template, String prefix) { + if (template.getName().startsWith(prefix)) + return 90; + return 0; + } + + private String getPrefix(ITextViewer viewer, int offset) { + int i = offset; + IDocument document = viewer.getDocument(); + if (i > document.getLength()) + return ""; + + try { + while (i > 0) { + char ch = document.getChar(i - 1); + if (!Character.isLetterOrDigit(ch)) + break; + i--; + } + + return document.get(i, offset - i); + } catch (BadLocationException e) { + return ""; + } + } + + /** + * Always return the default image. + */ + private Image getImage(Template template) { + ImageRegistry registry = WikiEditorPlugin.getDefault().getImageRegistry(); + Image image = registry.get(TEMPLATE_ICON); + if (image == null) { + ImageDescriptor desc = WikiEditorPlugin.imageDescriptorFromPlugin("net.sourceforge.phpeclipse.wiki.editor", TEMPLATE_ICON); + registry.put(TEMPLATE_ICON, desc); + image = registry.get(TEMPLATE_ICON); + } + return image; + } + + public IContextInformation[] computeContextInformation(ITextViewer viewer, int offset) { + return null; + } + + public char[] getCompletionProposalAutoActivationCharacters() { + return null; + } + + public char[] getContextInformationAutoActivationCharacters() { + return null; + } + + public String getErrorMessage() { + return null; + } + + public IContextInformationValidator getContextInformationValidator() { + return null; + } +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/WikiEditor.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/WikiEditor.java new file mode 100644 index 0000000..5cd82f8 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/WikiEditor.java @@ -0,0 +1,164 @@ +/*********************************************************************************************************************************** + * Copyright (c) 2000, 2004 IBM Corporation and others. All rights reserved. This program and the accompanying materials are made + * available under the terms of the Common Public License v1.0 which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: IBM Corporation - initial API and implementation + **********************************************************************************************************************************/ +package net.sourceforge.phpeclipse.wiki.editor; + +import net.sourceforge.phpeclipse.webbrowser.views.BrowserView; +import net.sourceforge.phpeclipse.wiki.builder.CreatePageAction; +import net.sourceforge.phpeclipse.wiki.editor.model.WikipediaSection; +import net.sourceforge.phpeclipse.wiki.editor.model.WikipediaText; +import net.sourceforge.phpeclipse.wiki.preferences.Util; + +import org.eclipse.jface.action.IAction; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.source.ISourceViewer; +import org.eclipse.jface.text.source.IVerticalRuler; +import org.eclipse.jface.text.source.projection.ProjectionSupport; +import org.eclipse.jface.text.source.projection.ProjectionViewer; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.ui.IEditorInput; +import org.eclipse.ui.IFileEditorInput; +import org.eclipse.ui.IViewPart; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.texteditor.AbstractDecoratedTextEditor; +import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds; +import org.eclipse.ui.texteditor.TextOperationAction; +import org.eclipse.ui.views.contentoutline.IContentOutlinePage; + +public class WikiEditor extends AbstractDecoratedTextEditor { + + private WikiOutlinePage fOutlinePage; + + private WikipediaSection fSection; + + private ProjectionSupport fProjectionSupport; + + private WikiOccurrencesUpdater fOccurrencesUpdater; + + public WikiEditor() { + setSourceViewerConfiguration(new WikiSourceViewerConfiguration(this, getSharedColors())); + } + + public WikipediaSection getSection() { + return fSection; + } + + public void setSection(WikipediaSection section) { + fSection = section; + if (fOutlinePage != null) + fOutlinePage.setWiki(section); + + if (fOccurrencesUpdater != null) + fOccurrencesUpdater.update(getSourceViewer()); + } + + /* + * @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class) + */ + public Object getAdapter(Class required) { + if (IContentOutlinePage.class.equals(required)) { + if (fOutlinePage == null) + fOutlinePage = new WikiOutlinePage(this); + return fOutlinePage; + } + if (fProjectionSupport != null) { + Object adapter = fProjectionSupport.getAdapter(getSourceViewer(), required); + if (adapter != null) + return adapter; + } + return super.getAdapter(required); + } + + public void outlinePageClosed() { + fOutlinePage = null; + } + + /* + * @see org.eclipse.ui.texteditor.AbstractTextEditor#createActions() + */ + protected void createActions() { + super.createActions(); + + IAction action = new TextOperationAction(WikiEditorPlugin.getDefault().getResourceBundle(), "ContentAssistProposal.", this, + ISourceViewer.CONTENTASSIST_PROPOSALS); + action.setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS); + setAction("ContentAssist.", action); + markAsStateDependentAction("ContentAssist.", true); + } + + /* + * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#createPartControl(org.eclipse.swt.widgets.Composite) + */ + public void createPartControl(Composite parent) { + super.createPartControl(parent); + + ProjectionViewer projectionViewer = (ProjectionViewer) getSourceViewer(); + fProjectionSupport = new ProjectionSupport(projectionViewer, getAnnotationAccess(), getSharedColors()); + fProjectionSupport.install(); + projectionViewer.doOperation(ProjectionViewer.TOGGLE); + + fOccurrencesUpdater = new WikiOccurrencesUpdater(this); + } + + /* + * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#createSourceViewer(org.eclipse.swt.widgets.Composite, + * org.eclipse.jface.text.source.IVerticalRuler, int) + */ + protected ISourceViewer createSourceViewer(Composite parent, IVerticalRuler ruler, int styles) { + fAnnotationAccess = createAnnotationAccess(); + fOverviewRuler = createOverviewRuler(getSharedColors()); + + ISourceViewer viewer = new ProjectionViewer(parent, ruler, fOverviewRuler, true, styles); + // ensure decoration support has been created and configured: + getSourceViewerDecorationSupport(viewer); + + return viewer; + } + + /* + * @see org.eclipse.ui.IWorkbenchPart#dispose() + */ + public void dispose() { + fOccurrencesUpdater.dispose(); + super.dispose(); + } + + public IDocument getDocument() { + IDocument doc = getDocumentProvider().getDocument(getEditorInput()); + return doc; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.ui.texteditor.AbstractTextEditor#editorSaved() + */ + protected void editorSaved() { + super.editorSaved(); + // doesn't work here, wikibuilder has to be finished with generating html page + IWorkbenchPage page = WikiEditorPlugin.getDefault().getActivePage(); + try { + IViewPart part = page.findView(BrowserView.ID_BROWSER); + if (part == null) { + part = page.showView(BrowserView.ID_BROWSER); + } else { + // if (bringToTopPreview) { + // page.bringToTop(part); + // } + } + IEditorInput editorInput = null; + editorInput = this.getEditorInput(); + if (editorInput instanceof IFileEditorInput) { + CreatePageAction.createPage(((IFileEditorInput) editorInput).getFile()); + ((BrowserView) part).refresh(); + } + } catch (Exception e) { + } + } + + +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/WikiEditorContributor.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/WikiEditorContributor.java new file mode 100644 index 0000000..f3d93c9 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/WikiEditorContributor.java @@ -0,0 +1,92 @@ +/*********************************************************************************************************************************** + * Copyright (c) 2000, 2004 IBM Corporation and others. All rights reserved. This program and the accompanying materials are made + * available under the terms of the Common Public License v1.0 which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: IBM Corporation - initial API and implementation + **********************************************************************************************************************************/ + +package net.sourceforge.phpeclipse.wiki.editor; + +import net.sourceforge.phpeclipse.webbrowser.views.BrowserView; +import net.sourceforge.phpeclipse.wiki.editor.action.WeblogWikiAction; +import net.sourceforge.phpeclipse.wiki.preferences.Util; + +import org.eclipse.core.resources.IFile; +import org.eclipse.jface.action.IMenuManager; +import org.eclipse.jface.action.Separator; +import org.eclipse.ui.IActionBars; +import org.eclipse.ui.IEditorInput; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.IFileEditorInput; +import org.eclipse.ui.IViewPart; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.texteditor.BasicTextEditorActionContributor; +import org.eclipse.ui.texteditor.ITextEditor; +import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds; +import org.eclipse.ui.texteditor.RetargetTextEditorAction; + +public class WikiEditorContributor extends BasicTextEditorActionContributor { + + private static final String CONTENTASSIST_ACTION = "net.sourceforge.phpeclipse.wiki.editor.ContentAssist"; + + private RetargetTextEditorAction fContentAssist; + public WikiEditorContributor() { + super(); + fContentAssist = new RetargetTextEditorAction(WikiEditorPlugin.getDefault().getResourceBundle(), "ContentAssistProposal."); + fContentAssist.setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS); + } + + public void setActiveEditor(IEditorPart part) { + super.setActiveEditor(part); + ITextEditor editor = (part instanceof ITextEditor) ? (ITextEditor) part : null; + fContentAssist.setAction(getAction(editor, CONTENTASSIST_ACTION)); + // jsurfer + setBrowserPreview(editor); + } + + public void setBrowserPreview(ITextEditor editor) { + IWorkbenchPage page = WikiEditorPlugin.getDefault().getActivePage(); + try { + IViewPart part = page.findView(BrowserView.ID_BROWSER); + if (part == null) { + part = page.showView(BrowserView.ID_BROWSER); + } else { + // if (bringToTopPreview) { + // page.bringToTop(part); + // } + } + IEditorInput editorInput = null; + if (editor != null) { + editorInput = editor.getEditorInput(); + } + if (editorInput instanceof IFileEditorInput) { + IFile file = ((IFileEditorInput) editorInput).getFile(); + String srcBasePath = Util.getWikiTextsPath(file); + String binBasePath = Util.getProjectsWikiOutputPath(file.getProject(), WikiEditorPlugin.HTML_OUTPUT_PATH); + String htmlName = Util.getHTMLFileName(file, binBasePath, srcBasePath); + if (htmlName!=null) { + ((BrowserView) part).setUrl(htmlName); + } + } + } catch (Exception e) { + } + } + + public void contributeToMenu(IMenuManager menu) { + + super.contributeToMenu(menu); + +} + + public void init(IActionBars bars, IWorkbenchPage page) { + super.init(bars, page); + bars.setGlobalActionHandler(CONTENTASSIST_ACTION, fContentAssist); + + } + + public void dispose() { + setActiveEditor(null); + super.dispose(); + } +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/WikiEditorMessages.properties b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/WikiEditorMessages.properties new file mode 100644 index 0000000..9b35369 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/WikiEditorMessages.properties @@ -0,0 +1,10 @@ +ContentAssistProposal.label=Content Assist +ContentAssistProposal.tooltip=Content Assist +ContentAssistProposal.description=Content Assist + +Export.exportFile=Export Wiki file: +Export.exportFolder=Export Wiki folder: +Export.wizardTitle=Wiki Text Exporter +Export.wizardDescription=Export Wiki texts to the file system +Export.wizardBrowse=Browse... +Export.wizardSelectFolder=Select a folder diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/WikiEditorPlugin.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/WikiEditorPlugin.java new file mode 100644 index 0000000..6226851 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/WikiEditorPlugin.java @@ -0,0 +1,350 @@ +package net.sourceforge.phpeclipse.wiki.editor; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.text.MessageFormat; +import java.util.Hashtable; +import java.util.List; +import java.util.MissingResourceException; +import java.util.ResourceBundle; + +import net.sourceforge.phpeclipse.wiki.internal.IConfigurationWorkingCopy; +import net.sourceforge.phpeclipse.wiki.internal.ConfigurationManager; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IExtension; +import org.eclipse.core.runtime.IPluginDescriptor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Platform; +import org.eclipse.core.runtime.Status; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.jface.text.templates.ContextTypeRegistry; +import org.eclipse.jface.text.templates.persistence.TemplateStore; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.IWorkbenchWindow; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.editors.text.templates.ContributionContextTypeRegistry; +import org.eclipse.ui.editors.text.templates.ContributionTemplateStore; +import org.eclipse.ui.plugin.AbstractUIPlugin; + +public class WikiEditorPlugin extends AbstractUIPlugin { + + private static WikiEditorPlugin fgPlugin; + public static final String HTTP_QUERY = "HTTP Query"; + public static final String WIKIPEDIA_GET_TEXT = "Wikipedia-Load Text"; + public static final String WEBLOG_API_SEND = "MetaWeblog API-Post"; + + public static final String[] CONFIGURATION_TYPES = { + HTTP_QUERY, + WIKIPEDIA_GET_TEXT, + WEBLOG_API_SEND + }; + //image paths + public static final String ICON_PATH = "icons/full/"; //$NON-NLS-1$ + + public final static String PLUGIN_ID = "net.sourceforge.phpeclipse.wiki"; + + public final static String HTML_OUTPUT_PATH = "__static_wiki_folder"; + + public final static String WIKI_TEXTS_BASE_PATH = "__wiki_texts_base_path"; + + private static ConfigurationManager manager; + + public static final String IMG_MONITOR_ON = "monitorOn"; + + public static final String IMG_MONITOR_OFF = "monitorOff"; + + /** + * Creates an image and places it in the image registry. + * + * @param id + * the identifier for the image + * @param baseURL + * the base URL for the image + */ + protected static void createImageDescriptor(WikiEditorPlugin plugin, String id, URL baseURL) { + // Delegate to the plugin instance to avoid concurrent class loading problems + plugin.privateCreateImageDescriptor(id, baseURL); + } + + public static WikiEditorPlugin getDefault() { + return fgPlugin; + } + + /** + * Returns the image descriptor for the given image ID. Returns null if there is no such image. + * + * @param id + * the identifier for the image to retrieve + * @return the image associated with the given ID + */ + public static ImageDescriptor getImageDescriptor(String id) { + // Delegate to the plugin instance to avoid concurrent class loading problems + return getDefault().privateGetImageDescriptor(id); + } + + /** + * Convenience method to get an image descriptor for an extension + * + * @param extension + * the extension declaring the image + * @param subdirectoryAndFilename + * the path to the image + * @return the image + */ + public static ImageDescriptor getImageDescriptorFromExtension(IExtension extension, String subdirectoryAndFilename) { + IPluginDescriptor pluginDescriptor = extension.getDeclaringPluginDescriptor(); + URL path = pluginDescriptor.getInstallURL(); + URL fullPathString = null; + try { + fullPathString = new URL(path, subdirectoryAndFilename); + return ImageDescriptor.createFromURL(fullPathString); + } catch (MalformedURLException e) { + } + return null; + } + + public static String getResourceString(String key) { + ResourceBundle bundle = WikiEditorPlugin.getDefault().getResourceBundle(); + try { + return (bundle != null) ? bundle.getString(key) : key; + } catch (MissingResourceException e) { + return key; + } + } + + /** + * Returns the standard display to be used. The method first checks, if the thread calling this method has an associated display. + * If so, this display is returned. Otherwise the method returns the default display. + */ + public static Display getStandardDisplay() { + Display display = Display.getCurrent(); + if (display == null) { + display = Display.getDefault(); + } + return display; + } + + private ContributionContextTypeRegistry fContextTypeRegistry; + + private ResourceBundle fResourceBundle; + + private ContributionTemplateStore fTemplateStore; + + private Hashtable imageDescriptors = new Hashtable(20); + + public WikiEditorPlugin(IPluginDescriptor descriptor) { + super(descriptor); + initializeImages(); + fgPlugin = this; + manager = ConfigurationManager.getInstance(); + try { + fResourceBundle = ResourceBundle.getBundle("net.sourceforge.phpeclipse.wiki.editor.WikiEditorMessages"); + } catch (MissingResourceException x) { + fResourceBundle = null; + } + } + + /** + * Creates an image and places it in the image registry. + */ + protected void createImageDescriptor(String id, URL baseURL) { + URL url = null; + try { + url = new URL(baseURL, ICON_PATH + id); + } catch (MalformedURLException e) { + } + ImageDescriptor desc = ImageDescriptor.createFromURL(url); + imageDescriptors.put(id, desc); + } + + public IWorkbenchPage getActivePage() { + IWorkbenchWindow window = getWorkbench().getActiveWorkbenchWindow(); + if (window != null) + return window.getActivePage(); + return null; + } + + public ContextTypeRegistry getContextTypeRegistry() { + if (fContextTypeRegistry == null) { + fContextTypeRegistry = new ContributionContextTypeRegistry(); + fContextTypeRegistry.addContextType("net.sourceforge.phpeclipse.wiki.editor.templates"); + } + return fContextTypeRegistry; + } + + public Image getImage(String key) { + Image image = getImageRegistry().get(key); + if (image == null) { + ImageDescriptor d = getImageDescriptor(key); + image = d.createImage(); + getImageRegistry().put(key, image); + } + return image; + } + + public ResourceBundle getResourceBundle() { + return fResourceBundle; + } + + public TemplateStore getTemplateStore() { + if (fTemplateStore == null) { + fTemplateStore = new ContributionTemplateStore(getContextTypeRegistry(), getDefault().getPreferenceStore(), "templates"); + try { + fTemplateStore.load(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + return fTemplateStore; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.ui.plugin.AbstractUIPlugin#initializeDefaultPreferences(org.eclipse.jface.preference.IPreferenceStore) + */ + protected void initializeDefaultPreferences(IPreferenceStore store) { + } + + /* + * Initializes the table of images used in this plugin. The plugin is provided because this method is called before the plugin + * staic variable has been set. See the comment on the getPlugin() method for a description of why this is required. + */ + private void initializeImages() { + URL baseURL = getDescriptor().getInstallURL(); + + // special + createImageDescriptor("glyphs/glyph1.gif", baseURL); //$NON-NLS-1$ + createImageDescriptor("glyphs/glyph2.gif", baseURL); //$NON-NLS-1$ + createImageDescriptor("glyphs/glyph3.gif", baseURL); //$NON-NLS-1$ + createImageDescriptor("glyphs/glyph4.gif", baseURL); //$NON-NLS-1$ + createImageDescriptor("glyphs/glyph5.gif", baseURL); //$NON-NLS-1$ + createImageDescriptor("glyphs/glyph6.gif", baseURL); //$NON-NLS-1$ + createImageDescriptor("glyphs/glyph7.gif", baseURL); //$NON-NLS-1$ + createImageDescriptor("glyphs/glyph8.gif", baseURL); //$NON-NLS-1$ + + } + + public void log(String message) { + getDefault().getLog().log(new Status(IStatus.OK, PLUGIN_ID, IStatus.OK, message, null)); + } + + public void log(String message, Exception e) { + getDefault().getLog().log(new Status(IStatus.ERROR, PLUGIN_ID, IStatus.OK, "Caught exception", e)); + } + + public void logAndReport(String title, String message, Exception e) { + log(message, e); + reportError(title, message); + } + + private void privateCreateImageDescriptor(String id, URL baseURL) { + URL url = null; + try { + url = new URL(baseURL, ICON_PATH + id); + } catch (MalformedURLException e) { + } + ImageDescriptor desc = ImageDescriptor.createFromURL(url); + imageDescriptors.put(id, desc); + } + + private ImageDescriptor privateGetImageDescriptor(String id) { + if (!imageDescriptors.containsKey(id)) { + URL baseURL = WikiEditorPlugin.getDefault().getDescriptor().getInstallURL(); + createImageDescriptor(getDefault(), id, baseURL); + } + return (ImageDescriptor) imageDescriptors.get(id); + } + + public void reportError(String title, String message) { + try { + Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); + MessageDialog.openError(shell, title, message); + } catch (RuntimeException e) { + log(e.getLocalizedMessage(), e); + } + } + + public void startup() throws CoreException { + super.startup(); + } + + /** + * Returns the translated String found with the given key. + * + * @return java.lang.String + * @param key + * java.lang.String + */ + public static String getResource(String key) { + try { + return Platform.getResourceString(getDefault().getBundle(), key); + } catch (Exception e) { + return key; + } + } + + /** + * Returns the translated String found with the given key, and formatted with the given object. + * + * @param key + * java.lang.String + * @param obj + * java.lang.Object[] + * @return java.lang.String + */ + public static String getResource(String key, Object[] obj) { + try { + return MessageFormat.format(getResource(key), obj); + } catch (Exception e) { + return key; + } + } + + /** + * Returns the translated String found with the given key, and formatted with the given object. + * + * @param key + * java.lang.String + * @param s + * java.lang.String + * @return java.lang.String + */ + public static String getResource(String key, String s) { + try { + return MessageFormat.format(getResource(key), new String[] { s }); + } catch (Exception e) { + return key; + } + } + + /** + * Return a list of all the existing configurations. + * + * @return java.util.List + */ + public static List getConfigurations() { + return manager.getConfigurations(); + } + + /** + * Create a new monitor. + * + * @return working copy + */ + public static IConfigurationWorkingCopy createConfiguration() { + return manager.createConfiguration(); + } + + public static String[] getTypes() { + return CONFIGURATION_TYPES; + } +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/WikiFoldingStructureProvider.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/WikiFoldingStructureProvider.java new file mode 100644 index 0000000..742ced9 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/WikiFoldingStructureProvider.java @@ -0,0 +1,104 @@ +package net.sourceforge.phpeclipse.wiki.editor; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import net.sourceforge.phpeclipse.wiki.editor.model.WikipediaText; +import net.sourceforge.phpeclipse.wiki.editor.model.WikipediaSection; + +import org.eclipse.core.runtime.IProgressMonitor; + +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.Position; +import org.eclipse.jface.text.source.Annotation; +import org.eclipse.jface.text.source.projection.ProjectionAnnotation; +import org.eclipse.jface.text.source.projection.ProjectionAnnotationModel; + +public class WikiFoldingStructureProvider { + + private WikiEditor fEditor; + + private IDocument fDocument; + + private IProgressMonitor fProgressMonitor; + + public WikiFoldingStructureProvider(WikiEditor editor) { + fEditor = editor; + } + + public void setProgressMonitor(IProgressMonitor progressMonitor) { + fProgressMonitor = progressMonitor; + } + + public void setDocument(IDocument document) { + fDocument = document; + } + + public void updateFoldingRegions(WikipediaSection section) { + try { + + ProjectionAnnotationModel model = (ProjectionAnnotationModel) fEditor.getAdapter(ProjectionAnnotationModel.class); + if (model == null) + return; + + Set currentRegions = new HashSet(); + addFoldingRegions(currentRegions, section.getChildren()); + updateFoldingRegions(model, currentRegions); + } catch (BadLocationException e) { + e.printStackTrace(); + } + } + + private void updateFoldingRegions(ProjectionAnnotationModel model, Set currentRegions) { + Annotation[] deletions = computeDifferences(model, currentRegions); + + Map additionsMap = new HashMap(); + for (Iterator iter = currentRegions.iterator(); iter.hasNext();) + additionsMap.put(new ProjectionAnnotation(), iter.next()); + + if ((deletions.length != 0 || additionsMap.size() != 0) && (fProgressMonitor == null || !fProgressMonitor.isCanceled())) + model.modifyAnnotations(deletions, additionsMap, new Annotation[] {}); + } + + private Annotation[] computeDifferences(ProjectionAnnotationModel model, Set current) { + List deletions = new ArrayList(); + for (Iterator iter = model.getAnnotationIterator(); iter.hasNext();) { + Object annotation = iter.next(); + if (annotation instanceof ProjectionAnnotation) { + Position position = model.getPosition((Annotation) annotation); + if (current.contains(position)) + current.remove(position); + else + deletions.add(annotation); + } + } + return (Annotation[]) deletions.toArray(new Annotation[deletions.size()]); + } + + private void addFoldingRegions(Set regions, Object[] elements) throws BadLocationException { + for (int i = 0; i < elements.length; i++) { + WikipediaSection element = (WikipediaSection) elements[i]; + if (element.getOffset() >= 0) { + int startLine = fDocument.getLineOfOffset(element.getOffset()); + int endLine = fDocument.getLineOfOffset(element.getOffset() + element.getLength()); + if (startLine < endLine) { + int start = fDocument.getLineOffset(startLine); + int end = fDocument.getLineOffset(endLine) + fDocument.getLineLength(endLine); + Position position = new Position(start, end - start); + regions.add(position); + } + + Object[] children = element.getChildren(); + if (children != null) { + addFoldingRegions(regions, children); + } + } + } + } +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/WikiOccurrencesUpdater.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/WikiOccurrencesUpdater.java new file mode 100644 index 0000000..5043237 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/WikiOccurrencesUpdater.java @@ -0,0 +1,165 @@ +/******************************************************************************* + * Copyright (c) 2000, 2004 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpeclipse.wiki.editor; + +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +import net.sourceforge.phpeclipse.wiki.editor.model.WikipediaText; + +import org.eclipse.jface.viewers.IPostSelectionProvider; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.ISelectionChangedListener; +import org.eclipse.jface.viewers.SelectionChangedEvent; + +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.ITextSelection; +import org.eclipse.jface.text.Position; +import org.eclipse.jface.text.source.Annotation; +import org.eclipse.jface.text.source.IAnnotationModel; +import org.eclipse.jface.text.source.ISourceViewer; + + + +class WikiOccurrencesUpdater implements ISelectionChangedListener { + /** + * Annotation fType for recipe occurrences. + */ + private static final String ANNOTATION_TYPE= "net.sourceforge.phpeclipse.wiki.editor.highlightannotation"; + /** + * The editor we operate on. + */ + private final WikiEditor fEditor; + /** + * The set of annotations added in the previous run, always replaced by a + * new run. + */ + private final List fOldAnnotations= new LinkedList(); + + /** + * Creates a new instance on editor editor. + * + * @param editor the editor to mark occurrences on. + */ + public WikiOccurrencesUpdater(WikiEditor editor) { + ((IPostSelectionProvider) editor.getSelectionProvider()).addPostSelectionChangedListener(this); + fEditor= editor; + } + + /* + * @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent) + */ + public void selectionChanged(SelectionChangedEvent event) { + update((ISourceViewer) event.getSource()); + } + + /** + * Updates the drawn annotations. + * + * @param viewer the viewer to get the document and annotation model from + */ + public void update(ISourceViewer viewer) { + if (viewer==null) { + return; + } +// try { + IDocument document= viewer.getDocument(); + IAnnotationModel model= viewer.getAnnotationModel(); + if (document == null || model == null) + return; + + removeOldAnnotations(model); + +// String word= getWordAtSelection(fEditor.getSelectionProvider().getSelection(), document); +// if (isIngredient(word)) { +// createNewAnnotations(word, document, model); +// } + +// } catch (BadLocationException e) { +// // ignore +// } + } + + /** + * Removes the previous set of annotations from the annotation model. + * + * @param model the annotation model + */ + private void removeOldAnnotations(IAnnotationModel model) { + for (Iterator it= fOldAnnotations.iterator(); it.hasNext();) { + Annotation annotation= (Annotation) it.next(); + model.removeAnnotation(annotation); + } + fOldAnnotations.clear(); + } + + /** + * Returns the word at the current selection / caret position. + * + * @param selection the selection + * @param document the document + * @return the currently selected text, or the word at the caret if the + * selection has length 0 + * @throws BadLocationException if accessing the document fails + */ + private String getWordAtSelection(ISelection selection, IDocument document) throws BadLocationException { + if (selection instanceof ITextSelection) { + ITextSelection ts= (ITextSelection) selection; + int offset= ts.getOffset(); + int end= offset + ts.getLength(); + + // non-empty selections + if (end != offset) + return ts.getText(); + + while (offset > 0 && isIngredientChar(document.getChar(offset - 1))) + offset--; + while (end < document.getLength() && isIngredientChar(document.getChar(end))) + end++; + + return document.get(offset, end - offset); + } + return ""; + } + + private boolean isIngredientChar(char c) { + return !Character.isWhitespace(c) && c != ':' && c != ',' && c != '.'; + } + + /** + * Adds an annotation for every occurrence of + * ingredient in the document. Also stores the created + * annotations in fOldAnnotations. + * + * @param ingredient the word to look for + * @param document the document + * @param model the annotation model + */ + private void createNewAnnotations(String ingredient, IDocument document, IAnnotationModel model) { + String content= document.get(); + int idx= content.indexOf(ingredient); + while (idx != -1) { + Annotation annotation= new Annotation(ANNOTATION_TYPE, false, ingredient); + Position position= new Position(idx, ingredient.length()); + + model.addAnnotation(annotation, position); + fOldAnnotations.add(annotation); + + idx= content.indexOf(ingredient, idx + 1); + } + } + + public void dispose() { + ((IPostSelectionProvider) fEditor.getSelectionProvider()).removePostSelectionChangedListener(this); + } +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/WikiOutlinePage.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/WikiOutlinePage.java new file mode 100644 index 0000000..92f74e1 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/WikiOutlinePage.java @@ -0,0 +1,143 @@ +/*********************************************************************************************************************************** + * Copyright (c) 2000, 2004 IBM Corporation and others. All rights reserved. This program and the accompanying materials are made + * available under the terms of the Common Public License v1.0 which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: IBM Corporation - initial API and implementation + **********************************************************************************************************************************/ +package net.sourceforge.phpeclipse.wiki.editor; + +import java.net.MalformedURLException; +import java.net.URL; + +import net.sourceforge.phpeclipse.wiki.editor.model.WikipediaText; +import net.sourceforge.phpeclipse.wiki.editor.model.WikipediaSection; + +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.widgets.Composite; + +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.jface.viewers.AbstractTreeViewer; +import org.eclipse.jface.viewers.ISelectionChangedListener; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.viewers.ITreeContentProvider; +import org.eclipse.jface.viewers.LabelProvider; +import org.eclipse.jface.viewers.SelectionChangedEvent; +import org.eclipse.jface.viewers.TreeViewer; +import org.eclipse.jface.viewers.Viewer; + +import org.eclipse.ui.views.contentoutline.ContentOutlinePage; + +public class WikiOutlinePage extends ContentOutlinePage { + + private WikiEditor fEditor; + + private static class WikiContentProvider implements ITreeContentProvider { + + public Object[] getChildren(Object parentElement) { + return ((WikipediaSection) parentElement).getChildren(); + } + + public Object getParent(Object element) { + return ((WikipediaSection) element).getParent(); + } + + public boolean hasChildren(Object element) { + Object[] children = getChildren(element); + return children != null && children.length != 0; + } + + public Object[] getElements(Object inputElement) { + return getChildren(inputElement); + } + + public void dispose() { + // do nothing + } + + public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { + // do nothing + } + } + + private static class WikiLabelProvider extends LabelProvider { + private static URL fgIconBaseURL = WikiEditorPlugin.getDefault().getBundle().getEntry("/icons/"); + + private final Image fIngredientsSectionIcon = createImage("ingredients.gif"); + + private final Image fIngredientIcon = createImage("ingredient.gif"); + + private final Image fPreparationSectionIcon = createImage("preparation.gif"); + + private final Image fStepIcon = createImage("step.gif"); + + public static Image createImage(String icon) { + try { + ImageDescriptor id = ImageDescriptor.createFromURL(new URL(fgIconBaseURL, icon)); + return id.createImage(); + } catch (MalformedURLException e) { + // no icon ... + } + return null; + } + + public String getText(Object element) { + return ((WikipediaSection) element).getName(); + } + + public Image getImage(Object element) { + if (element instanceof WikipediaSection) + return fStepIcon; + return super.getImage(element); + } + + public void dispose() { + super.dispose(); + if (fIngredientsSectionIcon != null) + fIngredientsSectionIcon.dispose(); + if (fIngredientIcon != null) + fIngredientIcon.dispose(); + if (fPreparationSectionIcon != null) + fPreparationSectionIcon.dispose(); + if (fStepIcon != null) + fStepIcon.dispose(); + } + } + + public WikiOutlinePage(WikiEditor editor) { + fEditor = editor; + } + + public void createControl(Composite parent) { + super.createControl(parent); + TreeViewer treeViewer = getTreeViewer(); + treeViewer.setLabelProvider(new WikiLabelProvider()); + treeViewer.setContentProvider(new WikiContentProvider()); + treeViewer.setAutoExpandLevel(AbstractTreeViewer.ALL_LEVELS); + treeViewer.addSelectionChangedListener(new ISelectionChangedListener() { + public void selectionChanged(SelectionChangedEvent event) { + if (!(event.getSelection() instanceof IStructuredSelection)) + return; + IStructuredSelection selection = (IStructuredSelection) event.getSelection(); + if (selection.size() != 1) + return; + Object element = selection.getFirstElement(); + if (!(element instanceof WikipediaSection)) + return; + WikipediaSection recipeElement = (WikipediaSection) element; + fEditor.selectAndReveal(recipeElement.getOffset(), recipeElement.getLength()); + } + }); + setWiki(fEditor.getSection()); + } + + public void setWiki(WikipediaSection section) { + getTreeViewer().setInput(section); + } + + public void dispose() { + super.dispose(); + fEditor.outlinePageClosed(); + fEditor = null; + } +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/WikiReconcilingStrategy.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/WikiReconcilingStrategy.java new file mode 100644 index 0000000..0645e1c --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/WikiReconcilingStrategy.java @@ -0,0 +1,79 @@ +/******************************************************************************* + * Copyright (c) 2000, 2004 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpeclipse.wiki.editor; + +import net.sourceforge.phpeclipse.wiki.editor.model.WikipediaOutlineParser; +import net.sourceforge.phpeclipse.wiki.editor.model.WikipediaSection; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.reconciler.DirtyRegion; +import org.eclipse.jface.text.reconciler.IReconcilingStrategy; +import org.eclipse.jface.text.reconciler.IReconcilingStrategyExtension; +import org.eclipse.swt.widgets.Shell; + + + +public class WikiReconcilingStrategy implements IReconcilingStrategy, IReconcilingStrategyExtension { + + private WikiEditor fEditor; + private IDocument fDocument; + private IProgressMonitor fProgressMonitor; + + private WikipediaOutlineParser fParser; + private WikiFoldingStructureProvider fFoldingStructureProvider; + + public WikiReconcilingStrategy(WikiEditor editor) { + fEditor= editor; + fParser= new WikipediaOutlineParser(); + fFoldingStructureProvider= new WikiFoldingStructureProvider(editor); + } + + public void setDocument(IDocument document) { + fDocument= document; + fFoldingStructureProvider.setDocument(fDocument); + } + + public void setProgressMonitor(IProgressMonitor monitor) { + fProgressMonitor= monitor; + fFoldingStructureProvider.setProgressMonitor(fProgressMonitor); + } + + public void reconcile(DirtyRegion dirtyRegion, IRegion subRegion) { + reconcile(); + } + + public void reconcile(IRegion partition) { + reconcile(); + } + + public void initialReconcile() { + reconcile(); + } + + private void reconcile() { + final WikipediaSection section= fParser.parse(fDocument); + if (section == null) + return; + + Shell shell= fEditor.getSite().getShell(); + if (shell == null || shell.isDisposed()) + return; + + shell.getDisplay().asyncExec(new Runnable() { + public void run() { + fEditor.setSection(section); + } + }); + fFoldingStructureProvider.updateFoldingRegions(section); + } +} diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/WikiSourceViewerConfiguration.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/WikiSourceViewerConfiguration.java new file mode 100644 index 0000000..3bc9c4e --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/WikiSourceViewerConfiguration.java @@ -0,0 +1,259 @@ +/*********************************************************************************************************************************** + * Copyright (c) 2000, 2004 IBM Corporation and others. All rights reserved. This program and the accompanying materials are made + * available under the terms of the Common Public License v1.0 which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: IBM Corporation - initial API and implementation + **********************************************************************************************************************************/ +package net.sourceforge.phpeclipse.wiki.editor; + +import org.eclipse.core.runtime.NullProgressMonitor; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.RGB; + +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.TextAttribute; +import org.eclipse.jface.text.contentassist.ContentAssistant; +import org.eclipse.jface.text.contentassist.IContentAssistProcessor; +import org.eclipse.jface.text.contentassist.IContentAssistant; +import org.eclipse.jface.text.presentation.IPresentationReconciler; +import org.eclipse.jface.text.presentation.PresentationReconciler; +import org.eclipse.jface.text.reconciler.IReconciler; +import org.eclipse.jface.text.reconciler.MonoReconciler; +import org.eclipse.jface.text.rules.DefaultDamagerRepairer; +import org.eclipse.jface.text.rules.IRule; +import org.eclipse.jface.text.rules.IToken; +import org.eclipse.jface.text.rules.ITokenScanner; +import org.eclipse.jface.text.rules.IWordDetector; +import org.eclipse.jface.text.rules.RuleBasedScanner; +import org.eclipse.jface.text.rules.SingleLineRule; +import org.eclipse.jface.text.rules.Token; +import org.eclipse.jface.text.rules.WordRule; +import org.eclipse.jface.text.source.IAnnotationHover; +import org.eclipse.jface.text.source.ISharedTextColors; +import org.eclipse.jface.text.source.ISourceViewer; +import org.eclipse.jface.text.source.SourceViewerConfiguration; + +public class WikiSourceViewerConfiguration extends SourceViewerConfiguration { + + /** + * A no-op implementation of IAnnotationHover that will trigger the text editor to set up annotation hover support. + */ + private static final class NullHover implements IAnnotationHover { + + /* + * @see org.eclipse.jface.text.source.IAnnotationHover#getHoverInfo(org.eclipse.jface.text.source.ISourceViewer, int) + */ + public String getHoverInfo(ISourceViewer sourceViewer, int lineNumber) { + return null; + } + } + + /** + * Simple word detector that detects any sequence of non-whitespace as a word. + */ + private static final class SimpleWordDetector implements IWordDetector { + /* + * @see org.eclipse.jface.text.rules.IWordDetector#isWordStart(char) + */ + public boolean isWordStart(char c) { + return isWordPart(c); + } + + /* + * @see org.eclipse.jface.text.rules.IWordDetector#isWordPart(char) + */ + public boolean isWordPart(char c) { + return !Character.isWhitespace(c); + } + } + + private static final class SimpleListDetector implements IWordDetector { + /* + * @see org.eclipse.jface.text.rules.IWordDetector#isWordStart(char) + */ + public boolean isWordStart(char c) { + return c == '*' || c == '#'; + } + + /* + * @see org.eclipse.jface.text.rules.IWordDetector#isWordPart(char) + */ + public boolean isWordPart(char c) { + return true; + } + } + + private final ISharedTextColors fColors; + + private WikiEditor fEditor; + + public WikiSourceViewerConfiguration(WikiEditor editor, ISharedTextColors colors) { + fEditor = editor; + fColors = colors; + } + + /* + * @see org.eclipse.jface.text.source.SourceViewerConfiguration#getPresentationReconciler(org.eclipse.jface.text.source.ISourceViewer) + */ + public IPresentationReconciler getPresentationReconciler(ISourceViewer sourceViewer) { + PresentationReconciler reconciler = new PresentationReconciler(); + DefaultDamagerRepairer dr = new DefaultDamagerRepairer(getRecipeScanner()); + reconciler.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE); + reconciler.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE); + return reconciler; + } + + private ITokenScanner getRecipeScanner() { + RuleBasedScanner scanner = new RuleBasedScanner(); + + IRule[] rules = new IRule[11]; + rules[0] = createHeader6Rule(); + rules[1] = createHeader5Rule(); + rules[2] = createHeader4Rule(); + rules[3] = createHeader3Rule(); + rules[4] = createHeader2Rule(); + rules[5] = createHeader1Rule(); + rules[6] = createHRRule(); + rules[7] = createLinkRule(); + rules[8] = createExternalHTTPRule(); + rules[9] = createListRule(); + rules[10] = createNumberedListRule(); + + scanner.setRules(rules); + return scanner; + } + + // private IRule createSectionTitleRule() { + // IToken titleToken= new Token(new TextAttribute(null, null, SWT.BOLD)); + // WordRule wordRule= new WordRule(new SimpleWordDetector()); + // wordRule.addWord(IngredientsSection.TITLE + ":", titleToken); + // wordRule.addWord(PreparationSection.TITLE + ":", titleToken); + // return wordRule; + // } + + private IRule createHRRule() { + IToken quantityToken = new Token(new TextAttribute(fColors.getColor(new RGB(0, 0, 140)), null, SWT.ITALIC)); + SingleLineRule singleLineRule = new SingleLineRule("----", "\n", quantityToken); + singleLineRule.setColumnConstraint(0); + return singleLineRule; + } + + private IRule createHeader1Rule() { + IToken quantityToken = new Token(new TextAttribute(fColors.getColor(new RGB(0, 0, 140)), null, SWT.ITALIC)); + SingleLineRule singleLineRule = new SingleLineRule("=", "=", quantityToken); + singleLineRule.setColumnConstraint(0); + return singleLineRule; + } + + private IRule createHeader2Rule() { + IToken quantityToken = new Token(new TextAttribute(fColors.getColor(new RGB(0, 0, 140)), null, SWT.ITALIC)); + SingleLineRule singleLineRule = new SingleLineRule("==", "==", quantityToken); + singleLineRule.setColumnConstraint(0); + return singleLineRule; + } + + private IRule createHeader3Rule() { + IToken quantityToken = new Token(new TextAttribute(fColors.getColor(new RGB(0, 0, 140)), null, SWT.ITALIC)); + SingleLineRule singleLineRule = new SingleLineRule("===", "===", quantityToken); + singleLineRule.setColumnConstraint(0); + return singleLineRule; + } + + private IRule createHeader4Rule() { + IToken quantityToken = new Token(new TextAttribute(fColors.getColor(new RGB(0, 0, 140)), null, SWT.ITALIC)); + SingleLineRule singleLineRule = new SingleLineRule("====", "====", quantityToken); + singleLineRule.setColumnConstraint(0); + return singleLineRule; + } + + private IRule createHeader5Rule() { + IToken quantityToken = new Token(new TextAttribute(fColors.getColor(new RGB(0, 0, 140)), null, SWT.ITALIC)); + SingleLineRule singleLineRule = new SingleLineRule("=====", "=====", quantityToken); + singleLineRule.setColumnConstraint(0); + return singleLineRule; + } + + private IRule createHeader6Rule() { + IToken quantityToken = new Token(new TextAttribute(fColors.getColor(new RGB(0, 0, 140)), null, SWT.ITALIC)); + SingleLineRule singleLineRule = new SingleLineRule("======", "======", quantityToken); + singleLineRule.setColumnConstraint(0); + return singleLineRule; + } + + // private IRule createLeadingDashRule() { + // IToken dashToken= new Token(new TextAttribute(fColors.getColor(new RGB(200, 100, 100)), null, SWT.BOLD)); + // WordRule wordRule= new WordRule(new SimpleWordDetector()); + // wordRule.addWord("-", dashToken); + // wordRule.setColumnConstraint(0); + // return wordRule; + // } + + private IRule createListRule() { + IToken dashToken = new Token(new TextAttribute(fColors.getColor(new RGB(63, 127, 95)), null, SWT.BOLD)); + // WordRule wordRule= new WordRule(new SimpleListDetector()); + // wordRule.addWord("*", dashToken); + SingleLineRule singleLineRule = new SingleLineRule("*", "\n", dashToken); + singleLineRule.setColumnConstraint(0); + return singleLineRule; + } + + private IRule createNumberedListRule() { + IToken dashToken = new Token(new TextAttribute(fColors.getColor(new RGB(63, 127, 95)), null, SWT.BOLD)); + // WordRule wordRule= new WordRule(new SimpleListDetector()); + // wordRule.addWord("#", dashToken); + SingleLineRule singleLineRule = new SingleLineRule("#", "\n", dashToken); + singleLineRule.setColumnConstraint(0); + return singleLineRule; + } + + private IRule createLinkRule() { + IToken stepToken = new Token(new TextAttribute(fColors.getColor(new RGB(200, 100, 100)), null, SWT.BOLD)); + SingleLineRule stepRule = new SingleLineRule("[[", "]]", stepToken); + // stepRule.setColumnConstraint(0); + return stepRule; + } + + private IRule createExternalHTTPRule() { + IToken stepToken = new Token(new TextAttribute(fColors.getColor(new RGB(200, 100, 100)), null, SWT.BOLD)); + SingleLineRule stepRule = new SingleLineRule("[http", "]", stepToken); + // stepRule.setColumnConstraint(0); + return stepRule; + } + + /* + * @see SourceViewerConfiguration#getReconciler(ISourceViewer) + */ + public IReconciler getReconciler(ISourceViewer sourceViewer) { + WikiReconcilingStrategy strategy = new WikiReconcilingStrategy(fEditor); + MonoReconciler reconciler = new MonoReconciler(strategy, false); + reconciler.setProgressMonitor(new NullProgressMonitor()); + reconciler.setDelay(500); + + return reconciler; + } + + /* + * @see org.eclipse.jface.text.source.SourceViewerConfiguration#getContentAssistant(org.eclipse.jface.text.source.ISourceViewer) + */ + public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) { + ContentAssistant assistant = new ContentAssistant(); + + IContentAssistProcessor processor = new WikiCompletionProcessor(fEditor); + assistant.setContentAssistProcessor(processor, IDocument.DEFAULT_CONTENT_TYPE); + + assistant.setContextInformationPopupOrientation(IContentAssistant.CONTEXT_INFO_ABOVE); + assistant.setInformationControlCreator(getInformationControlCreator(sourceViewer)); + assistant.enableAutoInsert(true); + + return assistant; + } + + /* + * @see org.eclipse.jface.text.source.SourceViewerConfiguration#getAnnotationHover(org.eclipse.jface.text.source.ISourceViewer) + */ + public IAnnotationHover getAnnotationHover(ISourceViewer sourceViewer) { + return new NullHover(); + } +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/action/WeblogWikiAction.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/action/WeblogWikiAction.java new file mode 100644 index 0000000..db7c908 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/action/WeblogWikiAction.java @@ -0,0 +1,42 @@ +/******************************************************************************* + * Copyright (c) 2000, 2004 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package net.sourceforge.phpeclipse.wiki.editor.action; + +import net.sourceforge.phpeclipse.wiki.editor.WikiEditor; +import net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin; + +import org.eclipse.ui.texteditor.ITextEditor; +import org.eclipse.ui.texteditor.TextEditorAction; + + +public class WeblogWikiAction extends TextEditorAction { + + private boolean fForward; + + public WeblogWikiAction(String prefix, boolean forward) { + super(WikiEditorPlugin.getDefault().getResourceBundle(), prefix, null); + } + + public void run() { + + } + + public void setEditor(ITextEditor editor) { + if (editor instanceof WikiEditor) + super.setEditor(editor); + update(); + } + + public void update() { + setEnabled(getTextEditor() instanceof WikiEditor); + } +} diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/model/WikipediaOutlineParser.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/model/WikipediaOutlineParser.java new file mode 100644 index 0000000..694f4f9 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/model/WikipediaOutlineParser.java @@ -0,0 +1,128 @@ +/*********************************************************************************************************************************** + * Copyright (c) 2000, 2004 IBM Corporation and others. All rights reserved. This program and the accompanying materials are made + * available under the terms of the Common Public License v1.0 which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: IBM Corporation - initial API and implementation + **********************************************************************************************************************************/ +package net.sourceforge.phpeclipse.wiki.editor.model; + +import java.util.Stack; + +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IRegion; + +public class WikipediaOutlineParser { + + private IDocument fDocument; + + /** + * Next line to read. + */ + private int fLine; + + private int fLineCount; + + public WikipediaSection parse(IDocument document) { + try { + fDocument = document; + fLine = 0; + fLineCount = fDocument.getNumberOfLines(); + return parseWikipediaText(); + } catch (BadLocationException e) { + e.printStackTrace(); + return null; + } + } + + private WikipediaSection parseWikipediaText() throws BadLocationException { + Stack stack = new Stack(); + char ch; + WikipediaText wikiText = new WikipediaText(); + WikipediaSection section; + // int startOffset = -1; + String textString; + String headerString = null; + char[] text; + IRegion region = null; + int headerStartOffset; + int headerEndOffset; + int headerLevelCounter; + + while (fLine < fLineCount) { + region = fDocument.getLineInformation(fLine); + textString = fDocument.get(region.getOffset(), region.getLength()); + text = textString.toCharArray(); + fLine++; + + headerStartOffset = 0; + if (text.length >= 2 && text[headerStartOffset++] == '=') { + headerEndOffset = text.length; + while (headerEndOffset > 0 && Character.isWhitespace(text[--headerEndOffset])) { + // + } + if (text[headerEndOffset] == '=') { + // header section + while (headerStartOffset < text.length && headerStartOffset < 6 && text[headerStartOffset++] == '=') { + // + } + headerLevelCounter = 1; + while (headerEndOffset > 0 && headerLevelCounter < headerStartOffset && text[--headerEndOffset] == '=') { + headerLevelCounter++; + } + + // if (!stack.isEmpty()) { + // section = (WikipediaSection) stack.pop(); + // section.setLength(region.getOffset() - section.getOffset() - 1); + // wikiText.add(section); + // } + + // headerString = new String(text, headerStartOffset - 1, headerEndOffset - headerStartOffset + 2); + // stack.push(new WikipediaSection(wikiText, headerString, headerLevelCounter, region.getOffset(), 1)); + if (headerStartOffset > 0 && (headerEndOffset - headerStartOffset + 2 > 0)) { + headerString = new String(text, headerStartOffset - 1, headerEndOffset - headerStartOffset + 2); + addSection(wikiText, new WikipediaSection(wikiText, headerString, headerLevelCounter, region.getOffset(), 1), stack, + region); + + } + + } + } + } + if (!stack.isEmpty()) { + reduceSection(wikiText, stack, region); + // section = (WikipediaSection) stack.pop(); + // section.setLength(region.getOffset() - section.getOffset() - 1); + // wikiText.add(section); + } + return wikiText; + } + + private void addSection(WikipediaSection wikiText, WikipediaSection currentSection, Stack stack, IRegion region) { + int level = currentSection.getHeaderLevel(); + while (!stack.isEmpty()) { + WikipediaSection section = (WikipediaSection) stack.peek(); + if (section.getHeaderLevel() < level) { + currentSection.setParent(section); + section.add(currentSection); + stack.push(currentSection); + return; + } else { // if (section.getHeaderLevel() <= level) { + stack.pop(); + section.setLength(region.getOffset() - section.getOffset() - 1); + } + } + currentSection.setParent(wikiText); + wikiText.add(currentSection); + stack.push(currentSection); + } + + private void reduceSection(WikipediaSection wikiText, Stack stack, IRegion region) { + while (!stack.isEmpty()) { + WikipediaSection section = (WikipediaSection) stack.peek(); + stack.pop(); + section.setLength(region.getOffset() - section.getOffset() - 1); + } + } +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/model/WikipediaSection.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/model/WikipediaSection.java new file mode 100644 index 0000000..23b0516 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/model/WikipediaSection.java @@ -0,0 +1,118 @@ +/*********************************************************************************************************************************** + * Copyright (c) 2000, 2004 IBM Corporation and others. All rights reserved. This program and the accompanying materials are made + * available under the terms of the Common Public License v1.0 which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: IBM Corporation - initial API and implementation + **********************************************************************************************************************************/ +package net.sourceforge.phpeclipse.wiki.editor.model; + +import java.util.ArrayList; + +public class WikipediaSection { + protected static WikipediaSection[] NO_CHILDREN = new WikipediaSection[0]; + + private WikipediaSection fParent; + + private String fName; + + private int fOffset; + private int fLength; + private int fheaderLevel; + protected ArrayList recipeElements; + + WikipediaSection(WikipediaSection parent, String name, int level, int offset, int length) { + fParent = parent; + fName = name; + fheaderLevel = level; + fOffset = offset; + fLength = length; + recipeElements = new ArrayList(); + } + + + public Object[] getChildren() { + return recipeElements.toArray(); + } + + public String getName() { + return fName; + } + + public int getOffset() { + return fOffset; + } + + public int getLength() { + return fLength; + } + + /** + * @param index + * @param element + */ + public void add(int index, WikipediaSection element) { + recipeElements.add(index, element); + } + + /** + * @param o + * @return + */ + public boolean add(WikipediaSection o) { + return recipeElements.add(o); + } + + /** + * @param index + * @return + */ + public WikipediaSection get(int index) { + return (WikipediaSection) recipeElements.get(index); + } + + /** + * @return + */ + public int size() { + return recipeElements.size(); + } + + /** + * @param length The length to set. + */ + public void setLength(int length) { + fLength = length; + } + + /** + * @param offset The fOffset to set. + */ + public void setoffset(int offset) { + fOffset = offset; + } + /** + * @return Returns the headerLevel. + */ + public int getHeaderLevel() { + return fheaderLevel; + } + /** + * @param fheaderLevel The headerLevel to set. + */ + public void setHeaderLevel(int fheaderLevel) { + this.fheaderLevel = fheaderLevel; + } + /** + * @return Returns the parent. + */ + public WikipediaSection getParent() { + return fParent; + } + /** + * @param parent The parent to set. + */ + public void setParent(WikipediaSection parent) { + fParent = parent; + } +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/model/WikipediaText.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/model/WikipediaText.java new file mode 100644 index 0000000..bd2e4ab --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/editor/model/WikipediaText.java @@ -0,0 +1,23 @@ +/******************************************************************************* + * Copyright (c) 2000, 2004 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpeclipse.wiki.editor.model; + +import java.util.ArrayList; + +public class WikipediaText extends WikipediaSection { + + + WikipediaText() { + super(null, null, -1, -1, -1); + } + + +} diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/export/WikiExportWizard.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/export/WikiExportWizard.java new file mode 100644 index 0000000..e6d8ab4 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/export/WikiExportWizard.java @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2002 Team in a Box Ltd. All rights reserved. This file is made available under the terms and conditions of the + * Common Public License v 1.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/cpl-v1.0.html + * + * Contributors: Team in a Box Ltd http://www.teaminabox.co.uk/ + */ + +package net.sourceforge.phpeclipse.wiki.export; + +import java.io.File; +import java.lang.reflect.InvocationTargetException; + +import net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin; +import net.sourceforge.phpeclipse.wiki.preferences.Util; + +import org.eclipse.core.resources.IContainer; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.QualifiedName; +import org.eclipse.core.runtime.Status; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.operation.IRunnableWithProgress; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.wizard.Wizard; +import org.eclipse.ui.INewWizard; +import org.eclipse.ui.IWorkbench; + +public final class WikiExportWizard extends Wizard implements INewWizard { + static final QualifiedName DIRECTORY_QUALIFIED_NAME = new QualifiedName(WikiEditorPlugin.PLUGIN_ID, "exportDirectory"); + + private WikiExportWizardPage page; + + private ISelection selection; + + public WikiExportWizard() { + super(); + setNeedsProgressMonitor(true); + } + + public void addPages() { + page = new WikiExportWizardPage(selection); + addPage(page); + } + + public boolean performFinish() { + persistExportProperties(); + + final IContainer folder = page.getFolder(); + final String exportDirectory = page.getExportDirectoryPath(); + + return runOperationForContainer(new IRunnableWithProgress() { + public void run(IProgressMonitor monitor) throws InvocationTargetException { + try { + startExport(monitor, folder, exportDirectory); + } catch (Exception e) { + throw new InvocationTargetException(e); + } finally { + monitor.done(); + } + } + }); + } + + private boolean runOperationForContainer(IRunnableWithProgress op) { + try { + getContainer().run(true, true, op); + } catch (InterruptedException e) { + return false; + } catch (InvocationTargetException e) { + WikiEditorPlugin.getDefault().log("", e); + MessageDialog.openError(getShell(), "Error", e.getTargetException().getMessage()); + return false; + } + + return true; + } + + private void startExport(IProgressMonitor monitor, IContainer folder, String exportDirectory) throws CoreException { + try { + final String srcBasePath = Util.getWikiTextsPath(folder); + new WikiExporter().export(folder, exportDirectory, srcBasePath, monitor); + } catch (Exception ioex) { + throw new CoreException(new Status(IStatus.ERROR, "Failed to write Wiki Documents", IStatus.OK, ioex.getMessage(), ioex)); + } + } + + private void persistExportProperties() { + IProject project = page.getFolder().getProject(); + try { + project.setPersistentProperty(WikiExportWizard.DIRECTORY_QUALIFIED_NAME, new File(page.getExportDirectoryPath()) + .getAbsolutePath()); + } catch (CoreException cex) { + noteException(cex); + } + } + + private void noteException(CoreException cex) { + WikiEditorPlugin.getDefault().log("Export Error", cex); + throw new RuntimeException("An error occurred. Please see the log for details."); + } + + public void init(IWorkbench workbench, IStructuredSelection selection) { + this.selection = selection; + } +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/export/WikiExportWizardPage.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/export/WikiExportWizardPage.java new file mode 100644 index 0000000..c3250fb --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/export/WikiExportWizardPage.java @@ -0,0 +1,228 @@ +/* + * Copyright (c) 2002 Team in a Box Ltd. All rights reserved. This file is made available under the terms and conditions of the + * Common Public License v 1.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/cpl-v1.0.html + * + * Contributors: Team in a Box Ltd http://www.teaminabox.co.uk/ + */ + +package net.sourceforge.phpeclipse.wiki.export; + +import net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin; + +import org.eclipse.core.resources.IContainer; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IFolder; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.Path; +import org.eclipse.jface.preference.StringFieldEditor; +import org.eclipse.jface.util.IPropertyChangeListener; +import org.eclipse.jface.util.PropertyChangeEvent; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.window.Window; +import org.eclipse.jface.wizard.WizardPage; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.DirectoryDialog; +import org.eclipse.swt.widgets.Label; +import org.eclipse.ui.dialogs.ContainerSelectionDialog; + +public final class WikiExportWizardPage extends WizardPage implements IPropertyChangeListener, SelectionListener { + private StringFieldEditor folderText; + + private StringFieldEditor exportDirectoryText; + + private ISelection selection; + + public WikiExportWizardPage(ISelection selection) { + super(WikiEditorPlugin.getResourceString("Export.wizardTitle")); + setTitle(WikiEditorPlugin.getResourceString("Export.wizardTitle")); + setDescription(WikiEditorPlugin.getResourceString("Export.wizardDescription")); + this.selection = selection; + } + + public void createControl(Composite parent) { + Composite rootComposite = createControlsContainer(parent); + + try { + initialize(); + } catch (RuntimeException rex) { + throw rex; + } catch (CoreException cex) { + WikiEditorPlugin.getDefault().log("", cex); + throw new RuntimeException("Caught CoreException. See log for details."); + } + dialogChanged(); + setControl(rootComposite); + } + + private Composite createControlsContainer(Composite parent) { + Composite container = new Composite(parent, SWT.NULL); + GridLayout layout = new GridLayout(); + layout.numColumns = 1; + layout.verticalSpacing = 20; + container.setLayout(layout); + container.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL)); + + createCommonControls(container); + return container; + } + + private void createCommonControls(Composite parent) { + Composite container = new Composite(parent, SWT.NULL); + GridLayout layout = new GridLayout(); + layout.numColumns = 3; + layout.verticalSpacing = 9; + container.setLayout(layout); + container.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL)); + + createFolderControls(container); + createExportDirectoryControls(container); + } + + private void createExportDirectoryControls(Composite container) { + exportDirectoryText = addStringFieldEditor(container, WikiEditorPlugin.getResourceString("Export.wizardExportDirectory")); + + Button button = new Button(container, SWT.PUSH); + button.setText(WikiEditorPlugin.getResourceString("Export.wizardBrowse")); + button.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent e) { + handleBrowseHtmlExportLocation(); + } + }); + } + + private void createFolderControls(Composite container) { + folderText = addStringFieldEditor(container, WikiEditorPlugin.getResourceString("Export.wizardFolder")); + + Button button = new Button(container, SWT.PUSH); + button.setText(WikiEditorPlugin.getResourceString("Export.wizardBrowse")); + button.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent e) { + try { + handleBrowseFolders(); + } catch (CoreException cex) { + WikiEditorPlugin.getDefault().log("", cex); + throw new RuntimeException("Caught CoreException. See log for details."); + } + } + }); + } + + private StringFieldEditor addStringFieldEditor(Composite container, String labelText) { + Label label = new Label(container, SWT.NULL); + label.setText(labelText); + + Composite editorComposite = new Composite(container, SWT.NULL); + editorComposite.setLayout(new GridLayout()); + editorComposite.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL)); + StringFieldEditor editor = new StringFieldEditor("", "", editorComposite); + + editor.setPropertyChangeListener(this); + + return editor; + } + + private void initialize() throws CoreException { + if (selection == null || selection.isEmpty() || !(selection instanceof IStructuredSelection)) { + return; + } + + IStructuredSelection ssel = (IStructuredSelection) selection; + if (ssel.size() == 1) { + initialiseFromSelectedObject(ssel.getFirstElement()); + } + } + + private void initialiseFromSelectedObject(Object obj) throws CoreException { + if (obj instanceof IFolder || obj instanceof IProject) { + initialiseFolder(((IResource) obj)); + } + } + + private void initialiseFolder(IResource resource) throws CoreException { + folderText.setStringValue(resource.getFullPath().toString()); + initialiseExportDirectoryText(resource); + } + + private void initialiseExportDirectoryText(IResource resource) throws CoreException { + String exportDir = resource.getProject().getPersistentProperty(WikiExportWizard.DIRECTORY_QUALIFIED_NAME); + if (exportDir != null) { + exportDirectoryText.setStringValue(exportDir); + } else { + exportDirectoryText.setStringValue(""); + } + } + + private void handleBrowseHtmlExportLocation() { + DirectoryDialog dialog = new DirectoryDialog(getShell(), SWT.SINGLE | SWT.OPEN); + String path = dialog.open(); + if (path != null) { + exportDirectoryText.setStringValue(path); + } + } + + private void handleBrowseFolders() throws CoreException { + ContainerSelectionDialog dialog = new ContainerSelectionDialog(getShell(), ResourcesPlugin.getWorkspace().getRoot(), false, + WikiEditorPlugin.getResourceString("Export.wizardSelectFolder")); + if (dialog.open() == Window.OK) { + Object[] result = dialog.getResult(); + if (result != null && result.length == 1) { + IResource resource = ResourcesPlugin.getWorkspace().getRoot().findMember((IPath) result[0]); + if (resource instanceof IFile) { + return; + } + initialiseFolder(resource); + } + } + } + + private void dialogChanged() { + if (getFolderText().length() == 0) { + updateStatus("Folder must be specified"); + } else if (getExportDirectoryPath().length() == 0) { + updateStatus("Directory must be specified"); + } else { + updateStatus(null); + } + } + + private void updateStatus(String message) { + setErrorMessage(message); + setPageComplete(message == null); + } + + public String getExportDirectoryPath() { + return exportDirectoryText.getStringValue(); + } + + public void propertyChange(PropertyChangeEvent event) { + dialogChanged(); + } + + public void widgetSelected(SelectionEvent e) { + dialogChanged(); + } + + public void widgetDefaultSelected(SelectionEvent e) { + dialogChanged(); + } + + String getFolderText() { + return folderText.getStringValue(); + } + + public IContainer getFolder() { + return (IContainer) ResourcesPlugin.getWorkspace().getRoot().findMember(new Path(getFolderText())); + } +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/export/WikiExporter.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/export/WikiExporter.java new file mode 100644 index 0000000..1463a25 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/export/WikiExporter.java @@ -0,0 +1,169 @@ +package net.sourceforge.phpeclipse.wiki.export; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.nio.MappedByteBuffer; +import java.nio.channels.FileChannel; +import java.util.TreeSet; + +import net.sourceforge.phpeclipse.wiki.builder.CreatePageAction; +import net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin; + +import org.eclipse.core.resources.IContainer; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IFolder; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; + +import de.java2html.converter.JavaSource2HTMLConverter; +import de.java2html.javasource.JavaSource; +import de.java2html.javasource.JavaSourceParser; +import de.java2html.options.Java2HtmlConversionOptions; + +public final class WikiExporter { + + public static final String HTML_EXTENSION = ".html"; + + public static final String WORKSPACE = "workspace"; + + // private File exportDirectory; + + // private ExportLinkMaker exportLinkMaker; + private TreeSet index; + + public WikiExporter() { + // exportLinkMaker = new ExportLinkMaker(); + index = new TreeSet(String.CASE_INSENSITIVE_ORDER); + } + + public void export(IContainer folder, String exportDirectoryName, String srcBasePath, IProgressMonitor monitor) throws IOException, CoreException, + InstantiationException, IllegalAccessException, ClassNotFoundException { + // exportDirectory = new File(exportDirectoryName); + IResource[] resources = folder.members(IResource.FILE); +// monitor.beginTask(WikiEditorPlugin.getResourceString("Export.wikiPages"), resources.length + 1); + for (int i = 0; i < resources.length; i++) { + if (resources[i] instanceof IFile) { + monitor.subTask(WikiEditorPlugin.getResourceString("Export.exportFile")+resources[i].getLocation()); + CreatePageAction.createPage((IFile) resources[i], exportDirectoryName, srcBasePath); + monitor.worked(1); + } else if (resources[i] instanceof IFolder) { + monitor.subTask(WikiEditorPlugin.getResourceString("Export.exportFolder")+resources[i].getLocation()); + export((IFolder) resources[i], exportDirectoryName, srcBasePath, monitor); + monitor.worked(1); + } + } + // monitor.subTask(WikiEditorPlugin.getResourceString("Export.linkedResources")); + // exportLinkedResources(); + // createIndex(); +// monitor.worked(1); + } + + /** + * TODO: This is a horrible hack for a quick solution. + */ + // private void createIndex() throws IOException { + // File indexFile = createHtmlFile("index"); + // + // PrintWriter writer = new PrintWriter(new FileWriter(indexFile)); + // writer.println(""); + // writer.println(""); + // writer.println(""); + // writer.println(" "); + // writer.print(" Index"); + // writer.println(" "); + // writer.println(" "); + // + // Iterator iterator = index.iterator(); + // while (iterator.hasNext()) { + // String name = (String) iterator.next(); + // writer.print("
"); + // writer.println("" + name + ""); + // } + // + // writer.println(" "); + // writer.println(" "); + // writer.flush(); + // writer.close(); + // } + // private void exportLinkedResources() throws IOException { + // if (!exportLinkMaker.hasLinkedDocuments()) { + // return; + // } + // File workspaceExport = new File(exportDirectory, WikiExporter.WORKSPACE); + // if (!workspaceExport.exists()) { + // workspaceExport.mkdir(); + // } + // HashMap map = exportLinkMaker.getLinkedResources(); + // Iterator iterator = map.keySet().iterator(); + // while (iterator.hasNext()) { + // IResource resource = (IResource) iterator.next(); + // String location = (String) map.get(resource); + // export(resource, location); + // } + // } + // private void export(IResource resource, String location) throws IOException { + // File destination = new File(exportDirectory, location); + // + // if (destination.isDirectory()) { + // return; + // } + // if (!destination.exists()) { + // destination.getParentFile().mkdirs(); + // } + // File source = new File(resource.getLocation().toString()); + // if (isJavaResource(resource)) { + // javaToHtml(source, new File(destination.getParentFile(), destination.getName())); + // } else { + // copy(source, destination); + // } + // } + private boolean isJavaResource(IResource resource) { + return "java".equals(resource.getFileExtension()); + } + + private void javaToHtml(File source, File destination) throws IOException { + JavaSource java = new JavaSourceParser().parse(new FileReader(source)); + JavaSource2HTMLConverter converter = new JavaSource2HTMLConverter(java); + Java2HtmlConversionOptions options = Java2HtmlConversionOptions.getDefault(); + options.setShowLineNumbers(true); + options.setShowFileName(true); + options.setShowJava2HtmlLink(true); + converter.setConversionOptions(options); + FileWriter writer = new FileWriter(destination); + converter.convert(writer); + writer.flush(); + writer.close(); + } + + private void copy(File source, File dest) throws IOException { + FileChannel in = null; + FileChannel out = null; + try { + in = new FileInputStream(source).getChannel(); + out = new FileOutputStream(dest).getChannel(); + long size = in.size(); + MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); + out.write(buf); + } finally { + if (in != null) { + in.close(); + } + if (out != null) { + out.close(); + } + } + } + + private boolean isWikiFile(IResource resource) { + return resource instanceof IFile && resource.getFileExtension().equals("wp"); + } + + // private File createHtmlFile(String name) { + // return new File(exportDirectory, name + WikiExporter.HTML_EXTENSION); + // } +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/internal/Configuration.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/internal/Configuration.java new file mode 100644 index 0000000..0b2c404 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/internal/Configuration.java @@ -0,0 +1,113 @@ +/********************************************************************** + * Copyright (c) 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM - Initial API and implementation + **********************************************************************/ +package net.sourceforge.phpeclipse.wiki.internal; + +import net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin; + + +/** + * + */ +public class Configuration implements IConfiguration { + private static final String MEMENTO_ID = "id"; + private static final String MEMENTO_USER = "user"; + private static final String MEMENTO_URL = "url"; + private static final String MEMENTO_PASSWORD = "password"; + private static final String MEMENTO_TYPE_ID = "type-id"; + + protected String id; + protected String fUrl; + protected String fPassword; + protected String fUser; + protected String fType; + + public Configuration() { + this( WikiEditorPlugin.HTTP_QUERY ); // default type + } + + public Configuration(String type) { + this.fType = type; + } + + /* (non-Javadoc) + * @see org.eclipse.monitor.internal.IConfiguration#getId() + */ + public String getId() { + return id; + } + + public String getURL() { + return fUrl; + } + + /* (non-Javadoc) + * @see org.eclipse.monitor.internal.IConfiguration#getRemotePort() + */ + public String getPassword() { + return fPassword; + } + + /* (non-Javadoc) + * @see org.eclipse.monitor.internal.IConfiguration#getLocalPort() + */ + public String getUser() { + return fUser; + } + + /** + */ + public String getType() { + return fType; + } + + /* (non-Javadoc) + * @see org.eclipse.monitor.internal.IConfiguration#isRunning() + */ + public boolean isActive() { + return ConfigurationManager.getInstance().isActive(this); + } + + public void delete() { + ConfigurationManager.getInstance().removeConfiguration(this); + } + + public boolean isWorkingCopy() { + return false; + } + + public IConfigurationWorkingCopy getWorkingCopy() { + return new ConfigurationWorkingCopy(this); + } + + protected void setInternal(IConfiguration monitor) { + id = monitor.getId(); + fUrl = monitor.getURL(); + fPassword = monitor.getPassword(); + fUser = monitor.getUser(); + fType = monitor.getType(); + } + + protected void save(IMemento memento) { + memento.putString(MEMENTO_ID, id); + memento.putString(MEMENTO_TYPE_ID, fType); + memento.putString(MEMENTO_USER, fUser); + memento.putString(MEMENTO_URL, fUrl); + memento.putString(MEMENTO_PASSWORD, fPassword); + } + + protected void load(IMemento memento) { + id = memento.getString(MEMENTO_ID); + fType = memento.getString(MEMENTO_TYPE_ID); + fUser = memento.getString(MEMENTO_USER); + fUrl = memento.getString(MEMENTO_URL); + fPassword = memento.getString(MEMENTO_PASSWORD); + } +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/internal/ConfigurationManager.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/internal/ConfigurationManager.java new file mode 100644 index 0000000..034bb14 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/internal/ConfigurationManager.java @@ -0,0 +1,188 @@ +/********************************************************************** + * Copyright (c) 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM - Initial API and implementation + **********************************************************************/ +package net.sourceforge.phpeclipse.wiki.internal; + +import java.io.ByteArrayInputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import net.sourceforge.phpeclipse.webbrowser.internal.Trace; +import net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin; + +import org.eclipse.core.runtime.Preferences; +/** + * + */ +public class ConfigurationManager { + private static final int ADD = 0; + private static final int CHANGE = 1; + private static final int REMOVE = 2; + + // configurations + protected List configurations; + protected Map threads = new HashMap(); + + protected List monitorListeners = new ArrayList(); + + private Preferences.IPropertyChangeListener pcl; + protected boolean ignorePreferenceChanges = false; + + protected static ConfigurationManager instance; + + public static ConfigurationManager getInstance() { + if (instance == null) + instance = new ConfigurationManager(); + return instance; + } + + private ConfigurationManager() { + loadConfigurations(); + + pcl = new Preferences.IPropertyChangeListener() { + public void propertyChange(Preferences.PropertyChangeEvent event) { + if (ignorePreferenceChanges) + return; + String property = event.getProperty(); + if (property.equals("configurations")) { + loadConfigurations(); + } + } + }; + + WikiEditorPlugin.getDefault().getPluginPreferences().addPropertyChangeListener(pcl); + } + + protected void dispose() { + WikiEditorPlugin.getDefault().getPluginPreferences().removePropertyChangeListener(pcl); + } + + public IConfigurationWorkingCopy createConfiguration() { + return new ConfigurationWorkingCopy(); + } + + public List getConfigurations() { + return new ArrayList(configurations); + } + + protected void addConfiguration(IConfiguration configuration) { + if (!configurations.contains(configuration)) + configurations.add(configuration); + fireConfigurationEvent(configuration, ADD); + saveConfigurations(); + } + + protected boolean isActive(IConfiguration configuration) { + return (threads.get(configuration) != null); + } + + protected void removeConfiguration(IConfiguration configuration) { + configurations.remove(configuration); + fireConfigurationEvent(configuration, REMOVE); + saveConfigurations(); + } + + protected void configurationChanged(IConfiguration configuration) { + fireConfigurationEvent(configuration, CHANGE); + saveConfigurations(); + } + + /** + * Add monitor listener. + * + * @param listener + */ + public void addConfigurationListener(IConfigurationListener listener) { + monitorListeners.add(listener); + } + + /** + * Remove monitor listener. + * + * @param listener + */ + public void removeConfigurationListener(IConfigurationListener listener) { + monitorListeners.remove(listener); + } + + /** + * Fire a monitor event. + * @param rr + * @param fType + */ + protected void fireConfigurationEvent(IConfiguration monitor, int type) { + Object[] obj = monitorListeners.toArray(); + + int size = obj.length; + for (int i = 0; i < size; i++) { + IConfigurationListener listener = (IConfigurationListener) obj[i]; + if (type == ADD) + listener.monitorAdded(monitor); + else if (type == CHANGE) + listener.monitorChanged(monitor); + else if (type == REMOVE) + listener.monitorRemoved(monitor); + } + } + + + + + protected void loadConfigurations() { + Trace.trace(Trace.FINEST, "Loading Configurations"); + + configurations = new ArrayList(); + Preferences prefs = WikiEditorPlugin.getDefault().getPluginPreferences(); + String xmlString = prefs.getString("configurations"); + if (xmlString != null && xmlString.length() > 0) { + try { + ByteArrayInputStream in = new ByteArrayInputStream(xmlString.getBytes()); + IMemento memento = XMLMemento.loadMemento(in); + + IMemento[] children = memento.getChildren("config"); + if (children != null) { + int size = children.length; + for (int i = 0; i < size; i++) { + Configuration monitor = new Configuration(); + monitor.load(children[i]); + configurations.add(monitor); + } + } + } catch (Exception e) { + Trace.trace(Trace.WARNING, "Could not load configurations: " + e.getMessage()); + } + } + } + + protected void saveConfigurations() { + try { + ignorePreferenceChanges = true; + XMLMemento memento = XMLMemento.createWriteRoot("configurations"); + + Iterator iterator = configurations.iterator(); + while (iterator.hasNext()) { + Configuration monitor = (Configuration) iterator.next(); + IMemento child = memento.createChild("config"); + monitor.save(child); + } + + String xmlString = memento.saveToString(); + Preferences prefs = WikiEditorPlugin.getDefault().getPluginPreferences(); + prefs.setValue("configurations", xmlString); + WikiEditorPlugin.getDefault().savePluginPreferences(); + } catch (Exception e) { + Trace.trace(Trace.SEVERE, "Could not save Configurations", e); + } + ignorePreferenceChanges = false; + } +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/internal/ConfigurationWorkingCopy.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/internal/ConfigurationWorkingCopy.java new file mode 100644 index 0000000..c75a2fd --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/internal/ConfigurationWorkingCopy.java @@ -0,0 +1,79 @@ +/********************************************************************** + * Copyright (c) 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM - Initial API and implementation + **********************************************************************/ +package net.sourceforge.phpeclipse.wiki.internal; + +/** + * + */ +public class ConfigurationWorkingCopy extends Configuration implements IConfigurationWorkingCopy { + protected Configuration monitor; + + // creation + public ConfigurationWorkingCopy() { } + + // working copy + public ConfigurationWorkingCopy(Configuration monitor) { + this.monitor = monitor; + setInternal(monitor); + } + + public void setId(String newId) { + id = newId; + } + + + public void setURL(String url) { + fUrl = url; + } + + + public void setPassword(String password) { + fPassword = password; + } + + + public void setUser(String user) { + fUser = user; + } + + + public void setType(String t) { + fType = t; + } + + public boolean isWorkingCopy() { + return true; + } + + public IConfigurationWorkingCopy getWorkingCopy() { + return this; + } + + public IConfiguration save() { + ConfigurationManager mm = ConfigurationManager.getInstance(); + if (monitor != null) { + //boolean restart = false; +// if (monitor.isRunning()) { +// //restart = true; +// mm.stopMonitor(monitor); +// } + monitor.setInternal(this); + mm.configurationChanged(monitor); + //if (restart) + // mm.startMonitor(monitor); + } else { + monitor = new Configuration(); + monitor.setInternal(this); + mm.addConfiguration(monitor); + } + return monitor; + } +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/internal/IConfiguration.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/internal/IConfiguration.java new file mode 100644 index 0000000..2d230ce --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/internal/IConfiguration.java @@ -0,0 +1,32 @@ +/********************************************************************** + * Copyright (c) 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM - Initial API and implementation + **********************************************************************/ +package net.sourceforge.phpeclipse.wiki.internal; +/** + * + */ +public interface IConfiguration { + public String getId(); + + public String getURL(); + + public String getType(); + + public String getPassword(); + + public String getUser(); + + public IConfigurationWorkingCopy getWorkingCopy(); + + public boolean isActive(); + + public void delete(); + +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/internal/IConfigurationListener.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/internal/IConfigurationListener.java new file mode 100644 index 0000000..d2e5f70 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/internal/IConfigurationListener.java @@ -0,0 +1,21 @@ +/********************************************************************** + * Copyright (c) 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM - Initial API and implementation + **********************************************************************/ +package net.sourceforge.phpeclipse.wiki.internal; +/** + * + */ +public interface IConfigurationListener { + public void monitorAdded(IConfiguration monitor); + + public void monitorChanged(IConfiguration monitor); + + public void monitorRemoved(IConfiguration monitor); +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/internal/IConfigurationWorkingCopy.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/internal/IConfigurationWorkingCopy.java new file mode 100644 index 0000000..86634fb --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/internal/IConfigurationWorkingCopy.java @@ -0,0 +1,27 @@ +/********************************************************************** + * Copyright (c) 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM - Initial API and implementation + **********************************************************************/ +package net.sourceforge.phpeclipse.wiki.internal; +/** + * + */ +public interface IConfigurationWorkingCopy extends IConfiguration { + public void setId(String id); + + public void setURL(String url); + + public void setPassword(String port); + + public void setUser(String port); + + public void setType(String type); + + public IConfiguration save(); +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/internal/IMemento.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/internal/IMemento.java new file mode 100644 index 0000000..a7b5ce4 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/internal/IMemento.java @@ -0,0 +1,192 @@ +/********************************************************************** + * Copyright (c) 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - Initial API and implementation + **********************************************************************/ +package net.sourceforge.phpeclipse.wiki.internal; + +import java.util.List; +/** + * Interface to a memento used for saving the important state of an object + * in a form that can be persisted in the file system. + *

+ * Mementos were designed with the following requirements in mind: + *

    + *
  1. Certain objects need to be saved and restored across platform sessions. + *
  2. + *
  3. When an object is restored, an appropriate class for an object might not + * be available. It must be possible to skip an object in this case.
  4. + *
  5. When an object is restored, the appropriate class for the object may be + * different from the one when the object was originally saved. If so, the + * new class should still be able to read the old form of the data.
  6. + *
+ *

+ *

+ * Mementos meet these requirements by providing support for storing a + * mapping of arbitrary string keys to primitive values, and by allowing + * mementos to have other mementos as children (arranged into a tree). + * A robust external storage format based on XML is used. + *

+ * The key for an attribute may be any alpha numeric value. However, the + * value of TAG_ID is reserved for internal use. + *

+ * This interface is not intended to be implemented by clients. + *

+ * + * @see IPersistableElement + * @see IElementFactory + */ +public interface IMemento { + /** + * Special reserved key used to store the memento id + * (value "org.eclipse.ui.id"). + * + * @see #getId + */ + public static final String TAG_ID = "IMemento.internal.id"; //$NON-NLS-1$ + + /** + * Creates a new child of this memento with the given fType. + *

+ * The getChild and getChildren methods + * are used to retrieve children of a given fType. + *

+ * + * @param fType the fType + * @return a new child memento + * @see #getChild + * @see #getChildren + */ + public IMemento createChild(String type); + + /** + * Creates a new child of this memento with the given fType and id. + * The id is stored in the child memento (using a special reserved + * key, TAG_ID) and can be retrieved using getId. + *

+ * The getChild and getChildren methods + * are used to retrieve children of a given fType. + *

+ * + * @param fType the fType + * @param id the child id + * @return a new child memento with the given fType and id + * @see #getId + */ + public IMemento createChild(String type, String id); + + /** + * Returns the first child with the given fType id. + * + * @param fType the fType id + * @return the first child with the given fType + */ + public IMemento getChild(String type); + + /** + * Returns all children with the given fType id. + * + * @param fType the fType id + * @return the list of children with the given fType + */ + public IMemento[] getChildren(String type); + + /** + * Returns the floating point value of the given key. + * + * @param key the key + * @return the value, or null if the key was not found or was found + * but was not a floating point number + */ + public Float getFloat(String key); + + /** + * Returns the id for this memento. + * + * @return the memento id, or null if none + * @see #createChild(java.lang.String,java.lang.String) + */ + public String getId(); + + /** + * Returns the name for this memento. + * + * @return the memento name, or null if none + * @see #createChild(java.lang.String,java.lang.String) + */ + public String getName(); + + /** + * Returns the integer value of the given key. + * + * @param key the key + * @return the value, or null if the key was not found or was found + * but was not an integer + */ + public Integer getInteger(String key); + + /** + * Returns the string value of the given key. + * + * @param key the key + * @return the value, or null if the key was not found or was found + * but was not an integer + */ + public String getString(String key); + + /** + * Returns the boolean value of the given key. + * + * @param key the key + * @return the value, or null if the key was not found or was found + * but was not a boolean + */ + public Boolean getBoolean(String key); + + public List getNames(); + + /** + * Sets the value of the given key to the given floating point number. + * + * @param key the key + * @param value the value + */ + public void putFloat(String key, float value); + + /** + * Sets the value of the given key to the given integer. + * + * @param key the key + * @param value the value + */ + public void putInteger(String key, int value); + + /** + * Sets the value of the given key to the given boolean value. + * + * @param key the key + * @param value the value + */ + public void putBoolean(String key, boolean value); + + /** + * Copy the attributes and children from memento + * to the receiver. + * + * @param memento the IMemento to be copied. + */ + public void putMemento(IMemento memento); + + /** + * Sets the value of the given key to the given string. + * + * @param key the key + * @param value the value + */ + public void putString(String key, String value); +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/internal/XMLMemento.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/internal/XMLMemento.java new file mode 100644 index 0000000..ceac609 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/internal/XMLMemento.java @@ -0,0 +1,448 @@ +/********************************************************************** + * Copyright (c) 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - Initial API and implementation + **********************************************************************/ +package net.sourceforge.phpeclipse.wiki.internal; + +import java.io.*; +import java.util.*; +import java.net.URL; +import org.w3c.dom.*; +import org.xml.sax.*; + +import javax.xml.parsers.*; +import javax.xml.transform.*; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +/** + * A Memento is a class independent container for persistence + * info. It is a reflection of 3 storage requirements. + * + * 1) We need the ability to persist an object and restore it. + * 2) The class for an object may be absent. If so we would + * like to skip the object and keep reading. + * 3) The class for an object may change. If so the new class + * should be able to read the old persistence info. + * + * We could ask the objects to serialize themselves into an + * ObjectOutputStream, DataOutputStream, or Hashtable. However + * all of these approaches fail to meet the second requirement. + * + * Memento supports binary persistance with a version ID. + */ +public final class XMLMemento implements IMemento { + private Document factory; + private Element element; + + /** + * Answer a memento for the document and element. For simplicity + * you should use createReadRoot and createWriteRoot to create the initial + * mementos on a document. + */ + public XMLMemento(Document doc, Element el) { + factory = doc; + element = el; + } + + /** + * @see IMemento. + */ + public IMemento createChild(String type) { + Element child = factory.createElement(type); + element.appendChild(child); + return new XMLMemento(factory, child); + } + + /** + * @see IMemento. + */ + public IMemento createChild(String type, String id) { + Element child = factory.createElement(type); + child.setAttribute(TAG_ID, id); + element.appendChild(child); + return new XMLMemento(factory, child); + } + + /** + * Create a Document from a Reader and answer a root memento for reading + * a document. + */ + protected static XMLMemento createReadRoot(Reader reader) { + Document document = null; + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder parser = factory.newDocumentBuilder(); + document = parser.parse(new InputSource(reader)); + Node node = document.getFirstChild(); + if (node instanceof Element) + return new XMLMemento(document, (Element) node); + } catch (ParserConfigurationException e) { + } catch (IOException e) { + } catch (SAXException e) { + } finally { + try { + reader.close(); + } catch (Exception e) { } + } + return null; + } + + /** + * Answer a root memento for writing a document. + */ + public static XMLMemento createWriteRoot(String type) { + Document document; + try { + document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); + Element element = document.createElement(type); + document.appendChild(element); + return new XMLMemento(document, element); + } catch (ParserConfigurationException e) { + throw new Error(e); + } + } + + /** + * @see IMemento. + */ + public IMemento getChild(String type) { + // Get the nodes. + NodeList nodes = element.getChildNodes(); + int size = nodes.getLength(); + if (size == 0) + return null; + + // Find the first node which is a child of this node. + for (int nX = 0; nX < size; nX ++) { + Node node = nodes.item(nX); + if (node instanceof Element) { + Element element2 = (Element)node; + if (element2.getNodeName().equals(type)) + return new XMLMemento(factory, element2); + } + } + + // A child was not found. + return null; + } + + /** + * @see IMemento. + */ + public IMemento [] getChildren(String type) { + // Get the nodes. + NodeList nodes = element.getChildNodes(); + int size = nodes.getLength(); + if (size == 0) + return new IMemento[0]; + + // Extract each node with given fType. + ArrayList list = new ArrayList(size); + for (int nX = 0; nX < size; nX ++) { + Node node = nodes.item(nX); + if (node instanceof Element) { + Element element2 = (Element)node; + if (element2.getNodeName().equals(type)) + list.add(element2); + } + } + + // Create a memento for each node. + size = list.size(); + IMemento [] results = new IMemento[size]; + for (int x = 0; x < size; x ++) { + results[x] = new XMLMemento(factory, (Element)list.get(x)); + } + return results; + } + + /** + * Return the contents of this memento as a byte array. + * + * @return byte[] + */ + public byte[] getContents() throws IOException { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + save(out); + return out.toByteArray(); + } + + /** + * Returns an input stream for writing to the disk with a local locale. + * + * @return java.io.InputStream + */ + public InputStream getInputStream() throws IOException { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + save(out); + return new ByteArrayInputStream(out.toByteArray()); + } + + /** + * @see IMemento. + */ + public Float getFloat(String key) { + Attr attr = element.getAttributeNode(key); + if (attr == null) + return null; + String strValue = attr.getValue(); + try { + return new Float(strValue); + } catch (NumberFormatException e) { + return null; + } + } + + /** + * @see IMemento. + */ + public String getId() { + return element.getAttribute(TAG_ID); + } + + /** + * @see IMemento. + */ + public String getName() { + return element.getNodeName(); + } + + /** + * @see IMemento. + */ + public Integer getInteger(String key) { + Attr attr = element.getAttributeNode(key); + if (attr == null) + return null; + String strValue = attr.getValue(); + try { + return new Integer(strValue); + } catch (NumberFormatException e) { + return null; + } + } + + /** + * @see IMemento. + */ + public String getString(String key) { + Attr attr = element.getAttributeNode(key); + if (attr == null) + return null; + return attr.getValue(); + } + + public List getNames() { + NamedNodeMap map = element.getAttributes(); + int size = map.getLength(); + List list = new ArrayList(); + for (int i = 0; i < size; i++) { + Node node = map.item(i); + String name = node.getNodeName(); + list.add(name); + } + return list; + } + + /** + * Loads a memento from the given filename. + * + * @param in java.io.InputStream + * @return org.eclipse.ui.IMemento + * @exception java.io.IOException + */ + public static IMemento loadMemento(InputStream in) { + return createReadRoot(new InputStreamReader(in)); + } + + /** + * Loads a memento from the given filename. + * + * @param in java.io.InputStream + * @return org.eclipse.ui.IMemento + * @exception java.io.IOException + */ + public static IMemento loadCorruptMemento(InputStream in) { + Document document = null; + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder parser = factory.newDocumentBuilder(); + document = parser.parse(in); + Node node = document.getFirstChild(); + if (node instanceof Element) + return new XMLMemento(document, (Element) node); + } catch (ParserConfigurationException e) { + } catch (IOException e) { + } catch (SAXException e) { + } finally { + try { + in.close(); + } catch (Exception e) { } + } + return null; + } + + /** + * Loads a memento from the given filename. + * + * @param filename java.lang.String + * @return org.eclipse.ui.IMemento + * @exception java.io.IOException + */ + public static IMemento loadMemento(String filename) throws IOException { + return XMLMemento.createReadRoot(new FileReader(filename)); + } + + /** + * Loads a memento from the given filename. + * + * @param url java.net.URL + * @return org.eclipse.ui.IMemento + * @exception java.io.IOException + */ + public static IMemento loadMemento(URL url) throws IOException { + return XMLMemento.createReadRoot(new InputStreamReader(url.openStream())); + } + + /** + * @see IMemento. + */ + private void putElement(Element element2) { + NamedNodeMap nodeMap = element2.getAttributes(); + int size = nodeMap.getLength(); + for (int i = 0; i < size; i++){ + Attr attr = (Attr)nodeMap.item(i); + putString(attr.getName(),attr.getValue()); + } + + NodeList nodes = element2.getChildNodes(); + size = nodes.getLength(); + for (int i = 0; i < size; i ++) { + Node node = nodes.item(i); + if (node instanceof Element) { + XMLMemento child = (XMLMemento)createChild(node.getNodeName()); + child.putElement((Element)node); + } + } + } + + /** + * @see IMemento. + */ + public void putFloat(String key, float f) { + element.setAttribute(key, String.valueOf(f)); + } + + /** + * @see IMemento. + */ + public void putInteger(String key, int n) { + element.setAttribute(key, String.valueOf(n)); + } + + /** + * @see IMemento. + */ + public void putMemento(IMemento memento) { + XMLMemento xmlMemento = (XMLMemento) memento; + putElement(xmlMemento.element); + } + + /** + * @see IMemento. + */ + public void putString(String key, String value) { + if (value == null) + return; + element.setAttribute(key, value); + } + + /** + * Save this Memento to a Writer. + */ + public void save(Writer writer) throws IOException { + Result result = new StreamResult(writer); + Source source = new DOMSource(factory); + try { + Transformer transformer = TransformerFactory.newInstance().newTransformer(); + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$ + transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$ + transformer.transform(source, result); + } catch (Exception e) { + throw (IOException) (new IOException().initCause(e)); + } + } + + /** + * Save this Memento to a Writer. + */ + public void save(OutputStream os) throws IOException { + Result result = new StreamResult(os); + Source source = new DOMSource(factory); + try { + Transformer transformer = TransformerFactory.newInstance().newTransformer(); + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$ + transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$ + transformer.transform(source, result); + } catch (Exception e) { + throw (IOException) (new IOException().initCause(e)); + } + } + + /** + * Saves the memento to the given file. + * + * @param filename java.lang.String + * @exception java.io.IOException + */ + public void saveToFile(String filename) throws IOException { + Writer w = null; + try { + w = new FileWriter(filename); + save(w); + } catch (IOException e) { + throw e; + } catch (Exception e) { + throw new IOException(e.getLocalizedMessage()); + } finally { + if (w != null) { + try { + w.close(); + } catch (Exception e) { } + } + } + } + + public String saveToString() throws IOException { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + save(out); + return out.toString("UTF-8"); + } + + /* + * @see IMemento#getBoolean(String) + */ + public Boolean getBoolean(String key) { + Attr attr = element.getAttributeNode(key); + if (attr == null) + return null; + String strValue = attr.getValue(); + if ("true".equalsIgnoreCase(strValue)) + return new Boolean(true); + else + return new Boolean(false); + } + + /* + * @see IMemento#putBoolean(String, boolean) + */ + public void putBoolean(String key, boolean value) { + element.setAttribute(key, value ? "true" : "false"); + } +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/preferences/AlternateUserValidationDialog.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/preferences/AlternateUserValidationDialog.java new file mode 100644 index 0000000..b4cc992 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/preferences/AlternateUserValidationDialog.java @@ -0,0 +1,237 @@ +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpeclipse.wiki.preferences; + +import java.util.ArrayList; +import java.util.List; + +import net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin; + +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.VerifyEvent; +import org.eclipse.swt.events.VerifyListener; +import org.eclipse.swt.graphics.FontData; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Event; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Listener; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Text; + +public class AlternateUserValidationDialog extends Dialog { + String user; + String password = ""; //$NON-NLS-1$ + List numXs = new ArrayList(); + Label icon1; + Label icon2; + Label icon3; + Label icon4; + Text passwordText; + boolean inUpdate = false; + + Image[] images; + + public AlternateUserValidationDialog(Shell parentShell, String user) { + super(parentShell); + this.user = user; + initializeImages(); + } + + protected void configureShell(Shell newShell) { + super.configureShell(newShell); + newShell.setText(Messages.bind("AlternateUserValidationDialog.Enter_Password_2")); //$NON-NLS-1$ + } + + protected Control createContents(Composite parent) { + Composite main = new Composite(parent, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.numColumns = 3; + main.setLayout(layout); + main.setLayoutData(new GridData(GridData.FILL_BOTH)); + + Composite iconComposite = new Composite(main, SWT.NONE); + layout = new GridLayout(); + layout.numColumns = 2; + iconComposite.setLayout(layout); + iconComposite.setLayoutData(new GridData()); + + icon1 = createLabel(iconComposite); + icon2 = createLabel(iconComposite); + icon3 = createLabel(iconComposite); + icon4 = createLabel(iconComposite); + + Composite middleComposite = new Composite(main, SWT.NONE); + middleComposite.setLayout(new GridLayout()); + middleComposite.setLayoutData(new GridData()); + + Label l = new Label(middleComposite, SWT.NULL); + l.setText(Messages.bind("AlternateUserValidationDialog.message", user)); //$NON-NLS-1$ + l.setLayoutData(new GridData()); + l = new Label(middleComposite, SWT.NULL); + l.setText(""); //$NON-NLS-1$ + l.setLayoutData(new GridData()); + passwordText = new Text(middleComposite, SWT.SINGLE | SWT.BORDER); + GridData data = new GridData(); + data.widthHint = 250; + passwordText.setLayoutData(data); + + passwordText.addVerifyListener(new VerifyListener() { + public void verifyText(VerifyEvent e) { + if (inUpdate) return; + e.doit = false; + inUpdate = true; + switch ((int)e.character) { + case 8: { + // backspace pressed + if (password.length() > 0) { + password = password.substring(0, password.length() - 1); + } + // get rid of bogus Xs + int numX = ((Integer)numXs.get(numXs.size() - 1)).intValue(); + numXs.remove(numXs.size() - 1); + String oldText = passwordText.getText(); + String newText = oldText.substring(0, oldText.length() - numX); + passwordText.setText(newText); + passwordText.setSelection(newText.length()); + break; + } + default: { + String oldText = passwordText.getText(); + String x = getXs(); + numXs.add(numXs.size(), new Integer(x.length())); + String newText = oldText + x; + passwordText.setText(newText); + passwordText.setSelection(newText.length()); + password += e.character; + } + } + inUpdate = false; + updateImages(); + } + }); + /*passwordText.addTraverseListener(new TraverseListener() { + public void keyTraversed(TraverseEvent e) { + switch (e.detail) { + case SWT.TRAVERSE_ARROW_NEXT: + case SWT.TRAVERSE_ARROW_PREVIOUS: + e.detail = SWT.TRAVERSE_NONE; + e.doit = false; + break; + } + } + });*/ + Composite buttonComposite = new Composite(main, SWT.NONE); + buttonComposite.setLayout(new GridLayout()); + buttonComposite.setLayoutData(new GridData()); + Button b = new Button(buttonComposite, SWT.PUSH); + b.setText(Messages.bind("AlternateUserValidationDialog.OK_6")); //$NON-NLS-1$ + data = new GridData(); + data.widthHint = 70; + b.setLayoutData(data); + b.addListener(SWT.Selection, new Listener() { + public void handleEvent(Event event) { + okPressed(); + } + }); + buttonComposite.getShell().setDefaultButton(b); + b = new Button(buttonComposite, SWT.PUSH); + b.setText(Messages.bind("AlternateUserValidationDialog.Cancel_7")); //$NON-NLS-1$ + data = new GridData(); + data.widthHint = 70; + b.setLayoutData(data); + b.addListener(SWT.Selection, new Listener() { + public void handleEvent(Event event) { + cancelPressed(); + } + }); + Dialog.applyDialogFont(parent); + return main; + } + + public boolean close() { + boolean result = super.close(); + if (images != null) { + for (int i = 0; i < images.length; i++) { + images[i].dispose(); + images[i] = null; + } + images = null; + } + return result; + } + public String getPassword() { + return password; + } + + Label createLabel(Composite parent) { + Label result = new Label(parent, SWT.NULL); + GridData data = new GridData(); + data.widthHint = 22; + data.heightHint = 22; + result.setLayoutData(data); + result.setImage(getImage()); + return result; + } + Image getImage() { + double random = Math.random(); + random *= 7; // Random number between 0.0 and 7.0 + long num = Math.round(random); + return images[(int)num]; + } + void initializeImages() { + images = new Image[8]; + for (int i = 0; i < images.length; i++) { + images[i] = WikiEditorPlugin.getDefault().getImageDescriptor("glyphs/glyph" + (i+1) + ".gif").createImage(); //$NON-NLS-1$ //$NON-NLS-2$ + } + FontData fd = new FontData(); + fd.setStyle(SWT.BOLD); + fd.setHeight(10); + // On Windows, set the font to Sans Serif for an authentic look + if (System.getProperty("os.name").indexOf("Windows") != -1) { //$NON-NLS-1$ //$NON-NLS-2$ + fd.setName("Microsoft Sans Serif"); //$NON-NLS-1$ + } + } + void updateImages() { + icon1.setImage(getImage()); + icon2.setImage(getImage()); + icon3.setImage(getImage()); + icon4.setImage(getImage()); + } + public void setUsername(String user) { + this.user = user; + } + String getXs() { + double random = Math.random(); + random *= 2; + random += 2; + long num = Math.round(random); + // Random number between 2 and 4 + switch ((int)num) { + case 2: + return "XX"; //$NON-NLS-1$ + case 3: + return "XXX"; //$NON-NLS-1$ + case 4: + return "XXXX"; //$NON-NLS-1$ + } + return "X"; //$NON-NLS-1$ + } + protected void cancelPressed() { + password = null; + super.cancelPressed(); + } +} diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/preferences/FieldEditorOverlayPage.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/preferences/FieldEditorOverlayPage.java new file mode 100644 index 0000000..104a819 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/preferences/FieldEditorOverlayPage.java @@ -0,0 +1,366 @@ +/******************************************************************************* + * Copyright (c) 2003 Berthold Daum. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * Berthold Daum + *******************************************************************************/ +package net.sourceforge.phpeclipse.wiki.preferences; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.eclipse.core.resources.IResource; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.core.runtime.QualifiedName; +import org.eclipse.jface.preference.FieldEditor; +import org.eclipse.jface.preference.FieldEditorPreferencePage; +import org.eclipse.jface.preference.IPreferenceNode; +import org.eclipse.jface.preference.IPreferencePage; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.preference.PreferenceDialog; +import org.eclipse.jface.preference.PreferenceManager; +import org.eclipse.jface.preference.PreferenceNode; +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.BusyIndicator; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.ui.IWorkbenchPropertyPage; + +/** + */ +public abstract class FieldEditorOverlayPage extends FieldEditorPreferencePage + implements + IWorkbenchPropertyPage { + /** + * * Name of resource property for the selection of workbench or project + * settings ** + */ + public static final String USEPROJECTSETTINGS = "useProjectSettings"; //$NON-NLS-1$ + private static final String FALSE = "false"; //$NON-NLS-1$ + private static final String TRUE = "true"; //$NON-NLS-1$ + private boolean fUseFileSettings = false; + // Stores all created field editors + private List editors = new ArrayList(); + // Stores owning element of properties + private IAdaptable element; + // Additional buttons for property pages + private Button useWorkspaceSettingsButton, useProjectSettingsButton, + configureButton; + // Overlay preference store for property pages + private IPreferenceStore overlayStore; + // The image descriptor of this pages title image + private ImageDescriptor image; + // Cache for page id + private String pageId; + /** + * Constructor + * + * @param style - + * layout style + */ + public FieldEditorOverlayPage(int style) { + super(style); + } + /** + * Constructor + * + * @param style - + * layout style + */ + public FieldEditorOverlayPage(int style, boolean isFileSettings) { + super(style); + fUseFileSettings = isFileSettings; + } + /** + * Constructor + * + * @param title - + * title string + * @param style - + * layout style + */ + public FieldEditorOverlayPage(String title, int style) { + super(title, style); + } + public FieldEditorOverlayPage(String title, int style, boolean isFileSettings) { + super(title, style); + fUseFileSettings = isFileSettings; + } + /** + * Constructor + * + * @param title - + * title string + * @param image - + * title image + * @param style - + * layout style + */ + public FieldEditorOverlayPage(String title, ImageDescriptor image, int style) { + super(title, image, style); + this.image = image; + } + /** + * Returns the id of the current preference page as defined in plugin.xml + * Subclasses must implement. + * + * @return - the qualifier + */ + protected abstract String getPageId(); + /** + * Receives the object that owns the properties shown in this property page. + * + * @see org.eclipse.ui.IWorkbenchPropertyPage#setElement(org.eclipse.core.runtime.IAdaptable) + */ + public void setElement(IAdaptable element) { + this.element = element; + } + /** + * Delivers the object that owns the properties shown in this property page. + * + * @see org.eclipse.ui.IWorkbenchPropertyPage#getElement() + */ + public IAdaptable getElement() { + return element; + } + /** + * Returns true if this instance represents a property page + * + * @return - true for property pages, false for preference pages + */ + public boolean isPropertyPage() { + return getElement() != null; + } + /** + * We override the addField method. This allows us to store each field editor + * added by subclasses in a list for later processing. + * + * @see org.eclipse.jface.preference.FieldEditorPreferencePage#addField(org.eclipse.jface.preference.FieldEditor) + */ + protected void addField(FieldEditor editor) { + editors.add(editor); + super.addField(editor); + } + /** + * We override the createControl method. In case of property pages we create + * a new PropertyStore as local preference store. After all control have been + * create, we enable/disable these controls. + * + * @see org.eclipse.jface.preference.PreferencePage#createControl() + */ + public void createControl(Composite parent) { + // Special treatment for property pages + if (isPropertyPage()) { + // Cache the page id + pageId = getPageId(); + // Create an overlay preference store and fill it with properties + overlayStore = new PropertyStore((IResource) getElement(), super + .getPreferenceStore(), pageId); + // Set overlay store as current preference store + } + super.createControl(parent); + // Update state of all subclass controls + if (isPropertyPage()) + updateFieldEditors(); + } + /** + * We override the createContents method. In case of property pages we insert + * two radio buttons at the top of the page. + * + * @see org.eclipse.jface.preference.PreferencePage#createContents(org.eclipse.swt.widgets.Composite) + */ + protected Control createContents(Composite parent) { + if (isPropertyPage()) + createSelectionGroup(parent); + return super.createContents(parent); + } + /** + * Creates and initializes a selection group with two choice buttons and one + * push button. + * + * @param parent - + * the parent composite + */ + private void createSelectionGroup(Composite parent) { + Composite comp = new Composite(parent, SWT.NONE); + GridLayout layout = new GridLayout(2, false); + layout.marginHeight = 0; + layout.marginWidth = 0; + comp.setLayout(layout); + comp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + Composite radioGroup = new Composite(comp, SWT.NONE); + radioGroup.setLayout(new GridLayout()); + radioGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + useWorkspaceSettingsButton = createRadioButton(radioGroup, Messages + .getString("OverlayPage.Use_Workspace_Settings")); //$NON-NLS-1$ + if (fUseFileSettings) { + useProjectSettingsButton = createRadioButton(radioGroup, Messages + .getString("OverlayPage.Use_File_Settings")); //$NON-NLS-1$ + } else { + useProjectSettingsButton = createRadioButton(radioGroup, Messages + .getString("OverlayPage.Use_Project_Settings")); //$NON-NLS-1$ + } + configureButton = new Button(comp, SWT.PUSH); + configureButton.setText(Messages + .getString("OverlayPage.Configure_Workspace_Settings")); //$NON-NLS-1$ + configureButton.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent e) { + configureWorkspaceSettings(); + } + }); + // Set workspace/project radio buttons + try { + String use = ((IResource) getElement()) + .getPersistentProperty(new QualifiedName(pageId, USEPROJECTSETTINGS)); + if (TRUE.equals(use)) { + useProjectSettingsButton.setSelection(true); + configureButton.setEnabled(false); + } else + useWorkspaceSettingsButton.setSelection(true); + } catch (CoreException e) { + useWorkspaceSettingsButton.setSelection(true); + } + } + /** + * Convenience method creating a radio button + * + * @param parent - + * the parent composite + * @param label - + * the button label + * @return - the new button + */ + private Button createRadioButton(Composite parent, String label) { + final Button button = new Button(parent, SWT.RADIO); + button.setText(label); + button.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent e) { + configureButton.setEnabled(button == useWorkspaceSettingsButton); + updateFieldEditors(); + } + }); + return button; + } + /** + * Returns in case of property pages the overlay store, in case of preference + * pages the standard preference store + * + * @see org.eclipse.jface.preference.PreferencePage#getPreferenceStore() + */ + public IPreferenceStore getPreferenceStore() { + if (isPropertyPage()) + return overlayStore; + return super.getPreferenceStore(); + } + /* + * Enables or disables the field editors and buttons of this page + */ + private void updateFieldEditors() { + // We iterate through all field editors + boolean enabled = useProjectSettingsButton.getSelection(); + updateFieldEditors(enabled); + } + /** + * Enables or disables the field editors and buttons of this page Subclasses + * may override. + * + * @param enabled - + * true if enabled + */ + protected void updateFieldEditors(boolean enabled) { + Composite parent = getFieldEditorParent(); + Iterator it = editors.iterator(); + while (it.hasNext()) { + FieldEditor editor = (FieldEditor) it.next(); + editor.setEnabled(enabled, parent); + } + } + /** + * We override the performOk method. In case of property pages we copy the + * values in the overlay store into the property values of the selected + * project. We also save the state of the radio buttons. + * + * @see org.eclipse.jface.preference.IPreferencePage#performOk() + */ + public boolean performOk() { + boolean result = super.performOk(); + if (result && isPropertyPage()) { + // Save state of radiobuttons in project properties + IResource resource = (IResource) getElement(); + try { + String value = (useProjectSettingsButton.getSelection()) ? TRUE : FALSE; + resource.setPersistentProperty(new QualifiedName(pageId, + USEPROJECTSETTINGS), value); + } catch (CoreException e) { + } + } + return result; + } + /** + * We override the performDefaults method. In case of property pages we + * switch back to the workspace settings and disable the field editors. + * + * @see org.eclipse.jface.preference.PreferencePage#performDefaults() + */ + protected void performDefaults() { + if (isPropertyPage()) { + useWorkspaceSettingsButton.setSelection(true); + useProjectSettingsButton.setSelection(false); + configureButton.setEnabled(true); + updateFieldEditors(); + } + super.performDefaults(); + } + /** + * Creates a new preferences page and opens it + * + * @see com.bdaum.SpellChecker.preferences.SpellCheckerPreferencePage#configureWorkspaceSettings() + */ + protected void configureWorkspaceSettings() { + try { + // create a new instance of the current class + IPreferencePage page = (IPreferencePage) this.getClass().newInstance(); + page.setTitle(getTitle()); + page.setImageDescriptor(image); + // and show it + showPreferencePage(pageId, page); + } catch (InstantiationException e) { + e.printStackTrace(); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + } + /** + * Show a single preference pages + * + * @param id - + * the preference page identification + * @param page - + * the preference page + */ + protected void showPreferencePage(String id, IPreferencePage page) { + final IPreferenceNode targetNode = new PreferenceNode(id, page); + PreferenceManager manager = new PreferenceManager(); + manager.addToRoot(targetNode); + final PreferenceDialog dialog = new PreferenceDialog(getControl() + .getShell(), manager); + BusyIndicator.showWhile(getControl().getDisplay(), new Runnable() { + public void run() { + dialog.create(); + dialog.setMessage(targetNode.getLabelText()); + dialog.open(); + } + }); + } +} diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/preferences/ITeamUIImages.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/preferences/ITeamUIImages.java new file mode 100644 index 0000000..9e71634 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/preferences/ITeamUIImages.java @@ -0,0 +1,13 @@ +package net.sourceforge.phpeclipse.wiki.preferences; + +/** + * Internal images for wiki ui. + */ +public interface ITeamUIImages { + + /** + * Icon for authentication dialogs. + */ + public final String IMG_KEY_LOCK = "wizban/keylock.gif"; //$NON-NLS-1$ + +} diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/preferences/InfiniteSubProgressMonitor.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/preferences/InfiniteSubProgressMonitor.java new file mode 100644 index 0000000..47e8b37 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/preferences/InfiniteSubProgressMonitor.java @@ -0,0 +1,91 @@ +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpeclipse.wiki.preferences; + + +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.SubProgressMonitor; + +/** + * Provides an infinite progress monitor by subdividing by half repeatedly. + * + * The ticks parameter represents the number of ticks shown in the progress dialog + * (or propogated up to a parent IProgressMonitor). The totalWork parameter provided + * in actually a hint used to determine how work is translated into ticks. + * The number of totalWork that can actually be worked is n*totalWork/2 where + * 2^n = totalWork. What this means is that if you provide a totalWork of 32 (2^5) than + * the maximum number of ticks is 5*32/2 = 80. + * + */ +public class InfiniteSubProgressMonitor extends SubProgressMonitor { + + int totalWork; + int halfWay; + int currentIncrement; + int nextProgress; + int worked; + + /** + * Constructor for InfiniteSubProgressMonitor. + * @param monitor + * @param ticks + */ + public InfiniteSubProgressMonitor(IProgressMonitor monitor, int ticks) { + this(monitor, ticks, 0); + } + + /** + * Constructor for InfiniteSubProgressMonitor. + * @param monitor + * @param ticks + * @param style + */ + public InfiniteSubProgressMonitor(IProgressMonitor monitor, int ticks, int style) { + super(monitor, ticks, style); + } + + public void beginTask(String name, int totalWork) { + super.beginTask(name, totalWork); + this.totalWork = totalWork; + this.halfWay = totalWork / 2; + this.currentIncrement = 1; + this.nextProgress = currentIncrement; + this.worked = 0; + } + + public void worked(int work) { + if (worked >= totalWork) return; + if (--nextProgress <= 0) { + super.worked(1); + worked++; + if (worked >= halfWay) { + // we have passed the current halfway point, so double the + // increment and reset the halfway point. + currentIncrement *= 2; + halfWay += (totalWork - halfWay) / 2; + } + // reset the progress counter to another full increment + nextProgress = currentIncrement; + } + } + + /** + * Don't allow clearing of the subtask. This will stop the flickering + * of the subtask in the progress dialogs. + * + * @see IProgressMonitor#subTask(String) + */ + public void subTask(String name) { + if(name != null && ! name.equals("")) { //$NON-NLS-1$ + super.subTask(name); + } + } +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/preferences/Messages.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/preferences/Messages.java new file mode 100644 index 0000000..7bbed9a --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/preferences/Messages.java @@ -0,0 +1,93 @@ +/******************************************************************************* + * Copyright (c) 2003 Berthold Daum. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * Berthold Daum + *******************************************************************************/ + +package net.sourceforge.phpeclipse.wiki.preferences; + +import java.text.MessageFormat; +import java.util.MissingResourceException; +import java.util.ResourceBundle; + + +public class Messages { + + private final static String RESOURCE_BUNDLE= "net.sourceforge.phpeclipse.wiki.preferences.Messages";//$NON-NLS-1$ + + private static ResourceBundle fgResourceBundle = null; + + private static boolean notRead = true; + + public Messages() { + } + public static ResourceBundle getResourceBundle() { + if (notRead) { + notRead = false; + try { + fgResourceBundle = ResourceBundle.getBundle(RESOURCE_BUNDLE); + } + catch (Exception e) { + } + } + + return fgResourceBundle; + } + public static String getString(String key) { + try { + return getResourceBundle().getString(key); + } catch (Exception e) { + return "!" + key + "!";//$NON-NLS-2$ //$NON-NLS-1$ + } + } + + /** + * Lookup the message with the given ID in this catalog and bind its + * substitution locations with the given string. + */ + public static String bind(String id, String binding) { + return bind(id, new String[] { binding }); + } + + /** + * Lookup the message with the given ID in this catalog and bind its + * substitution locations with the given strings. + */ + public static String bind(String id, String binding1, String binding2) { + return bind(id, new String[] { binding1, binding2 }); + } + + /** + * Gets a string from the resource bundle. We don't want to crash because of a missing String. + * Returns the key if not found. + */ + public static String bind(String key) { + try { + return getString(key); + } catch (MissingResourceException e) { + return key; + } catch (NullPointerException e) { + return "!" + key + "!"; //$NON-NLS-1$ //$NON-NLS-2$ + } + } + + /** + * Gets a string from the resource bundle and binds it with the given arguments. If the key is + * not found, return the key. + */ + public static String bind(String key, Object[] args) { + try { + return MessageFormat.format(bind(key), args); + } catch (MissingResourceException e) { + return key; + } catch (NullPointerException e) { + return "!" + key + "!"; //$NON-NLS-1$ //$NON-NLS-2$ + } + } +} + diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/preferences/Messages.properties b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/preferences/Messages.properties new file mode 100644 index 0000000..5598a72 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/preferences/Messages.properties @@ -0,0 +1,23 @@ +WikiProjectPreferences.StaticWikiFolder=Projects Wikipedia to HTML output path: +WikiProjectPreferences.WikiTextsFolder=Projects associated Wikipedia texts path: + +OverlayPage.Use_Workspace_Settings=Use &workspace settings +OverlayPage.Use_Project_Settings=Use pr&oject settings +OverlayPage.Use_File_Settings=Use &file settings +OverlayPage.Configure_Workspace_Settings=&Configure Workspace Settings ... +PropertyStore.Cannot_write_resource_property=Cannot write resource property + +UserValidationDialog.5=Configuration: +UserValidationDialog.6=&Save Password +UserValidationDialog.7=Saved passwords are stored on your computer in a file that's difficult, but not impossible, for an intruder to read. + +UserValidationDialog.required=Password Required +UserValidationDialog.labelUser={0} +UserValidationDialog.labelPassword={1} +UserValidationDialog.password=&Password: +UserValidationDialog.user=&User name: + +AlternateUserValidationDialog.Enter_Password_2=Enter Password +AlternateUserValidationDialog.OK_6=OK +AlternateUserValidationDialog.Cancel_7=Cancel +AlternateUserValidationDialog.message=Enter the password for {0}: \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/preferences/OverlayPage.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/preferences/OverlayPage.java new file mode 100644 index 0000000..45b9446 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/preferences/OverlayPage.java @@ -0,0 +1,335 @@ +/******************************************************************************* + * Copyright (c) 2003 Berthold Daum. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * Berthold Daum + *******************************************************************************/ +package net.sourceforge.phpeclipse.wiki.preferences; + +import org.eclipse.core.resources.IResource; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.QualifiedName; +import org.eclipse.jface.preference.IPreferenceNode; +import org.eclipse.jface.preference.IPreferencePage; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.preference.PreferenceDialog; +import org.eclipse.jface.preference.PreferenceManager; +import org.eclipse.jface.preference.PreferenceNode; +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.BusyIndicator; +import org.eclipse.swt.custom.CTabFolder; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.TabFolder; +import org.eclipse.ui.dialogs.PropertyPage; +import org.eclipse.ui.part.PageBook; + +/** + * @author Berthold Daum + */ +public abstract class OverlayPage extends PropertyPage { + + /*** Name of resource property for the selection of workbench or project settings ***/ + public static final String USEPROJECTSETTINGS = "useProjectSettings"; //$NON-NLS-1$ + + private static final String FALSE = "false"; //$NON-NLS-1$ + private static final String TRUE = "true"; //$NON-NLS-1$ + + // Additional buttons for property pages + private Button useWorkspaceSettingsButton, + useProjectSettingsButton, + configureButton; + + // Overlay preference store for property pages + private PropertyStore overlayStore; + + // The image descriptor of this pages title image + private ImageDescriptor image; + + // Cache for page id + private String pageId; + + // Container for subclass controls + private Composite contents; + + /** + * Constructor + */ + public OverlayPage() { + super(); + } + + /** + * Constructor + * @param title - title string + */ + public OverlayPage(String title) { + super(); + setTitle(title); + } + + /** + * Constructor + * @param title - title string + * @param image - title image + */ + public OverlayPage(String title, ImageDescriptor image) { + super(); + setTitle(title); + setImageDescriptor(image); + this.image = image; + } + + /** + * Returns the id of the current preference page as defined in plugin.xml + * Subclasses must implement. + * + * @return - the qualifier + */ + protected abstract String getPageId(); + + /** + * Returns true if this instance represents a property page + * @return - true for property pages, false for preference pages + */ + public boolean isPropertyPage() { + return getElement() != null; + } + + /** + * We need to implement createContents method. In case of property pages we insert two radio buttons + * and a push button at the top of the page. Below this group we create a new composite for the contents + * created by subclasses. + * + * @see org.eclipse.jface.preference.PreferencePage#createContents(org.eclipse.swt.widgets.Composite) + */ + protected Control createContents(Composite parent) { + if (isPropertyPage()) + createSelectionGroup(parent); + contents = new Composite(parent, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.marginHeight = 0; + layout.marginWidth = 0; + contents.setLayout(layout); + contents.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + return contents; + } + + /** + * Creates and initializes a selection group with two choice buttons and one push button. + * @param parent - the parent composite + */ + private void createSelectionGroup(Composite parent) { + Composite comp = new Composite(parent, SWT.NONE); + GridLayout layout = new GridLayout(2, false); + layout.marginHeight = 0; + layout.marginWidth = 0; + comp.setLayout(layout); + comp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + Composite radioGroup = new Composite(comp, SWT.NONE); + radioGroup.setLayout(new GridLayout()); + radioGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + useWorkspaceSettingsButton = createRadioButton(radioGroup, Messages.getString("OverlayPage.Use_Workspace_Settings")); //$NON-NLS-1$ + useProjectSettingsButton = createRadioButton(radioGroup, Messages.getString("OverlayPage.Use_Project_Settings")); //$NON-NLS-1$ + configureButton = new Button(comp, SWT.PUSH); + configureButton.setText(Messages.getString("OverlayPage.Configure_Workspace_Settings")); //$NON-NLS-1$ + configureButton.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent e) { + configureWorkspaceSettings(); + } + }); + // Set workspace/project radio buttons + try { + String use = + ((IResource) getElement()).getPersistentProperty( + new QualifiedName(pageId, USEPROJECTSETTINGS)); + if (TRUE.equals(use)) { + useProjectSettingsButton.setSelection(true); + configureButton.setEnabled(false); + } else + useWorkspaceSettingsButton.setSelection(true); + } catch (CoreException e) { + useWorkspaceSettingsButton.setSelection(true); + } + } + + /** + * Convenience method creating a radio button + * @param parent - the parent composite + * @param label - the button label + * @return - the new button + */ + private Button createRadioButton(Composite parent, String label) { + final Button button = new Button(parent, SWT.RADIO); + button.setText(label); + button.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent e) { + configureButton.setEnabled( + button == useWorkspaceSettingsButton); + setControlsEnabled(); + } + }); + return button; + } + + /** + * In case of property pages we create a new PropertyStore as local overlay store. + * After all controls have been create, we enable/disable these controls + * + * @see org.eclipse.jface.preference.PreferencePage#createControl() + */ + public void createControl(Composite parent) { + // Special treatment for property pages + if (isPropertyPage()) { + // Cache the page id + pageId = getPageId(); + // Create an overlay preference store and fill it with properties + overlayStore = + new PropertyStore( + (IResource) getElement(), + super.getPreferenceStore(), + pageId); + // Set overlay store as current preference store + } + super.createControl(parent); + // Update enablement of all subclass controls + if (isPropertyPage()) + setControlsEnabled(); + } + + /* + * Returns in case of property pages the overlay store - otherwise the standard preference store + * @see org.eclipse.jface.preference.PreferencePage#getPreferenceStore() + */ + public IPreferenceStore getPreferenceStore() { + if (isPropertyPage()) + return overlayStore; + return super.getPreferenceStore(); + } + + /** + * Enables or disables the controls of this page + */ + private void setControlsEnabled() { + boolean enabled = useProjectSettingsButton.getSelection(); + setControlsEnabled(enabled); + } + + /** + * Enables or disables the controls of this page + * Subclasses may override. + * + * @param enabled - true if controls shall be enabled + */ + protected void setControlsEnabled(boolean enabled) { + setControlsEnabled(contents, enabled); + } + + /** + * Enables or disables a tree of controls starting at the specified root. + * We spare tabbed notebooks and pagebooks to allow for fUser navigation. + * + * @param root - the root composite + * @param enabled - true if controls shall be enabled + */ + private void setControlsEnabled(Composite root, boolean enabled) { + Control[] children = root.getChildren(); + for (int i = 0; i < children.length; i++) { + Control child = children[i]; + if (!(child instanceof CTabFolder) && !(child instanceof TabFolder) && !(child instanceof PageBook)) + child.setEnabled(enabled); + if (child instanceof Composite) + setControlsEnabled((Composite) child, enabled); + } + } + + /** + * We override the performOk method. In case of property pages + * we save the state of the radio buttons. + * + * @see org.eclipse.jface.preference.IPreferencePage#performOk() + */ + public boolean performOk() { + boolean result = super.performOk(); + if (result && isPropertyPage()) { + // Save state of radiobuttons in project properties + IResource resource = (IResource) getElement(); + try { + String value = + (useProjectSettingsButton.getSelection()) ? TRUE : FALSE; + resource.setPersistentProperty( + new QualifiedName(pageId, USEPROJECTSETTINGS), + value); + } catch (CoreException e) { + } + } + return result; + } + + /** + * We override the performDefaults method. In case of property pages we + * switch back to the workspace settings and disable the page controls. + * + * @see org.eclipse.jface.preference.PreferencePage#performDefaults() + */ + protected void performDefaults() { + if (isPropertyPage()) { + useWorkspaceSettingsButton.setSelection(true); + useProjectSettingsButton.setSelection(false); + configureButton.setEnabled(true); + setControlsEnabled(); + } + super.performDefaults(); + } + + /** + * Creates a new preferences page and opens it + * @see com.bdaum.SpellChecker.preferences.SpellCheckerPreferencePage#configureWorkspaceSettings() + */ + protected void configureWorkspaceSettings() { + try { + // create a new instance of the current class + IPreferencePage page = + (IPreferencePage) this.getClass().newInstance(); + page.setTitle(getTitle()); + page.setImageDescriptor(image); + // and show it + showPreferencePage(pageId, page); + } catch (InstantiationException e) { + e.printStackTrace(); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + } + + /** + * Show a single preference pages + * @param id - the preference page identification + * @param page - the preference page + */ + protected void showPreferencePage(String id, IPreferencePage page) { + final IPreferenceNode targetNode = new PreferenceNode(id, page); + PreferenceManager manager = new PreferenceManager(); + manager.addToRoot(targetNode); + final PreferenceDialog dialog = + new PreferenceDialog(getControl().getShell(), manager); + BusyIndicator.showWhile(getControl().getDisplay(), new Runnable() { + public void run() { + dialog.create(); + dialog.setMessage(targetNode.getLabelText()); + dialog.open(); + } + }); + } + +} diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/preferences/PropertyStore.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/preferences/PropertyStore.java new file mode 100644 index 0000000..2bd7ac9 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/preferences/PropertyStore.java @@ -0,0 +1,234 @@ +/******************************************************************************* + * Copyright (c) 2003 Berthold Daum. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * Berthold Daum + *******************************************************************************/ + +package net.sourceforge.phpeclipse.wiki.preferences; + +import java.io.IOException; +import java.io.OutputStream; + +import org.eclipse.core.resources.IResource; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.QualifiedName; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.preference.PreferenceStore; + +/** + * @author Berthold Daum + * + */ +public class PropertyStore extends PreferenceStore { + + private IResource resource; + private IPreferenceStore workbenchStore; + private String pageId; + private boolean inserting = false; + + public PropertyStore( + IResource resource, + IPreferenceStore workbenchStore, + String pageId) { + this.resource = resource; + this.workbenchStore = workbenchStore; + this.pageId = pageId; + } + + /*** Write modified values back to properties ***/ + + /* (non-Javadoc) + * @see org.eclipse.jface.preference.IPersistentPreferenceStore#save() + */ + public void save() throws IOException { + writeProperties(); + } + + /* (non-Javadoc) + * @see org.eclipse.jface.preference.PreferenceStore#save(java.io.OutputStream, java.lang.String) + */ + public void save(OutputStream out, String header) throws IOException { + writeProperties(); + } + + /** + * Writes modified preferences into resource properties. + */ + private void writeProperties() throws IOException { + String[] preferences = super.preferenceNames(); + for (int i = 0; i < preferences.length; i++) { + String name = preferences[i]; + try { + setProperty(name, getString(name)); + } catch (CoreException e) { + throw new IOException(Messages.getString("PropertyStore.Cannot_write_resource_property") + name); //$NON-NLS-1$ + } + } + } + + /** + * Convenience method to set a property + * @param name - the preference name + * @param value - the property value or null to delete the property + * @throws CoreException + */ + private void setProperty(String name, String value) throws CoreException { + resource.setPersistentProperty(new QualifiedName(pageId, name), value); + } + + /*** Get default values (Delegate to workbench store) ***/ + + /* (non-Javadoc) + * @see org.eclipse.jface.preference.IPreferenceStore#getDefaultBoolean(java.lang.String) + */ + public boolean getDefaultBoolean(String name) { + return workbenchStore.getDefaultBoolean(name); + } + + /* (non-Javadoc) + * @see org.eclipse.jface.preference.IPreferenceStore#getDefaultDouble(java.lang.String) + */ + public double getDefaultDouble(String name) { + return workbenchStore.getDefaultDouble(name); + } + + /* (non-Javadoc) + * @see org.eclipse.jface.preference.IPreferenceStore#getDefaultFloat(java.lang.String) + */ + public float getDefaultFloat(String name) { + return workbenchStore.getDefaultFloat(name); + } + + /* (non-Javadoc) + * @see org.eclipse.jface.preference.IPreferenceStore#getDefaultInt(java.lang.String) + */ + public int getDefaultInt(String name) { + return workbenchStore.getDefaultInt(name); + } + + /* (non-Javadoc) + * @see org.eclipse.jface.preference.IPreferenceStore#getDefaultLong(java.lang.String) + */ + public long getDefaultLong(String name) { + return workbenchStore.getDefaultLong(name); + } + + /* (non-Javadoc) + * @see org.eclipse.jface.preference.IPreferenceStore#getDefaultString(java.lang.String) + */ + public String getDefaultString(String name) { + return workbenchStore.getDefaultString(name); + } + + /*** Get property values ***/ + + /* (non-Javadoc) + * @see org.eclipse.jface.preference.IPreferenceStore#getBoolean(java.lang.String) + */ + public boolean getBoolean(String name) { + insertValue(name); + return super.getBoolean(name); + } + + /* (non-Javadoc) + * @see org.eclipse.jface.preference.IPreferenceStore#getDouble(java.lang.String) + */ + public double getDouble(String name) { + insertValue(name); + return super.getDouble(name); + } + + /* (non-Javadoc) + * @see org.eclipse.jface.preference.IPreferenceStore#getFloat(java.lang.String) + */ + public float getFloat(String name) { + insertValue(name); + return super.getFloat(name); + } + + /* (non-Javadoc) + * @see org.eclipse.jface.preference.IPreferenceStore#getInt(java.lang.String) + */ + public int getInt(String name) { + insertValue(name); + return super.getInt(name); + } + + /* (non-Javadoc) + * @see org.eclipse.jface.preference.IPreferenceStore#getLong(java.lang.String) + */ + public long getLong(String name) { + insertValue(name); + return super.getLong(name); + } + + /* (non-Javadoc) + * @see org.eclipse.jface.preference.IPreferenceStore#getString(java.lang.String) + */ + public String getString(String name) { + insertValue(name); + return super.getString(name); + } + + /** + * @param name + */ + private synchronized void insertValue(String name) { + if (inserting) + return; + if (super.contains(name)) + return; + inserting = true; + String prop = null; + try { + prop = getProperty(name); + } catch (CoreException e) { + } + if (prop == null) + prop = workbenchStore.getString(name); + if (prop != null) + setValue(name, prop); + inserting = false; + } + + /** + * Convenience method to fetch a property + * @param name - the preference name + * @return - the property value + * @throws CoreException + */ + private String getProperty(String name) throws CoreException { + return resource.getPersistentProperty(new QualifiedName(pageId, name)); + } + + /*** Misc ***/ + + /* (non-Javadoc) + * @see org.eclipse.jface.preference.IPreferenceStore#contains(java.lang.String) + */ + public boolean contains(String name) { + return workbenchStore.contains(name); + } + + /* (non-Javadoc) + * @see org.eclipse.jface.preference.IPreferenceStore#setToDefault(java.lang.String) + */ + public void setToDefault(String name) { + setValue(name, getDefaultString(name)); + } + + /* (non-Javadoc) + * @see org.eclipse.jface.preference.IPreferenceStore#isDefault(java.lang.String) + */ + public boolean isDefault(String name) { + String defaultValue = getDefaultString(name); + if (defaultValue == null) return false; + return defaultValue.equals(getString(name)); + } + +} diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/preferences/TeamImages.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/preferences/TeamImages.java new file mode 100644 index 0000000..14ae034 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/preferences/TeamImages.java @@ -0,0 +1,50 @@ +/******************************************************************************* + * Copyright (c) 2000, 2004 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpeclipse.wiki.preferences; + +import net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin; + +import org.eclipse.core.runtime.IExtension; +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.ui.ISharedImages; + +/** + * TeamImages provides convenience methods for accessing shared images + * provided by the org.eclipse.team.ui plug-in. + *

+ * This class provides ImageDescriptors for each named image in + * {@link ISharedImages}. All Image objects created from the + * provided descriptors are managed the caller and must be disposed appropriately. + *

+ * @since 2.0 + */ +public class TeamImages { + /** + * Returns the image descriptor for the given image ID. + * Returns null if there is no such image. + * + * @param id the identifier for the image to retrieve + * @return the image descriptor associated with the given ID + */ + public static ImageDescriptor getImageDescriptor(String id) { + return WikiEditorPlugin.getImageDescriptor(id); + } + /** + * Convenience method to get an image descriptor for an extension. + * + * @param extension the extension declaring the image + * @param subdirectoryAndFilename the path to the image + * @return the image descriptor for the extension + */ + public static ImageDescriptor getImageDescriptorFromExtension(IExtension extension, String subdirectoryAndFilename) { + return WikiEditorPlugin.getImageDescriptorFromExtension(extension, subdirectoryAndFilename); + } +} diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/preferences/UserValidationDialog.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/preferences/UserValidationDialog.java new file mode 100644 index 0000000..652d150 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/preferences/UserValidationDialog.java @@ -0,0 +1,290 @@ +/******************************************************************************* + * Copyright (c) 2000, 2004 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpeclipse.wiki.preferences; + + + + +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.jface.dialogs.IDialogConstants; +import org.eclipse.jface.window.Window; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Text; + +/** + * A dialog for prompting for a username and fPassword + */ +public class UserValidationDialog extends Dialog { + // widgets + protected Text usernameField; + protected Text passwordField; + protected Button allowCachingButton; + + protected String domain; + protected String defaultUsername; + protected String password = null; + protected boolean allowCaching = false; + protected Image keyLockImage; + + // whether or not the username can be changed + protected boolean isUsernameMutable = true; + protected boolean showAllowCachingButton = true; + protected String username = null; + protected String message = null; + + /** + * Creates a new UserValidationDialog. + * + * @param parentShell the parent shell + * @param location the location + * @param defaultName the default fUser name + * @param message a mesage to display to the fUser + */ + public UserValidationDialog(Shell parentShell, String location, String defaultName, String message) { + super(parentShell); + this.defaultUsername = defaultName; + this.domain = location; + this.message = message; + } + /** + * @see Window#configureShell + */ + protected void configureShell(Shell newShell) { + super.configureShell(newShell); + newShell.setText(Messages.getString("UserValidationDialog.required")); //$NON-NLS-1$ + // set F1 help +// WorkbenchHelp.setHelp(newShell, IHelpContextIds.USER_VALIDATION_DIALOG); + } + /** + * @see Window#create + */ + public void create() { + super.create(); + // add some default values + usernameField.setText(defaultUsername); + + if (isUsernameMutable) { + // give focus to username field + usernameField.selectAll(); + usernameField.setFocus(); + } else { + usernameField.setEditable(false); + passwordField.setFocus(); + } + } + + /** + * @see Dialog#createDialogArea + */ + protected Control createDialogArea(Composite parent) { + Composite top = new Composite(parent, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.numColumns = 2; + + top.setLayout(layout); + top.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + + Composite imageComposite = new Composite(top, SWT.NONE); + layout = new GridLayout(); + imageComposite.setLayout(layout); + imageComposite.setLayoutData(new GridData(GridData.FILL_VERTICAL)); + + Composite main = new Composite(top, SWT.NONE); + layout = new GridLayout(); + layout.numColumns = 3; + main.setLayout(layout); + main.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + + Label imageLabel = new Label(imageComposite, SWT.NONE); + keyLockImage = TeamImages.getImageDescriptor(ITeamUIImages.IMG_KEY_LOCK).createImage(); + imageLabel.setImage(keyLockImage); + GridData data = new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL); + imageLabel.setLayoutData(data); + + if (message != null) { + Label messageLabel = new Label(main, SWT.WRAP); + messageLabel.setText(message); + data = new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL); + data.horizontalSpan = 3; + data.widthHint = 300; + messageLabel.setLayoutData(data); + } + if (domain != null) { + Label d = new Label(main, SWT.WRAP); + d.setText(Messages.getString("UserValidationDialog.5")); //$NON-NLS-1$ + data = new GridData(); + d.setLayoutData(data); + Label label = new Label(main, SWT.WRAP); + if (isUsernameMutable) { + label.setText(Messages.bind("UserValidationDialog.labelUser", domain)); //$NON-NLS-1$ + } else { + label.setText(Messages.bind("UserValidationDialog.labelPassword", new Object[]{defaultUsername, domain})); //$NON-NLS-1$ + } + data = new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL); + data.horizontalSpan = 2; + data.widthHint = 300; + label.setLayoutData(data); + } + createUsernameFields(main); + createPasswordFields(main); + + if(domain != null && showAllowCachingButton) { + allowCachingButton = new Button(main, SWT.CHECK); + allowCachingButton.setText(Messages.getString("UserValidationDialog.6")); //$NON-NLS-1$ + data = new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL); + data.horizontalSpan = 3; + allowCachingButton.setLayoutData(data); + allowCachingButton.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent e) { + allowCaching = allowCachingButton.getSelection(); + } + }); + Composite warningComposite = new Composite(main, SWT.NONE); + layout = new GridLayout(); + layout.numColumns = 2; + layout.marginHeight = 0; + layout.marginHeight = 0; + warningComposite.setLayout(layout); + data = new GridData(GridData.FILL_HORIZONTAL); + data.horizontalSpan = 3; + warningComposite.setLayoutData(data); + Label warningLabel = new Label(warningComposite, SWT.NONE); + warningLabel.setImage(getImage(DLG_IMG_MESSAGE_WARNING)); + warningLabel.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.HORIZONTAL_ALIGN_BEGINNING)); + Label warningText = new Label(warningComposite, SWT.WRAP); + warningText.setText(Messages.getString("UserValidationDialog.7")); //$NON-NLS-1$ + data = new GridData(GridData.FILL_HORIZONTAL); + data.widthHint = 300; + warningText.setLayoutData(data); + } + + Dialog.applyDialogFont(parent); + + return main; + } + /** + * Create a spacer. + */ + protected void createSpacer(Composite top, int columnSpan, int vertSpan) { + Label l = new Label(top, SWT.NONE); + GridData data = new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL); + data.horizontalSpan = columnSpan; + data.verticalSpan = vertSpan; + l.setLayoutData(data); + } + + /** + * Creates the three widgets that represent the fPassword entry area. + * + * @param parent the parent of the widgets + */ + protected void createPasswordFields(Composite parent) { + new Label(parent, SWT.NONE).setText(Messages.getString("UserValidationDialog.fPassword")); //$NON-NLS-1$ + + passwordField = new Text(parent, SWT.BORDER | SWT.PASSWORD); + GridData data = new GridData(GridData.FILL_HORIZONTAL); + data.horizontalSpan = 2; + data.widthHint = convertHorizontalDLUsToPixels(IDialogConstants.ENTRY_FIELD_WIDTH); + passwordField.setLayoutData(data); + } + /** + * Creates the three widgets that represent the fUser name entry area. + * + * @param parent the parent of the widgets + */ + protected void createUsernameFields(Composite parent) { + new Label(parent, SWT.NONE).setText(Messages.getString("UserValidationDialog.fUser")); //$NON-NLS-1$ + + usernameField = new Text(parent, SWT.BORDER); + GridData data = new GridData(GridData.FILL_HORIZONTAL); + data.horizontalSpan = 2; + data.widthHint = convertHorizontalDLUsToPixels(IDialogConstants.ENTRY_FIELD_WIDTH); + usernameField.setLayoutData(data); + } + + /** + * Returns the fPassword entered by the fUser, or null + * if the fUser canceled. + * + * @return the entered fPassword + */ + public String getPassword() { + return password; + } + + /** + * Returns the username entered by the fUser, or null + * if the fUser canceled. + * + * @return the entered username + */ + public String getUsername() { + return username; + } + + /** + * Returns true if the save fPassword checkbox was selected. + * @return true if the save fPassword checkbox was selected and false + * otherwise. + */ + public boolean getAllowCaching() { + return allowCaching; + } + + /** + * Notifies that the ok button of this dialog has been pressed. + *

+ * The default implementation of this framework method sets + * this dialog's return code to Window.OK + * and closes the dialog. Subclasses may override. + *

+ */ + protected void okPressed() { + password = passwordField.getText(); + username = usernameField.getText(); + + super.okPressed(); + } + /** + * Sets whether or not the username field should be mutable. + * This method must be called before create(), otherwise it + * will be ignored. + * + * @param value whether the username is mutable + */ + public void setUsernameMutable(boolean value) { + isUsernameMutable = value; + } + + public void setShowAllowCachingButton(boolean value) { + showAllowCachingButton = value; + } + + /* (non-Javadoc) + * @see org.eclipse.jface.dialogs.Dialog#close() + */ + public boolean close() { + if(keyLockImage != null) { + keyLockImage.dispose(); + } + return super.close(); + } +} diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/preferences/Util.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/preferences/Util.java new file mode 100644 index 0000000..4d154f7 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/preferences/Util.java @@ -0,0 +1,197 @@ +package net.sourceforge.phpeclipse.wiki.preferences; + +import net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin; + +import org.eclipse.core.resources.IContainer; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IFolder; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IWorkspaceRoot; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.core.runtime.Path; +import org.eclipse.core.runtime.QualifiedName; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.IWorkbenchWindow; +import org.eclipse.ui.PlatformUI; +import org.plog4u.wiki.filter.FilterUtil; + +public class Util { + public static Shell findShell() { + IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); + if (window != null) { + return window.getShell(); + } + Display display = Display.getCurrent(); + if (display == null) { + display = Display.getDefault(); + return display.getActiveShell(); + } + // worst case, just create our own. + return new Shell(WikiEditorPlugin.getStandardDisplay()); + } + + public static String getProjectsWikiOutputPath(IResource resource, String key) { + return getOverlayedPrefProjectValue(resource, WikiProjectPreferences.PREF_ID, key); + // int index = temp.indexOf(File.pathSeparatorChar); + // if (index >= 0) { + // temp = temp.substring(0, index); + // } + // return temp; + } + + public static String getPreferenceValue(IResource resource, String key) { + return getOverlayedPrefProjectValue(resource, WikiProjectPreferences.PREF_ID, key); + } + + public static String getHTMLFileName(IFile file, String binBasePath, String srcBasePath) { + StringBuffer htmlBuffer = new StringBuffer(); + String htmlName = null; + // String srcBasePath = Util.getWikiTextsPath(file); + // String fileName = file.getProjectRelativePath().toString(); + String fileName = file.getLocation().toString(); + if (fileName.startsWith(srcBasePath)) { + fileName = fileName.substring(srcBasePath.length()); + if (fileName.charAt(0) != '/') { + fileName = "/" + fileName; + } + int index = fileName.lastIndexOf(".wp"); + if (index >= 0) { + htmlName = binBasePath + fileName.substring(0, index) + ".html"; + } else { + htmlName = binBasePath + fileName; + } + } + return htmlName; + } + + public static String getOverlayedPrefProjectValue(IResource resource, String pageId, String key) { + IProject project = resource.getProject(); + String value = null; + if (useProjectSettings(project, pageId)) { + value = getProperty(resource, pageId, key); + } + if (value != null) + return value; + return WikiEditorPlugin.getDefault().getPreferenceStore().getString(key); + } + + public static String getOverlayedPrefResourceValue(IResource resource, String pageId, String key) { + String value = null; + if (useProjectSettings(resource, pageId)) { + value = getProperty(resource, pageId, key); + } + if (value != null) + return value; + return WikiEditorPlugin.getDefault().getPreferenceStore().getString(key); + } + + private static String getProperty(IResource resource, String pageId, String key) { + try { + return resource.getPersistentProperty(new QualifiedName(pageId, key)); + } catch (CoreException e) { + } + return null; + } + + private static void setProperty(IResource resource, String pageId, String key, String value) { + try { + resource.setPersistentProperty(new QualifiedName(pageId, key), value); + } catch (CoreException e) { + } + } + + private static boolean useProjectSettings(IResource resource, String pageId) { + String use = getProperty(resource, pageId, FieldEditorOverlayPage.USEPROJECTSETTINGS); + return "true".equals(use); + } + + public static void setWikiTextsPath(IProject project) { + String value = project.getLocation().toString(); + IPreferenceStore store = WikiEditorPlugin.getDefault().getPreferenceStore(); + String globalBasePath = store.getString(WikiEditorPlugin.WIKI_TEXTS_BASE_PATH); + if (globalBasePath == null || globalBasePath.equals("")) { + store.setValue(WikiEditorPlugin.WIKI_TEXTS_BASE_PATH, value + "/wpsrc"); + } + String htmlFolder = store.getString(WikiEditorPlugin.HTML_OUTPUT_PATH); + if (htmlFolder == null || htmlFolder.equals("")) { + // set a global default + store.setValue(WikiEditorPlugin.HTML_OUTPUT_PATH, value + "/wpbin"); + } + setProperty(project, WikiProjectPreferences.PREF_ID, FieldEditorOverlayPage.USEPROJECTSETTINGS, "true"); + setProperty(project, WikiProjectPreferences.PREF_ID, WikiEditorPlugin.WIKI_TEXTS_BASE_PATH, value + "/wpsrc"); + setProperty(project, WikiProjectPreferences.PREF_ID, WikiEditorPlugin.HTML_OUTPUT_PATH, value + "/wpbin"); + + // IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); + // IResource resource = root.findMember(project.getLocation()); + NullProgressMonitor _monitor = new NullProgressMonitor(); + // if (resource!=null && resource.exists() && (resource instanceof IContainer)) { + // IContainer container = (IContainer) resource; + final IFolder srcFolder = project.getFolder(new Path("wpsrc")); + if (!srcFolder.exists()) { + try { + srcFolder.create(true, false, _monitor); + } catch (CoreException e) { + } + } + final IFolder binFolder = project.getFolder(new Path("wpbin")); + if (!binFolder.exists()) { + try { + binFolder.create(true, false, _monitor); + } catch (CoreException e) { + } + } + // } + + } + + public static String getWikiTextsPath(IResource file) { + return Util.getPreferenceValue(file.getProject(), WikiEditorPlugin.WIKI_TEXTS_BASE_PATH); + } + + public static String getProjectsWikiTextsPath(IProject project) { + return Util.getPreferenceValue(project, WikiEditorPlugin.WIKI_TEXTS_BASE_PATH); + } + + public static String getWikiFileName(String wikiLink, IFile currentFile, String key) { + // String basePath = currentFile.getProject().getLocation().toString(); + String basePath = getWikiTextsPath(currentFile); + return basePath + "/" + FilterUtil.normalizeWikiLink(wikiLink) + ".wp"; + } + + public static String getFileWikiName(IFile currentFile, String key) { + String filePath = currentFile.getLocation().toString(); + // String basePath = currentFile.getProject().getLocation().toString(); + String basePath = getWikiTextsPath(currentFile); + StringBuffer result = new StringBuffer(); + int lastIndex = filePath.lastIndexOf(".wp"); + if (lastIndex < 0) { + lastIndex = filePath.length(); + } + char ch; + for (int i = basePath.length() + 1; i < lastIndex; i++) { + ch = filePath.charAt(i); + switch (ch) { + case '/': + result.append(':'); + break; + default: + result.append(ch); + } + } + return result.toString(); + } + + public static String getWikiTitle(IFile currentFile) { + String fileName = currentFile.getName(); + String fileExt = currentFile.getFileExtension().toLowerCase(); + if (fileExt.equals("wp")) { + return fileName.substring(0, fileName.length() - 3); + } + return null; + } +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/preferences/WikiProjectPreferences.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/preferences/WikiProjectPreferences.java new file mode 100644 index 0000000..3ce415c --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/preferences/WikiProjectPreferences.java @@ -0,0 +1,57 @@ +package net.sourceforge.phpeclipse.wiki.preferences; + +import net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin; + +import org.eclipse.jface.preference.DirectoryFieldEditor; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.preference.PathEditor; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.IWorkbenchPreferencePage; + +/** + * + * This page will be added to the project's property page dialog when the "Properties..." popup menu item is selected + */ +public class WikiProjectPreferences extends FieldEditorOverlayPage implements IWorkbenchPreferencePage { + + public final static String PREF_ID = "net.sourceforge.phpeclipse.wiki.preferences.WikiProjectPreferences"; + + public WikiProjectPreferences() { + super(GRID); + } + + /* + * (non-Javadoc) + * + * @see net.sourceforge.phpeclipse.wiki.preferences.FieldEditorOverlayPage#getPageId() + */ + protected String getPageId() { + return PREF_ID; + } + + protected void createFieldEditors() { + Composite composite = getFieldEditorParent(); + + addField(new DirectoryFieldEditor(WikiEditorPlugin.HTML_OUTPUT_PATH, Messages.getString("WikiProjectPreferences.StaticWikiFolder"), composite)); + addField(new DirectoryFieldEditor(WikiEditorPlugin.WIKI_TEXTS_BASE_PATH, Messages.getString("WikiProjectPreferences.WikiTextsFolder"), composite)); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.preference.PreferencePage#doGetPreferenceStore() + */ + protected IPreferenceStore doGetPreferenceStore() { + return WikiEditorPlugin.getDefault().getPreferenceStore(); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench) + */ + public void init(IWorkbench workbench) { + setDescription("Default entries static wiki pages."); + } +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/renderer/AbstractContentRenderer.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/renderer/AbstractContentRenderer.java new file mode 100644 index 0000000..4c86952 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/renderer/AbstractContentRenderer.java @@ -0,0 +1,430 @@ +package net.sourceforge.phpeclipse.wiki.renderer; + +import java.io.IOException; +import java.util.StringTokenizer; + +import net.sourceforge.phpeclipse.wiki.editor.WikiEditor; +import net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin; +import net.sourceforge.phpeclipse.wiki.preferences.Util; + +import org.eclipse.core.resources.IProject; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.Path; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.IDocument; + +public abstract class AbstractContentRenderer implements IContentRenderer { + protected IProject fProject; + + public static final String CLASS_MONO_SPACE = "monospace"; + + public static final String CLASS_QUOTE = "quote"; + + public static final String TABLE_DELIMETER = "|"; + + public static final String HR = "hr"; + + public static final String NEW_WIKIDOC_HREF = "?"; + + public static final String WIKI_HREF = "http://--wiki/"; + + public static final String[][] REPLACE_TEXT = new String[][] { { "<", "<" }, { "\"", """ } }; + + private WikiEditor editor; + + protected StringBuffer buffer; + + private int currentLine; + + private int currentListDepth; + + private boolean inTable; + + private void setEditor(WikiEditor editor) { + this.editor = editor; + } + + protected StringBuffer getBuffer() { + return buffer; + } + + protected WikiEditor getEditor() { + return editor; + } + + // public void render(String content, StringBuffer buf) { + // try { + // buffer = buf; + // appendHeader(); + // + // int index = 0; + // int startIndex = 0; + // String line; + // while (index < content.length()) { + // if (content.charAt(index++) == '\n') { + // line = content.substring(startIndex, index); + // startIndex = index; + // appendLine(line); + // + // } + // index++; + // } + // if (startIndex < content.length()) { + // line = content.substring(startIndex, content.length()); + // renderLine(line); + // } + // appendFooter(); + // // return buffer.toString(); + // } catch (Exception e) { + // WikiEditorPlugin.getDefault().log(buffer.toString()); + // WikiEditorPlugin.getDefault().log(e.getLocalizedMessage(), e); + // // return "

" + e.getLocalizedMessage() + + // // "

"; + // } + // } + + // protected void renderLine(String line) { + // if (isHeader(line)) { + // appendHeader(line); + // } else if (isList(line)) { + // appendListItem(line); + // } else if (tableLine(line)) { + // processTable(line); + // } else if (process(line)) { + // return; + // } else { + // buffer.append(line); + // } + // } + + // public final String render(WikiEditor editor) { + // initialise(editor); + // try { + // buffer = new StringBuffer(); + // appendHeader(); + // buffer.append("

").append(editor.getWikiNameBeingEdited()).append("

"); + // appendContents(); + // appendFooter(); + // return buffer.toString(); + // } catch (Exception e) { + // WikiEditorPlugin.getDefault().log(buffer.toString()); + // WikiEditorPlugin.getDefault().log(e.getLocalizedMessage(), e); + // return "

" + e.getLocalizedMessage() + "

"; + // } + // } + + private void initialise(WikiEditor editor) { + setEditor(editor); + currentListDepth = 0; + inTable = false; + initialise(); + } + + protected abstract void initialise(); + + protected void appendHeader() throws IOException { + buffer.append(""); + // String basePath = Util.getMiscProjectsPreferenceValue(fProject, WikiConstants.HTML_OUTPUT_PATH); + // buffer.append(""); + + // if (WikiEditorPlugin.getDefault().getPluginPreferences().contains(WikiConstants.BROWSER_CSS_URL)) { + // buffer.append(""); + // } + // appendStyle(); + + buffer.append("\n"); + } + + private void appendContents() { + IDocument document = editor.getDocument(); + currentLine = 0; + while (currentLine < document.getNumberOfLines()) { + String line = getLine(document, currentLine); + // appendLine(line); + currentLine++; + } + } + + protected void appendNewLine() { + getBuffer().append(System.getProperty("line.separator")); + } + + // protected String getNextLine() { + // if (hasLine(currentLine + 1)) { + // currentLine++; + // return getLine(editor.getDocument(), currentLine); + // } + // throw new RuntimeException("Should not be called if there is no next line."); + // } + + // protected String peekNextLine() { + // if (hasLine(currentLine + 1)) { + // return getLine(editor.getDocument(), currentLine + 1); + // } + // return ""; + // } + + protected boolean hasNextLine() { + return hasLine(currentLine + 1); + } + + private boolean hasLine(int lineNumber) { + return lineNumber < editor.getDocument().getNumberOfLines(); + } + + protected void appendFooter() { + buffer.append("\n"); + } + + // protected void appendStyle() throws IOException { + // buffer.append(""); + // } + // + // protected void appendLine(String line) { + // if (isHeader(line)) { + // appendHeader(line); + // } else if (isList(line)) { + // appendListItem(line); + // } else if (tableLine(line)) { + // processTable(line); + // } else if (process(line)) { + // return; + // } else { + // buffer.append("

"); + // append(processTags(line)); + // buffer.append("

"); + // } + // } + + // private final void appendListItem(String line) { + // int bullet = getListDepth(line); + // if (bullet > currentListDepth) { + // repeatAppend("
    ", bullet - currentListDepth); + // currentListDepth = bullet; + // } else if (bullet < currentListDepth) { + // repeatAppend("
", currentListDepth - bullet); + // currentListDepth = bullet; + // } + // getBuffer().append("
  • "); + // String content = ""; + // if (bullet < line.length() - 1) { + // content = getListtext(line); + // } + // append(processTags(content)); + // getBuffer().append("
  • "); + // if (!isList(peekNextLine())) { + // repeatAppend("", currentListDepth); + // currentListDepth = 0; + // } + // } + + protected abstract String getListtext(String line); + + protected void repeatAppend(String item, int n) { + for (int i = 0; i < n; i++) { + getBuffer().append(item); + } + } + + protected abstract int getListDepth(String line); + + protected abstract String processTags(String line); + + private String getLine(IDocument document, int n) { + try { + String line = document.get(document.getLineOffset(n), document.getLineLength(n)); + if (document.getLineDelimiter(n) != null) { + line = line.substring(0, line.length() - document.getLineDelimiter(n).length()); + } + for (int i = 0; i < REPLACE_TEXT.length; i++) { + line = line.replaceAll(REPLACE_TEXT[i][0], REPLACE_TEXT[i][1]); + } + return line; + } catch (BadLocationException e) { + WikiEditorPlugin.getDefault().logAndReport("Error", e.getLocalizedMessage(), e); + return e.getLocalizedMessage(); + } + } + + // protected void append(String line) { + // TextRegion[] regions = TextRegionBuilder.getTextRegions(line, editor); + // for (int i = 0; i < regions.length; i++) { + // regions[i].accept(new TextRegionVisitor() { + // public Object visit(UndefinedTextRegion undefinedTextRegion) { + // buffer.append(undefinedTextRegion.getText()); + // return null; + // } + // + // public Object visit(UrlTextRegion urlTextRegion) { + // appendLink(urlTextRegion.getText(), urlTextRegion.getText()); + // return null; + // } + // + // public Object visit(WikiNameTextRegion wikiNameTextRegion) { + // if (editor.hasWikiSibling(wikiNameTextRegion)) { + // appendLink(AbstractContentRenderer.WIKI_HREF + wikiNameTextRegion.getText(), wikiNameTextRegion.getText()); + // } else { + // buffer.append(wikiNameTextRegion.getText()); + // appendLink(AbstractContentRenderer.WIKI_HREF + wikiNameTextRegion.getText(), AbstractContentRenderer.NEW_WIKIDOC_HREF); + // } + // return null; + // } + // + // public Object visit(WikiUrlTextRegion wikiUrlTextRegion) { + // String link; + // if (wikiUrlTextRegion.getLink().startsWith(WikiConstants.ECLIPSE_PREFIX)) { + // link = AbstractContentRenderer.WIKI_HREF + wikiUrlTextRegion.getLink(); + // } else { + // link = wikiUrlTextRegion.getLink(); + // } + // appendLink(link, wikiUrlTextRegion.getText()); + // return null; + // } + // + // public Object visit(BasicTextRegion basicTextRegion) { + // buffer.append(basicTextRegion.getText()); + // return null; + // } + // + // public Object visit(EclipseResourceTextRegion eclipseResourceTextRegion) { + // appendLink(AbstractContentRenderer.WIKI_HREF + eclipseResourceTextRegion.getText(), eclipseResourceTextRegion.getText()); + // return null; + // } + // + // public Object visit(JavaTypeTextRegion region) { + // try { + // if (region.getType().getUnderlyingResource() != null) { + // String url = AbstractContentRenderer.WIKI_HREF + WikiConstants.ECLIPSE_PREFIX + // + region.getType().getUnderlyingResource().getFullPath().toString(); + // appendLink(url, region.getText()); + // } else { + // append(region.getText()); + // } + // } catch (JavaModelException e) { + // WikiPlugin.getDefault().logAndReport("Error", e.getLocalizedMessage(), e); + // } + // return null; + // } + // + // }); + // } + // } + + protected void appendLink(String url, String text) { + buffer.append("").append(text).append(""); + } + + protected abstract boolean isHeader(String line); + + protected abstract void appendHeader(String line); + + protected abstract boolean isList(String line); + + /** + * Gives implementors a chance to do processing on this line. + * + * @return if true, the line will not be processed further + */ + protected abstract boolean process(String line); + + /** + * Replace all occurrences of markeup which occurs in pairs with an opening and closing tag in the given line. e.g. + * + *
    +   * 
    +   *  
    +   *   
    +   *    
    +   *     
    +   *          replacePair("my ''bold'' word", "''", "<b>", ",</b>") returns "my <b>bold</b> word"
    +   *      
    +   *     
    +   *    
    +   *   
    +   *  
    +   * 
    + */ + protected String replacePair(String line, String search, String openingTag, String closingTag) { + StringBuffer buffer = new StringBuffer(); + String[] foo = line.split(search); + for (int i = 0; i < foo.length; i++) { + if (i % 2 == 1) { + buffer.append(openingTag).append(foo[i]).append(closingTag); + } else { + buffer.append(foo[i]); + } + } + return buffer.toString(); + } + + protected void appendHR() { + getBuffer().append("
    "); + } + + private boolean tableLine(String line) { + return line.startsWith(AbstractContentRenderer.TABLE_DELIMETER); + } + + // private void processTable(String line) { + // if (!inTable) { + // inTable = true; + // getBuffer().append(getTableTag()); + // } + // getBuffer().append(""); + // StringTokenizer tokenizer = new StringTokenizer(line, AbstractContentRenderer.TABLE_DELIMETER); + // while (tokenizer.hasMoreTokens()) { + // String cell = tokenizer.nextToken(); + // String element = "td"; + // if (cell.trim().startsWith("*")) { + // element = "th"; + // cell = cell.replaceAll("\\*", ""); + // } + // getBuffer().append("<").append(element).append(">"); + // append(processTags(cell)); + // getBuffer().append(""); + // } + // getBuffer().append(""); + // if (!tableLine(peekNextLine())) { + // getBuffer().append(""); + // inTable = false; + // } + // } + + /** + * @return the tag for table (can be overridden to add style) + */ + protected String getTableTag() { + return ""; + } + + public void forEachHeader(IDocument document, StructureClosure closure) throws BadLocationException { + for (int i = 0; i < document.getNumberOfLines(); i++) { + String line = getLine(document, i); + if (isHeader(line)) { + String header = getHeaderText(line); + closure.acceptHeader(header, document.getLineOffset(i)); + } + } + } + + /** + * Get the header from a line with header markup + * + * @param line + * guaranteed to be a valid header as defined by b {@link #isHeader(String) isHeader(String)} + */ + protected abstract String getHeaderText(String line); + + /** + * @param project + * The fProject to set. + */ + public void setProject(IProject project) { + fProject = project; + } +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/renderer/IContentRenderer.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/renderer/IContentRenderer.java new file mode 100644 index 0000000..2ed554f --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/renderer/IContentRenderer.java @@ -0,0 +1,16 @@ +package net.sourceforge.phpeclipse.wiki.renderer; + +import net.sourceforge.phpeclipse.wiki.editor.WikiEditor; + +import org.eclipse.core.resources.IProject; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.IDocument; + + +public interface IContentRenderer { + void forEachHeader(IDocument document, StructureClosure closure) throws BadLocationException; + + // new interface methods + public void render(String content, StringBuffer buf, int level, boolean completeHTMLPage); + public void setProject(IProject project); +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/renderer/RendererFactory.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/renderer/RendererFactory.java new file mode 100644 index 0000000..337c150 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/renderer/RendererFactory.java @@ -0,0 +1,26 @@ +package net.sourceforge.phpeclipse.wiki.renderer; + +import net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin; + +import org.eclipse.core.resources.IProject; + + + +public final class RendererFactory { + + private RendererFactory() { + super(); + } + + public static IContentRenderer createContentRenderer(IProject project) throws InstantiationException, IllegalAccessException, ClassNotFoundException { + IContentRenderer renderer =(AbstractContentRenderer) Class.forName(getContentRendererName()).newInstance(); + renderer.setProject(project); + return renderer; + } + + public static String getContentRendererName() { + return WikipediaContentRenderer.class.getName(); +// return WikiEditorPlugin.getDefault().getPreferenceStore().getString(WikiConstants.BROWSER_RENDERER); + } + +} diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/renderer/StructureClosure.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/renderer/StructureClosure.java new file mode 100644 index 0000000..3bc5059 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/renderer/StructureClosure.java @@ -0,0 +1,10 @@ +package net.sourceforge.phpeclipse.wiki.renderer; + + +public interface StructureClosure { + /** + * @param header the text of the header without markup + * @param offset the offset in the document where the header is located + */ + void acceptHeader(String header, int offset); +} diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/renderer/WikipediaContentRenderer.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/renderer/WikipediaContentRenderer.java new file mode 100644 index 0000000..c2d6e2c --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/renderer/WikipediaContentRenderer.java @@ -0,0 +1,158 @@ +/* + * Thanks to Bent Andre Solheim for the improved header rendering. + */ +package net.sourceforge.phpeclipse.wiki.renderer; + +import java.io.IOException; +import java.io.StringWriter; + +import net.sourceforge.phpeclipse.wiki.builder.BuilderRenderEngine; +import net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin; + +import org.eclipse.core.resources.IProject; +import org.radeox.api.engine.RenderEngine; +import org.radeox.api.engine.context.InitialRenderContext; +import org.radeox.engine.context.BaseInitialRenderContext; +import org.radeox.macro.MacroRepository; + +public final class WikipediaContentRenderer extends AbstractContentRenderer { + public static final String BULLET_MARKUP = "*"; + + public static final String ALT_BULLET_MARKUP = "-"; + + protected InitialRenderContext context; + + protected BuilderRenderEngine engine; + + protected void initialise() { + + } + + protected void appendHeader(String line) { + String header = getHeaderText(line); + String headerStartTag = "

    "; + getBuffer().append(headerStartTag); + getBuffer().append(header); + getBuffer().append("

    "); + } + + private int getHeaderSize(String line) { + int size = 0; + int index = 0; + while (index < line.length() && line.charAt(index) != ' ') { + if (line.charAt(index) == '1') { + size++; + } + index++; + } + return size; + } + + private String getHeaderCss(int size) { + int max = Math.min(3, size); + StringBuffer css = new StringBuffer(); + css.append("class=\"").append("heading"); + for (int i = 0; i < max; i++) { + css.append("-1"); + } + css.append("\""); + return css.toString(); + } + + protected String getHeaderText(String line) { + return line.substring(line.indexOf(' ')).trim(); + } + + protected int getListDepth(String line) { + char bullet = getBullet(line); + for (int i = 0; i < line.length(); i++) { + if (line.charAt(i) != bullet) { + return i; + } + } + return line.length(); + } + + private char getBullet(String line) { + char bullet = line.startsWith(WikipediaContentRenderer.BULLET_MARKUP) ? WikipediaContentRenderer.BULLET_MARKUP.charAt(0) + : WikipediaContentRenderer.ALT_BULLET_MARKUP.charAt(0); + return bullet; + } + + protected boolean isHeader(String line) { + return line.startsWith("1") && line.indexOf(' ') > 0; + } + + protected boolean isList(String line) { + return !line.trim().equals("----") + && (line.startsWith(WikipediaContentRenderer.BULLET_MARKUP) || line.startsWith(WikipediaContentRenderer.ALT_BULLET_MARKUP)); + } + + protected boolean process(String line) { + if (line.trim().matches("^----*$")) { + appendHR(); + return true; + } + return false; + } + + protected String processTags(String line) { + line = line.replaceAll("\\\\", "
    "); + line = extractMacroMarkup(line); + line = replacePair(line, "__", "", ""); + line = replacePair(line, "~~", "", ""); + line = replacePair(line, "--", "", ""); + return line; + } + + private String extractMacroMarkup(String line) { + return line.replaceAll("\\{.*?\\}", ""); + } + + protected String getListtext(String line) { + return line.substring(getListDepth(line)).trim(); + } + + protected String getTableTag() { + return "
    "; + } + + public final void render(String content, StringBuffer buf, int level, boolean completeHTMLPage) { + try { + buffer = buf; + if (completeHTMLPage) { + appendHeader(); + } + StringWriter writer = new StringWriter(); + try { + engine.setLevel(level); + engine.render(writer, content, context); + buffer.append(writer); + } catch (IOException e) { + // never reach + } + if (completeHTMLPage) { + appendFooter(); + } + // return buffer.toString(); + } catch (Exception e) { + WikiEditorPlugin.getDefault().log(buffer.toString()); + WikiEditorPlugin.getDefault().log(e.getLocalizedMessage(), e); + // return "

    " + e.getLocalizedMessage() + "

    "; + } + } + + /* + * (non-Javadoc) + * + * @see net.sourceforge.phpeclipse.wiki.renderer.IContentRenderer#setProject(org.eclipse.core.resources.IProject) + */ + public void setProject(IProject project) { + super.setProject(project); + context = new BaseInitialRenderContext(); + engine = new BuilderRenderEngine(project, context); + context.setRenderEngine(engine); + MacroRepository repository = MacroRepository.getInstance(); + repository.setInitialContext(context); + } +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/ui/internal/ConfigurationComposite.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/ui/internal/ConfigurationComposite.java new file mode 100644 index 0000000..cffe190 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/ui/internal/ConfigurationComposite.java @@ -0,0 +1,260 @@ +/********************************************************************** + * Copyright (c) 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM - Initial API and implementation + **********************************************************************/ +package net.sourceforge.phpeclipse.wiki.ui.internal; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin; +import net.sourceforge.phpeclipse.wiki.internal.IConfiguration; +import net.sourceforge.phpeclipse.wiki.internal.IConfigurationWorkingCopy; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.viewers.ColumnWeightData; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.ISelectionChangedListener; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.viewers.SelectionChangedEvent; +import org.eclipse.jface.viewers.StructuredSelection; +import org.eclipse.jface.viewers.TableLayout; +import org.eclipse.jface.viewers.TableViewer; +import org.eclipse.jface.window.Window; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Table; +import org.eclipse.swt.widgets.TableColumn; +/** + * + */ +public class ConfigurationComposite extends Composite { + protected Table table; + protected TableViewer tableViewer; + + protected Button edit; + protected Button remove; + protected Button start; + protected Button stop; + + protected List selection2; + + public ConfigurationComposite(Composite parent, int style) { + super(parent, style); + + createWidgets(); + } + + protected void createWidgets() { + GridLayout layout = new GridLayout(); + layout.horizontalSpacing = 6; + layout.verticalSpacing = 6; + layout.marginWidth = 0; + layout.marginHeight = 0; + layout.numColumns = 2; + setLayout(layout); + + GridData data = new GridData(GridData.FILL_BOTH); + setLayoutData(data); + + Label label = new Label(this, SWT.WRAP); + label.setText(WikiEditorPlugin.getResource("%configurationsList")); + label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_CENTER)); + + label = new Label(this, SWT.NONE); + + table = new Table(this, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.MULTI | SWT.FULL_SELECTION); + data = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL); + data.widthHint = 300; +// WorkbenchHelp.setHelp(table, ContextIds.PREF_MONITORS); + + table.setLayoutData(data); + table.setHeaderVisible(true); + table.setLinesVisible(true); + + TableLayout tableLayout = new TableLayout(); + + TableColumn statusColumn = new TableColumn(table, SWT.NONE); + statusColumn.setText(WikiEditorPlugin.getResource("%columnStatus")); + ColumnWeightData colData = new ColumnWeightData(6, 30, true); + tableLayout.addColumnData(colData); + + TableColumn typeColumn = new TableColumn(table, SWT.NONE); + typeColumn.setText(WikiEditorPlugin.getResource("%columnType")); + colData = new ColumnWeightData(5, 30, true); + tableLayout.addColumnData(colData); + + TableColumn urlColumn = new TableColumn(table, SWT.NONE); + urlColumn.setText(WikiEditorPlugin.getResource("%columnURL")); + colData = new ColumnWeightData(12, 150, true); + tableLayout.addColumnData(colData); + + TableColumn localColumn = new TableColumn(table, SWT.NONE); + localColumn.setText(WikiEditorPlugin.getResource("%columnUser")); + colData = new ColumnWeightData(5, 50, true); + tableLayout.addColumnData(colData); + + table.setLayout(tableLayout); + + tableViewer = new TableViewer(table); + tableViewer.setContentProvider(new ConfigurationContentProvider()); + tableViewer.setLabelProvider(new ConfigurationTableLabelProvider()); + tableViewer.setInput("root"); + + tableViewer.addSelectionChangedListener(new ISelectionChangedListener() { + public void selectionChanged(SelectionChangedEvent event) { + setSelection(event.getSelection()); + } + }); + + Composite buttonComp = new Composite(this, SWT.NONE); + layout = new GridLayout(); + layout.horizontalSpacing = 0; + layout.verticalSpacing = 8; + layout.marginWidth = 0; + layout.marginHeight = 0; + layout.numColumns = 1; + buttonComp.setLayout(layout); + data = new GridData(GridData.HORIZONTAL_ALIGN_END | GridData.VERTICAL_ALIGN_FILL); + buttonComp.setLayoutData(data); + + Button add = SWTUtil.createButton(buttonComp, WikiEditorPlugin.getResource("%add")); + add.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent e) { + ConfigurationDialog dialog = new ConfigurationDialog(getShell()); + if (dialog.open() == Window.CANCEL) + return; + tableViewer.refresh(); + + List list = WikiEditorPlugin.getConfigurations(); + Object configuration = list.get(list.size() - 1); + tableViewer.setSelection(new StructuredSelection(configuration)); + } + }); + + edit = SWTUtil.createButton(buttonComp, WikiEditorPlugin.getResource("%edit")); + edit.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent e) { + IConfiguration monitor = (IConfiguration) getSelection().get(0); + IConfigurationWorkingCopy wc = monitor.getWorkingCopy(); + + ConfigurationDialog dialog = new ConfigurationDialog(getShell(), wc); + if (dialog.open() != Window.CANCEL) { + try { + tableViewer.refresh(wc.save()); + } catch (Exception ex) { } + } + } + }); + edit.setEnabled(false); + + remove = SWTUtil.createButton(buttonComp, WikiEditorPlugin.getResource("%remove")); + remove.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent e) { + Iterator iterator = getSelection().iterator(); + while (iterator.hasNext()) { + IConfiguration monitor = (IConfiguration) iterator.next(); + try { + monitor.delete(); + } catch (Exception ex) { } + tableViewer.remove(monitor); + + List list = WikiEditorPlugin.getConfigurations(); + Object monitor2 = list.get(list.size() - 1); + tableViewer.setSelection(new StructuredSelection(monitor2)); + } + } + }); + remove.setEnabled(false); + + start = SWTUtil.createButton(buttonComp, WikiEditorPlugin.getResource("%start")); + start.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent e) { + Iterator iterator = getSelection().iterator(); + while (iterator.hasNext()) { + IConfiguration configuration = (IConfiguration) iterator.next(); +// try { +// WikiEditorPlugin.startMonitor(monitor); +// } catch (CoreException ce) { +// MessageDialog.openError(getShell(), WikiEditorPlugin.getResource("%errorDialogTitle"), ce.getStatus().getMessage()); +// } catch (Exception ce) { +// MessageDialog.openError(getShell(), WikiEditorPlugin.getResource("%errorDialogTitle"), ce.getMessage()); +// } + tableViewer.refresh(configuration, true); + } + tableViewer.setSelection(tableViewer.getSelection()); + } + }); + start.setEnabled(false); + + stop = SWTUtil.createButton(buttonComp, WikiEditorPlugin.getResource("%stop")); + stop.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent e) { + Iterator iterator = getSelection().iterator(); + while (iterator.hasNext()) { + IConfiguration monitor = (IConfiguration) iterator.next(); + try { +// WikiEditorPlugin.stopMonitor(monitor); + } catch (Exception ex) { } + tableViewer.refresh(monitor, true); + } + tableViewer.setSelection(tableViewer.getSelection()); + } + }); + stop.setEnabled(false); + } + + protected List getSelection() { + return selection2; + } + + protected void setSelection(ISelection sel2) { + IStructuredSelection sel = (IStructuredSelection) sel2; + Iterator iterator = sel.iterator(); + selection2 = new ArrayList(); + + while (iterator.hasNext()) { + Object obj = iterator.next(); + if (obj instanceof IConfiguration) + selection2.add(obj); + } + + if (!selection2.isEmpty()) { + remove.setEnabled(true); + + boolean allStopped = true; + boolean allStarted = true; + + iterator = selection2.iterator(); + while (iterator.hasNext()) { + IConfiguration monitor = (IConfiguration) iterator.next(); + if (monitor.isActive()) + allStopped = false; + else + allStarted = false; + } + start.setEnabled(allStopped); + stop.setEnabled(allStarted); + edit.setEnabled(selection2.size() == 1 && allStopped); + } else { + edit.setEnabled(false); + remove.setEnabled(false); + start.setEnabled(false); + stop.setEnabled(false); + } + } +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/ui/internal/ConfigurationContentProvider.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/ui/internal/ConfigurationContentProvider.java new file mode 100644 index 0000000..dae90f1 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/ui/internal/ConfigurationContentProvider.java @@ -0,0 +1,75 @@ +/********************************************************************** + * Copyright (c) 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM - Initial API and implementation + **********************************************************************/ +package net.sourceforge.phpeclipse.wiki.ui.internal; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin; +import net.sourceforge.phpeclipse.wiki.internal.IConfiguration; + +import org.eclipse.jface.viewers.IStructuredContentProvider; +import org.eclipse.jface.viewers.Viewer; +/** + * Configuration content provider. + */ +public class ConfigurationContentProvider implements IStructuredContentProvider { + /** + * ConfigurationContentProvider constructor comment. + */ + public ConfigurationContentProvider() { + super(); + } + + /** + * Disposes of this content provider. + * This is called by the viewer when it is disposed. + */ + public void dispose() { } + + /** + * Returns the elements to display in the viewer + * when its input is set to the given element. + * These elements can be presented as rows in a table, items in a list, etc. + * The result is not modified by the viewer. + * + * @param inputElement the input element + * @return the array of elements to display in the viewer + */ + public Object[] getElements(Object inputElement) { + List list = new ArrayList(); + Iterator iterator = WikiEditorPlugin.getConfigurations().iterator(); + while (iterator.hasNext()) { + IConfiguration monitor = (IConfiguration) iterator.next(); + list.add(monitor); + } + return list.toArray(); + } + + /** + * Notifies this content provider that the given viewer's input + * has been switched to a different element. + *

    + * A typical use for this method is registering the content provider as a listener + * to changes on the new input (using model-specific means), and deregistering the viewer + * from the old input. In response to these change notifications, the content provider + * propagates the changes to the viewer. + *

    + * + * @param viewer the viewer + * @param oldInput the old input element, or null if the viewer + * did not previously have an input + * @param newInput the new input element, or null if the viewer + * does not have an input + */ + public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {} +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/ui/internal/ConfigurationDialog.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/ui/internal/ConfigurationDialog.java new file mode 100644 index 0000000..04ef13e --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/ui/internal/ConfigurationDialog.java @@ -0,0 +1,258 @@ +/********************************************************************** + * Copyright (c) 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM - Initial API and implementation + **********************************************************************/ +package net.sourceforge.phpeclipse.wiki.ui.internal; + +import net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin; +import net.sourceforge.phpeclipse.wiki.internal.IConfigurationWorkingCopy; + +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.jface.dialogs.IDialogConstants; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.ModifyEvent; +import org.eclipse.swt.events.ModifyListener; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Combo; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Group; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Text; +/** + * + */ +public class ConfigurationDialog extends Dialog { + protected IConfigurationWorkingCopy fConfiguration; + protected boolean isEdit; + + private Button okButton; + private Text fUserName; + private Text fUrl; + private Text fPassword; + + interface StringModifyListener { + public void valueChanged(String s); + } + + interface BooleanModifyListener { + public void valueChanged(boolean b); + } + + interface TypeModifyListener { + public void valueChanged(String fType); + } + + /** + * @param parentShell + */ + public ConfigurationDialog(Shell parentShell, IConfigurationWorkingCopy configuration) { + super(parentShell); + this.fConfiguration = configuration; + isEdit = true; + } + + public ConfigurationDialog(Shell parentShell) { + super(parentShell); + fConfiguration = WikiEditorPlugin.createConfiguration(); + isEdit = false; + } + + protected void configureShell(Shell shell) { + super.configureShell(shell); + if (isEdit) + shell.setText(WikiEditorPlugin.getResource("%editConfig")); + else + shell.setText(WikiEditorPlugin.getResource("%newConfig")); + } + + protected Label createLabel(Composite comp, String txt) { + Label label = new Label(comp, SWT.NONE); + label.setText(txt); + label.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING | GridData.VERTICAL_ALIGN_BEGINNING)); + return label; + } + + protected Text createText(Composite comp, String txt, final StringModifyListener listener) { + final Text text = new Text(comp, SWT.BORDER); + if (txt != null) + text.setText(txt); + GridData data = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING); + data.widthHint = 150; + text.setLayoutData(data); + if (listener != null) + text.addModifyListener(new ModifyListener() { + public void modifyText(ModifyEvent e) { + listener.valueChanged(text.getText()); + } + }); + return text; + } + + protected Combo createTypeCombo(Composite comp, final String[] types, String sel, final TypeModifyListener listener) { + final Combo combo = new Combo(comp, SWT.DROP_DOWN | SWT.READ_ONLY); + int size = types.length; + String[] items = new String[size]; + int index = -1; + for (int i = 0; i < size; i++) { + items[i] = types[i]; + if (types[i].equals(sel)) + index = i; + } + combo.setItems(items); + if (index >= 0) + combo.select(index); + GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_BEGINNING); + data.widthHint = 150; + combo.setLayoutData(data); + if (listener != null) + combo.addSelectionListener(new SelectionListener() { + public void widgetSelected(SelectionEvent e) { + listener.valueChanged(types[combo.getSelectionIndex()]); + } + public void widgetDefaultSelected(SelectionEvent e) { + widgetSelected(e); + } + }); + return combo; + } + + /* (non-Javadoc) + * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite) + */ + protected Control createDialogArea(Composite parent) { + Composite composite = (Composite) super.createDialogArea(parent); + ((GridLayout)composite.getLayout()).numColumns = 2; + +// WorkbenchHelp.setHelp(composite, ContextIds.PREF_DIALOG); + + Group group = new Group(composite, SWT.NONE); + GridLayout layout = new GridLayout(2, false); + group.setLayout(layout); + GridData data = new GridData(GridData.FILL_HORIZONTAL); + data.horizontalSpan = 2; + group.setLayoutData(data); + group.setText(WikiEditorPlugin.getResource("%remoteGroup")); + + createLabel(group, WikiEditorPlugin.getResource("%url")); + fUrl = createText(group, fConfiguration.getURL(), new StringModifyListener() { + public void valueChanged(String s) { + fConfiguration.setURL(s); + validateFields(); + } + }); + + createLabel(composite, WikiEditorPlugin.getResource("%user")); + fUserName = createText(composite, fConfiguration.getUser() + "", new StringModifyListener() { + public void valueChanged(String s) { + fConfiguration.setUser(s); + validateFields(); + } + }); + + createLabel(group, WikiEditorPlugin.getResource("%password")); + fPassword = createText(group, fConfiguration.getPassword() + "", new StringModifyListener() { + public void valueChanged(String s) { + fConfiguration.setPassword(s); + validateFields(); + } + }); + + createLabel(group, WikiEditorPlugin.getResource("%parseType")); + createTypeCombo(group, WikiEditorPlugin.getTypes(), fConfiguration.getType(), new TypeModifyListener() { + public void valueChanged(String fType) { + fConfiguration.setType(fType); + } + }); + + return composite; + } + + /* (non-Javadoc) + * @see org.eclipse.jface.dialogs.Dialog#okPressed() + */ + protected void okPressed() { + fConfiguration.save(); + super.okPressed(); + } + + protected Control createButtonBar(Composite parent) { + Control buttonControl = super.createButtonBar(parent); + validateFields(); + return buttonControl; + } + + private void setOKButtonEnabled(boolean curIsEnabled) { + if (okButton == null) + okButton = getButton(IDialogConstants.OK_ID); + + if (okButton != null) + okButton.setEnabled(curIsEnabled); + } + + protected void validateFields() { + boolean result = true; + + String currHostname = fUrl.getText(); +// if (!isValidHostname(currHostname)) +// result = false; + + String currHostnamePort = fPassword.getText(); +// try { +// Integer.parseInt(currHostnamePort); +// } catch (Exception any) { +// result = false; +// } + + String currMonitorPort = fUserName.getText(); +// try { +// Integer.parseInt(currMonitorPort); +// } catch (Exception any) { +// result = false; +// } + +// if (result && isLocalhost(currHostname)) { +// if (currHostnamePort.equals(currMonitorPort)) +// result = false; +// } + setOKButtonEnabled(result); + } + +// protected static boolean isValidHostname(String host) { +// if (host == null || host.trim().length() < 1) +// return false; +// if (host.indexOf("/") >= 0) +// return false; +// if (host.indexOf("\\") >= 0) +// return false; +// if (host.indexOf(" ") >= 0) +// return false; +// return true; +// } + +// protected static boolean isLocalhost(String host) { +// if (host == null) +// return false; +// try { +// if ("localhost".equals(host) || "127.0.0.1".equals(host)) +// return true; +// InetAddress localHostaddr = InetAddress.getLocalHost(); +// if (localHostaddr.getHostName().equals(host)) +// return true; +// } catch (Exception e) { +// Trace.trace(Trace.WARNING, "Error checking for localhost", e); +// } +// return false; +// } +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/ui/internal/ConfigurationPreferencePage.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/ui/internal/ConfigurationPreferencePage.java new file mode 100644 index 0000000..ceb1d9a --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/ui/internal/ConfigurationPreferencePage.java @@ -0,0 +1,107 @@ +/********************************************************************** + * Copyright (c) 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM - Initial API and implementation + **********************************************************************/ +package net.sourceforge.phpeclipse.wiki.ui.internal; + +import net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin; + +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.jface.preference.PreferencePage; +import org.eclipse.swt.SWT; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Label; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.IWorkbenchPreferencePage; +/** + * The preference page that holds monitor properties. + */ +public class ConfigurationPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { + + /** + * ConfigurationPreferencePage constructor comment. + */ + public ConfigurationPreferencePage() { + super(); + noDefaultAndApplyButton(); + } + + /** + * Create the preference options. + * + * @param parent org.eclipse.swt.widgets.Composite + * @return org.eclipse.swt.widgets.Control + */ + protected Control createContents(Composite parent) { + initializeDialogUnits(parent); + + Composite composite = new Composite(parent, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.numColumns = 1; + layout.horizontalSpacing = convertHorizontalDLUsToPixels(4); + layout.verticalSpacing = convertVerticalDLUsToPixels(4); + layout.marginWidth = 0; + layout.marginHeight = 0; + composite.setLayout(layout); + GridData data = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL); + composite.setLayoutData(data); +// WorkbenchHelp.setHelp(composite, ContextIds.PREF); + + Label label = new Label(composite, SWT.WRAP); + label.setText(WikiEditorPlugin.getResource("%preferenceDescription")); + data = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); + label.setLayoutData(data); + + label = new Label(composite, SWT.NONE); + label.setText(""); + + ConfigurationComposite monitorComp = new ConfigurationComposite(composite, SWT.NONE); + data = new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL); + monitorComp.setLayoutData(data); + + Dialog.applyDialogFont(composite); + + return composite; + } + + /** + * Initializes this preference page using the passed desktop. + * + * @param desktop the current desktop + */ + public void init(IWorkbench workbench) { + } + + /** + * Performs special processing when this page's Defaults button has been pressed. + *

    + * This is a framework hook method for sublcasses to do special things when + * the Defaults button has been pressed. + * Subclasses may override, but should call super.performDefaults. + *

    + */ + protected void performDefaults() { +// displayButton.setSelection(WikiEditorPlugin.getDefaultShowOnActivityPreference()); + super.performDefaults(); + } + + /** + * Method declared on IPreferencePage. + * Subclasses should override + */ + public boolean performOk() { +// WikiEditorPlugin.setShowOnActivityPreference(displayButton.getSelection()); + WikiEditorPlugin.getDefault().savePluginPreferences(); + return true; + } +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/ui/internal/ConfigurationPrefrencesDialog.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/ui/internal/ConfigurationPrefrencesDialog.java new file mode 100644 index 0000000..46e8510 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/ui/internal/ConfigurationPrefrencesDialog.java @@ -0,0 +1,90 @@ +/********************************************************************** + * Copyright (c) 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html +  * + * Contributors: + * IBM - Initial API and implementation + **********************************************************************/ +package net.sourceforge.phpeclipse.wiki.ui.internal; + +import net.sourceforge.phpeclipse.webbrowser.internal.ContextIds; +import net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin; +import net.sourceforge.phpeclipse.wiki.internal.IConfigurationWorkingCopy; + +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.jface.dialogs.IDialogConstants; +import org.eclipse.swt.SWT; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.help.WorkbenchHelp; + +/** + * + */ +public class ConfigurationPrefrencesDialog extends Dialog { + protected IConfigurationWorkingCopy monitor; + + protected boolean isEdit; + + /** + * @param parentShell + */ + public ConfigurationPrefrencesDialog(Shell parentShell, IConfigurationWorkingCopy monitor) { + super(parentShell); + this.monitor = monitor; + isEdit = true; + } + + public ConfigurationPrefrencesDialog(Shell composite) { + super(composite); + isEdit = false; + } + + protected void configureShell(Shell shell) { + super.configureShell(shell); + shell.setText(WikiEditorPlugin.getResource("%preferenceTitle")); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite) + */ + protected Control createDialogArea(Composite parent) { + Composite compositeParent = (Composite) super.createDialogArea(parent); + + Composite composite = new Composite(compositeParent, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.marginHeight = convertHorizontalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); + layout.marginWidth = convertVerticalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); + layout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); + composite.setLayout(layout); + GridData data = new GridData(GridData.FILL_BOTH); + composite.setLayoutData(data); + // WorkbenchHelp.setHelp(composite, ContextIds.PREF); + + ConfigurationComposite monitorComp = new ConfigurationComposite(composite, SWT.NONE); + data = new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL); + monitorComp.setLayoutData(data); + + Dialog.applyDialogFont(composite); + + return composite; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.dialogs.Dialog#okPressed() + */ + protected void okPressed() { + WikiEditorPlugin.getDefault().savePluginPreferences(); + super.okPressed(); + } +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/ui/internal/ConfigurationTableLabelProvider.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/ui/internal/ConfigurationTableLabelProvider.java new file mode 100644 index 0000000..84154c0 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/ui/internal/ConfigurationTableLabelProvider.java @@ -0,0 +1,127 @@ +/********************************************************************** + * Copyright (c) 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM - Initial API and implementation + **********************************************************************/ +package net.sourceforge.phpeclipse.wiki.ui.internal; + +import net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin; +import net.sourceforge.phpeclipse.wiki.internal.IConfiguration; + +import org.eclipse.jface.viewers.ILabelProviderListener; +import org.eclipse.jface.viewers.ITableLabelProvider; +import org.eclipse.swt.graphics.Image; +/** + * Configuration table label provider. + */ +public class ConfigurationTableLabelProvider implements ITableLabelProvider { + /** + * ConfigurationTableLabelProvider constructor comment. + */ + public ConfigurationTableLabelProvider() { + super(); + } + + /** + * Adds a listener to this label provider. + * Has no effect if an identical listener is already registered. + *

    + * Label provider listeners are informed about state changes + * that affect the rendering of the viewer that uses this label provider. + *

    + * + * @param listener a label provider listener + */ + public void addListener(ILabelProviderListener listener) { } + + /** + * Disposes of this label provider. When a label provider is + * attached to a viewer, the viewer will automatically call + * this method when the viewer is being closed. When label providers + * are used outside of the context of a viewer, it is the client's + * responsibility to ensure that this method is called when the + * provider is no longer needed. + */ + public void dispose() { } + + /** + * Returns the label image for the given column of the given element. + * + * @param element the object representing the entire row, or + * null indicating that no input object is set + * in the viewer + * @param columnIndex the zero-based index of the column in which + * the label appears + */ + public Image getColumnImage(Object element, int columnIndex) { + if (columnIndex == 0) { + IConfiguration monitor = (IConfiguration) element; + if (monitor.isActive()) + return WikiEditorPlugin.getDefault().getImage(WikiEditorPlugin.IMG_MONITOR_ON); + else + return WikiEditorPlugin.getDefault().getImage(WikiEditorPlugin.IMG_MONITOR_OFF); + } + return null; + } + + /** + * Returns the label text for the given column of the given element. + * + * @param element the object representing the entire row, or + * null indicating that no input object is set + * in the viewer + * @param columnIndex the zero-based index of the column in which the label appears + */ + public String getColumnText(Object element, int columnIndex) { + IConfiguration monitor = (IConfiguration) element; + if (columnIndex == 0) { + if (monitor.isActive()) + return WikiEditorPlugin.getResource("%started"); + else + return WikiEditorPlugin.getResource("%stopped"); + } else if (columnIndex == 1) + return monitor.getURL() + ":" + monitor.getPassword(); + else if (columnIndex == 2) + return monitor.getType(); + else if (columnIndex == 3) + return monitor.getUser(); + else + return "X"; + } + + protected String notNull(String s) { + if (s != null) + return s; + else + return ""; + } + + /** + * Returns whether the label would be affected + * by a change to the given property of the given element. + * This can be used to optimize a non-structural viewer update. + * If the property mentioned in the update does not affect the label, + * then the viewer need not update the label. + * + * @param element the element + * @param property the property + * @return true if the label would be affected, + * and false if it would be unaffected + */ + public boolean isLabelProperty(Object element, String property) { + return false; + } + + /** + * Removes a listener to this label provider. + * Has no affect if an identical listener is not registered. + * + * @param listener a label provider listener + */ + public void removeListener(ILabelProviderListener listener) { } +} \ No newline at end of file diff --git a/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/ui/internal/SWTUtil.java b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/ui/internal/SWTUtil.java new file mode 100644 index 0000000..987c492 --- /dev/null +++ b/archive/net.sourceforge.phpeclipse.wiki/src/net/sourceforge/phpeclipse/wiki/ui/internal/SWTUtil.java @@ -0,0 +1,77 @@ +/********************************************************************** + * Copyright (c) 2003 IBM Corporation and others. + * All rights reserved.   This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM - Initial API and implementation + **********************************************************************/ +package net.sourceforge.phpeclipse.wiki.ui.internal; + +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.jface.dialogs.IDialogConstants; +import org.eclipse.jface.resource.JFaceResources; +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.FontMetrics; +import org.eclipse.swt.graphics.GC; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Label; +/** + * SWT Utility class. + */ +public class SWTUtil { + private static FontMetrics fontMetrics; + + protected static void initializeDialogUnits(Control testControl) { + // Compute and store a font metric + GC gc = new GC(testControl); + gc.setFont(JFaceResources.getDialogFont()); + fontMetrics = gc.getFontMetrics(); + gc.dispose(); + } + + /** + * Returns a width hint for a button control. + */ + protected static int getButtonWidthHint(Button button) { + int widthHint = Dialog.convertHorizontalDLUsToPixels(fontMetrics, IDialogConstants.BUTTON_WIDTH); + return Math.max(widthHint, button.computeSize(SWT.DEFAULT, SWT.DEFAULT, true).x); + } + + public static Button createButton(Composite comp, String label) { + Button b = new Button(comp, SWT.PUSH); + b.setText(label); + if (fontMetrics == null) + initializeDialogUnits(comp); + GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_BEGINNING); + data.widthHint = getButtonWidthHint(b); + data.heightHint = Dialog.convertVerticalDLUsToPixels(fontMetrics, IDialogConstants.BUTTON_HEIGHT); + b.setLayoutData(data); + return b; + } + + public static Button createCheckbox(Composite comp, String txt, boolean isSelected){ + Button button = new Button(comp, SWT.CHECK); + button.setText(txt); + GridLayout layout = new GridLayout(); + comp.setLayout(layout); + GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_BEGINNING); + data.horizontalIndent = 10; + button.setLayoutData(data); + button.setSelection(isSelected); + return button; + } + + public static Label createLabel(Composite comp, String txt) { + Label label = new Label(comp, SWT.NONE); + label.setText(txt); + label.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING | GridData.VERTICAL_ALIGN_BEGINNING)); + return label; + } +}