Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Merge remote branch 'origin/wip_experiment' into wip_experiment

  • Loading branch information...
commit f4712c7db828eae229afc9779ee5702c81c5b66f 2 parents 4ca7eae + f0e1fde
@lindydonna lindydonna authored
Showing with 1,077 additions and 472 deletions.
  1. +4 −2 org.scala-ide.sdt.core/.classpath
  2. +6 −0 org.scala-ide.sdt.core/.project
  3. +4 −1 org.scala-ide.sdt.core/META-INF/MANIFEST.MF
  4. +10 −9 org.scala-ide.sdt.core/build.properties
  5. BIN  org.scala-ide.sdt.core/lib/miglayout-3.7.4-swt.jar
  6. +17 −1 org.scala-ide.sdt.core/plugin.xml
  7. +7 −0 org.scala-ide.sdt.core/pom.xml
  8. +3 −3 org.scala-ide.sdt.core/src/scala/tools/eclipse/LocateSymbol.scala
  9. +53 −49 org.scala-ide.sdt.core/src/scala/tools/eclipse/ScalaHyperlinkDetector.scala
  10. +6 −22 org.scala-ide.sdt.core/src/scala/tools/eclipse/ScalaPresentationCompiler.scala
  11. +49 −0 org.scala-ide.sdt.core/src/scala/tools/eclipse/ScalaPreviewerFactory.scala
  12. +1 −1  org.scala-ide.sdt.core/src/scala/tools/eclipse/ScalaSourceViewerConfiguration.scala
  13. +12 −2 org.scala-ide.sdt.core/src/scala/tools/eclipse/ScalaStructureSelectEnclosingAction.scala
  14. +403 −28 org.scala-ide.sdt.core/src/scala/tools/eclipse/formatter/FormatterPreferencePage.scala
  15. +75 −0 org.scala-ide.sdt.core/src/scala/tools/eclipse/formatter/FormatterPreferences.scala
  16. +2 −1  org.scala-ide.sdt.core/src/scala/tools/eclipse/formatter/ScalaFormatterCleanUpProvider.scala
  17. +23 −12 org.scala-ide.sdt.core/src/scala/tools/eclipse/formatter/ScalaFormatterPreferenceInitializer.scala
  18. +27 −21 org.scala-ide.sdt.core/src/scala/tools/eclipse/formatter/ScalaFormattingStrategy.scala
  19. +20 −16 org.scala-ide.sdt.core/src/scala/tools/eclipse/javaelements/ScalaOverrideIndicatorBuilder.scala
  20. +3 −1 org.scala-ide.sdt.core/src/scala/tools/eclipse/javaelements/ScalaStructureBuilder.scala
  21. +5 −2 org.scala-ide.sdt.core/src/scala/tools/eclipse/lexical/ScalaDocumentPartitioner.scala
  22. +17 −46 org.scala-ide.sdt.core/src/scala/tools/eclipse/properties/SyntaxColouringPreferencePage.scala
  23. +11 −13 org.scala-ide.sdt.core/src/scala/tools/eclipse/ui/ScalaIndenter.scala
  24. +62 −0 org.scala-ide.sdt.core/src/scala/tools/eclipse/util/SWTUtils.scala
  25. +191 −175 org.scala-ide.sdt.core/src/scala/tools/eclipse/wizards/AbstractNewElementWizardPage.scala
  26. +66 −67 org.scala-ide.sdt.core/test/scala/tools/eclipse/ReferencesSearchTest.scala
View
6 org.scala-ide.sdt.core/.classpath
@@ -1,11 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
- <classpathentry kind="src" path="src"/>
+ <classpathentry kind="src" output="target/classes" path="src"/>
<classpathentry kind="src" output="target/test-classes" path="test"/>
+ <classpathentry kind="con" path="org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER"/>
<classpathentry kind="con" path="org.scala-ide.sdt.launching.SCALA_CONTAINER"/>
<classpathentry kind="con" path="org.scala-ide.sdt.launching.SCALA_COMPILER_CONTAINER"/>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
<classpathentry kind="con" path="org.eclipse.jdt.junit.JUNIT_CONTAINER/4"/>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
+ <classpathentry kind="lib" path="lib/miglayout-3.7.4-swt.jar"/>
<classpathentry kind="output" path="target/classes"/>
</classpath>
View
6 org.scala-ide.sdt.core/.project
@@ -20,8 +20,14 @@
<arguments>
</arguments>
</buildCommand>
+ <buildCommand>
+ <name>org.maven.ide.eclipse.maven2Builder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
</buildSpec>
<natures>
+ <nature>org.maven.ide.eclipse.maven2Nature</nature>
<nature>org.eclipse.pde.PluginNature</nature>
<nature>org.scala-ide.sdt.core.scalanature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
View
5 org.scala-ide.sdt.core/META-INF/MANIFEST.MF
@@ -42,7 +42,8 @@ Require-Bundle:
org.scala-ide.scala.compiler,
org.scala-refactoring.library,
scalariform,
- org.junit4;bundle-version="4.5.0"
+ org.junit4;bundle-version="4.5.0",
+ org.eclipse.ui.browser;bundle-version="3.3.0"
Import-Package:
org.eclipse.contribution.jdt.cuprovider;apply-aspects:=false,
org.eclipse.contribution.jdt.imagedescriptor;apply-aspects:=false,
@@ -73,3 +74,5 @@ Export-Package:
scala.tools.eclipse.util,
scala.tools.eclipse.wizards
Bundle-RequiredExecutionEnvironment: J2SE-1.5
+Bundle-ClassPath: .,
+ lib/miglayout-3.7.4-swt.jar
View
19 org.scala-ide.sdt.core/build.properties
@@ -1,12 +1,13 @@
source.. = src/
output.. = target/classes/
bin.includes = META-INF/,\
- .,\
- docs/,\
- icons/,\
- plugin.xml,\
- toc.xml,\
- license.html,\
- about.ini,\
- about.png,\
- templates/
+ .,\
+ docs/,\
+ icons/,\
+ plugin.xml,\
+ toc.xml,\
+ license.html,\
+ about.ini,\
+ about.png,\
+ templates/,\
+ lib/
View
BIN  org.scala-ide.sdt.core/lib/miglayout-3.7.4-swt.jar
Binary file not shown
View
18 org.scala-ide.sdt.core/plugin.xml
@@ -6,7 +6,23 @@
<page
class="scala.tools.eclipse.properties.CompilerSettings"
id="org.scala-ide.sdt.core.properties.compilerPropertyPage"
- name="Scala Compiler Properties">
+ name="Scala Compiler">
+ <filter
+ name="nature"
+ value="org.scala-ide.sdt.core.scalanature"/>
+ <enabledWhen>
+ <or> <instanceof value="org.eclipse.jdt.core.IJavaProject"/>
+ <instanceof value="org.eclipse.core.resources.IProject"/>
+ </or>
+ </enabledWhen>
+ </page>
+ </extension>
+ <extension
+ point="org.eclipse.ui.propertyPages">
+ <page
+ class="scala.tools.eclipse.formatter.FormatterPreferencePage"
+ id="scala.tools.eclipse.formatter.FormatterPropertyPage"
+ name="Scala Formatter">
<filter
name="nature"
value="org.scala-ide.sdt.core.scalanature"/>
View
7 org.scala-ide.sdt.core/pom.xml
@@ -17,6 +17,13 @@
<artifactId>org.scala-ide.sdt.aspects</artifactId>
<version>${project.version}</version>
</dependency>
+ <dependency>
+ <groupId>com.miglayout</groupId>
+ <artifactId>miglayout</artifactId>
+ <version>3.7.4</version>
+ <type>jar</type>
+ <scope>compile</scope>
+ </dependency>
</dependencies>
<build>
View
6 org.scala-ide.sdt.core/src/scala/tools/eclipse/LocateSymbol.scala
@@ -22,8 +22,8 @@ import scala.tools.nsc.io.AbstractFile
import javaelements.{ScalaSourceFile, ScalaClassFile, ScalaCompilationUnit}
trait LocateSymbol { self : ScalaPresentationCompiler =>
-
- def locate(sym : Symbol, scu : ScalaCompilationUnit) = {
+
+ def locate(sym : Symbol, scu : ScalaCompilationUnit): Option[(ScalaCompilationUnit, Int)] = {
def find[T, V](arr : Array[T])(f : T => Option[V]) : Option[V] = {
for(e <- arr) {
f(e) match {
@@ -58,7 +58,7 @@ trait LocateSymbol { self : ScalaPresentationCompiler =>
(if (sym.pos eq NoPosition) {
file.withSourceFile { (f, _) =>
val pos = new Response[Position]
- getLinkPos(sym, f, pos)
+ askLinkPos(sym, f, pos)
askReload(scu, scu.getContents)
pos.get.left.toOption
} (None)
View
102 org.scala-ide.sdt.core/src/scala/tools/eclipse/ScalaHyperlinkDetector.scala
@@ -28,58 +28,62 @@ class ScalaHyperlinkDetector extends AbstractHyperlinkDetector with Logger {
val textEditor = getAdapter(classOf[ITextEditor]).asInstanceOf[ITextEditor]
detectHyperlinks(textEditor, region, canShowMultipleHyperlinks)
}
-
- def detectHyperlinks(textEditor : ITextEditor, region : IRegion, canShowMultipleHyperlinks : Boolean) : Array[IHyperlink] = {
- EditorUtility.getEditorInputJavaElement(textEditor, false) match {
- case scu : ScalaCompilationUnit =>
- scu.withSourceFile({ (sourceFile, compiler) =>
- val wordRegion = ScalaWordFinder.findWord(scu.getContents, region.getOffset)
- if (wordRegion == null || wordRegion.getLength == 0)
- null
- else {
- val pos = compiler.rangePos(sourceFile, wordRegion.getOffset, wordRegion.getOffset, wordRegion.getOffset + wordRegion.getLength)
-
- val response = new compiler.Response[compiler.Tree]
- compiler.askTypeAt(pos, response)
- val typed = response.get
-
- log("detectHyperlinks: wordRegion = "+wordRegion)
-
- compiler.ask { () =>
- case class Hyperlink(file : Openable, pos : Int) extends IHyperlink {
- def getHyperlinkRegion = wordRegion
- def getTypeLabel = null
- def getHyperlinkText = "Open Declaration"
- def open = {
- EditorUtility.openInEditor(file, true) match {
- case editor : ITextEditor => editor.selectAndReveal(pos, 0)
- case _ =>
- }
+
+ case class Hyperlink(file: Openable, pos: Int)(wordRegion: IRegion) extends IHyperlink {
+ def getHyperlinkRegion = wordRegion
+ def getTypeLabel = null
+ def getHyperlinkText = "Open Declaration"
+ def open = {
+ EditorUtility.openInEditor(file, true) match {
+ case editor: ITextEditor => editor.selectAndReveal(pos, 0)
+ case _ =>
+ }
+ }
+ }
+
+ def detectHyperlinks(textEditor: ITextEditor, region: IRegion, canShowMultipleHyperlinks: Boolean): Array[IHyperlink] = {
+ if (textEditor == null) // can be null if generated through ScalaPreviewerFactory
+ null
+ else
+ EditorUtility.getEditorInputJavaElement(textEditor, false) match {
+ case scu: ScalaCompilationUnit =>
+ scu.withSourceFile({ (sourceFile, compiler) =>
+ val wordRegion = ScalaWordFinder.findWord(scu.getContents, region.getOffset)
+ if (wordRegion == null || wordRegion.getLength == 0)
+ null
+ else {
+ val pos = compiler.rangePos(sourceFile, wordRegion.getOffset, wordRegion.getOffset, wordRegion.getOffset + wordRegion.getLength)
+
+ val response = new compiler.Response[compiler.Tree]
+ compiler.askTypeAt(pos, response)
+ val typed = response.get
+
+ log("detectHyperlinks: wordRegion = " + wordRegion)
+ val hyperlinks: Option[Hyperlink] = compiler.ask { () =>
+ import compiler.{ log => _, _ }
+
+ typed.left.toOption map {
+ case Import(expr, sels) => sels find (_.namePos >= pos.start) map (sel => expr.tpe.member(sel.name)) getOrElse NoSymbol
+ case Annotated(atp, _) => atp.symbol
+ case st: SymTree => st.symbol
+ case t => log("unhandled tree " + t); NoSymbol
+ } flatMap { sym =>
+ if (sym.isPackage || sym == NoSymbol || sym.isJavaDefined)
+ None
+ else
+ compiler.locate(sym, scu) map { case (f, pos) => Hyperlink(f, pos)(wordRegion) }
}
}
-
- import compiler.{log =>_, _}
- typed.left.toOption map ( _ match {
- case Import(expr, sels) => sels find (_.namePos >= pos.start) map (sel => expr.tpe.member(sel.name)) getOrElse NoSymbol
- case Annotated(atp, _) => atp.symbol
- case st : SymTree => st.symbol
- case t =>
- log("unhandled tree " + t); NoSymbol
- }) flatMap { sym =>
- if (sym.isPackage || sym == NoSymbol || sym.isJavaDefined)
- None
- else
- compiler.locate(sym, scu) map { case (f, pos) => Hyperlink(f, pos) }
- }
- } map (Array(_ : IHyperlink)) getOrElse {
- log("!!! Falling back to selection engine for %s!".format(typed.left), Category.ERROR)
- codeSelect(textEditor, wordRegion, scu)
+ if (!hyperlinks.isDefined) {
+ log("!!! Falling back to selection engine for %s!".format(typed.left), Category.ERROR)
+ codeSelect(textEditor, wordRegion, scu)
+ } else
+ Array(hyperlinks.get: IHyperlink)
}
- }
- }) (null)
-
- case _ => null
- }
+ })(null)
+
+ case _ => null
+ }
}
//Default path used for selecting.
View
28 org.scala-ide.sdt.core/src/scala/tools/eclipse/ScalaPresentationCompiler.scala
@@ -51,9 +51,7 @@ class ScalaPresentationCompiler(project : ScalaProject, settings : Settings)
val response = new Response[Tree]
askLoadedTyped(unit.source, response)
response.get
- val result = unit.problems.toList flatMap presentationReporter.eclipseProblem
- //unit.problems.clear()
- result
+ unit.problems.toList flatMap presentationReporter.eclipseProblem
case None =>
Nil
}
@@ -63,27 +61,13 @@ class ScalaPresentationCompiler(project : ScalaProject, settings : Settings)
def withSourceFile[T](scu : ScalaCompilationUnit)(op : (SourceFile, ScalaPresentationCompiler) => T) : T =
op(sourceFiles(scu), this)
-
- override def ask[A](op: () => A): A = if (Thread.currentThread == compileRunner) op() else super.ask(op)
-
- override def askTypeAt(pos: Position, response: Response[Tree]) = {
- if (Thread.currentThread == compileRunner) getTypedTreeAt(pos, response) else super.askTypeAt(pos, response)
- }
-
- override def askParsedEntered(source: SourceFile, keepLoaded: Boolean, response: Response[Tree]) {
- if (Thread.currentThread == compileRunner)
- getParsedEntered(source, keepLoaded, response)
- else
- super.askParsedEntered(source, keepLoaded, response)
- }
def body(sourceFile : SourceFile) = {
- val tree = new Response[Tree]
- if (Thread.currentThread == compileRunner)
- getTypedTree(sourceFile, false, tree) else askType(sourceFile, false, tree)
- tree.get match {
- case Left(l) => l
- case Right(r) => throw r
+ val response = new Response[Tree]
+ askType(sourceFile, false, response)
+ response.get match {
+ case Left(tree) => tree
+ case Right(exc) => throw exc
}
}
View
49 org.scala-ide.sdt.core/src/scala/tools/eclipse/ScalaPreviewerFactory.scala
@@ -0,0 +1,49 @@
+package scala.tools.eclipse
+
+import org.eclipse.jface.util.{ IPropertyChangeListener, PropertyChangeEvent }
+import org.eclipse.jface.text.IDocument
+import org.eclipse.jface.text.Document
+import lexical.ScalaDocumentPartitioner
+import org.eclipse.jdt.ui.text.IJavaPartitions
+import org.eclipse.jface.text.IDocumentPartitioner
+import org.eclipse.swt.SWT
+import org.eclipse.jdt.ui.PreferenceConstants
+import org.eclipse.jface.resource.JFaceResources
+import org.eclipse.jdt.internal.ui.javaeditor.JavaSourceViewer
+import org.eclipse.swt.widgets.Control
+import org.eclipse.jface.preference.IPreferenceStore
+import org.eclipse.jface.text.TextUtilities
+import java.util.HashMap
+
+import org.eclipse.swt.widgets.Composite
+
+object ScalaPreviewerFactory {
+
+ def createPreviewer(parent: Composite, preferenceStore: IPreferenceStore, initialText: String): (Control, IDocument) = {
+
+ val previewViewer = new JavaSourceViewer(parent, null, null, false, SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER, preferenceStore)
+ val font = JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT)
+ previewViewer.getTextWidget.setFont(font)
+ previewViewer.setEditable(false)
+
+ val configuration = new ScalaSourceViewerConfiguration(preferenceStore, preferenceStore, null)
+ previewViewer.configure(configuration)
+
+ val document = new Document
+ document.set(initialText)
+ val partitioners = new HashMap[String, IDocumentPartitioner]
+ partitioners.put(IJavaPartitions.JAVA_PARTITIONING, new ScalaDocumentPartitioner(conservative = true))
+ TextUtilities.addDocumentPartitioners(document, partitioners)
+ previewViewer.setDocument(document)
+
+ preferenceStore.addPropertyChangeListener(new IPropertyChangeListener {
+ def propertyChange(event: PropertyChangeEvent) {
+ if (configuration.affectsTextPresentation(event))
+ configuration.handlePropertyChangeEvent(event)
+ previewViewer.invalidateTextPresentation()
+ }
+ })
+ (previewViewer.getControl, document)
+ }
+
+}
View
2  org.scala-ide.sdt.core/src/scala/tools/eclipse/ScalaSourceViewerConfiguration.scala
@@ -123,7 +123,7 @@ class ScalaSourceViewerConfiguration(store: IPreferenceStore, scalaPreferenceSto
override def getContentFormatter(sourceViewer: ISourceViewer) = {
val contentFormatter = new ContentFormatter
contentFormatter.enablePartitionAwareFormatting(false);
- contentFormatter.setFormattingStrategy(new ScalaFormattingStrategy(sourceViewer), IDocument.DEFAULT_CONTENT_TYPE)
+ contentFormatter.setFormattingStrategy(new ScalaFormattingStrategy(editor), IDocument.DEFAULT_CONTENT_TYPE)
contentFormatter
}
View
14 org.scala-ide.sdt.core/src/scala/tools/eclipse/ScalaStructureSelectEnclosingAction.scala
@@ -5,19 +5,29 @@ import org.eclipse.jdt.internal.ui.javaeditor.selectionactions._
import org.eclipse.jface.action.Action
import org.eclipse.jface.text.ITextSelection
+import scalariform.parser.ScalaParserException
import scalariform.astselect.AstSelector
import scalariform.utils.Range
-
/**
* A Scala-aware replacement for {@link org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectEnclosingAction}.
*/
class ScalaStructureSelectEnclosingAction(editor: ScalaSourceFileEditor, selectionHistory: SelectionHistory) extends Action {
+ private var previousAstSelector: Option[(String, AstSelector)] = None
+
override def run() {
val source = editor.getDocumentProvider.getDocument(editor.getEditorInput).get
+ val astSelector = previousAstSelector match {
+ case Some((previousSource, astSelector)) if previousSource == source => astSelector
+ case _ =>
+ try new AstSelector(source)
+ catch { case _: ScalaParserException => return }
+ }
+ previousAstSelector = Some(source, astSelector)
+
val selection = editor.getSelectionProvider.getSelection.asInstanceOf[ITextSelection]
val selectionRange = Range(selection.getOffset, selection.getLength)
- for (Range(offset, length) <- AstSelector.expandSelection(source, selectionRange)) {
+ for (Range(offset, length) <- astSelector.expandSelection(selectionRange)) {
selectionHistory.remember(new SourceRange(selection.getOffset, selection.getLength))
try {
selectionHistory.ignoreSelectionChanges()
View
431 org.scala-ide.sdt.core/src/scala/tools/eclipse/formatter/FormatterPreferencePage.scala
@@ -1,53 +1,428 @@
package scala.tools.eclipse.formatter
+import java.net.URL
+import org.eclipse.jface.dialogs.MessageDialog
+import java.io.FileOutputStream
+import scalariform.formatter.preferences.PreferencesImporterExporter
+import java.io.IOException
+import java.util.Properties
+import java.io.FileInputStream
+import org.eclipse.jdt.internal.ui.JavaPlugin
+import org.eclipse.ui.dialogs.PreferencesUtil
+import org.eclipse.jdt.internal.ui.preferences.PreferencesMessages
+import org.eclipse.jdt.core.IJavaProject
+import org.eclipse.core.resources.IProject
+import org.eclipse.ui.dialogs.PropertyPage
+import scala.tools.eclipse.ScalaPreviewerFactory
+import org.eclipse.ui.editors.text.TextEditor
+import org.eclipse.jface.util._
+import org.eclipse.swt.events._
+import org.eclipse.swt.widgets._
+import net.miginfocom.swt.MigLayout
+import net.miginfocom.layout._
+import scalariform.formatter.preferences._
+import org.eclipse.swt.events.{ SelectionAdapter, SelectionEvent }
+import java.util.HashMap
+import org.eclipse.jface.text.TextUtilities
+import org.eclipse.jdt.ui.text.IJavaPartitions
+import org.eclipse.jdt.internal.ui.preferences.OverlayPreferenceStore
+
+import org.eclipse.jface.resource.JFaceResources
+import org.eclipse.jdt.internal.ui.javaeditor.JavaSourceViewer
+import scala.tools.eclipse.ScalaSourceViewerConfiguration
+import org.eclipse.swt.layout._
+import org.eclipse.swt.widgets.TabItem
+import org.eclipse.swt.widgets.TabFolder
+import org.eclipse.swt.SWT
+import org.eclipse.swt.widgets.Control
+import org.eclipse.swt.widgets.Composite
import org.eclipse.ui._
import org.eclipse.jface.preference._
import scalariform.formatter._
import scalariform.formatter.preferences._
import scala.tools.eclipse.ScalaPlugin
+import org.eclipse.jdt.ui.PreferenceConstants
+import org.eclipse.jface.text.{ Document, IDocument }
+import scala.tools.eclipse.lexical.ScalaDocumentPartitioner
+import scala.tools.eclipse.properties.PropertyStore
+import org.eclipse.jface.text.IDocumentPartitioner
+import scala.tools.eclipse.formatter.FormatterPreferences._
+import scala.tools.eclipse.util.SWTUtils._
+import scala.tools.eclipse.util.FileUtils._
-class FormatterPreferencePage extends FieldEditorPreferencePage with IWorkbenchPreferencePage {
-
+class FormatterPreferencePage extends PropertyPage with IWorkbenchPreferencePage {
import FormatterPreferencePage._
-
- setPreferenceStore(ScalaPlugin.plugin.getPreferenceStore)
- def init(workbench: IWorkbench) {}
+ private var isWorkbenchPage = false
+
+ private var allEnableDisableControls: Set[Control] = Set()
+
+ override def init(workbench: IWorkbench) {
+ isWorkbenchPage = true
+ }
+
+ lazy val overlayStore = {
+ import OverlayPreferenceStore._
+ val keys =
+ for (preference <- AllPreferences.preferences)
+ yield preference.preferenceType match {
+ case BooleanPreference => new OverlayKey(BOOLEAN, preference.eclipseKey)
+ case IntegerPreference(_, _) => new OverlayKey(INT, preference.eclipseKey)
+ }
+ val overlayStore = new OverlayPreferenceStore(getPreferenceStore, keys.toArray)
+ overlayStore.load()
+ overlayStore.start()
+ overlayStore
+ }
+
+ abstract class PrefTab(tabName: String, previewText: String) {
+
+ protected var previewDocument: IDocument = _
+
+ def build(tabFolder: TabFolder) {
+ val tabItem = new TabItem(tabFolder, SWT.NONE)
+ tabItem.setText(tabName)
+ val tabComposite = new Composite(tabFolder, SWT.NONE)
+ tabItem.setControl(tabComposite)
+ buildContents(tabComposite)
+ }
+
+ protected def buildContents(composite: Composite)
+
+ private def formatPreviewText: String = ScalaFormatter.format(previewText, getPreferences(overlayStore))
+
+ protected def addCheckBox(parent: Composite, text: String, preference: BooleanPreferenceDescriptor) {
+ val checkBox = new Button(parent, SWT.CHECK | SWT.WRAP)
+ checkBox.setText(text)
+ checkBox.setToolTipText(preference.description + " (" + preference.key + ")")
+ checkBox.setSelection(overlayStore(preference))
+ checkBox.setLayoutData(new CC().spanX(2).growX.wrap)
+ checkBox.addSelectionListener { e: SelectionEvent =>
+ overlayStore(preference) = checkBox.getSelection
+ previewDocument.set(formatPreviewText)
+ }
+
+ overlayStore.addPropertyChangeListener { e: PropertyChangeEvent =>
+ if (e.getProperty == preference.eclipseKey)
+ checkBox.setSelection(overlayStore(preference))
+ }
+
+ allEnableDisableControls += checkBox
+ }
+
+ protected def addNumericField(parent: Composite, text: String, preference: PreferenceDescriptor[Int]) {
+ val IntegerPreference(min, max) = preference.preferenceType
+ val label = new Label(parent, SWT.LEFT)
+ label.setText(text)
+ label.setToolTipText(preference.description + " (" + preference.key + ")")
+ label.setLayoutData(new CC())
+ val field = new Text(parent, SWT.SINGLE | SWT.BORDER)
+ field.setText(overlayStore(preference).toString)
+ field.setLayoutData(new CC().sizeGroupX("numfield").alignX("right").minWidth("40px").wrap)
+
+ def validateNumber(s: String) =
+ try Integer.parseInt(s) match {
+ case n if n < min || n > max => None
+ case n => Some(n)
+ } catch {
+ case _: NumberFormatException => None
+ }
+
+ def valueChanged() {
+ validateNumber(field.getText) match {
+ case Some(n) =>
+ overlayStore(preference) = n
+ previewDocument.set(formatPreviewText)
+ setErrorMessage(null)
+ case None =>
+ setErrorMessage("Number must be an integer between " + min + " and " + max)
+ }
+ }
+
+ field.onKeyReleased { valueChanged() }
+ field.onFocusLost { valueChanged() }
+ overlayStore.addPropertyChangeListener { e: PropertyChangeEvent =>
+ if (e.getProperty == preference.eclipseKey)
+ field.setText(overlayStore(preference).toString)
+ }
+ allEnableDisableControls ++= Set(label, field)
+ }
+
+ protected def addPreview(parent: Composite) {
+ val previewLabel = new Label(parent, SWT.LEFT)
+ allEnableDisableControls += previewLabel
+ previewLabel.setText("Preview:")
+ previewLabel.setLayoutData(new CC().spanX(2).wrap)
+ val previewer = createPreviewer(parent)
+ previewer.setLayoutData(new CC().spanX(2).grow)
+ }
+
+ protected def createPreviewer(parent: Composite): Control = {
+ val (control, document) = ScalaPreviewerFactory.createPreviewer(parent, getPreferenceStore, formatPreviewText)
+ previewDocument = document
+ allEnableDisableControls += control
+ control
+ }
+ }
+
+ object IndentPrefTab extends PrefTab("Indentation && Alignment", INDENT_PREVIEW_TEXT) {
+
+ def buildContents(composite: Composite) {
+ composite.setLayout(new MigLayout(new LC().fill, new AC, new AC().index(8).grow(1)))
+
+ addNumericField(composite, "Spaces to indent:", IndentSpaces)
+ addCheckBox(composite, "Align parameters", AlignParameters)
+ addCheckBox(composite, "Double indent class declaration", DoubleIndentClassDeclaration)
+ addCheckBox(composite, "Align single-line case statements", AlignSingleLineCaseStatements)
+ addNumericField(composite, "Max arrow indent:", AlignSingleLineCaseStatements.MaxArrowIndent)
+ addCheckBox(composite, "Indent package blocks", IndentPackageBlocks)
+ addCheckBox(composite, "Indent local defs", IndentLocalDefs)
+
+ addPreview(composite)
+ }
+ }
+
+ object SpacesPrefTab extends PrefTab("Spaces", SPACES_PREVIEW_TEXT) {
+
+ def buildContents(composite: Composite) {
+ composite.setLayout(new MigLayout(new LC().fill, new AC, new AC().index(7).grow(1)))
+
+ addCheckBox(composite, "Space before colons", SpaceBeforeColon)
+ addCheckBox(composite, "Compact string concatenation", CompactStringConcatenation)
+ addCheckBox(composite, "Space inside brackets", SpaceInsideBrackets)
+ addCheckBox(composite, "Space inside parentheses", SpaceInsideParentheses)
+ addCheckBox(composite, "Preserve space before arguments", PreserveSpaceBeforeArguments)
+ addCheckBox(composite, "Spaces within pattern binders", SpacesWithinPatternBinders)
+
+ addPreview(composite)
+ }
+ }
+
+ object MiscPrefTab extends PrefTab("Miscellaneous", MISC_PREVIEW_TEXT) {
+
+ def buildContents(composite: Composite) {
+ composite.setLayout(new MigLayout(new LC().fill, new AC, new AC().index(5).grow(1)))
+
+ addCheckBox(composite, "Format XML", FormatXml)
+ addCheckBox(composite, "Rewrite arrow tokens", RewriteArrowSymbols)
+ addCheckBox(composite, "Preserve dangling close parenthesis", PreserveDanglingCloseParenthesis)
+ addCheckBox(composite, "Multiline Scaladoc comments start on first line", MultilineScaladocCommentsStartOnFirstLine)
+
+ addPreview(composite)
+ }
+ }
+
+ private def initUnderlyingPreferenceStore() {
+ val pluginId = ScalaPlugin.plugin.pluginId
+ val scalaPrefStore = ScalaPlugin.plugin.getPreferenceStore
+ setPreferenceStore(getElement match {
+ case project: IProject => new PropertyStore(project, scalaPrefStore, pluginId)
+ case project: IJavaProject => new PropertyStore(project.getProject, scalaPrefStore, pluginId)
+ case _ => scalaPrefStore
+ })
+ }
+
+ def createContents(parent: Composite): Control = {
+
+ initUnderlyingPreferenceStore() // done here to ensure that getElement will have been set
+
+ val control = new Composite(parent, SWT.NONE)
+ val rowConstraints = if (isWorkbenchPage)
+ new AC().index(0).grow(0).index(1).grow
+ else
+ new AC().index(0).grow(0).index(1).grow(0).index(2).grow(0).index(3).grow
+ control.setLayout(new MigLayout(new LC().insetsAll("0").fill, new AC(), rowConstraints))
+
+ if (!isWorkbenchPage) {
+
+ val projectSpecificButton = new Button(control, SWT.CHECK | SWT.WRAP)
+ projectSpecificButton.setText("Enable project specific settings")
+ projectSpecificButton.setSelection(getPreferenceStore.getBoolean(USE_PROJECT_SPECIFIC_SETTINGS_KEY))
+ projectSpecificButton.addSelectionListener { e: SelectionEvent =>
+ val enabled = projectSpecificButton.getSelection
+ getPreferenceStore.setValue(USE_PROJECT_SPECIFIC_SETTINGS_KEY, enabled)
+ allEnableDisableControls foreach { _.setEnabled(enabled) }
+ }
+ projectSpecificButton.setLayoutData(new CC)
+
+ val link = new Link(control, SWT.NONE)
+ link.setText("<a>" + PreferencesMessages.PropertyAndPreferencePage_useworkspacesettings_change + "</a>")
+ link.addSelectionListener {
+ PreferencesUtil.createPreferenceDialogOn(getShell, PAGE_ID, Array(PAGE_ID), null).open()
+ }
+ link.setLayoutData(new CC().alignX("right").wrap)
+
+ val horizontalLine = new Label(control, SWT.SEPARATOR | SWT.HORIZONTAL)
+ horizontalLine.setLayoutData(new CC().spanX(2).grow.wrap)
+ }
+
+ { // Manual link + import / export buttons
+ val buttonPanel = new Composite(control, SWT.NONE)
+
+ buttonPanel.setLayout(
+ new MigLayout(
+ new LC().insetsAll("0"),
+ new AC()
+ .index(0).grow.align("left")
+ .index(1).grow(0).align("right")
+ .index(2).grow(0).align("right")))
+
+ val link = new Link(buttonPanel, SWT.NONE)
+ link.setText("<a>Scalariform manual</a>")
+ link.addSelectionListener { e: SelectionEvent =>
+ val url = new URL(SCALARIFORM_DOC_URL)
+ PlatformUI.getWorkbench.getBrowserSupport.createBrowser(null).openURL(url)
+ }
+ link.setLayoutData(new CC)
+
+ val importButton = new Button(buttonPanel, SWT.PUSH)
+ importButton.setText("Import...")
+ importButton.setLayoutData(new CC().sizeGroupX("button"))
+ importButton.addSelectionListener { importPreferences() }
+
+ val exportButton = new Button(buttonPanel, SWT.PUSH)
+ exportButton.setText("Export...")
+ exportButton.setLayoutData(new CC().sizeGroupX("button").wrap)
+ exportButton.addSelectionListener { exportPreferences() }
+
+ buttonPanel.setLayoutData(new CC().spanX(2).growX.wrap)
+ allEnableDisableControls ++= Set(link, importButton, exportButton)
+ }
+
+ val tabFolder = new TabFolder(control, SWT.TOP)
+ tabFolder.setLayoutData(new CC().spanX(2).grow)
+
+ IndentPrefTab.build(tabFolder)
+ SpacesPrefTab.build(tabFolder)
+ MiscPrefTab.build(tabFolder)
+
+ allEnableDisableControls += tabFolder
+
+ if (!isWorkbenchPage) {
+ val enabled = getPreferenceStore.getBoolean(USE_PROJECT_SPECIFIC_SETTINGS_KEY)
+ allEnableDisableControls foreach { _.setEnabled(enabled) }
+ }
+ control
+ }
+
+ override def performOk() = {
+ super.performOk()
+ overlayStore.propagate()
+ ScalaPlugin.plugin.savePluginPreferences()
+ true
+ }
- override def createFieldEditors() {
+ override def dispose() {
+ overlayStore.stop()
+ super.dispose()
+ }
- for (preference <- AllPreferences.preferences) {
- val preferenceType = preference.preferenceType
- preferenceType match {
- case BooleanPreference =>
- val field = new BooleanFieldEditor(prefix + preference.key, preference.description, org.eclipse.swt.SWT.NONE, getFieldEditorParent())
- addField(field)
- case IntegerPreference(min, max) =>
- val field = new IntegerFieldEditor(prefix + preference.key, preference.description, getFieldEditorParent())
- field.setValidRange(min, max)
- addField(field)
+ override def performDefaults() {
+ overlayStore.loadDefaults()
+ super.performDefaults()
+ }
+
+ private def getPreferenceFileNameViaDialog(title: String, initialFileName: String = ""): Option[String] = {
+ val dialog = new FileDialog(getShell, SWT.SAVE)
+ dialog.setText(title)
+ dialog.setFileName(initialFileName)
+ val dialogSettings = ScalaPlugin.plugin.getDialogSettings
+ Option(dialogSettings get IMPORT_EXPORT_DIALOG_PATH) foreach dialog.setFilterPath
+ val fileName = dialog.open()
+ if (fileName == null)
+ None
+ else {
+ dialogSettings.put(IMPORT_EXPORT_DIALOG_PATH, dialog.getFilterPath)
+ Some(fileName)
+ }
+ }
+
+ private def exportPreferences() {
+ for (fileName <- getPreferenceFileNameViaDialog("Export formatter preferences", DEFAULT_PREFERENCE_FILE_NAME)) {
+ val preferences = FormatterPreferences.getPreferences(overlayStore)
+ try
+ PreferencesImporterExporter.savePreferences(fileName, preferences)
+ catch {
+ case e: IOException =>
+ ScalaPlugin.plugin.logError(e)
+ MessageDialog.openError(getShell, "Error writing to " + fileName, e.getMessage)
+ }
+ }
+ }
+
+ private def importPreferences() {
+ for (fileName <- getPreferenceFileNameViaDialog("Import formatter preferences")) {
+ val preferences = try
+ PreferencesImporterExporter.loadPreferences(fileName)
+ catch {
+ case e: IOException =>
+ ScalaPlugin.plugin.logError(e)
+ MessageDialog.openError(getShell, "Error opening " + fileName, e.getMessage)
+ return
}
+ overlayStore.importPreferences(preferences)
}
}
+
}
object FormatterPreferencePage {
- val prefix = "scala.tools.eclipse.formatter."
+ val DEFAULT_PREFERENCE_FILE_NAME = "formatterPreferences.properties"
- def getPreferences() = {
- val preferenceStore = ScalaPlugin.plugin.getPreferenceStore
- var preferences: IFormattingPreferences = FormattingPreferences()
+ val PAGE_ID = "scala.tools.eclipse.formatter.FormatterPreferencePage"
- for (preference <- AllPreferences.preferences) {
- preference.preferenceType match {
- case prefType@BooleanPreference =>
- preferences = preferences.setPreference(prefType.cast(preference), preferenceStore.getBoolean(prefix + preference.key))
- case prefType@IntegerPreference(_, _) =>
- preferences = preferences.setPreference(prefType.cast(preference), preferenceStore.getInt(prefix + preference.key))
- }
+ val IMPORT_EXPORT_DIALOG_PATH = "formatter.importExportDialogPath"
+
+ val SCALARIFORM_DOC_URL = "http://mdr.github.com/scalariform/"
+
+ val SPACES_PREVIEW_TEXT = """class ClassName[T](name: String) {
+
+ println("hello"+name+"world")
+
+ stack.pop() should equal (2)
+
+ x match {
+ case elem@Multi(values@_*) =>
+ }
+
+}
+"""
+
+ val INDENT_PREVIEW_TEXT = """package foo {
+class Bar(param: Int)
+extends Foo with Baz {
+ def method(s: String,
+n: Int) = {
+ def localDef {
+ // ..
+ }
+ s match {
+ case "wibble" => 42
+ case "foo" => 123
+ case _ => 100
}
- preferences
}
+}
+}"""
+ val MISC_PREVIEW_TEXT = """val xml = <foo>
+<bar/>
+ <baz attr= "value" />
+</foo>
+for (n <- 1 to 10)
+ n match {
+ case _ => 42
}
+/**
+ * Multiline Scaladoc
+ * comment
+ */
+val book = Book(
+ name = "Name",
+ author = "Author",
+ rating = 5
+)
+"""
+
+}
View
75 org.scala-ide.sdt.core/src/scala/tools/eclipse/formatter/FormatterPreferences.scala
@@ -0,0 +1,75 @@
+package scala.tools.eclipse.formatter
+
+import org.eclipse.core.resources.IProject
+import scalariform.formatter.preferences.IntegerPreferenceDescriptor
+import scalariform.formatter.preferences.BooleanPreferenceDescriptor
+import scalariform.formatter.preferences.FormattingPreferences
+import scalariform.formatter.preferences.AllPreferences
+import scala.tools.eclipse.ScalaPlugin
+import scalariform.formatter.preferences.IFormattingPreferences
+import org.eclipse.jface.preference.IPreferenceStore
+import scalariform.formatter.preferences.PreferenceDescriptor
+import scala.tools.eclipse.properties.PropertyStore
+
+object FormatterPreferences {
+
+ implicit def preference2PimpedPreference(preference: PreferenceDescriptor[_]) = new PimpedFormatterPreference(preference)
+
+ class PimpedFormatterPreference(preference: PreferenceDescriptor[_]) {
+
+ def eclipseKey = PREFIX + preference.key
+
+ def oldEclipseKey = OLD_PREFIX + preference.key
+ }
+
+ implicit def prefStore2PimpedPrefStore(preferenceStore: IPreferenceStore) = new PimpedPreferenceStore(preferenceStore)
+
+ class PimpedPreferenceStore(preferenceStore: IPreferenceStore) {
+
+ def apply(pref: PreferenceDescriptor[Boolean]) = preferenceStore.getBoolean(pref.eclipseKey)
+
+ def apply(pref: PreferenceDescriptor[Int]) = preferenceStore.getInt(pref.eclipseKey)
+
+ def update(pref: PreferenceDescriptor[Boolean], value: Boolean) { preferenceStore.setValue(pref.eclipseKey, value) }
+
+ def update(pref: PreferenceDescriptor[Int], value: Int) { preferenceStore.setValue(pref.eclipseKey, value) }
+
+ def importPreferences(preferences: IFormattingPreferences) {
+ for (preference <- AllPreferences.preferences)
+ preference match {
+ case bpd: BooleanPreferenceDescriptor =>
+ preferenceStore.setValue(preference.eclipseKey, preferences(bpd))
+ case ipd: IntegerPreferenceDescriptor =>
+ preferenceStore.setValue(preference.eclipseKey, preferences(ipd))
+ }
+ }
+
+ }
+
+ def getPreferences: IFormattingPreferences = getPreferences(ScalaPlugin.plugin.getPreferenceStore)
+
+ def getPreferences(preferenceStore: IPreferenceStore): IFormattingPreferences =
+ AllPreferences.preferences.foldLeft(FormattingPreferences()) { (preferences, pref) =>
+ pref match {
+ case pd: BooleanPreferenceDescriptor => preferences.setPreference(pd, preferenceStore(pd))
+ case pd: IntegerPreferenceDescriptor => preferences.setPreference(pd, preferenceStore(pd))
+ }
+ }
+
+ def getPreferences(project: IProject): IFormattingPreferences = getPreferences(getPreferenceStore(project))
+
+ private def getPreferenceStore(project: IProject): IPreferenceStore = {
+ val workspaceStore = ScalaPlugin.plugin.getPreferenceStore
+ val projectStore = new PropertyStore(project, workspaceStore, ScalaPlugin.plugin.pluginId)
+ val useProjectSettings = projectStore.getBoolean(FormatterPreferences.USE_PROJECT_SPECIFIC_SETTINGS_KEY)
+ val prefStore = if (useProjectSettings) projectStore else ScalaPlugin.plugin.getPreferenceStore
+ prefStore
+ }
+
+ val OLD_PREFIX = "scala.tools.eclipse.formatter."
+
+ val PREFIX = "formatter."
+
+ val USE_PROJECT_SPECIFIC_SETTINGS_KEY = PREFIX + "useProjectSpecificSettings"
+
+}
View
3  org.scala-ide.sdt.core/src/scala/tools/eclipse/formatter/ScalaFormatterCleanUpProvider.scala
@@ -15,10 +15,11 @@ import org.eclipse.jdt.internal.ui.javaeditor.DocumentAdapter
class ScalaFormatterCleanUpProvider extends IFormatterCleanUpProvider {
def createCleanUp(cu: ICompilationUnit): ICleanUpFix = {
+ val project = cu.getJavaProject.getProject
val document = cu.getBuffer.asInstanceOf[DocumentAdapter].getDocument
val lineDelimiter = TextUtilities.getDefaultLineDelimiter(document)
val edits =
- try ScalaFormatter.formatAsEdits(cu.getSource, FormatterPreferencePage.getPreferences, Some(lineDelimiter))
+ try ScalaFormatter.formatAsEdits(cu.getSource, FormatterPreferences.getPreferences(project), Some(lineDelimiter))
catch { case e: ScalaParserException => return null }
val resultEdit = new MultiTextEdit
for (TextEdit(start, length, replacement) <- edits)
View
35 org.scala-ide.sdt.core/src/scala/tools/eclipse/formatter/ScalaFormatterPreferenceInitializer.scala
@@ -1,5 +1,6 @@
package scala.tools.eclipse.formatter
+import org.eclipse.jface.preference.IPreferenceStore
import org.eclipse.core.runtime.preferences.{ AbstractPreferenceInitializer, DefaultScope }
import scala.tools.eclipse.ScalaPlugin
@@ -8,18 +9,28 @@ import scalariform.formatter.preferences._
class ScalaFormatterPreferenceInitializer extends AbstractPreferenceInitializer {
- def initializeDefaultPreferences(): Unit =
- ScalaPlugin.plugin.check {
- val preferenceStore = ScalaPlugin.plugin.getPluginPreferences
- for {
- preference <- AllPreferences.preferences
- val key = FormatterPreferencePage.prefix + preference.key
- } preference.preferenceType match {
- case prefType@BooleanPreference =>
- preferenceStore.setDefault(key, prefType.cast(preference).defaultValue)
- case prefType@IntegerPreference(_, _) =>
- preferenceStore.setDefault(key, prefType.cast(preference).defaultValue)
- }
+ import FormatterPreferences._
+ def initializeDefaultPreferences() {
+ val preferenceStore = ScalaPlugin.plugin.getPreferenceStore
+ for (preference <- AllPreferences.preferences) {
+ preference match {
+ case pd: BooleanPreferenceDescriptor =>
+ preferenceStore.setDefault(preference.eclipseKey, pd.defaultValue)
+ preferenceStore.setDefault(preference.oldEclipseKey, pd.defaultValue)
+ if (!preferenceStore.isDefault(preference.oldEclipseKey)) {
+ preferenceStore(pd) = preferenceStore.getBoolean(preference.oldEclipseKey)
+ preferenceStore.setToDefault(preference.oldEclipseKey)
+ }
+ case pd: IntegerPreferenceDescriptor =>
+ preferenceStore.setDefault(preference.eclipseKey, pd.defaultValue)
+ preferenceStore.setDefault(preference.oldEclipseKey, pd.defaultValue)
+ if (!preferenceStore.isDefault(preference.oldEclipseKey)) {
+ preferenceStore(pd) = preferenceStore.getInt(preference.oldEclipseKey)
+ preferenceStore.setToDefault(preference.oldEclipseKey)
+ }
+ }
}
+
+ }
}
View
48 org.scala-ide.sdt.core/src/scala/tools/eclipse/formatter/ScalaFormattingStrategy.scala
@@ -1,5 +1,12 @@
package scala.tools.eclipse.formatter
+import org.eclipse.core.resources.IProject
+import org.eclipse.jface.preference.IPreferenceStore
+import scala.tools.eclipse.properties.PropertyStore
+import scala.tools.eclipse.ScalaPlugin
+import org.eclipse.jdt.core.IJavaElement
+import org.eclipse.core.runtime.IAdaptable
+import org.eclipse.ui.texteditor.ITextEditor
import org.eclipse.jface.text.formatter.IFormattingStrategy
import org.eclipse.jface.text.source.ISourceViewer
import scalariform.parser.ScalaParserException
@@ -10,35 +17,34 @@ import org.eclipse.text.undo.DocumentUndoManagerRegistry
import org.eclipse.text.edits.{ TextEdit => JFaceTextEdit, _ }
import org.eclipse.jface.text.{ IDocument, TextUtilities }
-class ScalaFormattingStrategy(val sourceViewer: ISourceViewer) extends IFormattingStrategy {
+class ScalaFormattingStrategy(val editor: ITextEditor) extends IFormattingStrategy {
def format(content: String, isLineStart: Boolean, indentation: String, positions: Array[Int]): String = {
- format(sourceViewer.getDocument)
+ val project = editor.getEditorInput.asInstanceOf[IAdaptable].getAdapter(classOf[IJavaElement]).asInstanceOf[IJavaElement].getJavaProject.getProject
+ val document = editor.getDocumentProvider.getDocument(editor.getEditorInput)
+ val source = document.get
+ val lineDelimiter = Option(TextUtilities.getDefaultLineDelimiter(document))
+ val preferences = FormatterPreferences.getPreferences(project)
+
+ val edits =
+ try ScalaFormatter.formatAsEdits(source, preferences, lineDelimiter)
+ catch { case _: ScalaParserException => return null }
+ applyEdits(document, edits)
+
null
}
- private def format(document: IDocument) {
- val source = document.get
- val lineDelimiter = Option(TextUtilities.getDefaultLineDelimiter(document))
- try {
- val edits = ScalaFormatter.formatAsEdits(source, FormatterPreferencePage.getPreferences, lineDelimiter)
-
- val undoManager = DocumentUndoManagerRegistry.getDocumentUndoManager(document)
- undoManager.beginCompoundChange()
- val eclipseEdit = new MultiTextEdit
- for (TextEdit(start, length, replacement) <- edits)
- eclipseEdit.addChild(new ReplaceEdit(start, length, replacement))
- new TextEditProcessor(document, eclipseEdit, JFaceTextEdit.NONE).performEdits
- undoManager.endCompoundChange()
-
- } catch {
- case _: ScalaParserException =>
- case e => throw e
- }
+ private def applyEdits(document: IDocument, edits: List[TextEdit]) {
+ val undoManager = DocumentUndoManagerRegistry.getDocumentUndoManager(document)
+ undoManager.beginCompoundChange()
+ val eclipseEdit = new MultiTextEdit
+ for (TextEdit(start, length, replacement) <- edits)
+ eclipseEdit.addChild(new ReplaceEdit(start, length, replacement))
+ new TextEditProcessor(document, eclipseEdit, JFaceTextEdit.NONE).performEdits
+ undoManager.endCompoundChange()
}
def formatterStarts(initialIndentation: String) {}
def formatterStops() {}
-
}
View
36 org.scala-ide.sdt.core/src/scala/tools/eclipse/javaelements/ScalaOverrideIndicatorBuilder.scala
@@ -17,14 +17,14 @@ import scala.tools.eclipse.contribution.weaving.jdt.IScalaOverrideIndicator
import org.eclipse.ui.texteditor.ITextEditor
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility
-import scala.tools.eclipse.ScalaPresentationCompiler
+import scala.tools.eclipse.{ ScalaPresentationCompiler, ScalaPlugin }
trait ScalaOverrideIndicatorBuilder { self : ScalaPresentationCompiler =>
class OverrideIndicatorBuilderTraverser(scu : ScalaCompilationUnit, annotationMap : JMap[AnyRef, AnyRef]) extends Traverser {
val ANNOTATION_TYPE= "org.eclipse.jdt.ui.overrideIndicator"
- case class ScalaIndicator(text : String, base: Symbol, val isOverwrite : Boolean) extends Annotation(ANNOTATION_TYPE, false, text)
- with IScalaOverrideIndicator {
+ case class ScalaIndicator(text : String, base: Symbol, val isOverwrite : Boolean)
+ extends Annotation(ANNOTATION_TYPE, false, text) with IScalaOverrideIndicator {
def open = {
ask{ () => locate(base, scu) } map { case (file, pos) =>
EditorUtility.openInEditor(file, true) match {
@@ -58,19 +58,23 @@ trait ScalaOverrideIndicatorBuilder { self : ScalaPresentationCompiler =>
override def traverse(tree: Tree): Unit = {
tree match {
case defn: DefTree if (defn.symbol ne NoSymbol) && defn.symbol.pos.isOpaqueRange =>
- for(base <- defn.symbol.allOverriddenSymbols) {
- val isOverwrite = base.isDeferred && !defn.symbol.isDeferred
- val text = (if (isOverwrite) "implements " else "overrides ") + base.fullName
- val position = new JFacePosition(defn.pos.startOrPoint, 0)
-
- if (base.isJavaDefined) {
- val packageName = base.enclosingPackage.fullName
- val typeNames = enclosingTypeNames(base).mkString(".")
- val methodName = base.name.toString
- val paramTypes = base.tpe.paramss.flatMap(_.map(_.tpe))
- val methodTypeSignatures = paramTypes.map(mapParamTypeSignature(_))
- annotationMap.put(JavaIndicator(packageName, typeNames, methodName, methodTypeSignatures, text, isOverwrite), position)
- } else annotationMap.put(ScalaIndicator(text, base, isOverwrite), position)
+ try {
+ for(base <- defn.symbol.allOverriddenSymbols) {
+ val isOverwrite = base.isDeferred && !defn.symbol.isDeferred
+ val text = (if (isOverwrite) "implements " else "overrides ") + base.fullName
+ val position = new JFacePosition(defn.pos.startOrPoint, 0)
+
+ if (base.isJavaDefined) {
+ val packageName = base.enclosingPackage.fullName
+ val typeNames = enclosingTypeNames(base).mkString(".")
+ val methodName = base.name.toString
+ val paramTypes = base.tpe.paramss.flatMap(_.map(_.tpe))
+ val methodTypeSignatures = paramTypes.map(mapParamTypeSignature(_))
+ annotationMap.put(JavaIndicator(packageName, typeNames, methodName, methodTypeSignatures, text, isOverwrite), position)
+ } else annotationMap.put(ScalaIndicator(text, base, isOverwrite), position)
+ }
+ } catch {
+ case ex => ScalaPlugin.plugin.logError("Error creating override indicators for %s".format(scu.file.path), ex)
}
case _ =>
}
View
4 org.scala-ide.sdt.core/src/scala/tools/eclipse/javaelements/ScalaStructureBuilder.scala
@@ -313,6 +313,8 @@ trait ScalaStructureBuilder { self : ScalaPresentationCompiler =>
override def addClass(c : ClassDef) : Owner = {
val sym = c.symbol
if (sym eq NoSymbol) return self // Local class hasn't been attributed yet, can't show anything meaningful.
+ // make sure classes are completed
+ sym.initialize
val name = c.name.toString
val parentTree = c.impl.parents.head
@@ -789,7 +791,7 @@ trait ScalaStructureBuilder { self : ScalaPresentationCompiler =>
case vd : ValDef => (builder.addVal(vd), List(vd.rhs))
case td : TypeDef => (builder.addType(td), List(td.rhs))
case dd : DefDef => {
- if(dd.name != nme.MIXIN_CONSTRUCTOR) {
+ if(dd.name != nme.MIXIN_CONSTRUCTOR && (dd.symbol ne NoSymbol)) {
(builder.addDef(dd), List(dd.tpt, dd.rhs))
} else (builder, Nil)
}
View
7 org.scala-ide.sdt.core/src/scala/tools/eclipse/lexical/ScalaDocumentPartitioner.scala
@@ -5,7 +5,7 @@ import org.eclipse.jface.text.IDocument.DEFAULT_CONTENT_TYPE
import scala.collection.mutable.ListBuffer
import scala.math.{ max, min }
-class ScalaDocumentPartitioner extends IDocumentPartitioner with IDocumentPartitionerExtension with IDocumentPartitionerExtension2 {
+class ScalaDocumentPartitioner(conservative: Boolean = false) extends IDocumentPartitioner with IDocumentPartitionerExtension with IDocumentPartitionerExtension2 {
import ScalaDocumentPartitioner._
@@ -27,7 +27,10 @@ class ScalaDocumentPartitioner extends IDocumentPartitioner with IDocumentPartit
val oldPartitions = partitionRegions
val newPartitions = ScalaPartitionTokeniser.tokenise(event.getDocument.get)
partitionRegions = newPartitions
- calculateDirtyRegion(oldPartitions, newPartitions, event.getOffset, event.getLength, event.getText)
+ if (conservative)
+ new Region(0, event.getDocument.getLength)
+ else
+ calculateDirtyRegion(oldPartitions, newPartitions, event.getOffset, event.getLength, event.getText)
}
private def calculateDirtyRegion(oldPartitions: List[ScalaPartitionRegion], newPartitions: List[ScalaPartitionRegion], offset: Int, length: Int, text: String): IRegion =
View
63 org.scala-ide.sdt.core/src/scala/tools/eclipse/properties/SyntaxColouringPreferencePage.scala
@@ -1,5 +1,6 @@
package scala.tools.eclipse.properties
+import scala.tools.eclipse.ScalaPreviewerFactory
import java.util.HashMap
import org.eclipse.jdt.internal.ui.preferences.OverlayPreferenceStore
import PartialFunction.condOpt
@@ -52,6 +53,7 @@ import scala.tools.eclipse.ScalaSourceViewerConfiguration
import org.eclipse.jdt.ui.text.IJavaPartitions
import org.eclipse.jface.util.IPropertyChangeListener
import org.eclipse.jface.util.PropertyChangeEvent
+import scala.tools.eclipse.util.SWTUtils._
/**
* @see org.eclipse.jdt.internal.ui.preferences.JavaEditorColoringConfigurationBlock
@@ -176,28 +178,19 @@ class SyntaxColouringPreferencePage extends PreferencePage with IWorkbenchPrefer
widthHint = widthHint,
heightHint = convertHeightInCharsToPixels(9)))
- treeViewer.addDoubleClickListener(new IDoubleClickListener {
- def doubleClick(event: DoubleClickEvent) {
- val element = event.getSelection.asInstanceOf[IStructuredSelection].getFirstElement
- if (treeViewer.isExpandable(element))
- treeViewer.setExpandedState(element, !treeViewer.getExpandedState(element))
- }
- })
+ treeViewer.addDoubleClickListener { event: DoubleClickEvent =>
+ val element = event.getSelection.asInstanceOf[IStructuredSelection].getFirstElement
+ if (treeViewer.isExpandable(element))
+ treeViewer.setExpandedState(element, !treeViewer.getExpandedState(element))
+ }
- treeViewer.addSelectionChangedListener(new ISelectionChangedListener {
- def selectionChanged(event: SelectionChangedEvent) {
- handleSyntaxColorListSelection()
- }
- })
+ treeViewer.addSelectionChangedListener {
+ handleSyntaxColorListSelection()
+ }
treeViewer.setInput(new Object)
}
- private implicit def fnToSelectionAdapter[T](p: SelectionEvent => T): SelectionAdapter =
- new SelectionAdapter() {
- override def widgetSelected(e: SelectionEvent) = p(e)
- }
-
private def gridLayout(marginHeight: Int = 5, marginWidth: Int = 5, numColumns: Int = 1): GridLayout = {
val layout = new GridLayout
layout.marginHeight = marginHeight
@@ -310,23 +303,23 @@ class SyntaxColouringPreferencePage extends PreferencePage with IWorkbenchPrefer
widthHint = convertWidthInCharsToPixels(20),
heightHint = convertHeightInCharsToPixels(5)))
- foregroundColorButton.addSelectionListener { e: SelectionEvent =>
+ foregroundColorButton.addSelectionListener {
for (syntaxClass <- selectedSyntaxClass)
PreferenceConverter.setValue(overlayStore, syntaxClass.colourKey, syntaxForegroundColorEditor.getColorValue)
}
- boldCheckBox.addSelectionListener { e: SelectionEvent =>
+ boldCheckBox.addSelectionListener {
for (syntaxClass <- selectedSyntaxClass)
overlayStore.setValue(syntaxClass.boldKey, boldCheckBox.getSelection)
}
- italicCheckBox.addSelectionListener { e: SelectionEvent =>
+ italicCheckBox.addSelectionListener {
for (syntaxClass <- selectedSyntaxClass)
overlayStore.setValue(syntaxClass.italicKey, italicCheckBox.getSelection)
}
- underlineCheckBox.addSelectionListener { e: SelectionEvent =>
+ underlineCheckBox.addSelectionListener {
for (syntaxClass <- selectedSyntaxClass)
overlayStore.setValue(syntaxClass.underlineKey, underlineCheckBox.getSelection)
}
- strikethroughCheckBox.addSelectionListener { e: SelectionEvent =>
+ strikethroughCheckBox.addSelectionListener {
for (syntaxClass <- selectedSyntaxClass)
overlayStore.setValue(syntaxClass.strikethroughKey, strikethroughCheckBox.getSelection)
}
@@ -339,30 +332,8 @@ class SyntaxColouringPreferencePage extends PreferencePage with IWorkbenchPrefer
private def createPreviewer(parent: Composite): Control = {
val store = new ChainedPreferenceStore(Array(overlayStore, EditorsUI.getPreferenceStore))
-
- val previewViewer = new JavaSourceViewer(parent, null, null, false, SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER, store)
- val font = JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT)
- previewViewer.getTextWidget.setFont(font)
- previewViewer.setEditable(false)
-
- val configuration = new ScalaSourceViewerConfiguration(store, store, null)
- previewViewer.configure(configuration)
-
- store.addPropertyChangeListener(new IPropertyChangeListener() {
- def propertyChange(event: PropertyChangeEvent) {
- if (configuration.affectsTextPresentation(event))
- configuration.handlePropertyChangeEvent(event)
- previewViewer.invalidateTextPresentation()
- }
- })
-
- val document = new Document(previewText)
- val partitioners = new HashMap[String, IDocumentPartitioner]
- partitioners.put(IJavaPartitions.JAVA_PARTITIONING, new ScalaDocumentPartitioner)
- TextUtilities.addDocumentPartitioners(document, partitioners)
- previewViewer.setDocument(document)
-
- previewViewer.getControl
+ val (control, document) = ScalaPreviewerFactory.createPreviewer(parent, store, previewText)
+ control
}
private def selectedSyntaxClass: Option[ScalaSyntaxClass] =
View
24 org.scala-ide.sdt.core/src/scala/tools/eclipse/ui/ScalaIndenter.scala
@@ -7,29 +7,23 @@ package scala.tools.eclipse.ui
import org.eclipse.core.runtime.Assert
-
import org.eclipse.jface.text.BadLocationException
import org.eclipse.jface.text.IDocument
import org.eclipse.jface.text.IRegion
-
import org.eclipse.jdt.core.IJavaProject
import org.eclipse.jdt.core.JavaCore
import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants
-
-import org.eclipse.jdt.internal.ui.JavaPlugin;
+import org.eclipse.jdt.internal.ui.JavaPlugin
import org.eclipse.jdt.internal.ui.text.DocumentCharacterIterator
import org.eclipse.jdt.internal.ui.text.JavaHeuristicScanner
import org.eclipse.jdt.internal.ui.text.Symbols
-
import org.eclipse.jdt.internal.corext.util.CodeFormatterUtil
-
import org.eclipse.jdt.ui.PreferenceConstants
-
import java.lang.Math.min
-
import scala.collection.mutable.Map
-
import scala.annotation.tailrec
+import scala.tools.eclipse.ScalaPlugin
+import scala.tools.eclipse.formatter.FormatterPreferences
// TODO Move this out into a new file
trait PreferenceProvider {
@@ -64,9 +58,13 @@ class JdtPreferenceProvider(val project : IJavaProject) extends PreferenceProvid
preferenceStore.getBoolean(PreferenceConstants.EDITOR_CLOSE_BRACES).toString)
put(PreferenceConstants.EDITOR_SMART_TAB,
preferenceStore.getBoolean(PreferenceConstants.EDITOR_SMART_TAB).toString)
-
- put(ScalaIndenter.TAB_SIZE, CodeFormatterUtil.getTabWidth(project).toString)
- put(ScalaIndenter.INDENT_SIZE, CodeFormatterUtil.getIndentWidth(project).toString)
+
+ // TODO: Matt -- use better pref lookup when merged with formatter-preferences-page branch
+ val scalaPrefs = ScalaPlugin.plugin.getPreferenceStore
+ val key = FormatterPreferences.PREFIX + scalariform.formatter.preferences.IndentSpaces.key
+ val indent = scalaPrefs.getInt(key)
+ put(ScalaIndenter.TAB_SIZE, indent.toString)
+ put(ScalaIndenter.INDENT_SIZE, indent.toString)
def populateFromProject(key : String) = {
put(key, project.getOption(key, true))
@@ -285,7 +283,7 @@ class ScalaIndenter(
return 2 // sensible default
}
- private def prefTabChar = getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR)
+ private def prefTabChar = JavaCore.SPACE
private def hasGenerics : Boolean = true
View
62 org.scala-ide.sdt.core/src/scala/tools/eclipse/util/SWTUtils.scala
@@ -0,0 +1,62 @@
+package scala.tools.eclipse.util
+
+import org.eclipse.jface.viewers.{ DoubleClickEvent, IDoubleClickListener, SelectionChangedEvent, ISelectionChangedListener }
+import org.eclipse.swt.widgets.Control
+import org.eclipse.swt.events.{ KeyEvent, KeyAdapter, FocusAdapter, FocusEvent }
+import org.eclipse.jface.util.IPropertyChangeListener
+import org.eclipse.jface.util.PropertyChangeEvent
+import org.eclipse.swt.events.SelectionAdapter
+import org.eclipse.swt.events.SelectionEvent
+
+object SWTUtils {
+
+ implicit def fnToSelectionAdapter(p: SelectionEvent => Any): SelectionAdapter =
+ new SelectionAdapter() {
+ override def widgetSelected(e: SelectionEvent) { p(e) }
+ }
+
+ implicit def byNameToSelectionAdapter(p: => Any): SelectionAdapter =
+ new SelectionAdapter() {
+ override def widgetSelected(e: SelectionEvent) { p }
+ }
+
+ implicit def fnToPropertyChangeListener(p: PropertyChangeEvent => Any): IPropertyChangeListener =
+ new IPropertyChangeListener() {
+ def propertyChange(e: PropertyChangeEvent) { p(e) }
+ }
+
+ implicit def byNameToSelectionChangedListener(p: => Any): ISelectionChangedListener =
+ new ISelectionChangedListener {
+ def selectionChanged(event: SelectionChangedEvent) { p }
+ }
+
+ implicit def fnToDoubleClickListener(p: DoubleClickEvent => Any): IDoubleClickListener =
+ new IDoubleClickListener {
+ def doubleClick(event: DoubleClickEvent) { p(event) }
+ }
+
+ implicit def control2PimpedControl(control: Control): PimpedControl = new PimpedControl(control)
+
+ class PimpedControl(control: Control) {
+
+ def onKeyReleased(p: KeyEvent => Any) {
+ control.addKeyListener(new KeyAdapter {
+ override def keyReleased(e: KeyEvent) { p(e) }
+ })
+ }
+
+ def onKeyReleased(p: => Any) {
+ control.addKeyListener(new KeyAdapter {
+ override def keyReleased(e: KeyEvent) { p }
+ })
+ }
+
+ def onFocusLost(p: => Any) {
+ control.addFocusListener(new FocusAdapter {
+ override def focusLost(e: FocusEvent) { p }
+ })
+ }
+
+ }
+
+}
View
366 org.scala-ide.sdt.core/src/scala/tools/eclipse/wizards/AbstractNewElementWizardPage.scala
@@ -8,12 +8,29 @@ package scala.tools.eclipse.wizards
import org.eclipse.core.resources.IResource
-import org.eclipse.core.runtime.{ CoreException, FileLocator, IPath,
- IProgressMonitor, IStatus, NullProgressMonitor, Path, SubProgressMonitor }
+import org.eclipse.core.runtime.{
+ CoreException,
+ FileLocator,
+ IPath,
+ IProgressMonitor,
+ IStatus,
+ NullProgressMonitor,
+ Path,
+ SubProgressMonitor
+}
-import org.eclipse.jdt.core.{ Flags, ICompilationUnit, IJavaElement,
- IPackageFragment, IPackageFragmentRoot, IType, ITypeHierarchy,
- JavaModelException, Signature, WorkingCopyOwner }
+import org.eclipse.jdt.core.{
+ Flags,
+ ICompilationUnit,
+ IJavaElement,
+ IPackageFragment,
+ IPackageFragmentRoot,
+ IType,
+ ITypeHierarchy,
+ JavaModelException,
+ Signature,
+ WorkingCopyOwner
+}
import org.eclipse.jdt.core.dom.{ AST, ASTParser, CompilationUnit }
@@ -21,8 +38,12 @@ import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility
import org.eclipse.jdt.internal.corext.util.JavaModelUtil
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo
import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages
-import org.eclipse.jdt.internal.ui.wizards.dialogfields.{ DialogField,
- IDialogFieldListener, LayoutUtil, SelectionButtonDialogFieldGroup }
+import org.eclipse.jdt.internal.ui.wizards.dialogfields.{
+ DialogField,
+ IDialogFieldListener,
+ LayoutUtil,
+ SelectionButtonDialogFieldGroup
+}
import org.eclipse.jdt.ui.wizards.NewTypeWizardPage
@@ -39,75 +60,75 @@ import collection.mutable.Buffer
import scala.tools.eclipse.ScalaPlugin._
-abstract class AbstractNewElementWizardPage extends NewTypeWizardPage(1,"") {
-
+abstract class AbstractNewElementWizardPage extends NewTypeWizardPage(1, "") {
+
val declarationType: String
-
+
val imageName = "new" + declarationType.toLowerCase + "_wiz.gif"
val iPath = new Path("icons/full/wizban").append(imageName)
val url = FileLocator.find(plugin.getBundle, iPath, null)
-
+
setImageDescriptor(ImageDescriptor.createFromURL(url))
setTitle("Scala " + declarationType)
setDescription("Create a new Scala " + declarationType)
-
+
val PAGE_NAME = "New" + declarationType + "WizardPage"
val DEFAULT_SUPER_TYPE = "scala.AnyRef"
val SETTINGS_CREATEMAIN = "create_main"
val SETTINGS_CREATECONSTR = "create_constructor"
val SETTINGS_CREATEUNIMPLEMENTED = "create_unimplemented"
-
+
protected object dialogFieldListener extends IDialogFieldListener {
def dialogFieldChanged(field: DialogField) {
updateStatus(modifiersChanged)
}
}
-
+
val accessModifierNames = Array(
- NewWizardMessages.NewTypeWizardPage_modifiers_default,
- NewWizardMessages.NewTypeWizardPage_modifiers_protected,
- NewWizardMessages.NewTypeWizardPage_modifiers_private)
-
- val accessModifierButtons =
- new SelectionButtonDialogFieldGroup(SWT.RADIO, accessModifierNames, 3)
-
+ NewWizardMessages.NewTypeWizardPage_modifiers_default,
+ NewWizardMessages.NewTypeWizardPage_modifiers_protected,
+ NewWizardMessages.NewTypeWizardPage_modifiers_private)
+
+ val accessModifierButtons =
+ new SelectionButtonDialogFieldGroup(SWT.RADIO, accessModifierNames, 3)
+
accessModifierButtons.setDialogFieldListener(dialogFieldListener)
accessModifierButtons.setLabelText(getModifiersLabel)
accessModifierButtons.setSelection(0, true)
-
+
def defaultSelected = accessModifierButtons.isSelected(0)
def protectedSelected = accessModifierButtons.isSelected(1)
def privateSelected = accessModifierButtons.isSelected(2)
val otherModifierNames = Array(
- NewWizardMessages.NewTypeWizardPage_modifiers_abstract,
- NewWizardMessages.NewTypeWizardPage_modifiers_final)
-
- val otherModifierButtons =
- new SelectionButtonDialogFieldGroup(SWT.CHECK, otherModifierNames, 4)
-
+ NewWizardMessages.NewTypeWizardPage_modifiers_abstract,
+ NewWizardMessages.NewTypeWizardPage_modifiers_final)
+
+ val otherModifierButtons =
+ new SelectionButtonDialogFieldGroup(SWT.CHECK, otherModifierNames, 4)
+
otherModifierButtons.setDialogFieldListener(dialogFieldListener)
-
+
def abstractSelected = otherModifierButtons.isSelected(0)
def finalSelected = otherModifierButtons.isSelected(1)
-
+
val methodStubNames = Array(
- NewWizardMessages.NewClassWizardPage_methods_main,
- NewWizardMessages.NewClassWizardPage_methods_constructors,
- NewWizardMessages.NewClassWizardPage_methods_inherited)
-
- val methodStubButtons =
- new SelectionButtonDialogFieldGroup(SWT.CHECK, methodStubNames, 1)
+ NewWizardMessages.NewClassWizardPage_methods_main,
+ NewWizardMessages.NewClassWizardPage_methods_constructors,
+ NewWizardMessages.NewClassWizardPage_methods_inherited)
+
+ val methodStubButtons =
+ new SelectionButtonDialogFieldGroup(SWT.CHECK, methodStubNames, 1)
methodStubButtons.setDialogFieldListener(dialogFieldListener)
methodStubButtons.setLabelText(
- NewWizardMessages.NewClassWizardPage_methods_label)
-
+ NewWizardMessages.NewClassWizardPage_methods_label)
+
def createMainSelected = methodStubButtons.isSelected(0)
def createConstructorsSelected = methodStubButtons.isSelected(1)
def createInheritedSelected = methodStubButtons.isSelected(2)
-
- protected var createdType : IType = _
-
+
+ protected var createdType: IType = _
+
def init(selection: IStructuredSelection): Unit = {
val jelem = getInitialJavaElement(selection)
initContainerPage(jelem)
@@ -115,65 +136,64 @@ abstract class AbstractNewElementWizardPage extends NewTypeWizardPage(1,"") {
val dialogSettings = getDialogSettings()
initializeOptions(dialogSettings)
}
-
+
def initializeOptions(dialogSettings: IDialogSettings): Unit
-
+
override def getModifiers = {
var modifiers = 0
- if(privateSelected) modifiers += F_PRIVATE
- else if(protectedSelected) modifiers += F_PROTECTED
- if(abstractSelected) modifiers += F_ABSTRACT
- if(finalSelected) modifiers += F_FINAL
+ if (privateSelected) modifiers += F_PRIVATE
+ else if (protectedSelected) modifiers += F_PROTECTED
+ if (abstractSelected) modifiers += F_ABSTRACT
+ if (finalSelected) modifiers += F_FINAL
modifiers
}
-
+
override def setModifiers(modifiers: Int, canBeModified: Boolean) = {
-
- if (Flags.isPrivate(modifiers))
- accessModifierButtons.setSelection(2, true)
- else if (Flags.isProtected(modifiers))
- accessModifierButtons.setSelection(1, true)
- else
- accessModifierButtons.setSelection(0, true)
-
- if (Flags.isAbstract(modifiers))
- otherModifierButtons.setSelection(0, true)
-
- if (Flags.isFinal(modifiers))
- otherModifierButtons.setSelection(1, true)
-
- accessModifierButtons.setEnabled(canBeModified)
- otherModifierButtons.setEnabled(canBeModified)
+
+ if (Flags.isPrivate(modifiers))
+ accessModifierButtons.setSelection(2, true)
+ else if (Flags.isProtected(modifiers))
+ accessModifierButtons.setSelection(1, true)
+ else
+ accessModifierButtons.setSelection(0, true)
+
+ if (Flags.isAbstract(modifiers))
+ otherModifierButtons.setSelection(0, true)
+
+ if (Flags.isFinal(modifiers))
+ otherModifierButtons.setSelection(1, true)
+
+ accessModifierButtons.setEnabled(canBeModified)
+ otherModifierButtons.setEnabled(canBeModified)
}
-
+
override def setVisible(visible: Boolean) {
- super.setVisible(visible)
- if (visible) {
- setFocus()
- }
- else {
- val dialogSettings = getDialogSettings()
- if (dialogSettings != null) {
- var section = dialogSettings.getSection(PAGE_NAME)
- if (section == null) {
- section = dialogSettings.addNewSection(PAGE_NAME)
- }
- section.put(SETTINGS_CREATEMAIN, createMainSelected)
- section.put(SETTINGS_CREATECONSTR, createConstructorsSelected)
- section.put(SETTINGS_CREATEUNIMPLEMENTED, createInheritedSelected)
- }
+ super.setVisible(visible)
+ if (visible) {
+ setFocus()
+ } else {
+ val dialogSettings = getDialogSettings()
+ if (dialogSettings != null) {
+ var section = dialogSettings.getSection(PAGE_NAME)
+ if (section == null) {
+ section = dialogSettings.addNewSection(PAGE_NAME)
+ }
+ section.put(SETTINGS_CREATEMAIN, createMainSelected)
+ section.put(SETTINGS_CREATECONSTR, createConstructorsSelected)
+ section.put(SETTINGS_CREATEUNIMPLEMENTED, createInheritedSelected)
+ }
}
}
-
+
private def doStatusUpdate() {
- val parentStatus = if(isEnclosingTypeSelected) fEnclosingTypeStatus
- else fPackageStatus
-
- val status = Array(fContainerStatus, parentStatus, fTypeNameStatus,
- fModifierStatus, fSuperClassStatus,
- fSuperInterfacesStatus)
-
- // the mode severe status will be displayed and the OK button
+ val parentStatus = if (isEnclosingTypeSelected) fEnclosingTypeStatus
+ else fPackageStatus
+
+ val status = Array(fContainerStatus, parentStatus, fTypeNameStatus,
+ fModifierStatus, fSuperClassStatus,
+ fSuperInterfacesStatus)
+
+ // the mode severe status will be displayed and the OK button
// enabled/disabled.
updateStatus(status);
}
@@ -186,30 +206,30 @@ abstract class AbstractNewElementWizardPage extends NewTypeWizardPage(1,"") {
doStatusUpdate()
}
- override protected def getSuperInterfacesLabel(): String =
+ override protected def getSuperInterfacesLabel(): String =
"Traits and \nInterfaces:"
-
+
override protected def createModifierControls(composite: Composite, columns: Int) = {
LayoutUtil.setHorizontalSpan(accessModifierButtons.getLabelControl(composite), 1)
val control1 = accessModifierButtons.getSelectionButtonsGroup(composite)
- val gd1 = new GridData(GridData.HORIZONTAL_ALIGN_FILL)
- gd1.horizontalSpan = columns - 2
- control1.setLayoutData(gd1)
- DialogField.createEmptySpace(composite)
+ val gd1 = new GridData(GridData.HORIZONTAL_ALIGN_FILL)
+ gd1.horizontalSpan = columns - 2
+ control1.setLayoutData(gd1)
+ DialogField.createEmptySpace(composite)
- specifyModifierControls(composite, columns)
+ specifyModifierControls(composite, columns)
}
-
+
def specifyModifierControls(composite: Composite, columns: Int): Unit
-
+
protected def createMethodStubSelectionControls(composite: Composite, columns: Int) {
val labelControl = methodStubButtons.getLabelControl(composite)
- LayoutUtil.setHorizontalSpan(labelControl, columns)
+ LayoutUtil.setHorizontalSpan(labelControl, columns)
DialogField.createEmptySpace(composite)
- val buttonGroup= methodStubButtons.getSelectionButtonsGroup(composite)
- LayoutUtil.setHorizontalSpan(buttonGroup, columns - 1)
+ val buttonGroup = methodStubButtons.getSelectionButtonsGroup(composite)
+ LayoutUtil.setHorizontalSpan(buttonGroup, columns - 1)
}
-
+
/*
* Override to pick the UI components relevant for a Scala elements
*/
@@ -231,7 +251,7 @@ abstract class AbstractNewElementWizardPage extends NewTypeWizardPage(1,"") {
createSeparator(composite, columns)
createTypeNameControls(composite, columns)
- createModifierControls(composite, columns)
+ createModifierControls(composite, columns)
createSuperClassControls(composite, columns)
setSuperClass(DEFAULT_SUPER_TYPE, true)
@@ -244,79 +264,79 @@ abstract class AbstractNewElementWizardPage extends NewTypeWizardPage(1,"") {
Dialog.applyDialogFont(composite)
}
-
+
protected def makeCreatedType(implicit parentCU: ICompilationUnit)
/* (non-Javadoc)
* @see org.eclipse.jdt.ui.wizards.NewTypeWizardPage#createType(org.eclipse.core.runtime.IProgressMonitor)
*/
override def createType(progressMonitor: IProgressMonitor): Unit = {
-
- def reconcile(cu: ICompilationUnit,
- astLevel: Int = ICompilationUnit.NO_AST,
- forceProblemDetection: Boolean = false,
- enableStatementsRecovery: Boolean = false,
- workingCopyOwner: WorkingCopyOwner = null,
- monitor: IProgressMonitor = null): Unit = {
- cu.reconcile(astLevel, forceProblemDetection,
- enableStatementsRecovery, workingCopyOwner, monitor)
- }
-
- def superTypes: List[String] = {
+
+ def reconcile(cu: ICompilationUnit,
+ astLevel: Int = ICompilationUnit.NO_AST,
+ forceProblemDetection: Boolean = false,
+ enableStatementsRecovery: Boolean = false,
+ workingCopyOwner: WorkingCopyOwner = null,
+ monitor: IProgressMonitor = null): Unit = {
+ cu.reconcile(astLevel, forceProblemDetection,
+ enableStatementsRecovery, workingCopyOwner, monitor)
+ }
+
+ def superTypes: List[String] = {
import scala.collection.JavaConversions._
val javaArrayList = getSuperInterfaces
val jual = javaArrayList.toArray(new Array[String](javaArrayList.size))
(getSuperClass +: jual).toList
}
-
- val monitor = if (progressMonitor == null) new NullProgressMonitor()
- else progressMonitor
-
+
+ val monitor = if (progressMonitor == null) new NullProgressMonitor()
+ else progressMonitor
+
monitor.beginTask(NewWizardMessages.NewTypeWizardPage_operationdesc, 8)
implicit val packageFragment = {
val rt = getPackageFragmentRoot
val pf = getPackageFragment
- var p = pf match {
+ var p = pf match {
case ipf: IPackageFragment => ipf
- case _ => rt.getPackageFragment("")
+ case _ => rt.getPackageFragment("")
}
p.exists match {
case true => monitor.worked(1)
- case _ => p = rt.createPackageFragment(pf.getElementName, true,
- new SubProgressMonitor(monitor, 1))
+ case _ => p = rt.createPackageFragment(pf.getElementName, true,
+ new SubProgressMonitor(monitor, 1))
}
p
}
-
+
val packageName = {
!packageFragment.isDefaultPackage match {
case true => Some(packageFragment.getElementName)
case _ => None
}
}
-
+
implicit val ld = StubUtility.getLineDelimiterUsed(
- packageFragment.getJavaProject)
+ packageFragment.getJavaProject)
val typeName = getTypeNameWithoutParameters
val cuName = getCompilationUnitName(typeName)
try {
-
+
val parentCU = packageFragment.createCompilationUnit(
- cuName, "", false, new SubProgressMonitor(monitor, 2))
-
+ cuName, "", false, new SubProgressMonitor(monitor, 2))
+
parentCU.becomeWorkingCopy(new SubProgressMonitor(monitor, 1))
import CodeBuilder._
-
+
type CommentGetter = (ICompilationUnit, String) => String
def comment(cg: CommentGetter): Option[String] = {
val s = cg(parentCU, ld)
toOption(in = s)(guard = s != null && s.nonEmpty)
}
-
+
def elementModifiers = {
val mods = getModifiers
mods match {
@@ -324,57 +344,55 @@ abstract class AbstractNewElementWizardPage extends NewTypeWizardPage(1,"") {
case _ => Flags.toString(mods) + " "
}
}
-
+
import templates._
// generate basic element skeleton
-
+
val buffer = parentCU.getBuffer
//start control of buffer
val cb = CodeBuilder(packageName.getOrElse(""), superTypes, buffer)
cb.append(commentTemplate(comment(getFileComment _)))
cb.append(packageTemplate(packageName))
- cb.writeImports// to buffer
+ cb.writeImports // to buffer
cb.append(commentTemplate(comment(getTypeComment _)))
cb.append(elementModifiers)
cb.append(declarationType.toLowerCase)
cb.createElementDeclaration(getTypeName, superTypes, buffer)
cb.append(bodyStub)
-
+
reconcile(cu = parentCU)
-
+
makeCreatedType(parentCU)
// refine the created type
val typeHierarchy = createdType.newSupertypeHierarchy(Array(parentCU),
- new SubProgressMonitor(monitor, 1))
-
+ new SubProgressMonitor(monitor, 1))
+
cb.finishReWrites(typeHierarchy, createdType)(
- createConstructorsSelected)(createInheritedSelected)(
- createMainSelected)
-
+ createConstructorsSelected)(createInheritedSelected)(
+ createMainSelected)
+
//end control of buffer
-
+
val cu = createdType.getCompilationUnit
reconcile(cu = cu)
-
+
if (monitor.isCanceled) throw new InterruptedException()
cu.commitWorkingCopy(true, new SubProgressMonitor(monitor, 1))
parentCU.discardWorkingCopy
- }
- catch {
+ } catch {
case ex: JavaModelException => println("<<<<<<< Error >>>>>>>\n" + ex)
- }
- finally {
+ } finally {
monitor done
}
}
protected def getTypeNameWithoutParameters() = getTypeName.split('[')(0)
-
+
override def getCompilationUnitName(typeName: String) = typeName + ".scala"
-
+
/*
* Override because getTypeNameWithoutParameters is a private method in
* superclass
@@ -383,52 +401,50 @@ abstract class AbstractNewElementWizardPage extends NewTypeWizardPage(1,"") {
*/
override def getModifiedResource(): IResource = {
val enclosing = getEnclosingType()
- if (enclosing != null) {
- return enclosing.getResource()
- }
- val pack = getPackageFragment()
- if (pack != null) {
- val cuName = getCompilationUnitName(getTypeNameWithoutParameters())
- return pack.getCompilationUnit(cuName).getResource()
- }
- null
+ if (enclosing != null) {
+ return enclosing.getResource()
+ }
+ val pack = getPackageFragment()
+ if (pack != null) {
+ val cuName = getCompilationUnitName(getTypeNameWithoutParameters())
+ return pack.getCompilationUnit(cuName).getResource()
+ }
+ null
}
override def getCreatedType() = createdType
-
+
override protected def typeNameChanged(): IStatus = {
-
+
var status = super.typeNameChanged.asInstanceOf[StatusInfo]
println(">>>> Status = " + status)
val pack = getPackageFragment
-
+
if (pack != null) {
-
+
val project = pack.getJavaProject
-
+
try {
- if(!plugin.isScalaProject(project.getProject)) {
+ if (!plugin.isScalaProject(project.getProject)) {
val msg = project.getElementName + " is not a Scala project"