1
0
Fork 0
mirror of https://github.com/eclipse-cdt/cdt synced 2025-04-29 19:45:01 +02:00

Bug 95274 - Support code formatter

First stab at a built-in code formatter
This commit is contained in:
Anton Leherbauer 2006-11-10 13:55:48 +00:00
parent 665fdd2ca8
commit 12f3dd59c5
48 changed files with 10784 additions and 3859 deletions

View file

@ -39,3 +39,5 @@ org.eclipse.cdt.core/debug/pdomtimings=false
# Reports sequence of files indexed
org.eclipse.cdt.core/debug/indexer=false
# Code formatter debugging
org.eclipse.cdt.core/debug/formatter=false

View file

@ -56,6 +56,7 @@ Export-Package: org.eclipse.cdt.core,
org.eclipse.cdt.internal.errorparsers;x-internal:=true,
org.eclipse.cdt.internal.formatter;x-internal:=true,
org.eclipse.cdt.internal.formatter.align;x-internal:=true,
org.eclipse.cdt.internal.formatter.scanner,
org.eclipse.cdt.utils,
org.eclipse.cdt.utils.coff,
org.eclipse.cdt.utils.coff.parser,

View file

@ -1,5 +1,5 @@
/*******************************************************************************
* Copyright (c) 2000, 2005 QNX Software Systems and others.
* Copyright (c) 2000, 2006 QNX Software Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
@ -7,6 +7,7 @@
*
* Contributors:
* QNX Software Systems - Initial API and implementation
* Anton Leherbauer (Wind River Systems)
*******************************************************************************/
package org.eclipse.cdt.core;
@ -26,12 +27,15 @@ import org.eclipse.core.runtime.Platform;
public class ToolFactory {
/**
* Create an instance of the built-in code formatter.
* @param options - the options map to use for formatting with the default code formatter. Recognized options
* are documented on <code>CCorePlugin#getDefaultOptions()</code>. If set to <code>null</code>, then use
* the current settings from <code>CCorePlugin#getOptions</code>.
* @return an instance of the built-in code formatter
* Create an instance of a code formatter. A code formatter implementation can be contributed via the
* extension point "org.eclipse.cdt.core.CodeFormatter". If unable to find a registered extension, the factory
* will default to using the default code formatter.
* @param options - the options map to use for formatting with the code formatter. Recognized options
* are documented on <code>DefaultCodeFormatterConstants</code>. If set to <code>null</code>, then use
* the current settings from <code>CCorePlugin.getOptions()</code>.
* @return an instance of either a contributed the built-in code formatter
* @see CodeFormatter
* @see DefaultCodeFormatterConstants
* @see CCorePlugin#getOptions()
*/
public static CodeFormatter createCodeFormatter(Map options){
@ -55,21 +59,30 @@ public class ToolFactory {
return formatter;
}
} catch(CoreException e) {
//TODO: add more reasonable error processing
e.printStackTrace();
CCorePlugin.log(e.getStatus());
break;
}
}
}
}
}
// TODO: open this code later
// return new DefaultCodeFormatter(options);
return null;
}
}
return createDefaultCodeFormatter(options);
}
public static CodeFormatter createDefaultCodeFormatter(Map options){
if (options == null) options = CCorePlugin.getOptions();
return new CCodeFormatter(options);
}
/**
* Create an instance of the built-in code formatter.
*
* @param options - the options map to use for formatting with the default code formatter. Recognized options
* are documented on <code>DefaultCodeFormatterConstants</code>. If set to <code>null</code>, then use
* the current settings from <code>CCorePlugin.getOptions()</code>.
* @return an instance of the built-in code formatter
* @see CodeFormatter
* @see DefaultCodeFormatterConstants
* @see CCorePlugin#getOptions()
*/
public static CodeFormatter createDefaultCodeFormatter(Map options){
if (options == null)
options = CCorePlugin.getOptions();
return new CCodeFormatter(options);
}
}

View file

@ -36,7 +36,7 @@ public class CCorePreferenceInitializer extends AbstractPreferenceInitializer {
HashSet optionNames = CModelManager.OptionNames;
// Formatter settings
Map defaultOptionsMap = DefaultCodeFormatterConstants.getEclipseDefaultSettings(); // code formatter defaults
Map defaultOptionsMap = DefaultCodeFormatterConstants.getDefaultSettings(); // code formatter defaults
// Compiler settings
defaultOptionsMap.put(CCorePreferenceConstants.TRANSLATION_TASK_TAGS, CCorePreferenceConstants.DEFAULT_TASK_TAG);

View file

@ -0,0 +1,32 @@
/*******************************************************************************
* Copyright (c) 2000, 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Anton Leherbauer (Wind River Systems)
*******************************************************************************/
package org.eclipse.cdt.internal.formatter;
/**
* Unchecked exception wrapping invalid input checked exception which may occur
* when scanning original formatted source.
*
* @since 4.0
*/
public class AbortFormatting extends RuntimeException {
private static final long serialVersionUID= -5796507276311428526L;
Throwable nestedException;
public AbortFormatting(String message) {
super(message);
}
public AbortFormatting(Throwable nestedException) {
super(nestedException.getMessage());
this.nestedException = nestedException;
}
}

View file

@ -8,89 +8,168 @@
* Contributors:
* QNX Software Systems - Initial API and implementation
* Sergey Prigogin, Google
* Anton Leherbauer (Wind River Systems)
*******************************************************************************/
package org.eclipse.cdt.internal.formatter;
import java.util.Map;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.dom.ICodeReaderFactory;
import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit;
import org.eclipse.cdt.core.dom.ast.gnu.cpp.GPPLanguage;
import org.eclipse.cdt.core.formatter.CodeFormatter;
import org.eclipse.cdt.core.formatter.DefaultCodeFormatterConstants;
import org.eclipse.cdt.core.index.IIndex;
import org.eclipse.cdt.core.model.CoreModel;
import org.eclipse.cdt.core.model.ILanguage;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.core.parser.CodeReader;
import org.eclipse.cdt.core.parser.IScannerInfo;
import org.eclipse.cdt.core.parser.ScannerInfo;
import org.eclipse.cdt.internal.core.dom.SavedCodeReaderFactory;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.text.edits.TextEdit;
public class CCodeFormatter extends CodeFormatter {
private DefaultCodeFormatterOptions preferences;
public CCodeFormatter() {
this(new DefaultCodeFormatterOptions(DefaultCodeFormatterConstants.getEclipseDefaultSettings()), null);
}
public CCodeFormatter(DefaultCodeFormatterOptions preferences) {
this(preferences, null);
}
public CCodeFormatter(DefaultCodeFormatterOptions defaultCodeFormatterOptions, Map options) {
setOptions(options);
if (defaultCodeFormatterOptions != null) {
preferences.set(defaultCodeFormatterOptions.getMap());
}
}
private DefaultCodeFormatterOptions preferences;
private Map options;
public CCodeFormatter(Map options) {
this(null, options);
}
public String createIndentationString(final int indentationLevel) {
if (indentationLevel < 0) {
throw new IllegalArgumentException();
}
int tabs = 0;
int spaces = 0;
switch (preferences.tab_char) {
case DefaultCodeFormatterOptions.SPACE :
spaces = indentationLevel * preferences.tab_size;
break;
case DefaultCodeFormatterOptions.TAB :
tabs = indentationLevel;
break;
case DefaultCodeFormatterOptions.MIXED :
int tabSize = preferences.tab_size;
int spaceEquivalents = indentationLevel * preferences.indentation_size;
tabs = spaceEquivalents / tabSize;
spaces = spaceEquivalents % tabSize;
break;
default:
return EMPTY_STRING;
}
if (tabs == 0 && spaces == 0) {
return EMPTY_STRING;
}
StringBuffer buffer = new StringBuffer(tabs + spaces);
for (int i = 0; i < tabs; i++) {
buffer.append('\t');
}
for(int i = 0; i < spaces; i++) {
buffer.append(' ');
}
return buffer.toString();
}
public CCodeFormatter() {
this(DefaultCodeFormatterOptions.getDefaultSettings());
}
public void setOptions(Map options) {
if (options != null) {
preferences = new DefaultCodeFormatterOptions(options);
} else {
preferences = new DefaultCodeFormatterOptions(DefaultCodeFormatterConstants.getEclipseDefaultSettings());
}
}
public CCodeFormatter(DefaultCodeFormatterOptions preferences) {
this(preferences, null);
}
public TextEdit format(int kind, String source, int offset, int length, int indentationLevel, String lineSeparator) {
// TODO Not implemented yet
return null;
}
public CCodeFormatter(DefaultCodeFormatterOptions defaultCodeFormatterOptions, Map options) {
setOptions(options);
if (defaultCodeFormatterOptions != null) {
preferences.set(defaultCodeFormatterOptions.getMap());
}
}
public CCodeFormatter(Map options) {
this(null, options);
}
public String createIndentationString(final int indentationLevel) {
if (indentationLevel < 0) {
throw new IllegalArgumentException();
}
int tabs= 0;
int spaces= 0;
switch (preferences.tab_char) {
case DefaultCodeFormatterOptions.SPACE:
spaces= indentationLevel * preferences.tab_size;
break;
case DefaultCodeFormatterOptions.TAB:
tabs= indentationLevel;
break;
case DefaultCodeFormatterOptions.MIXED:
int tabSize= preferences.tab_size;
int spaceEquivalents= indentationLevel
* preferences.indentation_size;
tabs= spaceEquivalents / tabSize;
spaces= spaceEquivalents % tabSize;
break;
default:
return EMPTY_STRING;
}
if (tabs == 0 && spaces == 0) {
return EMPTY_STRING;
}
StringBuffer buffer= new StringBuffer(tabs + spaces);
for (int i= 0; i < tabs; i++) {
buffer.append('\t');
}
for (int i= 0; i < spaces; i++) {
buffer.append(' ');
}
return buffer.toString();
}
public void setOptions(Map options) {
if (options != null) {
this.options= options;
preferences= new DefaultCodeFormatterOptions(options);
} else {
this.options= CCorePlugin.getOptions();
preferences= DefaultCodeFormatterOptions.getDefaultSettings();
}
}
/*
* @see org.eclipse.cdt.core.formatter.CodeFormatter#format(int, java.lang.String, int, int, int, java.lang.String)
*/
public TextEdit format(int kind, String source, int offset, int length, int indentationLevel, String lineSeparator) {
TextEdit edit= null;
ITranslationUnit tu= (ITranslationUnit)options.get(DefaultCodeFormatterConstants.FORMATTER_TRANSLATION_UNIT);
if (tu == null) {
IFile file= (IFile)options.get(DefaultCodeFormatterConstants.FORMATTER_CURRENT_FILE);
if (file != null) {
tu= (ITranslationUnit)CoreModel.getDefault().create(file);
}
}
if (lineSeparator != null) {
this.preferences.line_separator = lineSeparator;
} else {
this.preferences.line_separator = System.getProperty("line.separator");
}
this.preferences.initial_indentation_level = indentationLevel;
if (tu != null) {
IIndex index;
try {
index = CCorePlugin.getIndexManager().getIndex(tu.getCProject());
index.acquireReadLock();
} catch (CoreException e) {
throw new AbortFormatting(e);
} catch (InterruptedException e) {
return null;
}
IASTTranslationUnit ast;
try {
try {
ast= tu.getAST(index, ITranslationUnit.AST_SKIP_ALL_HEADERS);
} catch (CoreException exc) {
throw new AbortFormatting(exc);
}
CodeFormatterVisitor codeFormatter = new CodeFormatterVisitor(this.preferences, this.options, offset, length);
edit= codeFormatter.format(source, ast);
} finally {
index.releaseReadLock();
}
} else {
ICodeReaderFactory codeReaderFactory;
codeReaderFactory = SavedCodeReaderFactory.getInstance();
IScannerInfo scanInfo = new ScannerInfo();
CodeReader reader;
reader= new CodeReader(source.toCharArray());
ILanguage language= (ILanguage)options.get(DefaultCodeFormatterConstants.FORMATTER_LANGUAGE);
if (language == null) {
language= GPPLanguage.getDefault();
}
IASTTranslationUnit ast;
try {
ast= language.getASTTranslationUnit(reader, scanInfo, codeReaderFactory, null);
CodeFormatterVisitor codeFormatter = new CodeFormatterVisitor(this.preferences, this.options, offset, length);
edit= codeFormatter.format(source, ast);
} catch (CoreException exc) {
throw new AbortFormatting(exc);
}
}
return edit;
}
}

View file

@ -0,0 +1,54 @@
/*******************************************************************************
* Copyright (c) 2000, 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Anton Leherbauer (Wind River Systems)
*******************************************************************************/
package org.eclipse.cdt.internal.formatter;
/**
* A location maintains positional information both in original source
* and in the output source.
* It remembers source offsets, line/column and indentation level.
*
* @since 4.0
*/
public class Location {
public int inputOffset;
public int outputLine;
public int outputColumn;
public int outputIndentationLevel;
public boolean needSpace;
public boolean pendingSpace;
public int numberOfIndentations;
// chunk management
public int lastNumberOfNewLines;
// edits management
int editsIndex;
OptimizedReplaceEdit textEdit;
public Location(Scribe scribe, int sourceRestart){
update(scribe, sourceRestart);
}
public void update(Scribe scribe, int sourceRestart){
this.outputColumn = scribe.column;
this.outputLine = scribe.line;
this.inputOffset = sourceRestart;
this.outputIndentationLevel = scribe.indentationLevel;
this.lastNumberOfNewLines = scribe.lastNumberOfNewLines;
this.needSpace = scribe.needSpace;
this.pendingSpace = scribe.pendingSpace;
this.editsIndex = scribe.editsIndex;
this.numberOfIndentations = scribe.numberOfIndentations;
textEdit = scribe.getLastEdit();
}
}

View file

@ -0,0 +1,28 @@
/*******************************************************************************
* Copyright (c) 2000, 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.formatter;
public class OptimizedReplaceEdit {
int offset;
int length;
String replacement;
public OptimizedReplaceEdit(int offset, int length, String replacement) {
this.offset = offset;
this.length = length;
this.replacement = replacement;
}
public String toString() {
return "(" + this.offset + ", length " + this.length + " :>" + this.replacement + "<"; //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$
}
}

File diff suppressed because it is too large Load diff

View file

@ -10,9 +10,14 @@
*******************************************************************************/
package org.eclipse.cdt.internal.formatter.align;
import org.eclipse.cdt.internal.formatter.Location;
import org.eclipse.cdt.internal.formatter.Scribe;
/**
* Alignment management
*
* @since 4.0
*/
public class Alignment {
@ -22,6 +27,9 @@ public class Alignment {
// link to enclosing alignment
public Alignment enclosing;
// start location of this alignment
public Location location;
// indentation management
public int fragmentIndex;
public int fragmentCount;
@ -39,6 +47,8 @@ public class Alignment {
public int[] fragmentBreaks;
public boolean wasSplit;
public Scribe scribe;
/*
* Alignment modes
*/
@ -56,7 +66,7 @@ public class Alignment {
/** foobar(<ul>
* <li> #fragment1, #fragment2, </li>
* <li> #fragment5, #fragment4, </li>
* <li> #fragment5, #fragment4, </li>
* </ul>
*/
public static final int M_COMPACT_FIRST_BREAK_SPLIT = 32; // compact mode, but will first try to break before first fragment
@ -72,10 +82,10 @@ public class Alignment {
/**
* foobar(<ul>
* <li> #fragment1, </li>
* <li> #fragment2, </li>
* <li> #fragment3 </li>
* <li> #fragment4, </li>
* <li> #fragment1, </li>
* <li> #fragment2, </li>
* <li> #fragment3, </li>
* <li> #fragment4, </li>
* </ul>
*/
public static final int M_NEXT_SHIFTED_SPLIT = 64; // one fragment per line, subsequent are indented further
@ -121,4 +131,288 @@ public class Alignment {
public static final int CHUNK_METHOD = 2;
public static final int CHUNK_TYPE = 3;
public static final int CHUNK_ENUM = 4;
// location to align and break on.
public Alignment(String name, int mode, int tieBreakRule, Scribe scribe, int fragmentCount, int sourceRestart, int continuationIndent){
this.name = name;
this.location = new Location(scribe, sourceRestart);
this.mode = mode;
this.tieBreakRule = tieBreakRule;
this.fragmentCount = fragmentCount;
this.scribe = scribe;
this.originalIndentationLevel = this.scribe.indentationLevel;
this.wasSplit = false;
// initialize the break indentation level, using modes and continuationIndentationLevel preference
final int indentSize = this.scribe.indentationSize;
int currentColumn = this.location.outputColumn;
if (currentColumn == 1) {
currentColumn = this.location.outputIndentationLevel + 1;
}
if ((mode & M_INDENT_ON_COLUMN) != 0) {
// indent broken fragments at next indentation level, based on current column
this.breakIndentationLevel = this.scribe.getNextIndentationLevel(currentColumn);
if (this.breakIndentationLevel == this.location.outputIndentationLevel) {
this.breakIndentationLevel += (continuationIndent * indentSize);
}
} else if ((mode & M_INDENT_BY_ONE) != 0) {
// indent broken fragments exactly one level deeper than current indentation
this.breakIndentationLevel = this.location.outputIndentationLevel + indentSize;
} else {
this.breakIndentationLevel = this.location.outputIndentationLevel + continuationIndent * indentSize;
}
this.shiftBreakIndentationLevel = this.breakIndentationLevel + indentSize;
this.fragmentIndentations = new int[this.fragmentCount];
this.fragmentBreaks = new int[this.fragmentCount];
// check for forced alignments
if ((this.mode & M_FORCE) != 0) {
couldBreak();
}
}
public boolean checkChunkStart(int kind, int startIndex, int sourceRestart) {
if (this.chunkKind != kind) {
this.chunkKind = kind;
// when redoing same chunk alignment, must not reset
if (startIndex != this.chunkStartIndex) {
this.chunkStartIndex = startIndex;
this.location.update(this.scribe, sourceRestart);
reset();
}
return true;
}
return false;
}
public void checkColumn() {
if ((this.mode & M_MULTICOLUMN) != 0) {
int currentIndentation = this.scribe.getNextIndentationLevel(this.scribe.column+(this.scribe.needSpace ? 1 : 0));
int fragmentIndentation = this.fragmentIndentations[this.fragmentIndex];
if (currentIndentation > fragmentIndentation) {
this.fragmentIndentations[this.fragmentIndex] = currentIndentation;
if (fragmentIndentation != 0) {
for (int i = this.fragmentIndex+1; i < this.fragmentCount; i++) {
this.fragmentIndentations[i] = 0;
}
this.needRedoColumnAlignment = true;
}
}
// backtrack only once all fragments got checked
if (this.needRedoColumnAlignment && this.fragmentIndex == this.fragmentCount-1) { // alignment too small
// if (CodeFormatterVisitor.DEBUG){
// System.out.println("ALIGNMENT TOO SMALL");
// System.out.println(this);
// }
this.needRedoColumnAlignment = false;
int relativeDepth = 0;
Alignment targetAlignment = this.scribe.memberAlignment;
while (targetAlignment != null){
if (targetAlignment == this){
throw new AlignmentException(AlignmentException.ALIGN_TOO_SMALL, relativeDepth);
}
targetAlignment = targetAlignment.enclosing;
relativeDepth++;
}
}
}
}
public boolean couldBreak(){
int i;
switch(mode & SPLIT_MASK){
/* # aligned fragment
* foo(
* #AAAAA, #BBBBB,
* #CCCC);
*/
case M_COMPACT_FIRST_BREAK_SPLIT :
if (this.fragmentBreaks[0] == NONE) {
this.fragmentBreaks[0] = BREAK;
this.fragmentIndentations[0] = this.breakIndentationLevel;
return wasSplit = true;
}
i = this.fragmentIndex;
do {
if (this.fragmentBreaks[i] == NONE) {
this.fragmentBreaks[i] = BREAK;
this.fragmentIndentations[i] = this.breakIndentationLevel;
return wasSplit = true;
}
} while (--i >= 0);
break;
/* # aligned fragment
* foo(#AAAAA, #BBBBB,
* #CCCC);
*/
case M_COMPACT_SPLIT :
i = this.fragmentIndex;
do {
if (this.fragmentBreaks[i] == NONE) {
this.fragmentBreaks[i] = BREAK;
this.fragmentIndentations[i] = this.breakIndentationLevel;
return wasSplit = true;
}
} while (--i >= 0);
break;
/* # aligned fragment
* foo(
* #AAAAA,
* #BBBBB,
* #CCCC);
*/
case M_NEXT_SHIFTED_SPLIT :
if (this.fragmentBreaks[0] == NONE) {
this.fragmentBreaks[0] = BREAK;
this.fragmentIndentations[0] = this.breakIndentationLevel;
for (i = 1; i < this.fragmentCount; i++){
this.fragmentBreaks[i] = BREAK;
this.fragmentIndentations[i] = this.shiftBreakIndentationLevel;
}
return wasSplit = true;
}
break;
/* # aligned fragment
* foo(
* #AAAAA,
* #BBBBB,
* #CCCC);
*/
case M_ONE_PER_LINE_SPLIT :
if (this.fragmentBreaks[0] == NONE) {
for (i = 0; i < this.fragmentCount; i++){
this.fragmentBreaks[i] = BREAK;
this.fragmentIndentations[i] = this.breakIndentationLevel;
}
return wasSplit = true;
}
/* # aligned fragment
* foo(#AAAAA,
* #BBBBB,
* #CCCC);
*/
case M_NEXT_PER_LINE_SPLIT :
if (this.fragmentBreaks[0] == NONE) {
if (this.fragmentCount > 1
&& this.fragmentBreaks[1] == NONE) {
if ((this.mode & M_INDENT_ON_COLUMN) != 0) {
this.fragmentIndentations[0] = this.breakIndentationLevel;
}
for (i = 1; i < this.fragmentCount; i++) {
this.fragmentBreaks[i] = BREAK;
this.fragmentIndentations[i] = this.breakIndentationLevel;
}
return wasSplit = true;
}
}
break;
}
return false; // cannot split better
}
public Alignment getAlignment(String targetName) {
if (targetName.equals(this.name)) return this;
if (this.enclosing == null) return null;
return this.enclosing.getAlignment(targetName);
}
// perform alignment effect for current fragment
public void performFragmentEffect(){
if ((this.mode & M_MULTICOLUMN) == 0) {
switch(this.mode & SPLIT_MASK) {
case Alignment.M_COMPACT_SPLIT :
case Alignment.M_COMPACT_FIRST_BREAK_SPLIT :
case Alignment.M_NEXT_PER_LINE_SPLIT :
case Alignment.M_NEXT_SHIFTED_SPLIT :
case Alignment.M_ONE_PER_LINE_SPLIT :
break;
default:
return;
}
}
if (this.fragmentBreaks[this.fragmentIndex] == BREAK) {
this.scribe.printNewLine();
}
if (this.fragmentIndentations[this.fragmentIndex] > 0) {
this.scribe.indentationLevel = this.fragmentIndentations[this.fragmentIndex];
}
}
// reset fragment indentation/break status
public void reset() {
if (fragmentCount > 0){
this.fragmentIndentations = new int[this.fragmentCount];
this.fragmentBreaks = new int[this.fragmentCount];
}
// check for forced alignments
if ((mode & M_FORCE) != 0) {
couldBreak();
}
}
public void toFragmentsString(StringBuffer buffer){
// default implementation
}
public String toString() {
StringBuffer buffer = new StringBuffer(10);
buffer
.append(getClass().getName())
.append(':')
.append("<name: ") //$NON-NLS-1$
.append(this.name)
.append(">"); //$NON-NLS-1$
if (this.enclosing != null) {
buffer
.append("<enclosingName: ") //$NON-NLS-1$
.append(this.enclosing.name)
.append('>');
}
buffer.append('\n');
for (int i = 0; i < this.fragmentCount; i++){
buffer
.append(" - fragment ") //$NON-NLS-1$
.append(i)
.append(": ") //$NON-NLS-1$
.append("<break: ") //$NON-NLS-1$
.append(this.fragmentBreaks[i] > 0 ? "YES" : "NO") //$NON-NLS-1$ //$NON-NLS-2$
.append(">") //$NON-NLS-1$
.append("<indent: ") //$NON-NLS-1$
.append(this.fragmentIndentations[i])
.append(">\n"); //$NON-NLS-1$
}
buffer.append('\n');
return buffer.toString();
}
public void update() {
for (int i = 1; i < this.fragmentCount; i++){
if (this.fragmentBreaks[i] == BREAK) {
this.fragmentIndentations[i] = this.breakIndentationLevel;
}
}
}
public boolean isWrapped() {
for (int i = 0, max = this.fragmentCount; i < max; i++) {
if (this.fragmentBreaks[i] == BREAK) {
return true;
}
}
return false;
}
}

View file

@ -0,0 +1,55 @@
/*******************************************************************************
* Copyright (c) 2000, 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.formatter.align;
/**
* Exception used to backtrack and break available alignments
* When the exception is thrown, it is assumed that some alignment will be changed.
*
* @since 4.0
*/
public class AlignmentException extends RuntimeException {
private static final long serialVersionUID= -1081237230006524966L;
public static final int LINE_TOO_LONG = 1;
public static final int ALIGN_TOO_SMALL = 2;
int reason;
int value;
public int relativeDepth;
public AlignmentException(int reason, int relativeDepth) {
this(reason, 0, relativeDepth);
}
public AlignmentException(int reason, int value, int relativeDepth) {
this.reason = reason;
this.value = value;
this.relativeDepth = relativeDepth;
}
public String toString(){
StringBuffer buffer = new StringBuffer(10);
switch(this.reason){
case LINE_TOO_LONG :
buffer.append("LINE_TOO_LONG"); //$NON-NLS-1$
break;
case ALIGN_TOO_SMALL :
buffer.append("ALIGN_TOO_SMALL"); //$NON-NLS-1$
break;
}
buffer
.append("<relativeDepth: ") //$NON-NLS-1$
.append(this.relativeDepth)
.append(">\n"); //$NON-NLS-1$
return buffer.toString();
}
}

View file

@ -0,0 +1,211 @@
/*******************************************************************************
* Copyright (c) 2006 Wind River Systems, Inc. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Anton Leherbauer (Wind River Systems) - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.formatter.scanner;
import java.io.CharArrayReader;
import java.io.Reader;
import org.eclipse.cdt.internal.core.CharOperation;
/**
* A scanner operating on a character array and allowing to reposition the scanner.
*
* @since 4.0
*/
public class Scanner extends SimpleScanner {
public char[] source;
public int eofPosition;
public int startPosition;
public Scanner() {
setReuseToken(true);
setSplitPreprocessor(false);
}
/*
* @see org.eclipse.cdt.internal.formatter.scanner.SimpleScanner#init(java.io.Reader, java.lang.String)
*/
protected void init(Reader reader, String filename) {
// not allowed
throw new UnsupportedOperationException();
}
/**
* Set the source text as character array.
*
* @param source the source text
*/
public void setSource(char[] source) {
this.source= source;
fContext= new ScannerContext().initialize(new CharArrayReader(source));
startPosition= -1;
eofPosition= source.length;
}
/**
* Reset scanner to given inclusive start and end offsets
* @param start inclusive start offset
* @param end inclusive end offset
*/
public void resetTo(int start, int end) {
Reader reader;
if (end >= source.length-1) {
reader= new CharArrayReader(source);
} else {
reader= new CharArrayReader(source, 0, Math.min(source.length, end+1));
}
fContext= new ScannerContext().initialize(reader, start);
startPosition= start;
if (source != null && source.length < end) {
eofPosition = source.length;
} else {
eofPosition = end < Integer.MAX_VALUE ? end + 1 : end;
}
}
/**
* Get the start offset of the current token.
* @return the start offset of the current token
*/
public int getCurrentTokenStartPosition() {
return fCurrentToken.offset;
}
/**
* Get the inclusive end offset of the current token.
* @return the inclusive end offset of the current token
*/
public int getCurrentTokenEndPosition() {
return getCurrentPosition() - 1;
}
/**
* Get the current scanner offset.
* @return the current scanner offset
*/
public int getCurrentPosition() {
return fContext.getOffset() - fContext.undoStackSize();
}
/**
* Get the next character.
* @return the next character
*/
public int getNextChar() {
return getChar();
}
/**
* Move to next character iff it is equal to the given expected character.
* If the characters do not match, the sanner does not move forward.
*
* @param c the expected character
* @return <code>true</code> if the next character was the expected character
*/
public boolean getNextChar(char c) {
if (c == getChar()) {
return true;
}
ungetChar(c);
return false;
}
/**
* Set current scanner offset to given offset.
*
* @param nextCharacterStart the desired scanner offset
*/
public void setCurrentPosition(int nextCharacterStart) {
int currentPos= getCurrentPosition();
int diff= currentPos - nextCharacterStart;
if (diff < 0) {
do {
getChar();
++diff;
} while(diff < 0);
} else if (diff == 0) {
// no-op
} else if (diff > fTokenBuffer.length()) {
resetTo(nextCharacterStart, source.length - 1);
} else /* if (diff <= fTokenBuffer.length()) */ {
while(diff > 0) {
if (fTokenBuffer.length() > 0) {
ungetChar(fTokenBuffer.charAt(fTokenBuffer.length() - 1));
}
--diff;
}
}
}
/**
* Get the text of the current token as a character array.
* @return the token text
*/
public char[] getCurrentTokenSource() {
return fCurrentToken.getText().toCharArray();
}
/**
* Get the next token as token type constant.
*
* @return the next token type
*/
public int getNextToken() {
Token token= nextToken();
if (token == null) {
return -1;
}
return token.type;
}
/**
* For debugging purposes.
*/
public String toString() {
if (this.startPosition == this.source.length)
return "EOF\n\n" + new String(this.source); //$NON-NLS-1$
if (this.getCurrentPosition() > this.source.length)
return "behind the EOF\n\n" + new String(this.source); //$NON-NLS-1$
char front[] = new char[this.startPosition];
System.arraycopy(this.source, 0, front, 0, this.startPosition);
int middleLength = (this.getCurrentPosition() - 1) - this.startPosition + 1;
char middle[];
if (middleLength > -1) {
middle = new char[middleLength];
System.arraycopy(
this.source,
this.startPosition,
middle,
0,
middleLength);
} else {
middle = CharOperation.NO_CHAR;
}
char end[] = new char[this.source.length - (this.getCurrentPosition() - 1)];
System.arraycopy(
this.source,
(this.getCurrentPosition() - 1) + 1,
end,
0,
this.source.length - (this.getCurrentPosition() - 1) - 1);
return new String(front)
+ "\n===============================\nStarts here -->" //$NON-NLS-1$
+ new String(middle)
+ "<-- Ends here\n===============================\n" //$NON-NLS-1$
+ new String(end);
}
}

View file

@ -0,0 +1,83 @@
/*******************************************************************************
* Copyright (c) 2004, 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial implementation
* Anton Leherbauer - adding tokens for preprocessing directives
* Markus Schorn - classification of preprocessing directives.
*******************************************************************************/
package org.eclipse.cdt.internal.formatter.scanner;
import java.io.IOException;
import java.io.Reader;
import java.util.Stack;
public class ScannerContext {
private Reader fReader;
private int fOffset;
private Stack fUndo = new Stack();
public ScannerContext() {
}
public ScannerContext initialize(Reader r) {
fReader = r;
fOffset = 0;
return this;
}
public ScannerContext initialize(Reader r, int offset) {
try {
r.skip(offset);
} catch (IOException exc) {
throw new RuntimeException(exc);
}
fReader = r;
fOffset = offset;
return this;
}
public int read() throws IOException {
++fOffset;
return fReader.read();
}
/**
* Returns the offset.
* @return int
*/
public final int getOffset() {
return fOffset;
}
/**
* Returns the reader.
* @return Reader
*/
public final Reader getReader() {
return fReader;
}
public final int undoStackSize() {
return fUndo.size();
}
/**
* Returns the undo.
* @return int
*/
public final int popUndo() {
return ((Integer)fUndo.pop()).intValue();
}
/**
* Sets the undo.
* @param undo The undo to set
*/
public void pushUndo(int undo) {
this.fUndo.push(new Integer(undo));
}
}

View file

@ -0,0 +1,859 @@
/*******************************************************************************
* Copyright (c) 2004, 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial implementation
* Anton Leherbauer - adding tokens for preprocessing directives
* Markus Schorn - classification of preprocessing directives.
*******************************************************************************/
package org.eclipse.cdt.internal.formatter.scanner;
import java.io.IOException;
import java.io.Reader;
import java.util.HashMap;
/**
* A C/C++ lexical scanner, which does no preprocessing,
* but tokenizes preprocessor directives, whitespace and comments.
*
* @since 4.0
*/
public class SimpleScanner {
private static final int EOFCHAR= -1;
protected static HashMap fgKeywords= new HashMap();
protected Token fCurrentToken;
protected ScannerContext fContext;
protected StringBuffer fTokenBuffer= new StringBuffer();
private int fPreprocessorToken= 0;
private boolean fReuseToken;
private boolean fSplitPreprocessor;
/**
*
*/
public SimpleScanner() {
super();
}
public void setReuseToken(boolean val) {
fReuseToken= val;
if (val) {
fCurrentToken= new Token(0, null);
}
}
public void setSplitPreprocessor(boolean val) {
fSplitPreprocessor= val;
}
protected void init(Reader reader, String filename) {
fReuseToken= false;
fSplitPreprocessor= true;
fPreprocessorToken= 0;
fContext = new ScannerContext().initialize(reader);
}
public SimpleScanner initialize(Reader reader, String filename) {
init(reader, filename);
return this;
}
public void cleanup() {
fContext= null;
fTokenBuffer= new StringBuffer();
fCurrentToken= null;
}
private final void setCurrentToken(Token t) {
fCurrentToken = t;
}
private final Token newToken(int t) {
if (!fReuseToken) {
setCurrentToken(new Token(t, fTokenBuffer.toString(), fContext));
}
else {
fCurrentToken.set(t, fTokenBuffer.toString(), fContext);
}
return fCurrentToken;
}
private Token newPreprocessorToken() {
if (fPreprocessorToken==0) {
fPreprocessorToken= categorizePreprocessor(fTokenBuffer);
}
return newToken(fPreprocessorToken);
}
private int categorizePreprocessor(StringBuffer text) {
boolean skipHash= true;
int i=0;
for (; i < text.length(); i++) {
char c= text.charAt(i);
if (!Character.isWhitespace(c)) {
if (!skipHash) {
break;
}
skipHash= false;
if (c != '#') {
break;
}
}
}
String innerText= text.substring(i);
if (innerText.startsWith("include")) { //$NON-NLS-1$
return Token.tPREPROCESSOR_INCLUDE;
}
if (innerText.startsWith("define")) { //$NON-NLS-1$
return Token.tPREPROCESSOR_DEFINE;
}
if (innerText.startsWith("undef")) { //$NON-NLS-1$
return Token.tPREPROCESSOR_DEFINE;
}
return Token.tPREPROCESSOR;
}
protected final int getChar() {
return getChar(false);
}
private int getChar(boolean insideString) {
int c = EOFCHAR;
if (fContext.undoStackSize() != 0) {
c = fContext.popUndo();
} else {
try {
c = fContext.read();
} catch (IOException e) {
c = EOFCHAR;
}
}
fTokenBuffer.append((char) c);
if (!insideString && c == '\\') {
c = getChar(false);
if (c == '\r') {
c = getChar(false);
if (c == '\n') {
c = getChar(false);
}
} else if (c == '\n') {
c = getChar(false);
}
}
return c;
}
protected void ungetChar(int c) {
fTokenBuffer.deleteCharAt(fTokenBuffer.length() - 1);
fContext.pushUndo(c);
}
public Token nextToken() {
fTokenBuffer.setLength(0);
boolean madeMistake = false;
int c = getChar();
while (c != EOFCHAR) {
if (fPreprocessorToken != 0) {
Token token= continuePPDirective(c);
if (token != null) {
return token;
}
}
if ((c == ' ') || (c == '\r') || (c == '\t') || (c == '\n')) {
while ((c == ' ') || (c == '\r') || (c == '\t') || (c == '\n')) {
c = getChar();
}
ungetChar(c);
return newToken(Token.tWHITESPACE);
} else if (c == '"' || (c == 'L' && !madeMistake)) {
boolean wideString = false;
if (c == 'L') {
int oldChar = c;
c = getChar();
if (c != '"') {
// we have made a mistake
ungetChar(c);
c = oldChar;
madeMistake = true;
continue;
} else {
wideString = true;
}
}
matchStringLiteral();
int type = wideString ? Token.tLSTRING : Token.tSTRING;
return newToken(type);
} else if (((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')) | (c == '_')) {
madeMistake = false;
c = getChar();
while (((c >= 'a') && (c <= 'z'))
|| ((c >= 'A') && (c <= 'Z'))
|| ((c >= '0') && (c <= '9'))
|| (c == '_')) {
c = getChar();
}
ungetChar(c);
String ident = fTokenBuffer.toString();
Object tokenTypeObject;
tokenTypeObject = fgKeywords.get(ident);
int tokenType = Token.tIDENTIFIER;
if (tokenTypeObject != null)
tokenType = ((Integer)tokenTypeObject).intValue();
return newToken(tokenType);
} else if ((c >= '0') && (c <= '9') || c == '.') {
boolean hex = false;
boolean floatingPoint = c == '.';
boolean firstCharZero = c == '0';
c = getChar();
if (c == 'x') {
if (!firstCharZero && floatingPoint) {
ungetChar(c);
return newToken(Token.tDOT);
}
hex = true;
c = getChar();
}
while ((c >= '0' && c <= '9') || (hex && ((c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')))) {
c = getChar();
}
if (c == '.') {
if (floatingPoint || hex) {
if (fTokenBuffer.toString().equals("..") && getChar() == '.') //$NON-NLS-1$
return newToken(Token.tELIPSE);
}
floatingPoint = true;
c = getChar();
while ((c >= '0' && c <= '9')) {
c = getChar();
}
}
if (c == 'e' || c == 'E') {
if (!floatingPoint)
floatingPoint = true;
// exponent type for floating point
c = getChar();
// optional + or -
if (c == '+' || c == '-') {
c = getChar();
}
// digit sequence of exponent part
while ((c >= '0' && c <= '9')) {
c = getChar();
}
// optional suffix
if (c == 'l' || c == 'L' || c == 'f' || c == 'F') {
c = getChar();
}
} else {
if (floatingPoint) {
//floating-suffix
if (c == 'l' || c == 'L' || c == 'f' || c == 'F') {
c = getChar();
}
} else {
//integer suffix
if (c == 'u' || c == 'U') {
c = getChar();
if (c == 'l' || c == 'L')
c = getChar();
} else if (c == 'l' || c == 'L') {
c = getChar();
if (c == 'u' || c == 'U')
c = getChar();
}
}
}
ungetChar(c);
int tokenType;
String result = fTokenBuffer.toString();
if (floatingPoint && result.equals(".")) //$NON-NLS-1$
tokenType = Token.tDOT;
else
tokenType = floatingPoint ? Token.tFLOATINGPT : Token.tINTEGER;
return newToken(tokenType);
} else if (c == '#') {
return matchPPDirective();
} else {
switch (c) {
case '\'':
matchCharLiteral();
return newToken(Token.tCHAR);
case ':':
c = getChar();
if (c == ':') {
return newToken(Token.tCOLONCOLON);
} else {
ungetChar(c);
return newToken(Token.tCOLON);
}
case ';':
return newToken(Token.tSEMI);
case ',':
return newToken(Token.tCOMMA);
case '?':
return newToken(Token.tQUESTION);
case '(':
return newToken(Token.tLPAREN);
case ')':
return newToken(Token.tRPAREN);
case '[':
return newToken(Token.tLBRACKET);
case ']':
return newToken(Token.tRBRACKET);
case '{':
return newToken(Token.tLBRACE);
case '}':
return newToken(Token.tRBRACE);
case '+':
c = getChar();
switch (c) {
case '=':
return newToken(Token.tPLUSASSIGN);
case '+':
return newToken(Token.tINCR);
default:
ungetChar(c);
return newToken(Token.tPLUS);
}
case '-':
c = getChar();
switch (c) {
case '=':
return newToken(Token.tMINUSASSIGN);
case '-':
return newToken(Token.tDECR);
case '>':
c = getChar();
switch (c) {
case '*':
return newToken(Token.tARROWSTAR);
default:
ungetChar(c);
return newToken(Token.tARROW);
}
default:
ungetChar(c);
return newToken(Token.tMINUS);
}
case '*':
c = getChar();
switch (c) {
case '=':
return newToken(Token.tSTARASSIGN);
default:
ungetChar(c);
return newToken(Token.tSTAR);
}
case '%':
c = getChar();
switch (c) {
case '=':
return newToken(Token.tMODASSIGN);
default:
ungetChar(c);
return newToken(Token.tMOD);
}
case '^':
c = getChar();
switch (c) {
case '=':
return newToken(Token.tXORASSIGN);
default:
ungetChar(c);
return newToken(Token.tXOR);
}
case '&':
c = getChar();
switch (c) {
case '=':
return newToken(Token.tAMPERASSIGN);
case '&':
return newToken(Token.tAND);
default:
ungetChar(c);
return newToken(Token.tAMPER);
}
case '|':
c = getChar();
switch (c) {
case '=':
return newToken(Token.tBITORASSIGN);
case '|':
return newToken(Token.tOR);
default:
ungetChar(c);
return newToken(Token.tBITOR);
}
case '~':
return newToken(Token.tCOMPL);
case '!':
c = getChar();
switch (c) {
case '=':
return newToken(Token.tNOTEQUAL);
default:
ungetChar(c);
return newToken(Token.tNOT);
}
case '=':
c = getChar();
switch (c) {
case '=':
return newToken(Token.tEQUAL);
default:
ungetChar(c);
return newToken(Token.tASSIGN);
}
case '<':
c = getChar();
switch (c) {
case '<':
c = getChar();
switch (c) {
case '=':
return newToken(Token.tSHIFTLASSIGN);
default:
ungetChar(c);
return newToken(Token.tSHIFTL);
}
case '=':
return newToken(Token.tLTEQUAL);
default:
ungetChar(c);
return newToken(Token.tLT);
}
case '>':
c = getChar();
switch (c) {
case '>':
c = getChar();
switch (c) {
case '=':
return newToken(Token.tSHIFTRASSIGN);
default:
ungetChar(c);
return newToken(Token.tSHIFTR);
}
case '=':
return newToken(Token.tGTEQUAL);
default:
ungetChar(c);
return newToken(Token.tGT);
}
case '.':
c = getChar();
switch (c) {
case '.':
c = getChar();
switch (c) {
case '.':
return newToken(Token.tELIPSE);
default:
break;
}
break;
case '*':
return newToken(Token.tDOTSTAR);
default:
ungetChar(c);
return newToken(Token.tDOT);
}
break;
case '/':
c = getChar();
switch (c) {
case '/': {
matchSinglelineComment();
return newToken(Token.tLINECOMMENT);
}
case '*': {
matchMultilineComment();
return newToken(Token.tBLOCKCOMMENT);
}
case '=':
return newToken(Token.tDIVASSIGN);
default:
ungetChar(c);
return newToken(Token.tDIV);
}
default:
// Bad character
return newToken(Token.tBADCHAR);
}
// throw EOF;
}
}
// we're done
// throw EOF;
return null;
}
private void matchCharLiteral() {
int c;
c = getChar(true);
int next = getChar(true);
if (c == '\\') {
if (next >= '0' && next <= '7') {
do {
next = getChar(true);
} while (next >= '0' && next <= '7');
} else if (next == 'x' || next == 'X' || next == 'u' || next == 'U') {
do {
next = getChar(true);
} while ((next >= '0' && next <= '9') || (next >= 'a' && next <= 'f')
|| (next >= 'A' && next <= 'F'));
} else {
next = getChar(true);
}
}
if (next != '\'') {
ungetChar(next);
}
}
private void matchStringLiteral() {
// string
boolean escaped= false;
int c = getChar(true);
LOOP:
for (;;) {
if (c == EOFCHAR)
break;
if (escaped) {
escaped= false;
int nc= getChar(true);
if (c=='\r' && nc=='\n') {
nc= getChar(true);
}
c= nc;
}
else {
switch(c) {
case '\\':
escaped= true;
break;
case '"':
break LOOP;
case '\r':
case '\n':
// unterminated string constant
ungetChar(c);
break LOOP;
}
c = getChar(true);
}
}
}
/**
* Matches a preprocesser directive.
*
* @return a preprocessor token
*/
private Token matchPPDirective() {
if (!fSplitPreprocessor) {
getRestOfPreprocessorLine();
return newToken(Token.tPREPROCESSOR);
}
return continuePPDirective(getChar());
}
private Token continuePPDirective(int c) {
boolean done= false;
while (!done) {
switch(c) {
case '\'':
if (fTokenBuffer.length() > 1) {
if (fPreprocessorToken==0) {
fPreprocessorToken= categorizePreprocessor(fTokenBuffer);
}
ungetChar(c);
return newPreprocessorToken();
}
matchCharLiteral();
return newToken(Token.tCHAR);
case '"':
if (fTokenBuffer.length() > 1) {
if (fPreprocessorToken==0) {
fPreprocessorToken= categorizePreprocessor(fTokenBuffer);
}
if (fPreprocessorToken==Token.tPREPROCESSOR_INCLUDE) {
matchStringLiteral();
c= getChar();
break;
}
else {
ungetChar(c);
return newPreprocessorToken();
}
}
matchStringLiteral();
return newToken(Token.tSTRING);
case '/': {
int next = getChar();
if (next == '/') {
Token result= null;
if (fTokenBuffer.length() > 2) {
ungetChar(next);
ungetChar(c);
result= newPreprocessorToken();
}
else {
matchSinglelineComment();
result= newToken(Token.tLINECOMMENT);
}
fPreprocessorToken= 0;
return result;
}
if (next == '*') {
if (fTokenBuffer.length() > 2) {
ungetChar(next);
ungetChar(c);
return newPreprocessorToken();
}
// multiline comment
if (matchMultilineComment()) {
fPreprocessorToken= 0;
}
return newToken(Token.tBLOCKCOMMENT);
}
c = next;
break;
}
case '\n':
case '\r':
case EOFCHAR:
done= true;
break;
default:
c= getChar();
break;
}
}
ungetChar(c);
Token result= null;
if (fTokenBuffer.length() > 0) {
result= newPreprocessorToken();
}
fPreprocessorToken= 0;
return result;
}
/**
* Read until end of preprocessor directive.
*/
private void getRestOfPreprocessorLine() {
int c = getChar();
while (true) {
while ((c != '\n') && (c != '\r') && (c != '/') && (c != EOFCHAR)) {
c = getChar();
}
if (c == '/') {
// we need to peek ahead at the next character to see if
// this is a comment or not
int next = getChar();
if (next == '/') {
// single line comment
matchSinglelineComment();
break;
} else if (next == '*') {
// multiline comment
if (matchMultilineComment())
break;
else
c = getChar();
continue;
} else {
// we are not in a comment
c = next;
continue;
}
} else {
ungetChar(c);
break;
}
}
}
private void matchSinglelineComment() {
int c = getChar();
while (c != '\n' && c != EOFCHAR) {
c = getChar();
}
ungetChar(c);
}
private boolean matchMultilineComment() {
boolean encounteredNewline = false;
int state = 0;
int c = getChar();
while (state != 2 && c != EOFCHAR) {
if (c == '\n')
encounteredNewline = true;
switch (state) {
case 0 :
if (c == '*')
state = 1;
break;
case 1 :
if (c == '/')
state = 2;
else if (c != '*')
state = 0;
break;
}
c = getChar();
}
ungetChar(c);
return encounteredNewline;
}
static {
fgKeywords.put("and", new Integer(Token.t_and)); //$NON-NLS-1$
fgKeywords.put("and_eq", new Integer(Token.t_and_eq)); //$NON-NLS-1$
fgKeywords.put("asm", new Integer(Token.t_asm)); //$NON-NLS-1$
fgKeywords.put("auto", new Integer(Token.t_auto)); //$NON-NLS-1$
fgKeywords.put("bitand", new Integer(Token.t_bitand)); //$NON-NLS-1$
fgKeywords.put("bitor", new Integer(Token.t_bitor)); //$NON-NLS-1$
fgKeywords.put("bool", new Integer(Token.t_bool)); //$NON-NLS-1$
fgKeywords.put("break", new Integer(Token.t_break)); //$NON-NLS-1$
fgKeywords.put("case", new Integer(Token.t_case)); //$NON-NLS-1$
fgKeywords.put("catch", new Integer(Token.t_catch)); //$NON-NLS-1$
fgKeywords.put("char", new Integer(Token.t_char)); //$NON-NLS-1$
fgKeywords.put("class", new Integer(Token.t_class)); //$NON-NLS-1$
fgKeywords.put("compl", new Integer(Token.t_compl)); //$NON-NLS-1$
fgKeywords.put("const", new Integer(Token.t_const)); //$NON-NLS-1$
fgKeywords.put("const_cast", new Integer(Token.t_const_cast)); //$NON-NLS-1$
fgKeywords.put("continue", new Integer(Token.t_continue)); //$NON-NLS-1$
fgKeywords.put("default", new Integer(Token.t_default)); //$NON-NLS-1$
fgKeywords.put("delete", new Integer(Token.t_delete)); //$NON-NLS-1$
fgKeywords.put("do", new Integer(Token.t_do)); //$NON-NLS-1$
fgKeywords.put("double", new Integer(Token.t_double)); //$NON-NLS-1$
fgKeywords.put("dynamic_cast", new Integer(Token.t_dynamic_cast)); //$NON-NLS-1$
fgKeywords.put("else", new Integer(Token.t_else)); //$NON-NLS-1$
fgKeywords.put("enum", new Integer(Token.t_enum)); //$NON-NLS-1$
fgKeywords.put("explicit", new Integer(Token.t_explicit)); //$NON-NLS-1$
fgKeywords.put("export", new Integer(Token.t_export)); //$NON-NLS-1$
fgKeywords.put("extern", new Integer(Token.t_extern)); //$NON-NLS-1$
fgKeywords.put("false", new Integer(Token.t_false)); //$NON-NLS-1$
fgKeywords.put("float", new Integer(Token.t_float)); //$NON-NLS-1$
fgKeywords.put("for", new Integer(Token.t_for)); //$NON-NLS-1$
fgKeywords.put("friend", new Integer(Token.t_friend)); //$NON-NLS-1$
fgKeywords.put("goto", new Integer(Token.t_goto)); //$NON-NLS-1$
fgKeywords.put("if", new Integer(Token.t_if)); //$NON-NLS-1$
fgKeywords.put("inline", new Integer(Token.t_inline)); //$NON-NLS-1$
fgKeywords.put("int", new Integer(Token.t_int)); //$NON-NLS-1$
fgKeywords.put("long", new Integer(Token.t_long)); //$NON-NLS-1$
fgKeywords.put("mutable", new Integer(Token.t_mutable)); //$NON-NLS-1$
fgKeywords.put("namespace", new Integer(Token.t_namespace)); //$NON-NLS-1$
fgKeywords.put("new", new Integer(Token.t_new)); //$NON-NLS-1$
fgKeywords.put("not", new Integer(Token.t_not)); //$NON-NLS-1$
fgKeywords.put("not_eq", new Integer(Token.t_not_eq)); //$NON-NLS-1$
fgKeywords.put("operator", new Integer(Token.t_operator)); //$NON-NLS-1$
fgKeywords.put("or", new Integer(Token.t_or)); //$NON-NLS-1$
fgKeywords.put("or_eq", new Integer(Token.t_or_eq)); //$NON-NLS-1$
fgKeywords.put("private", new Integer(Token.t_private)); //$NON-NLS-1$
fgKeywords.put("protected", new Integer(Token.t_protected)); //$NON-NLS-1$
fgKeywords.put("public", new Integer(Token.t_public)); //$NON-NLS-1$
fgKeywords.put("register", new Integer(Token.t_register)); //$NON-NLS-1$
fgKeywords.put("reinterpret_cast", new Integer(Token.t_reinterpret_cast)); //$NON-NLS-1$
fgKeywords.put("return", new Integer(Token.t_return)); //$NON-NLS-1$
fgKeywords.put("short", new Integer(Token.t_short)); //$NON-NLS-1$
fgKeywords.put("signed", new Integer(Token.t_signed)); //$NON-NLS-1$
fgKeywords.put("sizeof", new Integer(Token.t_sizeof)); //$NON-NLS-1$
fgKeywords.put("static", new Integer(Token.t_static)); //$NON-NLS-1$
fgKeywords.put("static_cast", new Integer(Token.t_static_cast)); //$NON-NLS-1$
fgKeywords.put("struct", new Integer(Token.t_struct)); //$NON-NLS-1$
fgKeywords.put("switch", new Integer(Token.t_switch)); //$NON-NLS-1$
fgKeywords.put("template", new Integer(Token.t_template)); //$NON-NLS-1$
fgKeywords.put("this", new Integer(Token.t_this)); //$NON-NLS-1$
fgKeywords.put("throw", new Integer(Token.t_throw)); //$NON-NLS-1$
fgKeywords.put("true", new Integer(Token.t_true)); //$NON-NLS-1$
fgKeywords.put("try", new Integer(Token.t_try)); //$NON-NLS-1$
fgKeywords.put("typedef", new Integer(Token.t_typedef)); //$NON-NLS-1$
fgKeywords.put("typeid", new Integer(Token.t_typeid)); //$NON-NLS-1$
fgKeywords.put("typename", new Integer(Token.t_typename)); //$NON-NLS-1$
fgKeywords.put("union", new Integer(Token.t_union)); //$NON-NLS-1$
fgKeywords.put("unsigned", new Integer(Token.t_unsigned)); //$NON-NLS-1$
fgKeywords.put("using", new Integer(Token.t_using)); //$NON-NLS-1$
fgKeywords.put("virtual", new Integer(Token.t_virtual)); //$NON-NLS-1$
fgKeywords.put("void", new Integer(Token.t_void)); //$NON-NLS-1$
fgKeywords.put("volatile", new Integer(Token.t_volatile)); //$NON-NLS-1$
fgKeywords.put("wchar_t", new Integer(Token.t_wchar_t)); //$NON-NLS-1$
fgKeywords.put("while", new Integer(Token.t_while)); //$NON-NLS-1$
fgKeywords.put("xor", new Integer(Token.t_xor)); //$NON-NLS-1$
fgKeywords.put("xor_eq", new Integer(Token.t_xor_eq)); //$NON-NLS-1$
// additional java keywords
fgKeywords.put("abstract", new Integer(Token.t_abstract)); //$NON-NLS-1$
fgKeywords.put("boolean", new Integer(Token.t_boolean)); //$NON-NLS-1$
fgKeywords.put("byte", new Integer(Token.t_byte)); //$NON-NLS-1$
fgKeywords.put("extends", new Integer(Token.t_extends)); //$NON-NLS-1$
fgKeywords.put("final", new Integer(Token.t_final)); //$NON-NLS-1$
fgKeywords.put("finally", new Integer(Token.t_finally)); //$NON-NLS-1$
fgKeywords.put("implements", new Integer(Token.t_implements)); //$NON-NLS-1$
fgKeywords.put("import", new Integer(Token.t_import)); //$NON-NLS-1$
fgKeywords.put("interface", new Integer(Token.t_interface)); //$NON-NLS-1$
fgKeywords.put("instanceof", new Integer(Token.t_instanceof)); //$NON-NLS-1$
fgKeywords.put("native", new Integer(Token.t_native)); //$NON-NLS-1$
fgKeywords.put("null", new Integer(Token.t_null)); //$NON-NLS-1$
fgKeywords.put("package", new Integer(Token.t_package)); //$NON-NLS-1$
fgKeywords.put("super", new Integer(Token.t_super)); //$NON-NLS-1$
fgKeywords.put("synchronized", new Integer(Token.t_synchronized)); //$NON-NLS-1$
fgKeywords.put("throws", new Integer(Token.t_throws)); //$NON-NLS-1$
fgKeywords.put("transient", new Integer(Token.t_transient)); //$NON-NLS-1$
}
}

View file

@ -0,0 +1,509 @@
/*******************************************************************************
* Copyright (c) 2004, 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial implementation
* Anton Leherbauer - adding tokens for preprocessing directives
* Markus Schorn - classification of preprocessing directives.
*******************************************************************************/
package org.eclipse.cdt.internal.formatter.scanner;
import org.eclipse.cdt.internal.formatter.scanner.ScannerContext;
public class Token {
public int type;
public String text;
public int offset;
public Token(int t, String i, ScannerContext context) {
set(t,i,context);
}
public void set(int t, String i, ScannerContext context) {
type = t;
text = i;
offset = context.getOffset() - text.length() - context.undoStackSize();
}
public Token(int t, String i) {
type = t;
text = i;
}
public String toString() {
return "Token type=" + type + " image =" + text + " offset=" + offset; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
public int getType() {
return type;
}
public String getText() {
return text;
}
public int getOffset() {
return offset;
}
public int getLength() {
return text.length();
}
public int getDelta(Token other) {
return other.getOffset() + other.getLength() - getOffset();
}
public boolean looksLikeExpressionStart() {
switch (type) {
case tINTEGER :
case t_false :
case t_true :
case tSTRING :
case tLSTRING :
case tFLOATINGPT :
case tCHAR :
case tAMPER :
case tDOT :
case tLPAREN :
return true;
default :
break;
}
return false;
}
public boolean looksLikeExpressionEnd() {
switch (type) {
case tINTEGER :
case tSTRING :
case tLSTRING :
case tFLOATINGPT :
case tCHAR :
case tRPAREN :
case tIDENTIFIER :
return true;
default :
break;
}
return false;
}
public boolean isPointer() {
return (type == tAMPER || type == tSTAR);
}
public boolean isOperator() {
switch (type) {
case t_new :
case t_delete :
case tPLUS :
case tMINUS :
case tSTAR :
case tDIV :
case tXOR :
case tMOD :
case tAMPER :
case tBITOR :
case tCOMPL :
case tNOT :
case tASSIGN :
case tLT :
case tGT :
case tPLUSASSIGN :
case tMINUSASSIGN :
case tSTARASSIGN :
case tDIVASSIGN :
case tMODASSIGN :
case tBITORASSIGN :
case tAMPERASSIGN :
case tXORASSIGN :
case tSHIFTL :
case tSHIFTR :
case tSHIFTLASSIGN :
case tSHIFTRASSIGN :
case tEQUAL :
case tNOTEQUAL :
case tLTEQUAL :
case tGTEQUAL :
case tAND :
case tOR :
case tINCR :
case tDECR :
case tCOMMA :
case tDOT :
case tDOTSTAR :
case tARROW :
case tARROWSTAR :
return true;
default :
return false;
}
}
public boolean isInfixOperator() {
switch (type) {
case tPLUS :
case tMINUS :
case tSTAR :
case tDIV :
case tXOR :
case tMOD :
case tAMPER :
case tBITOR :
case tASSIGN :
case tLT :
case tGT :
case tPLUSASSIGN :
case tMINUSASSIGN :
case tSTARASSIGN :
case tDIVASSIGN :
case tMODASSIGN :
case tBITORASSIGN :
case tAMPERASSIGN :
case tXORASSIGN :
case tSHIFTL :
case tSHIFTR :
case tSHIFTLASSIGN :
case tSHIFTRASSIGN :
case tEQUAL :
case tNOTEQUAL :
case tLTEQUAL :
case tGTEQUAL :
case tAND :
case tOR :
case tCOLON :
case tQUESTION :
return true;
default :
return false;
}
}
public boolean isPrefixOperator() {
switch (type) {
case tPLUS :
case tMINUS :
case tSTAR :
case tAMPER :
case tCOMPL :
case tNOT :
case tINCR :
case tDECR :
return true;
default :
return false;
}
}
public boolean isPostfixOperator() {
switch (type) {
case tINCR :
case tDECR :
return true;
default :
return false;
}
}
public boolean isAssignmentOperator() {
return isAssignmentOperator(type);
}
public static boolean isAssignmentOperator(int type) {
switch (type) {
case tASSIGN :
case tPLUSASSIGN :
case tMINUSASSIGN :
case tSTARASSIGN :
case tDIVASSIGN :
case tAMPERASSIGN :
case tBITORASSIGN :
case tXORASSIGN :
case tMODASSIGN :
case tSHIFTLASSIGN :
case tSHIFTRASSIGN :
return true;
default :
return false;
}
}
public boolean isControlStmt() {
switch (type) {
case t_if :
case t_else :
case t_for :
case t_do :
case t_while :
case t_switch :
case t_try :
case t_catch :
case t_finally :
return true;
default :
return false;
}
}
public boolean isWhiteSpace() {
return type == tWHITESPACE;
}
public boolean isComment() {
return isLineComment() || isBlockComment();
}
public boolean isLineComment() {
return type == tLINECOMMENT;
}
public boolean isBlockComment() {
return type == tBLOCKCOMMENT;
}
public boolean isCaseLabel() {
return type == t_case || type == t_default;
}
public boolean isStructType() {
return isStructType(type);
}
public static boolean isStructType(int type) {
return type == t_struct || type == t_union || type == t_class;
}
public boolean isVisibilityModifier() {
return isVisibilityModifier(type);
}
public static boolean isVisibilityModifier(int type) {
return type == t_public || type == t_protected || type == t_private;
}
public boolean isEndOfStatement() {
return type == tSEMI || type == tRBRACE;
}
public boolean isCPPToken() {
switch (type) {
case tCOLONCOLON :
case t_class :
case t_namespace :
case t_using :
case t_template :
case t_public :
case t_protected :
case t_private :
case t_operator :
case t_virtual :
case t_inline :
case t_friend :
case t_mutable :
case t_new :
case t_delete :
case t_reinterpret_cast :
case t_dynamic_cast :
case t_static_cast :
case t_finally :
return true;
default :
return false;
}
}
// overrider
public boolean isStringLiteral() {
return type == tSTRING || type == tLSTRING;
}
// overrider
public boolean isCharacterLiteral() {
return type == tCHAR;
}
// overrider
public boolean isPreprocessor() {
switch(type) {
case tPREPROCESSOR:
case tPREPROCESSOR_DEFINE:
case tPREPROCESSOR_INCLUDE:
return true;
}
return false;
}
// overrider
public boolean isIncludeDirective() {
return type==tPREPROCESSOR_INCLUDE;
}
// overrider
public boolean isMacroDefinition() {
return type==tPREPROCESSOR_DEFINE;
}
// Special Token types (non-grammar tokens)
public static final int tWHITESPACE = 1000;
public static final int tLINECOMMENT = 1001;
public static final int tBLOCKCOMMENT = 1002;
public static final int tPREPROCESSOR = 1003;
public static final int tPREPROCESSOR_INCLUDE = 1004;
public static final int tPREPROCESSOR_DEFINE = 1005;
public static final int tBADCHAR = 1006;
// Token types
static public final int tIDENTIFIER = 1;
static public final int tINTEGER = 2;
static public final int tCOLONCOLON = 3;
static public final int tCOLON = 4;
static public final int tSEMI = 5;
static public final int tCOMMA = 6;
static public final int tQUESTION = 7;
static public final int tLPAREN = 8;
static public final int tRPAREN = 9;
static public final int tLBRACKET = 10;
static public final int tRBRACKET = 11;
static public final int tLBRACE = 12;
static public final int tRBRACE = 13;
static public final int tPLUSASSIGN = 14;
static public final int tINCR = 15;
static public final int tPLUS = 16;
static public final int tMINUSASSIGN = 17;
static public final int tDECR = 18;
static public final int tARROWSTAR = 19;
static public final int tARROW = 20;
static public final int tMINUS = 21;
static public final int tSTARASSIGN = 22;
static public final int tSTAR = 23;
static public final int tMODASSIGN = 24;
static public final int tMOD = 25;
static public final int tXORASSIGN = 26;
static public final int tXOR = 27;
static public final int tAMPERASSIGN = 28;
static public final int tAND = 29;
static public final int tAMPER = 30;
static public final int tBITORASSIGN = 31;
static public final int tOR = 32;
static public final int tBITOR = 33;
static public final int tCOMPL = 34;
static public final int tNOTEQUAL = 35;
static public final int tNOT = 36;
static public final int tEQUAL = 37;
static public final int tASSIGN = 38;
static public final int tSHIFTL = 40;
static public final int tLTEQUAL = 41;
static public final int tLT = 42;
static public final int tSHIFTRASSIGN = 43;
static public final int tSHIFTR = 44;
static public final int tGTEQUAL = 45;
static public final int tGT = 46;
static public final int tSHIFTLASSIGN = 47;
static public final int tELIPSE = 48;
static public final int tDOTSTAR = 49;
static public final int tDOT = 50;
static public final int tDIVASSIGN = 51;
static public final int tDIV = 52;
static public final int tCLASSNAME = 53;
static public final int t_and = 54;
static public final int t_and_eq = 55;
static public final int t_asm = 56;
static public final int t_auto = 57;
static public final int t_bitand = 58;
static public final int t_bitor = 59;
static public final int t_bool = 60;
static public final int t_break = 61;
static public final int t_case = 62;
static public final int t_catch = 63;
static public final int t_char = 64;
static public final int t_class = 65;
static public final int t_compl = 66;
static public final int t_const = 67;
static public final int t_const_cast = 69;
static public final int t_continue = 70;
static public final int t_default = 71;
static public final int t_delete = 72;
static public final int t_do = 73;
static public final int t_double = 74;
static public final int t_dynamic_cast = 75;
static public final int t_else = 76;
static public final int t_enum = 77;
static public final int t_explicit = 78;
static public final int t_export = 79;
static public final int t_extern = 80;
static public final int t_false = 81;
static public final int t_float = 82;
static public final int t_for = 83;
static public final int t_friend = 84;
static public final int t_goto = 85;
static public final int t_if = 86;
static public final int t_inline = 87;
static public final int t_int = 88;
static public final int t_long = 89;
static public final int t_mutable = 90;
static public final int t_namespace = 91;
static public final int t_new = 92;
static public final int t_not = 93;
static public final int t_not_eq = 94;
static public final int t_operator = 95;
static public final int t_or = 96;
static public final int t_or_eq = 97;
static public final int t_private = 98;
static public final int t_protected = 99;
static public final int t_public = 100;
static public final int t_register = 101;
static public final int t_reinterpret_cast = 102;
static public final int t_return = 103;
static public final int t_short = 104;
static public final int t_sizeof = 105;
static public final int t_static = 106;
static public final int t_static_cast = 107;
static public final int t_signed = 108;
static public final int t_struct = 109;
static public final int t_switch = 110;
static public final int t_template = 111;
static public final int t_this = 112;
static public final int t_throw = 113;
static public final int t_true = 114;
static public final int t_try = 115;
static public final int t_typedef = 116;
static public final int t_typeid = 117;
static public final int t_typename = 118;
static public final int t_union = 119;
static public final int t_unsigned = 120;
static public final int t_using = 121;
static public final int t_virtual = 122;
static public final int t_void = 123;
static public final int t_volatile = 124;
static public final int t_wchar_t = 125;
static public final int t_while = 126;
static public final int t_xor = 127;
static public final int t_xor_eq = 128;
static public final int tSTRING = 129;
static public final int tFLOATINGPT = 130;
static public final int tLSTRING = 131;
static public final int tCHAR = 132;
static public final int t_restrict = 136;
static public final int t_interface = 200;
static public final int t_import = 201;
static public final int t_instanceof = 202;
static public final int t_extends = 203;
static public final int t_implements = 204;
static public final int t_final = 205;
static public final int t_super = 206;
static public final int t_package = 207;
static public final int t_boolean = 208;
static public final int t_abstract = 209;
static public final int t_finally = 210;
static public final int t_null = 211;
static public final int t_synchronized = 212;
static public final int t_throws = 213;
static public final int t_byte = 214;
static public final int t_transient = 215;
static public final int t_native = 216;
}

View file

@ -12,20 +12,13 @@ package org.eclipse.cdt.internal.corext.util;
import java.util.Map;
import org.eclipse.text.edits.TextEdit;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.ToolFactory;
import org.eclipse.cdt.core.formatter.CodeFormatter;
import org.eclipse.cdt.core.formatter.DefaultCodeFormatterConstants;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.core.runtime.Assert;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.BadPositionCategoryException;
import org.eclipse.jface.text.DefaultPositionUpdater;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.Position;
import org.eclipse.text.edits.TextEdit;
public class CodeFormatterUtil {
@ -119,28 +112,6 @@ public class CodeFormatterUtil {
}
}
/**
* Evaluates the edit on the given string.
* @throws IllegalArgumentException If the positions are not inside the string, a
* IllegalArgumentException is thrown.
*/
public static String evaluateFormatterEdit(String string, TextEdit edit, Position[] positions) {
try {
Document doc= createDocument(string, positions);
edit.apply(doc, 0);
if (positions != null) {
for (int i= 0; i < positions.length; i++) {
Assert.isTrue(!positions[i].isDeleted, "Position got deleted"); //$NON-NLS-1$
}
}
return doc.get();
} catch (BadLocationException e) {
CUIPlugin.getDefault().log(e); // bug in the formatter
Assert.isTrue(false, "Formatter created edits with wrong positions: " + e.getMessage()); //$NON-NLS-1$
}
return null;
}
/**
* Creates edits that describe how to format the given string. Returns <code>null</code> if the code could not be formatted for the given kind.
* @throws IllegalArgumentException If the offset and length are not inside the string, a
@ -161,63 +132,6 @@ public class CodeFormatterUtil {
return format(kind, source, 0, source.length(), indentationLevel, lineSeparator, options);
}
// private static TextEdit shifEdit(TextEdit oldEdit, int diff) {
// TextEdit newEdit;
// if (oldEdit instanceof ReplaceEdit) {
// ReplaceEdit edit= (ReplaceEdit) oldEdit;
// newEdit= new ReplaceEdit(edit.getOffset() - diff, edit.getLength(), edit.getText());
// } else if (oldEdit instanceof InsertEdit) {
// InsertEdit edit= (InsertEdit) oldEdit;
// newEdit= new InsertEdit(edit.getOffset() - diff, edit.getText());
// } else if (oldEdit instanceof DeleteEdit) {
// DeleteEdit edit= (DeleteEdit) oldEdit;
// newEdit= new DeleteEdit(edit.getOffset() - diff, edit.getLength());
// } else if (oldEdit instanceof MultiTextEdit) {
// newEdit= new MultiTextEdit();
// } else {
// return null; // not supported
// }
// TextEdit[] children= oldEdit.getChildren();
// for (int i= 0; i < children.length; i++) {
// TextEdit shifted= shifEdit(children[i], diff);
// if (shifted != null) {
// newEdit.addChild(shifted);
// }
// }
// return newEdit;
// }
private static Document createDocument(String string, Position[] positions) throws IllegalArgumentException {
Document doc= new Document(string);
try {
if (positions != null) {
final String POS_CATEGORY= "myCategory"; //$NON-NLS-1$
doc.addPositionCategory(POS_CATEGORY);
doc.addPositionUpdater(new DefaultPositionUpdater(POS_CATEGORY) {
protected boolean notDeleted() {
if (fOffset < fPosition.offset && (fPosition.offset + fPosition.length < fOffset + fLength)) {
fPosition.offset= fOffset + fLength; // deleted positions: set to end of remove
return false;
}
return true;
}
});
for (int i= 0; i < positions.length; i++) {
try {
doc.addPosition(POS_CATEGORY, positions[i]);
} catch (BadLocationException e) {
throw new IllegalArgumentException("Position outside of string. offset: " + positions[i].offset + ", length: " + positions[i].length + ", string size: " + string.length()); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
}
}
}
} catch (BadPositionCategoryException cannotHappen) {
// can not happen: category is correctly set up
}
return doc;
}
/**
* @return The formatter tab width on workspace level.
*/

View file

@ -0,0 +1,33 @@
/*******************************************************************************
* Copyright (c) 2005, 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.corext.util;
import com.ibm.icu.text.MessageFormat;
/**
* Helper class to format message strings.
*
* @since 3.1
*/
public class Messages {
public static String format(String message, Object object) {
return MessageFormat.format(message, new Object[] { object});
}
public static String format(String message, Object[] objects) {
return MessageFormat.format(message, objects);
}
private Messages() {
// Not for instantiation
}
}

View file

@ -13,7 +13,7 @@ package org.eclipse.cdt.internal.ui.dialogs;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.ui.CUIPlugin;
/**
* A settable IStatus
@ -22,6 +22,8 @@ import org.eclipse.cdt.core.CCorePlugin;
*/
public class StatusInfo implements IStatus {
public static final IStatus OK_STATUS= new StatusInfo();
private String fStatusMessage;
private int fSeverity;
@ -71,7 +73,7 @@ public class StatusInfo implements IStatus {
* @see IStatus#getPlugin()
*/
public String getPlugin() {
return CCorePlugin.PLUGIN_ID;
return CUIPlugin.PLUGIN_ID;
}
/**
* @see IStatus#getSeverity()
@ -119,4 +121,28 @@ public class StatusInfo implements IStatus {
fStatusMessage= warningMessage;
fSeverity= IStatus.WARNING;
}
/**
* Returns a string representation of the status, suitable
* for debugging purposes only.
*/
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append("StatusInfo "); //$NON-NLS-1$
if (fSeverity == OK) {
buf.append("OK"); //$NON-NLS-1$
} else if (fSeverity == ERROR) {
buf.append("ERROR"); //$NON-NLS-1$
} else if (fSeverity == WARNING) {
buf.append("WARNING"); //$NON-NLS-1$
} else if (fSeverity == INFO) {
buf.append("INFO"); //$NON-NLS-1$
} else {
buf.append("severity="); //$NON-NLS-1$
buf.append(fSeverity);
}
buf.append(": "); //$NON-NLS-1$
buf.append(fStatusMessage);
return buf.toString();
}
}

View file

@ -151,13 +151,16 @@ import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.CCorePreferenceConstants;
import org.eclipse.cdt.core.IPositionConverter;
import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit;
import org.eclipse.cdt.core.dom.ast.gnu.cpp.GPPLanguage;
import org.eclipse.cdt.core.formatter.DefaultCodeFormatterConstants;
import org.eclipse.cdt.core.index.IIndex;
import org.eclipse.cdt.core.model.CModelException;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.core.model.ILanguage;
import org.eclipse.cdt.core.model.ISourceRange;
import org.eclipse.cdt.core.model.ISourceReference;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.refactoring.actions.CRefactoringActionGroup;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.ui.IWorkingCopyManager;
@ -296,6 +299,19 @@ public class CEditor extends TextEditor implements ISelectionChangedListener, IR
else
preferences= new HashMap(cProject.getOptions(true));
if (inputCElement instanceof ITranslationUnit) {
ITranslationUnit tu= (ITranslationUnit)inputCElement;
ILanguage language= null;
try {
language= tu.getLanguage();
} catch (CoreException exc) {
// use fallback CPP
language= GPPLanguage.getDefault();
}
preferences.put(DefaultCodeFormatterConstants.FORMATTER_TRANSLATION_UNIT, tu);
preferences.put(DefaultCodeFormatterConstants.FORMATTER_LANGUAGE, language);
preferences.put(DefaultCodeFormatterConstants.FORMATTER_CURRENT_FILE, tu.getResource());
}
context.setProperty(FormattingContextProperties.CONTEXT_PREFERENCES, preferences);
return context;

View file

@ -0,0 +1,177 @@
/*******************************************************************************
* Copyright (c) 2000, 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Anton Leherbauer (Wind River Systems)
*******************************************************************************/
package org.eclipse.cdt.internal.ui.preferences.formatter;
import java.util.Map;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.cdt.core.formatter.DefaultCodeFormatterConstants;
public class BracesTabPage extends ModifyDialogTabPage {
// /**
// * Constant array for boolean selection
// */
// private static String[] FALSE_TRUE = {
// DefaultCodeFormatterConstants.FALSE,
// DefaultCodeFormatterConstants.TRUE
// };
/**
* Some C++ source code used for preview.
*/
private final static String PREVIEW=
createPreviewHeader(FormatterMessages.BracesTabPage_preview_header) +
"#include <math.h>\n" + //$NON-NLS-1$
"class Point {" + //$NON-NLS-1$
"public:" + //$NON-NLS-1$
"Point(double xc, double yc) : x(xc), y(yc) {}" + //$NON-NLS-1$
"double distance(const Point& other) const;" + //$NON-NLS-1$
"int compareX(const Point& other) const;" + //$NON-NLS-1$
"double x;" + //$NON-NLS-1$
"double y;" + //$NON-NLS-1$
"};" + //$NON-NLS-1$
"double Point::distance(const Point& other) const {" + //$NON-NLS-1$
"double dx = x - other.x;" + //$NON-NLS-1$
"double dy = y - other.y;" + //$NON-NLS-1$
"return sqrt(dx * dx + dy * dy);" + //$NON-NLS-1$
"}"+ //$NON-NLS-1$
"int Point::compareX(const Point& other) const {" + //$NON-NLS-1$
"if(x < other.x) {" + //$NON-NLS-1$
"return -1;" + //$NON-NLS-1$
"} else if(x > other.x){" + //$NON-NLS-1$
"return 1;" + //$NON-NLS-1$
"} else {" + //$NON-NLS-1$
"return 0;" + //$NON-NLS-1$
"}"+ //$NON-NLS-1$
"}"+ //$NON-NLS-1$
"namespace FOO {"+ //$NON-NLS-1$
"int foo(int bar) const {" + //$NON-NLS-1$
"switch(bar) {" + //$NON-NLS-1$
"case 0:" + //$NON-NLS-1$
"++bar;" + //$NON-NLS-1$
"break;" + //$NON-NLS-1$
"case 1:" + //$NON-NLS-1$
"--bar;" + //$NON-NLS-1$
"default: {" + //$NON-NLS-1$
"bar += bar;" + //$NON-NLS-1$
"break;" + //$NON-NLS-1$
"}"+ //$NON-NLS-1$
"}"+ //$NON-NLS-1$
"}"+ //$NON-NLS-1$
"} // end namespace FOO"; //$NON-NLS-1$
private TranslationUnitPreview fPreview;
private final String [] fBracePositions= {
DefaultCodeFormatterConstants.END_OF_LINE,
DefaultCodeFormatterConstants.NEXT_LINE,
DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED
};
private final String [] fExtendedBracePositions= {
DefaultCodeFormatterConstants.END_OF_LINE,
DefaultCodeFormatterConstants.NEXT_LINE,
DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED,
DefaultCodeFormatterConstants.NEXT_LINE_ON_WRAP
};
private final String [] fBracePositionNames= {
FormatterMessages.BracesTabPage_position_same_line,
FormatterMessages.BracesTabPage_position_next_line,
FormatterMessages.BracesTabPage_position_next_line_indented
};
private final String [] fExtendedBracePositionNames= {
FormatterMessages.BracesTabPage_position_same_line,
FormatterMessages.BracesTabPage_position_next_line,
FormatterMessages.BracesTabPage_position_next_line_indented,
FormatterMessages.BracesTabPage_position_next_line_on_wrap
};
/**
* Create a new BracesTabPage.
* @param modifyDialog
* @param workingValues
*/
public BracesTabPage(ModifyDialog modifyDialog, Map workingValues) {
super(modifyDialog, workingValues);
}
protected void doCreatePreferences(Composite composite, int numColumns) {
final Group group= createGroup(numColumns, composite, FormatterMessages.BracesTabPage_group_brace_positions_title);
createExtendedBracesCombo(group, numColumns, FormatterMessages.BracesTabPage_option_class_declaration, DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_TYPE_DECLARATION);
// createExtendedBracesCombo(group, numColumns, FormatterMessages.BracesTabPage_option_anonymous_class_declaration, DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ANONYMOUS_TYPE_DECLARATION);
// createExtendedBracesCombo(group, numColumns, FormatterMessages.BracesTabPage_option_constructor_declaration, DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_CONSTRUCTOR_DECLARATION);
createExtendedBracesCombo(group, numColumns, FormatterMessages.BracesTabPage_option_method_declaration, DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_METHOD_DECLARATION);
// createExtendedBracesCombo(group, numColumns, FormatterMessages.BracesTabPage_option_enum_declaration, DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ENUM_DECLARATION);
// createExtendedBracesCombo(group, numColumns, FormatterMessages.BracesTabPage_option_enumconst_declaration, DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ENUM_CONSTANT);
// createExtendedBracesCombo(group, numColumns, FormatterMessages.BracesTabPage_option_annotation_type_declaration, DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ANNOTATION_TYPE_DECLARATION);
createExtendedBracesCombo(group, numColumns, FormatterMessages.BracesTabPage_option_blocks, DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_BLOCK);
createExtendedBracesCombo(group, numColumns, FormatterMessages.BracesTabPage_option_blocks_in_case, DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_BLOCK_IN_CASE);
createBracesCombo(group, numColumns, FormatterMessages.BracesTabPage_option_switch_case, DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_SWITCH);
// ComboPreference arrayInitOption= createBracesCombo(group, numColumns, FormatterMessages.BracesTabPage_option_array_initializer, DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ARRAY_INITIALIZER);
// final CheckboxPreference arrayInitCheckBox= createIndentedCheckboxPref(group, numColumns, FormatterMessages.BracesTabPage_option_keep_empty_array_initializer_on_one_line, DefaultCodeFormatterConstants.FORMATTER_KEEP_EMPTY_ARRAY_INITIALIZER_ON_ONE_LINE, FALSE_TRUE);
// arrayInitOption.addObserver(new Observer() {
// public void update(Observable o, Object arg) {
// updateOptionEnablement((ComboPreference) o, arrayInitCheckBox);
// }
// });
// updateOptionEnablement(arrayInitOption, arrayInitCheckBox);
}
// /**
// * @param arrayInitOption
// * @param arrayInitCheckBox
// */
// protected final void updateOptionEnablement(ComboPreference arrayInitOption, CheckboxPreference arrayInitCheckBox) {
// arrayInitCheckBox.setEnabled(!arrayInitOption.hasValue(DefaultCodeFormatterConstants.END_OF_LINE));
// }
protected void initializePage() {
fPreview.setPreviewText(PREVIEW);
}
protected CPreview doCreateCPreview(Composite parent) {
fPreview= new TranslationUnitPreview(fWorkingValues, parent);
return fPreview;
}
private ComboPreference createBracesCombo(Composite composite, int numColumns, String message, String key) {
return createComboPref(composite, numColumns, message, key, fBracePositions, fBracePositionNames);
}
private ComboPreference createExtendedBracesCombo(Composite composite, int numColumns, String message, String key) {
return createComboPref(composite, numColumns, message, key, fExtendedBracePositions, fExtendedBracePositionNames);
}
// private CheckboxPreference createIndentedCheckboxPref(Composite composite, int numColumns, String message, String key, String [] values) {
// CheckboxPreference pref= createCheckboxPref(composite, numColumns, message, key, values);
// GridData data= (GridData) pref.getControl().getLayoutData();
// data.horizontalIndent= fPixelConverter.convertWidthInCharsToPixels(1);
// return pref;
// }
protected void doUpdatePreview() {
fPreview.update();
}
}

View file

@ -14,6 +14,15 @@ package org.eclipse.cdt.internal.ui.preferences.formatter;
import java.util.Map;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.preference.PreferenceStore;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.MarginPainter;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.DisposeEvent;
@ -22,34 +31,25 @@ import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.preference.PreferenceStore;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.MarginPainter;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants;
import org.eclipse.ui.texteditor.ChainedPreferenceStore;
import org.eclipse.cdt.core.formatter.DefaultCodeFormatterConstants;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.ui.PreferenceConstants;
import org.eclipse.cdt.ui.text.ICPartitions;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.internal.ui.InvisibleCharacterPainter;
import org.eclipse.cdt.internal.ui.editor.CSourceViewer;
import org.eclipse.cdt.internal.ui.text.CSourceViewerConfiguration;
import org.eclipse.cdt.internal.ui.text.CTextTools;
import org.eclipse.cdt.internal.ui.text.SimpleCSourceViewerConfiguration;
/**
* Abstract previewer for C/C++ source code formatting.
*
* @since 4.0
*/
public abstract class CPreview {
private final class CSourcePreviewerUpdater {
@ -99,6 +99,7 @@ public abstract class CPreview {
protected Map fWorkingValues;
private int fTabSize= 0;
private InvisibleCharacterPainter fWhitespacePainter;
/**
* Create a new C preview
@ -124,7 +125,9 @@ public abstract class CPreview {
final RGB rgb= PreferenceConverter.getColor(fPreferenceStore, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLOR);
fMarginPainter.setMarginRulerColor(tools.getColorManager().getColor(rgb));
fSourceViewer.addPainter(fMarginPainter);
fWhitespacePainter= new InvisibleCharacterPainter(fSourceViewer);
new CSourcePreviewerUpdater();
fSourceViewer.setDocument(fPreviewDocument);
}
@ -196,4 +199,17 @@ public abstract class CPreview {
public final void setWorkingValues(Map workingValues) {
fWorkingValues= workingValues;
}
/**
* Enable/disable display of whitespace characters.
*
* @param show flag, whether to display whitespace
*/
public void showWhitespace(boolean show) {
if (show) {
fSourceViewer.addPainter(fWhitespacePainter);
} else {
fSourceViewer.removePainter(fWhitespacePainter);
}
}
}

View file

@ -9,540 +9,166 @@
* IBM Corporation - initial API and implementation
* Aaron Luchko, aluchko@redhat.com - 105926 [Formatter] Exporting Unnamed profile fails silently
* Sergey Prigogin, Google
* Anton Leherbauer (Wind River Systems)
*******************************************************************************/
package org.eclipse.cdt.internal.ui.preferences.formatter;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.preferences.DefaultScope;
import org.eclipse.core.runtime.preferences.IScopeContext;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ProjectScope;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.core.runtime.preferences.IScopeContext;
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.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.window.Window;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.internal.ui.util.Messages;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.internal.ui.preferences.PreferencesAccess;
import org.eclipse.cdt.internal.ui.preferences.formatter.ProfileManager.CustomProfile;
import org.eclipse.cdt.internal.ui.preferences.formatter.ProfileManager.Profile;
import org.eclipse.cdt.internal.ui.util.ExceptionHandler;
import org.eclipse.cdt.internal.ui.util.PixelConverter;
import org.eclipse.cdt.internal.ui.util.SWTUtil;
import org.osgi.service.prefs.BackingStoreException;
/**
* The code formatter preference page.
*/
public class CodeFormatterConfigurationBlock {
public class CodeFormatterConfigurationBlock extends ProfileConfigurationBlock {
private static final String DIALOGSTORE_LASTLOADPATH= CUIPlugin.PLUGIN_ID + ".codeformatter.loadpath"; //$NON-NLS-1$
private static final String DIALOGSTORE_LASTSAVEPATH= CUIPlugin.PLUGIN_ID + ".codeformatter.savepath"; //$NON-NLS-1$
private class StoreUpdater implements Observer {
public StoreUpdater() {
fProfileManager.addObserver(this);
}
private static final String FORMATTER_DIALOG_PREFERENCE_KEY= "formatter_page"; //$NON-NLS-1$
private static final String DIALOGSTORE_LASTSAVELOADPATH= CUIPlugin.PLUGIN_ID + ".codeformatter.savepath"; //$NON-NLS-1$
private class PreviewController implements Observer {
public PreviewController(ProfileManager profileManager) {
profileManager.addObserver(this);
fCustomCodeFormatterBlock.addObserver(this);
fCodeStylePreview.setWorkingValues(profileManager.getSelected().getSettings());
fCodeStylePreview.update();
}
public void update(Observable o, Object arg) {
final int value= ((Integer)arg).intValue();
switch (value) {
case ProfileManager.PROFILE_DELETED_EVENT:
case ProfileManager.PROFILE_RENAMED_EVENT:
case ProfileManager.PROFILE_CREATED_EVENT:
case ProfileManager.SETTINGS_CHANGED_EVENT:
try {
ProfileStore.writeProfiles(fProfileManager.getSortedProfiles(), fInstanceScope); // update profile store
fProfileManager.commitChanges(fCurrContext); // update formatter settings with curently selected profile
} catch (CoreException x) {
CUIPlugin.getDefault().log(x);
}
break;
case ProfileManager.SELECTION_CHANGED_EVENT:
fProfileManager.commitChanges(fCurrContext); // update formatter settings with curently selected profile
break;
if (o == fCustomCodeFormatterBlock) {
fCodeStylePreview.setFormatterId((String)arg);
fCodeStylePreview.update();
return;
}
}
}
private class ProfileComboController implements Observer, SelectionListener {
private final List fSortedProfiles;
public ProfileComboController() {
fSortedProfiles= fProfileManager.getSortedProfiles();
fProfileCombo.addSelectionListener(this);
fProfileManager.addObserver(this);
updateProfiles();
updateSelection();
}
public void widgetSelected(SelectionEvent e) {
final int index= fProfileCombo.getSelectionIndex();
fProfileManager.setSelected((Profile)fSortedProfiles.get(index));
}
public void widgetDefaultSelected(SelectionEvent e) {}
public void update(Observable o, Object arg) {
if (arg == null) return;
final int value= ((Integer)arg).intValue();
switch (value) {
case ProfileManager.PROFILE_CREATED_EVENT:
case ProfileManager.PROFILE_DELETED_EVENT:
case ProfileManager.PROFILE_RENAMED_EVENT:
updateProfiles();
updateSelection();
break;
case ProfileManager.SELECTION_CHANGED_EVENT:
updateSelection();
break;
case ProfileManager.SETTINGS_CHANGED_EVENT:
fCodeStylePreview.setWorkingValues(((ProfileManager)o).getSelected().getSettings());
fCodeStylePreview.update();
}
}
private void updateProfiles() {
fProfileCombo.setItems(fProfileManager.getSortedDisplayNames());
}
private void updateSelection() {
fProfileCombo.setText(fProfileManager.getSelected().getName());
}
}
private class ButtonController implements Observer, SelectionListener {
public ButtonController() {
fProfileManager.addObserver(this);
fNewButton.addSelectionListener(this);
fRenameButton.addSelectionListener(this);
fEditButton.addSelectionListener(this);
fDeleteButton.addSelectionListener(this);
fSaveButton.addSelectionListener(this);
fLoadButton.addSelectionListener(this);
update(fProfileManager, null);
}
public void update(Observable o, Object arg) {
Profile selected= ((ProfileManager)o).getSelected();
final boolean notBuiltIn= !selected.isBuiltInProfile();
fEditButton.setText(notBuiltIn ? FormatterMessages.CodingStyleConfigurationBlock_edit_button_desc
: FormatterMessages.CodingStyleConfigurationBlock_show_button_desc);
fDeleteButton.setEnabled(notBuiltIn);
fSaveButton.setEnabled(notBuiltIn);
fRenameButton.setEnabled(notBuiltIn);
}
public void widgetSelected(SelectionEvent e) {
final Button button= (Button)e.widget;
if (button == fSaveButton)
saveButtonPressed();
else if (button == fEditButton)
modifyButtonPressed();
else if (button == fDeleteButton)
deleteButtonPressed();
else if (button == fNewButton)
newButtonPressed();
else if (button == fLoadButton)
loadButtonPressed();
else if (button == fRenameButton)
renameButtonPressed();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
private void renameButtonPressed() {
if (fProfileManager.getSelected().isBuiltInProfile())
return;
final CustomProfile profile= (CustomProfile) fProfileManager.getSelected();
final RenameProfileDialog renameDialog= new RenameProfileDialog(fComposite.getShell(), profile, fProfileManager);
if (renameDialog.open() == Window.OK) {
fProfileManager.setSelected(renameDialog.getRenamedProfile());
}
}
private void modifyButtonPressed() {
final ModifyDialog modifyDialog= new ModifyDialog(fComposite.getShell(), fProfileManager.getSelected(), fProfileManager, false);
modifyDialog.open();
}
private void deleteButtonPressed() {
if (MessageDialog.openQuestion(
fComposite.getShell(),
FormatterMessages.CodingStyleConfigurationBlock_delete_confirmation_title,
Messages.format(FormatterMessages.CodingStyleConfigurationBlock_delete_confirmation_question, fProfileManager.getSelected().getName()))) {
fProfileManager.deleteSelected();
}
}
private void newButtonPressed() {
final CreateProfileDialog p= new CreateProfileDialog(fComposite.getShell(), fProfileManager);
if (p.open() != Window.OK)
return;
if (!p.openEditDialog())
return;
final ModifyDialog modifyDialog= new ModifyDialog(fComposite.getShell(), p.getCreatedProfile(), fProfileManager, true);
modifyDialog.open();
}
private void saveButtonPressed() {
Profile selected= fProfileManager.getSelected();
if (selected.isSharedProfile()) {
final RenameProfileDialog renameDialog= new RenameProfileDialog(fComposite.getShell(), selected, fProfileManager);
if (renameDialog.open() != Window.OK) {
return;
}
selected= renameDialog.getRenamedProfile();
fProfileManager.setSelected(selected);
}
final FileDialog dialog= new FileDialog(fComposite.getShell(), SWT.SAVE);
dialog.setText(FormatterMessages.CodingStyleConfigurationBlock_save_profile_dialog_title);
dialog.setFilterExtensions(new String [] {"*.xml"}); //$NON-NLS-1$
final String lastPath= CUIPlugin.getDefault().getDialogSettings().get(DIALOGSTORE_LASTSAVEPATH);
if (lastPath != null) {
dialog.setFilterPath(lastPath);
}
final String path= dialog.open();
if (path == null)
return;
CUIPlugin.getDefault().getDialogSettings().put(DIALOGSTORE_LASTSAVEPATH, dialog.getFilterPath());
final File file= new File(path);
if (file.exists() && !MessageDialog.openQuestion(fComposite.getShell(), FormatterMessages.CodingStyleConfigurationBlock_save_profile_overwrite_title, Messages.format(FormatterMessages.CodingStyleConfigurationBlock_save_profile_overwrite_message, path))) {
return;
}
final Collection profiles= new ArrayList();
profiles.add(selected);
try {
ProfileStore.writeProfilesToFile(profiles, file);
} catch (CoreException e) {
final String title= FormatterMessages.CodingStyleConfigurationBlock_save_profile_error_title;
final String message= FormatterMessages.CodingStyleConfigurationBlock_save_profile_error_message;
ExceptionHandler.handle(e, fComposite.getShell(), title, message);
}
}
private void loadButtonPressed() {
final FileDialog dialog= new FileDialog(fComposite.getShell(), SWT.OPEN);
dialog.setText(FormatterMessages.CodingStyleConfigurationBlock_load_profile_dialog_title);
dialog.setFilterExtensions(new String [] {"*.xml"}); //$NON-NLS-1$
final String lastPath= CUIPlugin.getDefault().getDialogSettings().get(DIALOGSTORE_LASTLOADPATH);
if (lastPath != null) {
dialog.setFilterPath(lastPath);
}
final String path= dialog.open();
if (path == null)
return;
CUIPlugin.getDefault().getDialogSettings().put(DIALOGSTORE_LASTLOADPATH, dialog.getFilterPath());
final File file= new File(path);
Collection profiles= null;
try {
profiles= ProfileStore.readProfilesFromFile(file);
} catch (CoreException e) {
final String title= FormatterMessages.CodingStyleConfigurationBlock_load_profile_error_title;
final String message= FormatterMessages.CodingStyleConfigurationBlock_load_profile_error_message;
ExceptionHandler.handle(e, fComposite.getShell(), title, message);
}
if (profiles == null || profiles.isEmpty())
return;
final CustomProfile profile= (CustomProfile)profiles.iterator().next();
if (ProfileVersioner.getVersionStatus(profile) > 0) {
final String title= FormatterMessages.CodingStyleConfigurationBlock_load_profile_error_too_new_title;
final String message= FormatterMessages.CodingStyleConfigurationBlock_load_profile_error_too_new_message;
MessageDialog.openWarning(fComposite.getShell(), title, message);
}
if (fProfileManager.containsName(profile.getName())) {
final AlreadyExistsDialog aeDialog= new AlreadyExistsDialog(fComposite.getShell(), profile, fProfileManager);
if (aeDialog.open() != Window.OK)
return;
}
ProfileVersioner.updateAndComplete(profile);
fProfileManager.addProfile(profile);
}
}
// private class PreviewController implements Observer {
//
// public PreviewController() {
// fProfileManager.addObserver(this);
// fCodeStylePreview.setWorkingValues(fProfileManager.getSelected().getSettings());
// fCodeStylePreview.update();
// }
//
// public void update(Observable o, Object arg) {
// final int value= ((Integer)arg).intValue();
// switch (value) {
// case ProfileManager.PROFILE_CREATED_EVENT:
// case ProfileManager.PROFILE_DELETED_EVENT:
// case ProfileManager.SELECTION_CHANGED_EVENT:
// case ProfileManager.SETTINGS_CHANGED_EVENT:
// fCodeStylePreview.setWorkingValues(((ProfileManager)o).getSelected().getSettings());
// fCodeStylePreview.update();
// }
// }
// }
// /**
// * Some C source code used for preview.
// */
// private final static String PREVIEW=
// "/*\n* " + //$NON-NLS-1$
// FormatterMessages.CodingStyleConfigurationBlock_preview_title +
// "\n*/\n\n" + //$NON-NLS-1$
// "#include <math.h>\n" + //$NON-NLS-1$
// "class Point {" + //$NON-NLS-1$
// "public:" + //$NON-NLS-1$
// "Point(double xc, double yc) : x(xc), y(yc) {}" + //$NON-NLS-1$
// "double distance(const Point& other) const;" + //$NON-NLS-1$
// "double x;" + //$NON-NLS-1$
// "double y;" + //$NON-NLS-1$
// "};" + //$NON-NLS-1$
// "float Point::distance(const Point& other) const {" + //$NON-NLS-1$
// "double dx = x - other.x;" + //$NON-NLS-1$
// "double dy = y - other.y;" + //$NON-NLS-1$
// "return sqrt(dx * dx + dy * dy);" + //$NON-NLS-1$
// "}"; //$NON-NLS-1$
/**
* The GUI controls
* Some C++ source code used for preview.
*/
protected Composite fComposite;
protected Combo fProfileCombo;
protected Button fEditButton;
protected Button fRenameButton;
protected Button fDeleteButton;
protected Button fNewButton;
protected Button fLoadButton;
protected Button fSaveButton;
/**
* The ProfileManager, the model of this page.
*/
protected final ProfileManager fProfileManager;
private CustomCodeFormatterBlock fCustomCodeFormatterBlock;
private final static String PREVIEW=
"/*\n* " + //$NON-NLS-1$
FormatterMessages.CodingStyleConfigurationBlock_preview_title +
"\n*/\n" + //$NON-NLS-1$
"#include <math.h>\n" + //$NON-NLS-1$
"class Point {" + //$NON-NLS-1$
"public:" + //$NON-NLS-1$
"Point(double xc, double yc) : x(xc), y(yc) {}" + //$NON-NLS-1$
"double distance(const Point& other) const;" + //$NON-NLS-1$
"double x;" + //$NON-NLS-1$
"double y;" + //$NON-NLS-1$
"};" + //$NON-NLS-1$
"double Point::distance(const Point& other) const {" + //$NON-NLS-1$
"double dx = x - other.x;" + //$NON-NLS-1$
"double dy = y - other.y;" + //$NON-NLS-1$
"return sqrt(dx * dx + dy * dy);" + //$NON-NLS-1$
"}"; //$NON-NLS-1$
/**
* The CPreview.
*/
// protected TranslationUnitPreview fCodeStylePreview;
private PixelConverter fPixConv;
private IScopeContext fCurrContext;
private IScopeContext fInstanceScope;
protected TranslationUnitPreview fCodeStylePreview;
protected CustomCodeFormatterBlock fCustomCodeFormatterBlock;
/**
* Create a new <code>CodeFormatterConfigurationBlock</code>.
*/
public CodeFormatterConfigurationBlock(IProject project, PreferencesAccess access) {
fInstanceScope= access.getInstanceScope();
List profiles= null;
try {
profiles= ProfileStore.readProfiles(fInstanceScope);
} catch (CoreException e) {
CUIPlugin.getDefault().log(e);
super(project, access, DIALOGSTORE_LASTSAVELOADPATH);
if (project == null) {
//TLETODO formatter customizable on project level?
fCustomCodeFormatterBlock= new CustomCodeFormatterBlock(access);
}
if (profiles == null) {
try {
// bug 129427
profiles= ProfileStore.readProfilesFromPreferences(new DefaultScope());
} catch (CoreException e) {
CUIPlugin.getDefault().log(e);
}
}
protected IProfileVersioner createProfileVersioner() {
return new ProfileVersioner();
}
protected ProfileStore createProfileStore(IProfileVersioner versioner) {
return new FormatterProfileStore(versioner);
}
protected ProfileManager createProfileManager(List profiles, IScopeContext context, PreferencesAccess access, IProfileVersioner profileVersioner) {
return new FormatterProfileManager(profiles, context, access, profileVersioner);
}
protected void configurePreview(Composite composite, int numColumns, ProfileManager profileManager) {
if (fCustomCodeFormatterBlock != null) {
fCustomCodeFormatterBlock.createContents(composite);
}
if (profiles == null)
profiles= new ArrayList();
if (project != null) {
fCurrContext= access.getProjectScope(project);
} else {
fCurrContext= fInstanceScope;
}
fProfileManager= new ProfileManager(profiles, fCurrContext, access);
fCustomCodeFormatterBlock= new CustomCodeFormatterBlock(CUIPlugin.getDefault().getPluginPreferences());
createLabel(composite, FormatterMessages.CodingStyleConfigurationBlock_preview_label_text, numColumns);
TranslationUnitPreview result= new TranslationUnitPreview(profileManager.getSelected().getSettings(), composite);
result.setFormatterId(fCustomCodeFormatterBlock.getFormatterId());
result.setPreviewText(PREVIEW);
fCodeStylePreview= result;
new StoreUpdater();
}
/**
* Create the contents
* @param parent Parent composite
* @return Created control
*/
public Composite createContents(Composite parent) {
final int numColumns = 5;
fPixConv = new PixelConverter(parent);
fComposite = createComposite(parent, numColumns);
fProfileCombo= createProfileCombo(fComposite, numColumns - 3, fPixConv.convertWidthInCharsToPixels(20));
fEditButton= createButton(fComposite, FormatterMessages.CodingStyleConfigurationBlock_edit_button_desc, GridData.HORIZONTAL_ALIGN_BEGINNING);
fRenameButton= createButton(fComposite, FormatterMessages.CodingStyleConfigurationBlock_rename_button_desc, GridData.HORIZONTAL_ALIGN_BEGINNING);
fDeleteButton= createButton(fComposite, FormatterMessages.CodingStyleConfigurationBlock_remove_button_desc, GridData.HORIZONTAL_ALIGN_BEGINNING);
final Composite group= createComposite(fComposite, 4);
final GridData groupData= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
groupData.horizontalSpan= numColumns;
group.setLayoutData(groupData);
fNewButton= createButton(group, FormatterMessages.CodingStyleConfigurationBlock_new_button_desc, GridData.HORIZONTAL_ALIGN_BEGINNING);
((GridData)createLabel(group, "", 1).getLayoutData()).grabExcessHorizontalSpace= true; //$NON-NLS-1$
fLoadButton= createButton(group, FormatterMessages.CodingStyleConfigurationBlock_load_button_desc, GridData.HORIZONTAL_ALIGN_END);
fSaveButton= createButton(group, FormatterMessages.CodingStyleConfigurationBlock_save_button_desc, GridData.HORIZONTAL_ALIGN_END);
fCustomCodeFormatterBlock.createContents(fComposite);
// createLabel(fComposite, FormatterMessages.CodingStyleConfigurationBlock_preview_label_text, numColumns);
// configurePreview(fComposite, numColumns);
new ButtonController();
new ProfileComboController();
// new PreviewController();
return fComposite;
}
private static Button createButton(Composite composite, String text, final int style) {
final Button button= new Button(composite, SWT.PUSH);
button.setFont(composite.getFont());
button.setText(text);
final GridData gd= new GridData(style);
gd.widthHint= SWTUtil.getButtonWidthHint(button);
button.setLayoutData(gd);
return button;
}
private static Combo createProfileCombo(Composite composite, int span, int widthHint) {
final GridData gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan = span;
gd.widthHint= widthHint;
final Combo combo= new Combo(composite, SWT.DROP_DOWN | SWT.READ_ONLY);
combo.setFont(composite.getFont());
combo.setLayoutData(gd);
return combo;
}
private Label createLabel(Composite composite, String text, int numColumns) {
final GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
final GridData gd = new GridData(GridData.FILL_VERTICAL | GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan = numColumns;
gd.widthHint= 0;
final Label label = new Label(composite, SWT.WRAP);
label.setFont(composite.getFont());
label.setText(text);
label.setLayoutData(gd);
return label;
}
private Composite createComposite(Composite parent, int numColumns) {
final Composite composite = new Composite(parent, SWT.NONE);
composite.setFont(parent.getFont());
gd.verticalSpan= 7;
gd.widthHint = 0;
gd.heightHint = 0;
fCodeStylePreview.getControl().setLayoutData(gd);
final GridLayout layout = new GridLayout(numColumns, false);
layout.marginHeight = 0;
layout.marginWidth = 0;
composite.setLayout(layout);
return composite;
new PreviewController(profileManager);
}
// private void configurePreview(Composite composite, int numColumns) {
// fCodeStylePreview= new TranslationUnitPreview(fProfileManager.getSelected().getSettings(), composite);
// fCodeStylePreview.setPreviewText(PREVIEW);
//
// final GridData gd = new GridData(GridData.FILL_VERTICAL | GridData.HORIZONTAL_ALIGN_FILL);
// gd.horizontalSpan = numColumns;
// gd.verticalSpan= 7;
// gd.widthHint = 0;
// gd.heightHint = 0;
// fCodeStylePreview.getControl().setLayoutData(gd);
// }
public final boolean hasProjectSpecificOptions(IProject project) {
if (project != null) {
return ProfileManager.hasProjectSpecificSettings(new ProjectScope(project));
}
return false;
}
public boolean performOk() {
fCustomCodeFormatterBlock.performOk();
return true;
}
protected ModifyDialog createModifyDialog(Shell shell, Profile profile, ProfileManager profileManager, ProfileStore profileStore, boolean newProfile) {
return new FormatterModifyDialog(shell, profile, profileManager, profileStore, newProfile, FORMATTER_DIALOG_PREFERENCE_KEY, DIALOGSTORE_LASTSAVELOADPATH);
}
/*
* @see org.eclipse.cdt.internal.ui.preferences.formatter.ProfileConfigurationBlock#performApply()
*/
public void performApply() {
try {
fCurrContext.getNode(CUIPlugin.PLUGIN_ID).flush();
fCurrContext.getNode(CCorePlugin.PLUGIN_ID).flush();
if (fCurrContext != fInstanceScope) {
fInstanceScope.getNode(CUIPlugin.PLUGIN_ID).flush();
fInstanceScope.getNode(CCorePlugin.PLUGIN_ID).flush();
}
if (fCustomCodeFormatterBlock != null) {
fCustomCodeFormatterBlock.performOk();
} catch (BackingStoreException e) {
CUIPlugin.getDefault().log(e);
}
}
public void performDefaults() {
Profile profile= fProfileManager.getProfile(ProfileManager.DEFAULT_PROFILE);
if (profile != null) {
int defaultIndex= fProfileManager.getSortedProfiles().indexOf(profile);
if (defaultIndex != -1) {
fProfileManager.setSelected(profile);
}
}
fCustomCodeFormatterBlock.performDefaults();
}
public void dispose() {
super.performApply();
}
public void enableProjectSpecificSettings(boolean useProjectSpecificSettings) {
if (useProjectSpecificSettings) {
fProfileManager.commitChanges(fCurrContext);
} else {
fProfileManager.clearAllSettings(fCurrContext);
/*
* @see org.eclipse.cdt.internal.ui.preferences.formatter.ProfileConfigurationBlock#performDefaults()
*/
public void performDefaults() {
if (fCustomCodeFormatterBlock != null) {
fCustomCodeFormatterBlock.performDefaults();
}
super.performDefaults();
}
/*
* @see org.eclipse.cdt.internal.ui.preferences.formatter.ProfileConfigurationBlock#performOk()
*/
public boolean performOk() {
if (fCustomCodeFormatterBlock != null) {
fCustomCodeFormatterBlock.performOk();
}
return super.performOk();
}
}

View file

@ -1,5 +1,5 @@
/*******************************************************************************
* Copyright (c) 2000, 2005 IBM Corporation and others.
* Copyright (c) 2000, 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
@ -8,6 +8,7 @@
* Contributors:
* IBM Corporation - initial API and implementation
* Sergey Prigogin, Google
* Anton Leherbauer (Wind River Systems)
*******************************************************************************/
package org.eclipse.cdt.internal.ui.preferences.formatter;
@ -16,7 +17,10 @@ import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.cdt.internal.ui.preferences.formatter.IProfileVersioner;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.StatusDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
@ -32,11 +36,8 @@ import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.StatusDialog;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.cdt.internal.ui.preferences.formatter.ProfileManager.CustomProfile;
import org.eclipse.cdt.internal.ui.preferences.formatter.ProfileManager.Profile;
@ -62,10 +63,13 @@ public class CreateProfileDialog extends StatusDialog {
private CustomProfile fCreatedProfile;
protected boolean fOpenEditDialog;
private final IProfileVersioner fProfileVersioner;
public CreateProfileDialog(Shell parentShell, ProfileManager profileManager) {
public CreateProfileDialog(Shell parentShell, ProfileManager profileManager, IProfileVersioner profileVersioner) {
super(parentShell);
fProfileManager= profileManager;
fProfileVersioner= profileVersioner;
fSortedProfiles= fProfileManager.getSortedProfiles();
fSortedNames= fProfileManager.getSortedDisplayNames();
}
@ -145,7 +149,7 @@ public class CreateProfileDialog extends StatusDialog {
fEditCheckbox.setSelection(fOpenEditDialog);
fProfileCombo.setItems(fSortedNames);
fProfileCombo.setText(fProfileManager.getProfile(ProfileManager.DEFAULT_PROFILE).getName());
fProfileCombo.setText(fProfileManager.getDefaultProfile().getName());
updateStatus(fEmpty);
applyDialogFont(composite);
@ -182,7 +186,7 @@ public class CreateProfileDialog extends StatusDialog {
final Map baseSettings= new HashMap(((Profile)fSortedProfiles.get(fProfileCombo.getSelectionIndex())).getSettings());
final String profileName= fNameText.getText();
fCreatedProfile= new CustomProfile(profileName, baseSettings, ProfileVersioner.CURRENT_VERSION);
fCreatedProfile= new CustomProfile(profileName, baseSettings, fProfileVersioner.getCurrentVersion(), fProfileVersioner.getProfileKind());
fProfileManager.addProfile(fCreatedProfile);
super.okPressed();
}

View file

@ -8,6 +8,7 @@
* Contributors:
* QNX Software Systems - Initial API and implementation
* Sergey Prigogin, Google
* Anton Leherbauer (Wind River Systems)
*******************************************************************************/
package org.eclipse.cdt.internal.ui.preferences.formatter;
@ -15,59 +16,61 @@ package org.eclipse.cdt.internal.ui.preferences.formatter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Observable;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtension;
import org.eclipse.core.runtime.IExtensionPoint;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Preferences;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.jface.resource.JFaceResources;
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.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.PlatformUI;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.CCorePreferenceConstants;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.utils.ui.controls.ControlFactory;
import org.eclipse.cdt.internal.ui.ICHelpContextIds;
import org.eclipse.cdt.internal.ui.preferences.PreferencesAccess;
/**
*
* Allows to choose the formatter in a combo box.
* If no formatter is contributed, nothing is shown.
*/
public class CustomCodeFormatterBlock {
public class CustomCodeFormatterBlock extends Observable {
private HashMap idMap = new HashMap();
Preferences fPrefs;
protected Combo fFormatterCombo;
private IEclipsePreferences fPrefs;
private String fDefaultFormatterId;
private Combo fFormatterCombo;
private static final String ATTR_NAME = "name"; //$NON-NLS-1$
private static final String ATTR_ID = "id"; //$NON-NLS-1$
// This is a hack until we have a default Formatter.
// For now it is comment out in the plugin.xml
private static final String NONE = FormatterMessages.CustomCodeFormatterBlock_no_formatter;
private static final String DEFAULT = FormatterMessages.CustomCodeFormatterBlock_default_formatter;
public CustomCodeFormatterBlock(PreferencesAccess access) {
fPrefs = access.getInstanceScope().getNode(CUIPlugin.PLUGIN_ID);
IEclipsePreferences defaults= access.getDefaultScope().getNode(CUIPlugin.PLUGIN_ID);
fDefaultFormatterId= defaults.get(CCorePreferenceConstants.CODE_FORMATTER, null);
public CustomCodeFormatterBlock(Preferences prefs) {
fPrefs = prefs;
initializeFormatters();
}
public void performOk() {
if (fFormatterCombo == null) {
return;
}
String text = fFormatterCombo.getText();
String selection = (String)idMap.get(text);
if (selection != null && selection.length() > 0) {
HashMap options = CCorePlugin.getOptions();
String formatterID = (String)options.get(CCorePreferenceConstants.CODE_FORMATTER);
if (formatterID == null || !formatterID.equals(selection)) {
options.put(CCorePreferenceConstants.CODE_FORMATTER, selection);
CCorePlugin.setOptions(options);
}
String formatterId = (String)idMap.get(text);
if (formatterId != null && formatterId.length() > 0) {
fPrefs.put(CCorePreferenceConstants.CODE_FORMATTER, formatterId);
} else {
// simply reset to the default one.
performDefaults();
@ -75,37 +78,54 @@ public class CustomCodeFormatterBlock {
}
public void performDefaults() {
HashMap optionsDefault = CCorePlugin.getDefaultOptions();
HashMap options = CCorePlugin.getOptions();
String formatterID = (String)optionsDefault.get(CCorePreferenceConstants.CODE_FORMATTER);
options.put(CCorePreferenceConstants.CODE_FORMATTER, formatterID);
CCorePlugin.setOptions(options);
if (fDefaultFormatterId != null) {
fPrefs.put(CCorePreferenceConstants.CODE_FORMATTER, fDefaultFormatterId);
} else {
fPrefs.remove(CCorePreferenceConstants.CODE_FORMATTER);
}
if (fFormatterCombo == null) {
return;
}
fFormatterCombo.clearSelection();
fFormatterCombo.setText(NONE);
fFormatterCombo.setText(DEFAULT);
Iterator iterator = idMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry entry = (Map.Entry)iterator.next();
String val = (String)entry.getValue();
if (val != null && val.equals(formatterID)) {
if (val != null && val.equals(fDefaultFormatterId)) {
fFormatterCombo.setText((String)entry.getKey());
}
}
handleFormatterChanged();
}
/**
* Get the currently selected formatter id.
*
* @return the selected formatter id or <code>null</code> if the default is selected.
*/
public String getFormatterId() {
if (fFormatterCombo == null) {
return fPrefs.get(CCorePreferenceConstants.CODE_FORMATTER, fDefaultFormatterId);
}
String formatterId= (String)idMap.get(fFormatterCombo.getText());
return formatterId;
}
/* (non-Javadoc)
* @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
*/
public Control createContents(Composite parent) {
Composite composite = ControlFactory.createComposite(parent, 1);
((GridLayout)composite.getLayout()).marginWidth = 0;
((GridData)composite.getLayoutData()).horizontalSpan = 2;
if (getNumberOfAvailableFormatters() == 0) {
return parent;
}
Composite composite = ControlFactory.createGroup(parent, FormatterMessages.CustomCodeFormatterBlock_formatter_name, 1);
((GridData)composite.getLayoutData()).horizontalSpan = 5;
PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, ICHelpContextIds.CODEFORMATTER_PREFERENCE_PAGE);
ControlFactory.createEmptySpace(composite, 1);
Label label = ControlFactory.createLabel(composite, FormatterMessages.CustomCodeFormatterBlock_formatter_name);
fFormatterCombo = new Combo(composite, SWT.DROP_DOWN | SWT.READ_ONLY);
fFormatterCombo.setFont(parent.getFont());
fFormatterCombo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
@ -119,45 +139,44 @@ public class CustomCodeFormatterBlock {
fFormatterCombo.add((String) items.next());
}
label = ControlFactory.createLabel(parent, FormatterMessages.CustomCodeFormatterBlock_contributed_formatter_warning);
((GridData)label.getLayoutData()).horizontalSpan = 5;
final String noteTitle= FormatterMessages.CustomCodeFormatterBlock_formatter_note;
final String noteMessage= FormatterMessages.CustomCodeFormatterBlock_contributed_formatter_warning;
ControlFactory.createNoteComposite(JFaceResources.getDialogFont(), composite, noteTitle, noteMessage);
initDefault();
handleFormatterChanged();
if (getNumberOfAvailableFormatters() == 0) {
composite.setVisible(false);
label.setVisible(false);
}
return composite;
}
private void handleFormatterChanged() {
// TODO: UI part.
private void handleFormatterChanged() {
setChanged();
String formatterId= getFormatterId();
notifyObservers(formatterId);
}
private void initDefault() {
boolean init = false;
String selection = CCorePlugin.getOption(CCorePreferenceConstants.CODE_FORMATTER);
if (selection != null) {
String formatterID= fPrefs.get(CCorePreferenceConstants.CODE_FORMATTER, fDefaultFormatterId);
if (formatterID != null) {
Iterator iterator = idMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry entry = (Map.Entry)iterator.next();
String val = (String)entry.getValue();
if (val != null && val.equals(selection)) {
if (val != null && val.equals(formatterID)) {
fFormatterCombo.setText((String)entry.getKey());
init = true;
}
}
}
if (!init) {
fFormatterCombo.setText(NONE);
formatterID= null;
fFormatterCombo.setText(DEFAULT);
}
}
private void initializeFormatters() {
idMap = new HashMap();
idMap.put(NONE, null);
idMap.put(DEFAULT, null);
IExtensionPoint point = Platform.getExtensionRegistry().getExtensionPoint(CCorePlugin.PLUGIN_ID, CCorePlugin.FORMATTER_EXTPOINT_ID);
if (point != null) {
IExtension[] exts = point.getExtensions();
@ -165,7 +184,8 @@ public class CustomCodeFormatterBlock {
IConfigurationElement[] elements = exts[i].getConfigurationElements();
for (int j = 0; j < elements.length; ++j) {
String name = elements[j].getAttribute(ATTR_NAME);
idMap.put(name, elements[j].getAttribute(ATTR_ID));
String id= elements[j].getAttribute(ATTR_ID);
idMap.put(name, id);
}
}
}

View file

@ -8,6 +8,7 @@
* Contributors:
* IBM Corporation - initial API and implementation
* Sergey Prigogin, Google
* Anton Leherbauer (Wind River Systems)
*******************************************************************************/
package org.eclipse.cdt.internal.ui.preferences.formatter;
@ -24,6 +25,14 @@ final class FormatterMessages extends NLS {
// Do not instantiate
}
public static String ModifyDialog_BuiltIn_Status;
public static String ModifyDialog_Duplicate_Status;
public static String ModifyDialog_EmptyName_Status;
public static String ModifyDialog_Export_Button;
public static String ModifyDialog_NewCreated_Status;
public static String ModifyDialog_ProfileName_Label;
public static String ModifyDialog_Shared_Status;
public static String ProfileConfigurationBlock_load_profile_wrong_profile_message;
// public static String WhiteSpaceTabPage_assignments;
// public static String WhiteSpaceTabPage_assignments_before_assignment_operator;
// public static String WhiteSpaceTabPage_assignments_after_assignment_operator;
@ -252,46 +261,46 @@ final class FormatterMessages extends NLS {
// public static String LineWrappingTabPage_enum_constant_arguments;
// public static String LineWrappingTabPage_enum_constants;
// public static String LineWrappingTabPage_implements_clause;
// public static String LineWrappingTabPage_parameters;
// public static String LineWrappingTabPage_arguments;
public static String LineWrappingTabPage_parameters;
public static String LineWrappingTabPage_arguments;
// public static String LineWrappingTabPage_qualified_invocations;
// public static String LineWrappingTabPage_throws_clause;
// public static String LineWrappingTabPage_object_allocation;
// public static String LineWrappingTabPage_qualified_object_allocation;
// public static String LineWrappingTabPage_array_init;
public static String LineWrappingTabPage_array_init;
// public static String LineWrappingTabPage_explicit_constructor_invocations;
// public static String LineWrappingTabPage_conditionals;
public static String LineWrappingTabPage_conditionals;
// public static String LineWrappingTabPage_binary_exprs;
// public static String LineWrappingTabPage_indentation_default;
// public static String LineWrappingTabPage_indentation_on_column;
// public static String LineWrappingTabPage_indentation_by_one;
public static String LineWrappingTabPage_indentation_default;
public static String LineWrappingTabPage_indentation_on_column;
public static String LineWrappingTabPage_indentation_by_one;
// public static String LineWrappingTabPage_class_decls;
// public static String LineWrappingTabPage_method_decls;
public static String LineWrappingTabPage_method_decls;
// public static String LineWrappingTabPage_constructor_decls;
// public static String LineWrappingTabPage_function_calls;
// public static String LineWrappingTabPage_expressions;
public static String LineWrappingTabPage_function_calls;
public static String LineWrappingTabPage_expressions;
// public static String LineWrappingTabPage_statements;
// public static String LineWrappingTabPage_enum_decls;
// public static String LineWrappingTabPage_wrapping_policy_label_text;
// public static String LineWrappingTabPage_indentation_policy_label_text;
// public static String LineWrappingTabPage_force_split_checkbox_text;
// public static String LineWrappingTabPage_force_split_checkbox_multi_text;
// public static String LineWrappingTabPage_line_width_for_preview_label_text;
// public static String LineWrappingTabPage_group;
// public static String LineWrappingTabPage_multi_group;
// public static String LineWrappingTabPage_multiple_selections;
// public static String LineWrappingTabPage_occurences;
// public static String LineWrappingTabPage_splitting_do_not_split;
// public static String LineWrappingTabPage_splitting_wrap_when_necessary;
// public static String LineWrappingTabPage_splitting_always_wrap_first_others_when_necessary;
// public static String LineWrappingTabPage_splitting_wrap_always;
// public static String LineWrappingTabPage_splitting_wrap_always_indent_all_but_first;
// public static String LineWrappingTabPage_splitting_wrap_always_except_first_only_if_necessary;
// public static String LineWrappingTabPage_width_indent;
// public static String LineWrappingTabPage_width_indent_option_max_line_width;
// public static String LineWrappingTabPage_width_indent_option_default_indent_wrapped;
public static String LineWrappingTabPage_wrapping_policy_label_text;
public static String LineWrappingTabPage_indentation_policy_label_text;
public static String LineWrappingTabPage_force_split_checkbox_text;
public static String LineWrappingTabPage_force_split_checkbox_multi_text;
public static String LineWrappingTabPage_line_width_for_preview_label_text;
public static String LineWrappingTabPage_group;
public static String LineWrappingTabPage_multi_group;
public static String LineWrappingTabPage_multiple_selections;
public static String LineWrappingTabPage_occurences;
public static String LineWrappingTabPage_splitting_do_not_split;
public static String LineWrappingTabPage_splitting_wrap_when_necessary;
public static String LineWrappingTabPage_splitting_always_wrap_first_others_when_necessary;
public static String LineWrappingTabPage_splitting_wrap_always;
public static String LineWrappingTabPage_splitting_wrap_always_indent_all_but_first;
public static String LineWrappingTabPage_splitting_wrap_always_except_first_only_if_necessary;
public static String LineWrappingTabPage_width_indent;
public static String LineWrappingTabPage_width_indent_option_max_line_width;
public static String LineWrappingTabPage_width_indent_option_default_indent_wrapped;
// public static String LineWrappingTabPage_width_indent_option_default_indent_array;
// public static String LineWrappingTabPage_error_invalid_value;
public static String LineWrappingTabPage_error_invalid_value;
// public static String LineWrappingTabPage_enum_superinterfaces;
// public static String LineWrappingTabPage_assignment_alignment;
public static String AlreadyExistsDialog_message_profile_already_exists;
@ -316,19 +325,19 @@ final class FormatterMessages extends NLS {
// public static String BlankLinesTabPage_class_option_at_beginning_of_method_body;
// public static String BlankLinesTabPage_blank_lines_group_title;
// public static String BlankLinesTabPage_blank_lines_option_empty_lines_to_preserve;
// public static String BracesTabPage_preview_header;
// public static String BracesTabPage_position_same_line;
// public static String BracesTabPage_position_next_line;
// public static String BracesTabPage_position_next_line_indented;
// public static String BracesTabPage_position_next_line_on_wrap;
// public static String BracesTabPage_group_brace_positions_title;
// public static String BracesTabPage_option_class_declaration;
public static String BracesTabPage_preview_header;
public static String BracesTabPage_position_same_line;
public static String BracesTabPage_position_next_line;
public static String BracesTabPage_position_next_line_indented;
public static String BracesTabPage_position_next_line_on_wrap;
public static String BracesTabPage_group_brace_positions_title;
public static String BracesTabPage_option_class_declaration;
// public static String BracesTabPage_option_anonymous_class_declaration;
// public static String BracesTabPage_option_method_declaration;
public static String BracesTabPage_option_method_declaration;
// public static String BracesTabPage_option_constructor_declaration;
// public static String BracesTabPage_option_blocks;
// public static String BracesTabPage_option_blocks_in_case;
// public static String BracesTabPage_option_switch_case;
public static String BracesTabPage_option_blocks;
public static String BracesTabPage_option_blocks_in_case;
public static String BracesTabPage_option_switch_case;
// public static String BracesTabPage_option_array_initializer;
// public static String BracesTabPage_option_keep_empty_array_initializer_on_one_line;
// public static String BracesTabPage_option_enum_declaration;
@ -358,7 +367,8 @@ final class FormatterMessages extends NLS {
public static String CodingStyleConfigurationBlock_delete_confirmation_title;
public static String CodingStyleConfigurationBlock_delete_confirmation_question;
public static String CustomCodeFormatterBlock_formatter_name;
public static String CustomCodeFormatterBlock_no_formatter;
public static String CustomCodeFormatterBlock_default_formatter;
public static String CustomCodeFormatterBlock_formatter_note;
public static String CustomCodeFormatterBlock_contributed_formatter_warning;
// public static String CommentsTabPage_group1_title;
// public static String CommentsTabPage_enable_comment_formatting;
@ -397,8 +407,8 @@ final class FormatterMessages extends NLS {
public static String IndentationTabPage_general_group_option_tab_policy_MIXED;
public static String IndentationTabPage_general_group_option_tab_size;
public static String IndentationTabPage_general_group_option_indent_size;
public static String IndentationTabPage_field_alignment_group_title;
public static String IndentationTabPage_field_alignment_group_align_fields_in_columns;
// public static String IndentationTabPage_field_alignment_group_title;
// public static String IndentationTabPage_field_alignment_group_align_fields_in_columns;
public static String IndentationTabPage_indent_group_title;
public static String IndentationTabPage_class_group_option_indent_access_specifiers_within_class_body;
public static String IndentationTabPage_class_group_option_indent_declarations_compare_to_access_specifiers;
@ -409,20 +419,20 @@ final class FormatterMessages extends NLS {
public static String IndentationTabPage_switch_group_option_indent_statements_within_switch_body;
public static String IndentationTabPage_switch_group_option_indent_statements_within_case_body;
public static String IndentationTabPage_switch_group_option_indent_break_statements;
public static String IndentationTabPage_namespace_group_option_indent_declarations_within_namespace;
public static String IndentationTabPage_indent_empty_lines;
public static String IndentationTabPage_use_tabs_only_for_leading_indentations;
public static String IndentationTabPage_show_whitespace_in_preview_label_text;
public static String ModifyDialog_dialog_title;
public static String ModifyDialog_apply_button;
public static String ModifyDialog_dialog_show_title;
public static String ModifyDialog_dialog_show_warning_builtin;
public static String ModifyDialog_tabpage_braces_title;
public static String ModifyDialog_tabpage_indentation_title;
public static String ModifyDialog_tabpage_whitespace_title;
public static String ModifyDialog_tabpage_blank_lines_title;
public static String ModifyDialog_tabpage_new_lines_title;
public static String ModifyDialog_tabpage_control_statements_title;
// public static String ModifyDialog_tabpage_whitespace_title;
// public static String ModifyDialog_tabpage_blank_lines_title;
// public static String ModifyDialog_tabpage_new_lines_title;
// public static String ModifyDialog_tabpage_control_statements_title;
public static String ModifyDialog_tabpage_line_wrapping_title;
public static String ModifyDialog_tabpage_comments_title;
// public static String ModifyDialog_tabpage_comments_title;
public static String ModifyDialogTabPage_preview_label_text;
public static String ModifyDialogTabPage_error_msg_values_text_unassigned;
public static String ModifyDialogTabPage_error_msg_values_items_text_unassigned;
@ -445,13 +455,12 @@ final class FormatterMessages extends NLS {
// public static String NewLinesTabPage_array_group_option_before_closing_brace_of_array_initializer;
// public static String NewLinesTabPage_annotations_group_title;
// public static String NewLinesTabPage_annotations_group_option_after_annotation;
public static String ProfileManager_default_profile_name;
public static String ProfileManager_kandr_profile_name;
public static String ProfileManager_allman_profile_name;
public static String ProfileManager_gnu_profile_name;
public static String ProfileManager_whitesmiths_profile_name;
public static String ProfileManager_unmanaged_profile;
public static String ProfileManager_unmanaged_profile_with_name;
public static String RenameProfileDialog_status_message_profile_with_this_name_already_exists;
public static String RenameProfileDialog_status_message_profile_name_empty;
public static String RenameProfileDialog_dialog_title;
public static String RenameProfileDialog_dialog_label_enter_a_new_name;
public static String CPreview_formatter_exception;

View file

@ -302,46 +302,46 @@
#LineWrappingTabPage_enum_constant_arguments=Constant arguments
#LineWrappingTabPage_enum_constants=Constants
#LineWrappingTabPage_implements_clause='implements' clause
#LineWrappingTabPage_parameters=Parameters
#LineWrappingTabPage_arguments=Arguments
LineWrappingTabPage_parameters=Parameters
LineWrappingTabPage_arguments=Arguments
#LineWrappingTabPage_qualified_invocations=Qualified invocations
#LineWrappingTabPage_throws_clause='throws' clause
#LineWrappingTabPage_object_allocation=Object allocation arguments
#LineWrappingTabPage_qualified_object_allocation=Qualified object allocation arguments
#LineWrappingTabPage_array_init=Array initializers
LineWrappingTabPage_array_init=Array initializers
#LineWrappingTabPage_explicit_constructor_invocations=Explicit constructor invocations
#LineWrappingTabPage_conditionals=Conditionals
LineWrappingTabPage_conditionals=Conditionals
#LineWrappingTabPage_binary_exprs=Binary expressions
#LineWrappingTabPage_indentation_default=Default indentation
#LineWrappingTabPage_indentation_on_column=Indent on column
#LineWrappingTabPage_indentation_by_one=Indent by one
LineWrappingTabPage_indentation_default=Default indentation
LineWrappingTabPage_indentation_on_column=Indent on column
LineWrappingTabPage_indentation_by_one=Indent by one
#LineWrappingTabPage_class_decls=Class Declarations
#LineWrappingTabPage_method_decls=Method Declarations
LineWrappingTabPage_method_decls=Method Declarations
#LineWrappingTabPage_constructor_decls=Constructor declarations
#LineWrappingTabPage_function_calls=Function Calls
#LineWrappingTabPage_expressions=Expressions
LineWrappingTabPage_function_calls=Function Calls
LineWrappingTabPage_expressions=Expressions
#LineWrappingTabPage_statements=Statements
#LineWrappingTabPage_enum_decls='enum' declaration
#LineWrappingTabPage_wrapping_policy_label_text=Lin&e wrapping policy:
#LineWrappingTabPage_indentation_policy_label_text=Indent&ation policy:
#LineWrappingTabPage_force_split_checkbox_text=&Force split
#LineWrappingTabPage_force_split_checkbox_multi_text=&Force split
#LineWrappingTabPage_line_width_for_preview_label_text=&Set line width for preview window:
#LineWrappingTabPage_group=Settings for {0}
#LineWrappingTabPage_multi_group=Settings for {0} ({1} items)
#LineWrappingTabPage_multiple_selections=Settings for multiple selections ({0} items)
#LineWrappingTabPage_occurences={0} ({1} of {2})
#LineWrappingTabPage_splitting_do_not_split=Do not wrap
#LineWrappingTabPage_splitting_wrap_when_necessary=Wrap only when necessary
#LineWrappingTabPage_splitting_always_wrap_first_others_when_necessary=Always wrap first element, others when necessary
#LineWrappingTabPage_splitting_wrap_always=Wrap all elements, every element on a new line
#LineWrappingTabPage_splitting_wrap_always_indent_all_but_first=Wrap all elements, indent all but the first element
#LineWrappingTabPage_splitting_wrap_always_except_first_only_if_necessary=Wrap all elements, except first element if not necessary
#LineWrappingTabPage_width_indent=Line width and indentation levels
#LineWrappingTabPage_width_indent_option_max_line_width=Ma&ximum line width:
#LineWrappingTabPage_width_indent_option_default_indent_wrapped=Defa&ult indentation for wrapped lines:
LineWrappingTabPage_wrapping_policy_label_text=Lin&e wrapping policy:
LineWrappingTabPage_indentation_policy_label_text=Indent&ation policy:
LineWrappingTabPage_force_split_checkbox_text=&Force split
LineWrappingTabPage_force_split_checkbox_multi_text=&Force split
LineWrappingTabPage_line_width_for_preview_label_text=&Set line width for preview window:
LineWrappingTabPage_group=Settings for {0}
LineWrappingTabPage_multi_group=Settings for {0} ({1} items)
LineWrappingTabPage_multiple_selections=Settings for multiple selections ({0} items)
LineWrappingTabPage_occurences={0} ({1} of {2})
LineWrappingTabPage_splitting_do_not_split=Do not wrap
LineWrappingTabPage_splitting_wrap_when_necessary=Wrap only when necessary
LineWrappingTabPage_splitting_always_wrap_first_others_when_necessary=Always wrap first element, others when necessary
LineWrappingTabPage_splitting_wrap_always=Wrap all elements, every element on a new line
LineWrappingTabPage_splitting_wrap_always_indent_all_but_first=Wrap all elements, indent all but the first element
LineWrappingTabPage_splitting_wrap_always_except_first_only_if_necessary=Wrap all elements, except first element if not necessary
LineWrappingTabPage_width_indent=Line width and indentation levels
LineWrappingTabPage_width_indent_option_max_line_width=Ma&ximum line width:
LineWrappingTabPage_width_indent_option_default_indent_wrapped=Defa&ult indentation for wrapped lines:
#LineWrappingTabPage_width_indent_option_default_indent_array=Default indentation for arra&y initializers:
#LineWrappingTabPage_error_invalid_value=The key ''{0}'' contained an invalid value; resetting to defaults.
LineWrappingTabPage_error_invalid_value=The key ''{0}'' contained an invalid value; resetting to defaults.
#LineWrappingTabPage_enum_superinterfaces='implements' clause
#LineWrappingTabPage_assignment_alignment=Assignments
@ -373,25 +373,26 @@ AlreadyExistsDialog_overwrite_radio_button_desc=&Overwrite the existing profile.
#BlankLinesTabPage_blank_lines_group_title=Existing blank lines
#BlankLinesTabPage_blank_lines_option_empty_lines_to_preserve=N&umber of empty lines to preserve:
#BracesTabPage_preview_header=Braces
#BracesTabPage_position_same_line=Same line
#BracesTabPage_position_next_line=Next line
#BracesTabPage_position_next_line_indented=Next line indented
#BracesTabPage_position_next_line_on_wrap=Next line on wrap
BracesTabPage_preview_header=Braces
BracesTabPage_position_same_line=Same line
BracesTabPage_position_next_line=Next line
BracesTabPage_position_next_line_indented=Next line indented
BracesTabPage_position_next_line_on_wrap=Next line on wrap
#BracesTabPage_group_brace_positions_title=Brace positions
#BracesTabPage_option_class_declaration=&Class or interface declaration:
BracesTabPage_group_brace_positions_title=Brace positions
BracesTabPage_option_class_declaration=&Class declaration:
#BracesTabPage_option_anonymous_class_declaration=Anon&ymous class declaration:
#BracesTabPage_option_method_declaration=Met&hod declaration:
BracesTabPage_option_method_declaration=Met&hod declaration:
#BracesTabPage_option_constructor_declaration=Constr&uctor declaration:
#BracesTabPage_option_blocks=&Blocks:
#BracesTabPage_option_blocks_in_case=Bloc&ks in case statement:
#BracesTabPage_option_switch_case='&switch' statement:
BracesTabPage_option_blocks=&Blocks:
BracesTabPage_option_blocks_in_case=Bloc&ks in case statement:
BracesTabPage_option_switch_case='&switch' statement:
#BracesTabPage_option_array_initializer=Array initiali&zer:
#BracesTabPage_option_keep_empty_array_initializer_on_one_line=Keep empty array &initializer on one line
#BracesTabPage_option_enum_declaration=&Enum declaration:
#BracesTabPage_option_enumconst_declaration=Enum c&onstant body:
#BracesTabPage_option_annotation_type_declaration=&Annotation type declaration:
CodingStyleConfigurationBlock_save_profile_dialog_title=Export Profile
CodingStyleConfigurationBlock_save_profile_error_title=Export Profile
CodingStyleConfigurationBlock_save_profile_error_message=Could not export the profiles.
@ -420,8 +421,9 @@ CodingStyleConfigurationBlock_delete_confirmation_title=Confirm Remove
CodingStyleConfigurationBlock_delete_confirmation_question=Are you sure you want to remove profile ''{0}''?
CustomCodeFormatterBlock_formatter_name=Code &Formatter:
CustomCodeFormatterBlock_no_formatter=(NONE)
CustomCodeFormatterBlock_contributed_formatter_warning=Some formatters may not respect all code style settings.
CustomCodeFormatterBlock_default_formatter=[built-in]
CustomCodeFormatterBlock_formatter_note=Note:
CustomCodeFormatterBlock_contributed_formatter_warning=Contributed formatters may not respect all code style settings.
#CommentsTabPage_group1_title=General settings
#CommentsTabPage_enable_comment_formatting=Enable &comment formatting
@ -455,6 +457,15 @@ CreateProfileDialog_profile_name_label_text=&Profile name:
CreateProfileDialog_base_profile_label_text=I&nitialize settings with the following profile:
CreateProfileDialog_open_edit_dialog_checkbox_text=&Open the edit dialog now
ModifyDialog_dialog_title=Profile ''{0}''
ModifyDialog_apply_button=Apply
ModifyDialog_Export_Button=&Export...
ModifyDialog_Duplicate_Status=A profile with this name already exists.
ModifyDialog_BuiltIn_Status=This is a built-in profile, change the name to create a new profile.
ModifyDialog_Shared_Status=This is a shared profile, change the name to create a new profile.
ModifyDialog_EmptyName_Status=Profile name is empty.
ModifyDialogTabPage_preview_label_text=Pre&view:
IndentationTabPage_preview_header=Indentation
IndentationTabPage_general_group_title=General settings
@ -465,8 +476,8 @@ IndentationTabPage_general_group_option_tab_policy_MIXED=Mixed
IndentationTabPage_general_group_option_tab_size=Tab &size:
IndentationTabPage_general_group_option_indent_size=&Indentation size:
IndentationTabPage_field_alignment_group_title=Alignment of fields in class declarations
IndentationTabPage_field_alignment_group_align_fields_in_columns=&Align fields in columns
#IndentationTabPage_field_alignment_group_title=Alignment of fields in class declarations
#IndentationTabPage_field_alignment_group_align_fields_in_columns=&Align fields in columns
IndentationTabPage_indent_group_title=Indent
@ -476,6 +487,7 @@ IndentationTabPage_class_group_option_indent_declarations_within_enum_const=Decl
IndentationTabPage_class_group_option_indent_declarations_within_enum_decl=Declarations within enum declaration
IndentationTabPage_block_group_option_indent_statements_compare_to_body=Stat&ements within method/constructor body
IndentationTabPage_block_group_option_indent_statements_compare_to_block=Statements within bl&ocks
IndentationTabPage_namespace_group_option_indent_declarations_within_namespace=Declarations within '&namespace' definition
IndentationTabPage_indent_empty_lines=Empty lines
IndentationTabPage_switch_group_option_indent_statements_within_switch_body=Statements wit&hin 'switch' body
@ -483,19 +495,26 @@ IndentationTabPage_switch_group_option_indent_statements_within_case_body=Statem
IndentationTabPage_switch_group_option_indent_break_statements='brea&k' statements
IndentationTabPage_use_tabs_only_for_leading_indentations=Use tabs only for leading indentations
IndentationTabPage_show_whitespace_in_preview_label_text=Show whitespace
ModifyDialog_dialog_title=Edit Profile ''{0}''
ModifyDialog_apply_button=Apply
ModifyDialog_dialog_show_title=Show Profile ''{0}''
ModifyDialog_dialog_show_warning_builtin=This is a built-in profile, you will be prompted to enter a new name after closing this dialog.
ModifyDialog_tabpage_braces_title=B&races
ModifyDialog_ProfileName_Label=&Profile name:
ModifyDialog_NewCreated_Status=A new profile will be created.
ModifyDialog_tabpage_indentation_title=In&dentation
ModifyDialog_tabpage_whitespace_title=&White Space
ModifyDialog_tabpage_blank_lines_title=Bla&nk Lines
ModifyDialog_tabpage_new_lines_title=New &Lines
ModifyDialog_tabpage_control_statements_title=Con&trol Statements
#ModifyDialog_tabpage_whitespace_title=&White Space
#ModifyDialog_tabpage_blank_lines_title=Bla&nk Lines
#ModifyDialog_tabpage_new_lines_title=New &Lines
#ModifyDialog_tabpage_control_statements_title=Con&trol Statements
ModifyDialog_tabpage_line_wrapping_title=Line Wra&pping
ModifyDialog_tabpage_comments_title=Co&mments
#ModifyDialog_tabpage_comments_title=Co&mments
ModifyDialog_dialog_title=Profile ''{0}''
ModifyDialog_apply_button=Apply
ModifyDialog_Export_Button=&Export...
ModifyDialog_Duplicate_Status=A profile with this name already exists.
ModifyDialog_BuiltIn_Status=This is a built-in profile, change the name to create a new profile.
ModifyDialog_Shared_Status=This is a shared profile, change the name to create a new profile.
ModifyDialog_EmptyName_Status=Profile name is empty.
ModifyDialogTabPage_preview_label_text=Pre&view:
ModifyDialogTabPage_error_msg_values_text_unassigned=Values and text must be assigned.
@ -524,14 +543,15 @@ ModifyDialogTabPage_NumberPreference_error_invalid_value=Invalid value: Please e
#NewLinesTabPage_annotations_group_title=Annotations
#NewLinesTabPage_annotations_group_option_after_annotation=&Insert new line after annotations
ProfileManager_default_profile_name=Default [built-in]
ProfileManager_kandr_profile_name=K&R [built-in]
ProfileManager_allman_profile_name=BSD/Allman [built-in]
ProfileManager_gnu_profile_name=GNU [built-in]
ProfileManager_whitesmiths_profile_name=Whitesmiths [built-in]
ProfileManager_unmanaged_profile=Unmanaged profile
ProfileManager_unmanaged_profile_with_name=Unmanaged profile "{0}"
RenameProfileDialog_status_message_profile_with_this_name_already_exists=A profile with this name already exists.
RenameProfileDialog_status_message_profile_name_empty=Profile name is empty
RenameProfileDialog_dialog_title=Rename Profile
RenameProfileDialog_dialog_label_enter_a_new_name=Please &enter a new name:
CPreview_formatter_exception=The formatter threw an unhandled exception while formatting the preview.
ProfileConfigurationBlock_load_profile_wrong_profile_message=Import failed. This is not a valid profile: Expected ''{0}'' but encountered ''{1}''.

View file

@ -0,0 +1,37 @@
/*******************************************************************************
* Copyright (c) 2000, 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Anton Leherbauer (Wind River Systems)
*******************************************************************************/
package org.eclipse.cdt.internal.ui.preferences.formatter;
import java.util.Map;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.cdt.internal.ui.preferences.formatter.ProfileManager.Profile;
public class FormatterModifyDialog extends ModifyDialog {
public FormatterModifyDialog(Shell parentShell, Profile profile, ProfileManager profileManager, ProfileStore profileStore, boolean newProfile, String dialogPreferencesKey, String lastSavePathKey) {
super(parentShell, profile, profileManager, profileStore, newProfile, dialogPreferencesKey, lastSavePathKey);
}
protected void addPages(Map values) {
addTabPage(FormatterMessages.ModifyDialog_tabpage_indentation_title, new IndentationTabPage(this, values));
addTabPage(FormatterMessages.ModifyDialog_tabpage_braces_title, new BracesTabPage(this, values));
// addTabPage(FormatterMessages.ModifyDialog_tabpage_whitespace_title, new WhiteSpaceTabPage(this, values));
// addTabPage(FormatterMessages.ModifyDialog_tabpage_blank_lines_title, new BlankLinesTabPage(this, values));
// addTabPage(FormatterMessages.ModifyDialog_tabpage_new_lines_title, new NewLinesTabPage(this, values));
// addTabPage(FormatterMessages.ModifyDialog_tabpage_control_statements_title, new ControlStatementsTabPage(this, values));
addTabPage(FormatterMessages.ModifyDialog_tabpage_line_wrapping_title, new LineWrappingTabPage(this, values));
// addTabPage(FormatterMessages.ModifyDialog_tabpage_comments_title, new CommentsTabPage(this, values));
}
}

View file

@ -0,0 +1,126 @@
/*******************************************************************************
* Copyright (c) 2000, 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Anton Leherbauer (Wind River Systems)
*******************************************************************************/
package org.eclipse.cdt.internal.ui.preferences.formatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.preferences.DefaultScope;
import org.eclipse.core.runtime.preferences.IScopeContext;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.formatter.DefaultCodeFormatterConstants;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.ui.PreferenceConstants;
import org.eclipse.cdt.internal.ui.preferences.PreferencesAccess;
public class FormatterProfileManager extends ProfileManager {
public final static String KANDR_PROFILE= "org.eclipse.cdt.ui.default.kandr_profile"; //$NON-NLS-1$
public final static String ALLMAN_PROFILE= "org.eclipse.cdt.ui.default.allman_profile"; //$NON-NLS-1$
public final static String GNU_PROFILE= "org.eclipse.cdt.ui.default.gnu_profile"; //$NON-NLS-1$
public final static String WHITESMITHS_PROFILE= "org.eclipse.cdt.ui.default.whitesmites_profile"; //$NON-NLS-1$
public final static String DEFAULT_PROFILE= KANDR_PROFILE;
private final static KeySet[] KEY_SETS= new KeySet[] {
new KeySet(CCorePlugin.PLUGIN_ID, new ArrayList(DefaultCodeFormatterConstants.getDefaultSettings().keySet())),
new KeySet(CUIPlugin.PLUGIN_ID, Collections.EMPTY_LIST)
};
private final static String PROFILE_KEY= PreferenceConstants.FORMATTER_PROFILE;
private final static String FORMATTER_SETTINGS_VERSION= "formatter_settings_version"; //$NON-NLS-1$
public FormatterProfileManager(List profiles, IScopeContext context, PreferencesAccess preferencesAccess, IProfileVersioner profileVersioner) {
super(addBuiltinProfiles(profiles, profileVersioner), context, preferencesAccess, profileVersioner, KEY_SETS, PROFILE_KEY, FORMATTER_SETTINGS_VERSION);
}
private static List addBuiltinProfiles(List profiles, IProfileVersioner profileVersioner) {
final Profile kandrProfile= new BuiltInProfile(KANDR_PROFILE, FormatterMessages.ProfileManager_kandr_profile_name, getKandRSettings(), 2, profileVersioner.getCurrentVersion(), profileVersioner.getProfileKind());
profiles.add(kandrProfile);
final Profile allmanProfile= new BuiltInProfile(ALLMAN_PROFILE, FormatterMessages.ProfileManager_allman_profile_name, getAllmanSettings(), 2, profileVersioner.getCurrentVersion(), profileVersioner.getProfileKind());
profiles.add(allmanProfile);
final Profile gnuProfile= new BuiltInProfile(GNU_PROFILE, FormatterMessages.ProfileManager_gnu_profile_name, getGNUSettings(), 2, profileVersioner.getCurrentVersion(), profileVersioner.getProfileKind());
profiles.add(gnuProfile);
final Profile whitesmithsProfile= new BuiltInProfile(WHITESMITHS_PROFILE, FormatterMessages.ProfileManager_whitesmiths_profile_name, getWhitesmithsSettings(), 2, profileVersioner.getCurrentVersion(), profileVersioner.getProfileKind());
profiles.add(whitesmithsProfile);
return profiles;
}
/**
* @return Returns the default settings.
*/
public static Map getDefaultSettings() {
return DefaultCodeFormatterConstants.getDefaultSettings();
}
/**
* @return Returns the K&R settings.
*/
public static Map getKandRSettings() {
return DefaultCodeFormatterConstants.getKandRSettings();
}
/**
* @return Returns the ANSI settings.
*/
public static Map getAllmanSettings() {
return DefaultCodeFormatterConstants.getAllmanSettings();
}
/**
* @return Returns the GNU settings.
*/
public static Map getGNUSettings() {
return DefaultCodeFormatterConstants.getGNUSettings();
}
/**
* @return Returns the Whitesmiths settings.
*/
public static Map getWhitesmithsSettings() {
return DefaultCodeFormatterConstants.getWhitesmithsSettings();
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.preferences.formatter.ProfileManager#getSelectedProfileId(org.eclipse.core.runtime.preferences.IScopeContext)
*/
protected String getSelectedProfileId(IScopeContext instanceScope) {
String profileId= instanceScope.getNode(CUIPlugin.PLUGIN_ID).get(PROFILE_KEY, null);
if (profileId == null) {
// request from bug 129427
profileId= new DefaultScope().getNode(CUIPlugin.PLUGIN_ID).get(PROFILE_KEY, null);
// fix for bug 89739
// if (DEFAULT_PROFILE.equals(profileId)) { // default default:
// IEclipsePreferences node= instanceScope.getNode(CCorePlugin.PLUGIN_ID);
// if (node != null) {
// String tabSetting= node.get(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, null);
// if (CCorePlugin.SPACE.equals(tabSetting)) {
// profileId= TAB_WIDTH_8_PROFILE;
// }
// }
// }
}
return profileId;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.preferences.formatter.ProfileManager#getDefaultProfile()
*/
public Profile getDefaultProfile() {
return getProfile(DEFAULT_PROFILE);
}
}

View file

@ -0,0 +1,99 @@
/*******************************************************************************
* Copyright (c) 2000, 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Anton Leherbauer (Wind River Systems)
*******************************************************************************/
package org.eclipse.cdt.internal.ui.preferences.formatter;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.core.runtime.preferences.IScopeContext;
import org.osgi.service.prefs.BackingStoreException;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.internal.ui.preferences.PreferencesAccess;
import org.eclipse.cdt.internal.ui.preferences.formatter.ProfileManager.CustomProfile;
public class FormatterProfileStore extends ProfileStore {
/**
* Preference key where all profiles are stored
*/
private static final String PREF_FORMATTER_PROFILES= "org.eclipse.jdt.ui.formatterprofiles"; //$NON-NLS-1$
// private final IProfileVersioner fProfileVersioner;
public FormatterProfileStore(IProfileVersioner profileVersioner) {
super(PREF_FORMATTER_PROFILES, profileVersioner);
// fProfileVersioner= profileVersioner;
}
/**
* {@inheritDoc}
*/
public List readProfiles(IScopeContext scope) throws CoreException {
List profiles= super.readProfiles(scope);
return profiles;
}
public static void checkCurrentOptionsVersion() {
PreferencesAccess access= PreferencesAccess.getOriginalPreferences();
ProfileVersioner profileVersioner= new ProfileVersioner();
IScopeContext instanceScope= access.getInstanceScope();
IEclipsePreferences uiPreferences= instanceScope.getNode(CUIPlugin.PLUGIN_ID);
int version= uiPreferences.getInt(PREF_FORMATTER_PROFILES + VERSION_KEY_SUFFIX, 0);
if (version >= profileVersioner.getCurrentVersion()) {
return; // is up to date
}
try {
List profiles= (new FormatterProfileStore(profileVersioner)).readProfiles(instanceScope);
if (profiles == null) {
profiles= new ArrayList();
}
ProfileManager manager= new FormatterProfileManager(profiles, instanceScope, access, profileVersioner);
if (manager.getSelected() instanceof CustomProfile) {
manager.commitChanges(instanceScope); // updates core options
}
uiPreferences.putInt(PREF_FORMATTER_PROFILES + VERSION_KEY_SUFFIX, profileVersioner.getCurrentVersion());
savePreferences(instanceScope);
IProject[] projects= ResourcesPlugin.getWorkspace().getRoot().getProjects();
for (int i= 0; i < projects.length; i++) {
IScopeContext scope= access.getProjectScope(projects[i]);
if (manager.hasProjectSpecificSettings(scope)) {
manager= new FormatterProfileManager(profiles, scope, access, profileVersioner);
manager.commitChanges(scope); // updates JavaCore project options
savePreferences(scope);
}
}
} catch (CoreException e) {
CUIPlugin.getDefault().log(e);
} catch (BackingStoreException e) {
CUIPlugin.getDefault().log(e);
}
}
private static void savePreferences(final IScopeContext context) throws BackingStoreException {
try {
context.getNode(CUIPlugin.PLUGIN_ID).flush();
} finally {
context.getNode(CCorePlugin.PLUGIN_ID).flush();
}
}
}

View file

@ -0,0 +1,29 @@
/*******************************************************************************
* Copyright (c) 2000, 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.ui.preferences.formatter;
import org.eclipse.cdt.internal.ui.preferences.formatter.ProfileManager.CustomProfile;
public interface IProfileVersioner {
public int getFirstVersion();
public int getCurrentVersion();
public String getProfileKind();
/**
* Update the <code>profile</code> to the
* current version number
*/
public void update(CustomProfile profile);
}

View file

@ -9,63 +9,81 @@
* IBM Corporation - initial API and implementation
* istvan@benedek-home.de - 103706 [formatter] indent empty lines
* Sergey Prigogin, Google
* Anton Leherbauer (Wind River Systems)
*******************************************************************************/
package org.eclipse.cdt.internal.ui.preferences.formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import org.eclipse.core.runtime.Assert;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.jface.text.Assert;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.formatter.DefaultCodeFormatterConstants;
public class IndentationTabPage extends ModifyDialogTabPage {
// private final String PREVIEW=
// createPreviewHeader(FormatterMessages.IndentationTabPage_preview_header) +
// "class Example {" + //$NON-NLS-1$
// " int [] myArray= {1,2,3,4,5,6};" + //$NON-NLS-1$
// " int theInt= 1;" + //$NON-NLS-1$
// " String someString= \"Hello\";" + //$NON-NLS-1$
// " double aDouble= 3.0;" + //$NON-NLS-1$
// " void foo(int a, int b, int c, int d, int e, int f) {" + //$NON-NLS-1$
// " switch(a) {" + //$NON-NLS-1$
// " case 0: " + //$NON-NLS-1$
// " Other.doFoo();" + //$NON-NLS-1$
// " break;" + //$NON-NLS-1$
// " default:" + //$NON-NLS-1$
// " Other.doBaz();" + //$NON-NLS-1$
// " }" + //$NON-NLS-1$
// " }" + //$NON-NLS-1$
// " void bar(List v) {" + //$NON-NLS-1$
// " for (int i= 0; i < 10; i++) {" + //$NON-NLS-1$
// " v.add(new Integer(i));" + //$NON-NLS-1$
// " }" + //$NON-NLS-1$
// " }" + //$NON-NLS-1$
// "}" + //$NON-NLS-1$
// "\n" + //$NON-NLS-1$
// "enum MyEnum {" + //$NON-NLS-1$
// " UNDEFINED(0) {" + //$NON-NLS-1$
// " void foo() {}" + //$NON-NLS-1$
// " }" + //$NON-NLS-1$
// "}" + //$NON-NLS-1$
// "@interface MyAnnotation {" + //$NON-NLS-1$
// " int count() default 1;" + //$NON-NLS-1$
// "}";//$NON-NLS-1$
/**
* Some C++ source code used for preview.
*/
private final static String PREVIEW=
createPreviewHeader(FormatterMessages.IndentationTabPage_preview_header) +
"#include <math.h>\n" + //$NON-NLS-1$
"class Point {" + //$NON-NLS-1$
"public:" + //$NON-NLS-1$
"Point(double xc, double yc) : x(xc), y(yc) {}" + //$NON-NLS-1$
"double distance(const Point& other) const;" + //$NON-NLS-1$
"int compareX(const Point& other) const;" + //$NON-NLS-1$
"double x;" + //$NON-NLS-1$
"double y;" + //$NON-NLS-1$
"};" + //$NON-NLS-1$
"double Point::distance(const Point& other) const {" + //$NON-NLS-1$
"double dx = x - other.x;" + //$NON-NLS-1$
"double dy = y - other.y;" + //$NON-NLS-1$
"return sqrt(dx * dx + dy * dy);" + //$NON-NLS-1$
"}"+ //$NON-NLS-1$
"int Point::compareX(const Point& other) const {" + //$NON-NLS-1$
"if(x < other.x) {" + //$NON-NLS-1$
"return -1;" + //$NON-NLS-1$
"} else if(x > other.x){" + //$NON-NLS-1$
"return 1;" + //$NON-NLS-1$
"} else {" + //$NON-NLS-1$
"return 0;" + //$NON-NLS-1$
"}"+ //$NON-NLS-1$
"}"+ //$NON-NLS-1$
"namespace FOO {"+ //$NON-NLS-1$
"int foo(int bar) const {" + //$NON-NLS-1$
"switch(bar) {" + //$NON-NLS-1$
"case 0:" + //$NON-NLS-1$
"++bar;" + //$NON-NLS-1$
"break;" + //$NON-NLS-1$
"case 1:" + //$NON-NLS-1$
"--bar;" + //$NON-NLS-1$
"default: {" + //$NON-NLS-1$
"bar += bar;" + //$NON-NLS-1$
"break;" + //$NON-NLS-1$
"}"+ //$NON-NLS-1$
"}"+ //$NON-NLS-1$
"}"+ //$NON-NLS-1$
"} // end namespace FOO"; //$NON-NLS-1$
private static final String SHOW_WHITESPACE = "showWhitespace"; //$NON-NLS-1$
// private CompilationUnitPreview fPreview;
private TranslationUnitPreview fPreview;
private String fOldTabChar= null;
public IndentationTabPage(ModifyDialog modifyDialog, Map workingValues) {
super(modifyDialog, workingValues);
}
/*
* @see org.eclipse.cdt.internal.ui.preferences.formatter.ModifyDialogTabPage#doCreatePreferences(org.eclipse.swt.widgets.Composite, int)
*/
protected void doCreatePreferences(Composite composite, int numColumns) {
final Group generalGroup= createGroup(numColumns, composite, FormatterMessages.IndentationTabPage_general_group_title);
@ -100,8 +118,6 @@ public class IndentationTabPage extends ModifyDialogTabPage {
final Group classGroup = createGroup(numColumns, composite, FormatterMessages.IndentationTabPage_indent_group_title);
createCheckboxPref(classGroup, numColumns, FormatterMessages.IndentationTabPage_class_group_option_indent_access_specifiers_within_class_body, DefaultCodeFormatterConstants.FORMATTER_INDENT_ACCESS_SPECIFIER_COMPARE_TO_TYPE_HEADER, FALSE_TRUE);
createCheckboxPref(classGroup, numColumns, FormatterMessages.IndentationTabPage_class_group_option_indent_declarations_compare_to_access_specifiers, DefaultCodeFormatterConstants.FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_ACCESS_SPECIFIER, FALSE_TRUE);
createCheckboxPref(classGroup, numColumns, FormatterMessages.IndentationTabPage_class_group_option_indent_declarations_within_enum_decl, DefaultCodeFormatterConstants.FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_ENUM_DECLARATION_HEADER, FALSE_TRUE);
createCheckboxPref(classGroup, numColumns, FormatterMessages.IndentationTabPage_class_group_option_indent_declarations_within_enum_const, DefaultCodeFormatterConstants.FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_ENUM_CONSTANT_HEADER, FALSE_TRUE);
createCheckboxPref(classGroup, numColumns, FormatterMessages.IndentationTabPage_block_group_option_indent_statements_compare_to_body, DefaultCodeFormatterConstants.FORMATTER_INDENT_STATEMENTS_COMPARE_TO_BODY, FALSE_TRUE);
createCheckboxPref(classGroup, numColumns, FormatterMessages.IndentationTabPage_block_group_option_indent_statements_compare_to_block, DefaultCodeFormatterConstants.FORMATTER_INDENT_STATEMENTS_COMPARE_TO_BLOCK, FALSE_TRUE);
@ -109,27 +125,51 @@ public class IndentationTabPage extends ModifyDialogTabPage {
createCheckboxPref(classGroup, numColumns, FormatterMessages.IndentationTabPage_switch_group_option_indent_statements_within_switch_body, DefaultCodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_SWITCH, FALSE_TRUE);
createCheckboxPref(classGroup, numColumns, FormatterMessages.IndentationTabPage_switch_group_option_indent_statements_within_case_body, DefaultCodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_CASES, FALSE_TRUE);
createCheckboxPref(classGroup, numColumns, FormatterMessages.IndentationTabPage_switch_group_option_indent_break_statements, DefaultCodeFormatterConstants.FORMATTER_INDENT_BREAKS_COMPARE_TO_CASES, FALSE_TRUE);
createCheckboxPref(classGroup, numColumns, FormatterMessages.IndentationTabPage_indent_empty_lines, DefaultCodeFormatterConstants.FORMATTER_INDENT_EMPTY_LINES, FALSE_TRUE);
createCheckboxPref(classGroup, numColumns, FormatterMessages.IndentationTabPage_namespace_group_option_indent_declarations_within_namespace, DefaultCodeFormatterConstants.FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_NAMESPACE_HEADER, FALSE_TRUE);
createCheckboxPref(classGroup, numColumns, FormatterMessages.IndentationTabPage_indent_empty_lines, DefaultCodeFormatterConstants.FORMATTER_INDENT_EMPTY_LINES, FALSE_TRUE);
}
/*
* @see org.eclipse.cdt.internal.ui.preferences.formatter.ModifyDialogTabPage#initializePage()
*/
public void initializePage() {
// fPreview.setPreviewText(PREVIEW);
fPreview.setPreviewText(PREVIEW);
}
/* (non-Javadoc)
/*
* @see org.eclipse.cdt.internal.ui.preferences.formatter.ModifyDialogTabPage#doCreatePreviewPane(org.eclipse.swt.widgets.Composite, int)
*/
protected Composite doCreatePreviewPane(Composite composite, int numColumns) {
super.doCreatePreviewPane(composite, numColumns);
final Map previewPrefs= new HashMap();
final CheckboxPreference previewShowWhitespace= new CheckboxPreference(composite, numColumns / 2, previewPrefs, SHOW_WHITESPACE, FALSE_TRUE,
FormatterMessages.IndentationTabPage_show_whitespace_in_preview_label_text);
fDefaultFocusManager.add(previewShowWhitespace);
previewShowWhitespace.addObserver(new Observer() {
public void update(Observable o, Object arg) {
fPreview.showWhitespace(FALSE_TRUE[1] == previewPrefs.get(SHOW_WHITESPACE));
}
});
return composite;
}
/*
* @see org.eclipse.cdt.internal.ui.preferences.formatter.ModifyDialogTabPage#doCreateCPreview(org.eclipse.swt.widgets.Composite)
*/
protected CPreview doCreateCPreview(Composite parent) {
// fPreview= new CompilationUnitPreview(fWorkingValues, parent);
// return fPreview;
return null;
fPreview= new TranslationUnitPreview(fWorkingValues, parent);
return fPreview;
}
/* (non-Javadoc)
/*
* @see org.eclipse.cdt.internal.ui.preferences.formatter.ModifyDialogTabPage#doUpdatePreview()
*/
protected void doUpdatePreview() {
// fPreview.update();
fPreview.update();
}
private void updateTabPreferences(String tabPolicy, NumberPreference tabPreference, NumberPreference indentPreference, CheckboxPreference onlyForLeading) {

View file

@ -0,0 +1,842 @@
/*******************************************************************************
* Copyright (c) 2000, 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Anton Leherbauer (Wind River Systems)
*******************************************************************************/
package org.eclipse.cdt.internal.ui.preferences.formatter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelection;
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.StructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
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.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.cdt.core.formatter.DefaultCodeFormatterConstants;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.internal.corext.util.Messages;
/**
* The line wrapping tab page.
*/
public class LineWrappingTabPage extends ModifyDialogTabPage {
/**
* Represents a line wrapping category. All members are final.
*/
private final static class Category {
public final String key;
public final String name;
public final String previewText;
public final List children;
public int index;
public Category(String _key, String _previewText, String _name) {
this.key= _key;
this.name= _name;
this.previewText= _previewText != null ? createPreviewHeader(_name) + _previewText : null;
children= new ArrayList();
}
/**
* @param _name Category name
*/
public Category(String _name) {
this(null, null, _name);
}
public String toString() {
return name;
}
}
private final static String PREF_CATEGORY_INDEX= CUIPlugin.PLUGIN_ID + "formatter_page.line_wrapping_tab_page.last_category_index"; //$NON-NLS-1$
private final class CategoryListener implements ISelectionChangedListener, IDoubleClickListener {
private final List fCategoriesList;
private int fIndex= 0;
public CategoryListener(List categoriesTree) {
fCategoriesList= new ArrayList();
flatten(fCategoriesList, categoriesTree);
}
private void flatten(List categoriesList, List categoriesTree) {
for (final Iterator iter= categoriesTree.iterator(); iter.hasNext(); ) {
final Category category= (Category) iter.next();
category.index= fIndex++;
categoriesList.add(category);
flatten(categoriesList, category.children);
}
}
public void add(Category category) {
category.index= fIndex++;
fCategoriesList.add(category);
}
public void selectionChanged(SelectionChangedEvent event) {
if (event != null)
fSelection= (IStructuredSelection)event.getSelection();
if (fSelection.size() == 0) {
disableAll();
return;
}
if (!fOptionsGroup.isEnabled())
enableDefaultComponents(true);
fSelectionState.refreshState(fSelection);
final Category category= (Category)fSelection.getFirstElement();
fDialogSettings.put(PREF_CATEGORY_INDEX, category.index);
fOptionsGroup.setText(getGroupLabel(category));
}
private String getGroupLabel(Category category) {
if (fSelection.size() == 1) {
if (fSelectionState.getElements().size() == 1)
return Messages.format(FormatterMessages.LineWrappingTabPage_group, category.name.toLowerCase());
return Messages.format(FormatterMessages.LineWrappingTabPage_multi_group, new String[] {category.name.toLowerCase(), Integer.toString(fSelectionState.getElements().size())});
}
return Messages.format(FormatterMessages.LineWrappingTabPage_multiple_selections, new String[] {Integer.toString(fSelectionState.getElements().size())});
}
private void disableAll() {
enableDefaultComponents(false);
fIndentStyleCombo.setEnabled(false);
fForceSplit.setEnabled(false);
}
private void enableDefaultComponents(boolean enabled) {
fOptionsGroup.setEnabled(enabled);
fWrappingStyleCombo.setEnabled(enabled);
fWrappingStylePolicy.setEnabled(enabled);
}
public void restoreSelection() {
int index;
try {
index= fDialogSettings.getInt(PREF_CATEGORY_INDEX);
} catch (NumberFormatException ex) {
index= -1;
}
if (index < 0 || index > fCategoriesList.size() - 1) {
index= 1; // In order to select a category with preview initially
}
final Category category= (Category)fCategoriesList.get(index);
fCategoriesViewer.setSelection(new StructuredSelection(new Category[] {category}));
}
public void doubleClick(DoubleClickEvent event) {
final ISelection selection= event.getSelection();
if (selection instanceof IStructuredSelection) {
final Category node= (Category)((IStructuredSelection)selection).getFirstElement();
fCategoriesViewer.setExpandedState(node, !fCategoriesViewer.getExpandedState(node));
}
}
}
private class SelectionState {
private List fElements= new ArrayList();
public void refreshState(IStructuredSelection selection) {
Map wrappingStyleMap= new HashMap();
Map indentStyleMap= new HashMap();
Map forceWrappingMap= new HashMap();
fElements.clear();
evaluateElements(selection.iterator());
evaluateMaps(wrappingStyleMap, indentStyleMap, forceWrappingMap);
setPreviewText(getPreviewText(wrappingStyleMap, indentStyleMap, forceWrappingMap));
refreshControls(wrappingStyleMap, indentStyleMap, forceWrappingMap);
}
public List getElements() {
return fElements;
}
private void evaluateElements(Iterator iterator) {
Category category;
String value;
while (iterator.hasNext()) {
category= (Category) iterator.next();
value= (String)fWorkingValues.get(category.key);
if (value != null) {
if (!fElements.contains(category))
fElements.add(category);
}
else {
evaluateElements(category.children.iterator());
}
}
}
private void evaluateMaps(Map wrappingStyleMap, Map indentStyleMap, Map forceWrappingMap) {
Iterator iterator= fElements.iterator();
while (iterator.hasNext()) {
insertIntoMap(wrappingStyleMap, indentStyleMap, forceWrappingMap, (Category)iterator.next());
}
}
private String getPreviewText(Map wrappingMap, Map indentMap, Map forceMap) {
Iterator iterator= fElements.iterator();
String previewText= ""; //$NON-NLS-1$
while (iterator.hasNext()) {
Category category= (Category)iterator.next();
previewText= previewText + category.previewText + "\n\n"; //$NON-NLS-1$
}
return previewText;
}
private void insertIntoMap(Map wrappingMap, Map indentMap, Map forceMap, Category category) {
final String value= (String)fWorkingValues.get(category.key);
Integer wrappingStyle;
Integer indentStyle;
Boolean forceWrapping;
try {
wrappingStyle= new Integer(DefaultCodeFormatterConstants.getWrappingStyle(value));
indentStyle= new Integer(DefaultCodeFormatterConstants.getIndentStyle(value));
forceWrapping= new Boolean(DefaultCodeFormatterConstants.getForceWrapping(value));
} catch (IllegalArgumentException e) {
forceWrapping= new Boolean(false);
indentStyle= new Integer(DefaultCodeFormatterConstants.INDENT_DEFAULT);
wrappingStyle= new Integer(DefaultCodeFormatterConstants.WRAP_NO_SPLIT);
}
increaseMapEntry(wrappingMap, wrappingStyle);
increaseMapEntry(indentMap, indentStyle);
increaseMapEntry(forceMap, forceWrapping);
}
private void increaseMapEntry(Map map, Object type) {
Integer count= (Integer)map.get(type);
if (count == null) // not in map yet -> count == 0
map.put(type, new Integer(1));
else
map.put(type, new Integer(count.intValue() + 1));
}
private void refreshControls(Map wrappingStyleMap, Map indentStyleMap, Map forceWrappingMap) {
updateCombos(wrappingStyleMap, indentStyleMap);
updateButton(forceWrappingMap);
Integer wrappingStyleMax= getWrappingStyleMax(wrappingStyleMap);
boolean isInhomogeneous= (fElements.size() != ((Integer)wrappingStyleMap.get(wrappingStyleMax)).intValue());
updateControlEnablement(isInhomogeneous, wrappingStyleMax.intValue());
doUpdatePreview();
notifyValuesModified();
}
private Integer getWrappingStyleMax(Map wrappingStyleMap) {
int maxCount= 0, maxStyle= 0;
for (int i=0; i<WRAPPING_NAMES.length; i++) {
Integer count= (Integer)wrappingStyleMap.get(new Integer(i));
if (count == null)
continue;
if (count.intValue() > maxCount) {
maxCount= count.intValue();
maxStyle= i;
}
}
return new Integer(maxStyle);
}
private void updateButton(Map forceWrappingMap) {
Integer nrOfTrue= (Integer)forceWrappingMap.get(Boolean.TRUE);
Integer nrOfFalse= (Integer)forceWrappingMap.get(Boolean.FALSE);
if (nrOfTrue == null || nrOfFalse == null)
fForceSplit.setSelection(nrOfTrue != null);
else
fForceSplit.setSelection(nrOfTrue.intValue() > nrOfFalse.intValue());
int max= getMax(nrOfTrue, nrOfFalse);
String label= FormatterMessages.LineWrappingTabPage_force_split_checkbox_multi_text;
fForceSplit.setText(getLabelText(label, max, fElements.size()));
}
private String getLabelText(String label, int count, int nElements) {
if (nElements == 1 || count == 0)
return label;
return Messages.format(FormatterMessages.LineWrappingTabPage_occurences, new String[] {label, Integer.toString(count), Integer.toString(nElements)});
}
private int getMax(Integer nrOfTrue, Integer nrOfFalse) {
if (nrOfTrue == null)
return nrOfFalse.intValue();
if (nrOfFalse == null)
return nrOfTrue.intValue();
if (nrOfTrue.compareTo(nrOfFalse) >= 0)
return nrOfTrue.intValue();
return nrOfFalse.intValue();
}
private void updateCombos(Map wrappingStyleMap, Map indentStyleMap) {
updateCombo(fWrappingStyleCombo, wrappingStyleMap, WRAPPING_NAMES);
updateCombo(fIndentStyleCombo, indentStyleMap, INDENT_NAMES);
}
private void updateCombo(Combo combo, Map map, final String[] items) {
String[] newItems= new String[items.length];
int maxCount= 0, maxStyle= 0;
for(int i = 0; i < items.length; i++) {
Integer count= (Integer) map.get(new Integer(i));
int val= (count == null) ? 0 : count.intValue();
if (val > maxCount) {
maxCount= val;
maxStyle= i;
}
newItems[i]= getLabelText(items[i], val, fElements.size());
}
combo.setItems(newItems);
combo.setText(newItems[maxStyle]);
}
}
protected static final String[] INDENT_NAMES = {
FormatterMessages.LineWrappingTabPage_indentation_default,
FormatterMessages.LineWrappingTabPage_indentation_on_column,
FormatterMessages.LineWrappingTabPage_indentation_by_one
};
protected static final String[] WRAPPING_NAMES = {
FormatterMessages.LineWrappingTabPage_splitting_do_not_split,
FormatterMessages.LineWrappingTabPage_splitting_wrap_when_necessary, // COMPACT_SPLIT
FormatterMessages.LineWrappingTabPage_splitting_always_wrap_first_others_when_necessary, // COMPACT_FIRST_BREAK_SPLIT
FormatterMessages.LineWrappingTabPage_splitting_wrap_always, // ONE_PER_LINE_SPLIT
FormatterMessages.LineWrappingTabPage_splitting_wrap_always_indent_all_but_first, // NEXT_SHIFTED_SPLIT
FormatterMessages.LineWrappingTabPage_splitting_wrap_always_except_first_only_if_necessary
};
// private final Category fCompactIfCategory= new Category(
// DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_COMPACT_IF,
// "class Example {" + //$NON-NLS-1$
// "int foo(int argument) {" + //$NON-NLS-1$
// " if (argument==0) return 0;" + //$NON-NLS-1$
// " if (argument==1) return 42; else return 43;" + //$NON-NLS-1$
// "}}", //$NON-NLS-1$
// FormatterMessages.LineWrappingTabPage_compact_if_else
// );
//
//
// private final Category fTypeDeclarationSuperclassCategory= new Category(
// DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_SUPERCLASS_IN_TYPE_DECLARATION,
// "class Example extends OtherClass {}", //$NON-NLS-1$
// FormatterMessages.LineWrappingTabPage_extends_clause
// );
//
//
// private final Category fTypeDeclarationSuperinterfacesCategory= new Category(
// DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_SUPERINTERFACES_IN_TYPE_DECLARATION,
// "class Example implements I1, I2, I3 {}", //$NON-NLS-1$
// FormatterMessages.LineWrappingTabPage_implements_clause
// );
//
//
// private final Category fConstructorDeclarationsParametersCategory= new Category(
// DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_CONSTRUCTOR_DECLARATION,
// "class Example {Example(int arg1, int arg2, int arg3, int arg4, int arg5, int arg6) { this();}" + //$NON-NLS-1$
// "Example() {}}", //$NON-NLS-1$
// FormatterMessages.LineWrappingTabPage_parameters
// );
private final Category fMethodDeclarationsParametersCategory= new Category(
DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_METHOD_DECLARATION,
"class Example {void foo(int arg1, int arg2, int arg3, int arg4, int arg5, int arg6) {}};", //$NON-NLS-1$
FormatterMessages.LineWrappingTabPage_parameters
);
private final Category fMessageSendArgumentsCategory= new Category(
DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_METHOD_INVOCATION,
"class Other {static void bar(int arg1, int arg2, int arg3, int arg4, int arg5, int arg6) {}};"+ //$NON-NLS-1$
"void foo() {Other::bar(100, 200, 300, 400, 500, 600, 700, 800, 900);}", //$NON-NLS-1$
FormatterMessages.LineWrappingTabPage_arguments
);
// private final Category fMessageSendSelectorCategory= new Category(
// DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_SELECTOR_IN_METHOD_INVOCATION,
// "class Example {int foo(Some a) {return a.getFirst();}}", //$NON-NLS-1$
// FormatterMessages.LineWrappingTabPage_qualified_invocations
// );
//
// private final Category fMethodThrowsClauseCategory= new Category(
// DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_THROWS_CLAUSE_IN_METHOD_DECLARATION,
// "class Example {" + //$NON-NLS-1$
// "int foo() throws FirstException, SecondException, ThirdException {" + //$NON-NLS-1$
// " return Other.doSomething();}}", //$NON-NLS-1$
// FormatterMessages.LineWrappingTabPage_throws_clause
// );
//
// private final Category fConstructorThrowsClauseCategory= new Category(
// DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_THROWS_CLAUSE_IN_CONSTRUCTOR_DECLARATION,
// "class Example {" + //$NON-NLS-1$
// "Example() throws FirstException, SecondException, ThirdException {" + //$NON-NLS-1$
// " return Other.doSomething();}}", //$NON-NLS-1$
// FormatterMessages.LineWrappingTabPage_throws_clause
// );
//
//
// private final Category fAllocationExpressionArgumentsCategory= new Category(
// DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_ALLOCATION_EXPRESSION,
// "class Example {SomeClass foo() {return new SomeClass(100, 200, 300, 400, 500, 600, 700, 800, 900 );}}", //$NON-NLS-1$
// FormatterMessages.LineWrappingTabPage_object_allocation
// );
//
// private final Category fQualifiedAllocationExpressionCategory= new Category (
// DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_QUALIFIED_ALLOCATION_EXPRESSION,
// "class Example {SomeClass foo() {return SomeOtherClass.new SomeClass(100, 200, 300, 400, 500 );}}", //$NON-NLS-1$
// FormatterMessages.LineWrappingTabPage_qualified_object_allocation
// );
private final Category fArrayInitializerExpressionsCategory= new Category(
DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_EXPRESSIONS_IN_ARRAY_INITIALIZER,
"int[] array= {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14};", //$NON-NLS-1$
FormatterMessages.LineWrappingTabPage_array_init
);
// private final Category fExplicitConstructorArgumentsCategory= new Category(
// DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_EXPLICIT_CONSTRUCTOR_CALL,
// "class Example extends AnotherClass {Example() {super(100, 200, 300, 400, 500, 600, 700);}}", //$NON-NLS-1$
// FormatterMessages.LineWrappingTabPage_explicit_constructor_invocations
// );
private final Category fConditionalExpressionCategory= new Category(
DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_CONDITIONAL_EXPRESSION,
"int example(bool argument0, int otherArgument) {return argument ? 100000 : 200000;}}", //$NON-NLS-1$
FormatterMessages.LineWrappingTabPage_conditionals
);
// private final Category fBinaryExpressionCategory= new Category(
// DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_BINARY_EXPRESSION,
// "class Example extends AnotherClass {" + //$NON-NLS-1$
// "int foo() {" + //$NON-NLS-1$
// " int sum= 100 + 200 + 300 + 400 + 500 + 600 + 700 + 800;" + //$NON-NLS-1$
// " int product= 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10;" + //$NON-NLS-1$
// " boolean val= true && false && true && false && true;" + //$NON-NLS-1$
// " return product / sum;}}", //$NON-NLS-1$
// FormatterMessages.LineWrappingTabPage_binary_exprs
// );
//
// private final Category fEnumConstArgumentsCategory= new Category(
// DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_ENUM_CONSTANT,
// "enum Example {" + //$NON-NLS-1$
// "GREEN(0, 255, 0), RED(255, 0, 0) }", //$NON-NLS-1$
// FormatterMessages.LineWrappingTabPage_enum_constant_arguments
// );
//
// private final Category fEnumDeclInterfacesCategory= new Category(
// DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_SUPERINTERFACES_IN_ENUM_DECLARATION,
// "enum Example implements A, B, C {" + //$NON-NLS-1$
// "}", //$NON-NLS-1$
// FormatterMessages.LineWrappingTabPage_enum_superinterfaces
// );
//
// private final Category fEnumConstantsCategory= new Category(
// DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ENUM_CONSTANTS,
// "enum Example {" + //$NON-NLS-1$
// "CANCELLED, RUNNING, WAITING, FINISHED }" + //$NON-NLS-1$
// "enum Example {" + //$NON-NLS-1$
// "GREEN(0, 255, 0), RED(255, 0, 0) }", //$NON-NLS-1$
// FormatterMessages.LineWrappingTabPage_enum_constants
// );
//
// private final Category fAssignmentCategory= new Category(
// DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ASSIGNMENT,
// "class Example {" + //$NON-NLS-1$
// "private static final String string = \"TextTextText\";" + //$NON-NLS-1$
// "void foo() {" + //$NON-NLS-1$
// "for (int i = 0; i < 10; i++) {}" + //$NON-NLS-1$
// "String s;" + //$NON-NLS-1$
// "s = \"TextTextText\";}}", //$NON-NLS-1$
// FormatterMessages.LineWrappingTabPage_assignment_alignment
// );
/**
* The default preview line width.
*/
private static int DEFAULT_PREVIEW_WINDOW_LINE_WIDTH= 40;
/**
* The key to save the user's preview window width in the dialog settings.
*/
private static final String PREF_PREVIEW_LINE_WIDTH= CUIPlugin.PLUGIN_ID + ".codeformatter.line_wrapping_tab_page.preview_line_width"; //$NON-NLS-1$
/**
* The dialog settings.
*/
protected final IDialogSettings fDialogSettings;
protected TreeViewer fCategoriesViewer;
protected Label fWrappingStylePolicy;
protected Combo fWrappingStyleCombo;
protected Label fIndentStylePolicy;
protected Combo fIndentStyleCombo;
protected Button fForceSplit;
protected TranslationUnitPreview fPreview;
protected Group fOptionsGroup;
/**
* A collection containing the categories tree. This is used as model for the tree viewer.
* @see TreeViewer
*/
private final List fCategories;
/**
* The category listener which makes the selection persistent.
*/
protected final CategoryListener fCategoryListener;
/**
* The current selection of elements.
*/
protected IStructuredSelection fSelection;
/**
* An object containing the state for the UI.
*/
SelectionState fSelectionState;
/**
* A special options store wherein the preview line width is kept.
*/
protected final Map fPreviewPreferences;
/**
* The key for the preview line width.
*/
private final String LINE_SPLIT= DefaultCodeFormatterConstants.FORMATTER_LINE_SPLIT;
/**
* Create a new line wrapping tab page.
* @param modifyDialog
* @param workingValues
*/
public LineWrappingTabPage(ModifyDialog modifyDialog, Map workingValues) {
super(modifyDialog, workingValues);
fDialogSettings= CUIPlugin.getDefault().getDialogSettings();
final String previewLineWidth= fDialogSettings.get(PREF_PREVIEW_LINE_WIDTH);
fPreviewPreferences= new HashMap();
fPreviewPreferences.put(LINE_SPLIT, previewLineWidth != null ? previewLineWidth : Integer.toString(DEFAULT_PREVIEW_WINDOW_LINE_WIDTH));
fCategories= createCategories();
fCategoryListener= new CategoryListener(fCategories);
}
/**
* @return Create the categories tree.
*/
protected List createCategories() {
// final Category classDeclarations= new Category(FormatterMessages.LineWrappingTabPage_class_decls);
// classDeclarations.children.add(fTypeDeclarationSuperclassCategory);
// classDeclarations.children.add(fTypeDeclarationSuperinterfacesCategory);
// final Category constructorDeclarations= new Category(null, null, FormatterMessages.LineWrappingTabPage_constructor_decls);
// constructorDeclarations.children.add(fConstructorDeclarationsParametersCategory);
// constructorDeclarations.children.add(fConstructorThrowsClauseCategory);
final Category methodDeclarations= new Category(null, null, FormatterMessages.LineWrappingTabPage_method_decls);
methodDeclarations.children.add(fMethodDeclarationsParametersCategory);
// methodDeclarations.children.add(fMethodThrowsClauseCategory);
// final Category enumDeclarations= new Category(FormatterMessages.LineWrappingTabPage_enum_decls);
// enumDeclarations.children.add(fEnumConstantsCategory);
// enumDeclarations.children.add(fEnumDeclInterfacesCategory);
// enumDeclarations.children.add(fEnumConstArgumentsCategory);
final Category functionCalls= new Category(FormatterMessages.LineWrappingTabPage_function_calls);
functionCalls.children.add(fMessageSendArgumentsCategory);
// functionCalls.children.add(fMessageSendSelectorCategory);
// functionCalls.children.add(fExplicitConstructorArgumentsCategory);
// functionCalls.children.add(fAllocationExpressionArgumentsCategory);
// functionCalls.children.add(fQualifiedAllocationExpressionCategory);
final Category expressions= new Category(FormatterMessages.LineWrappingTabPage_expressions);
// expressions.children.add(fBinaryExpressionCategory);
expressions.children.add(fConditionalExpressionCategory);
expressions.children.add(fArrayInitializerExpressionsCategory);
// expressions.children.add(fAssignmentCategory);
// final Category statements= new Category(FormatterMessages.LineWrappingTabPage_statements);
// statements.children.add(fCompactIfCategory);
final List root= new ArrayList();
// root.add(classDeclarations);
// root.add(constructorDeclarations);
root.add(methodDeclarations);
// root.add(enumDeclarations);
root.add(functionCalls);
// root.add(expressions);
// root.add(statements);
return root;
}
/*
* @see org.eclipse.cdt.internal.ui.preferences.formatter.ModifyDialogTabPage#doCreatePreferences(org.eclipse.swt.widgets.Composite, int)
*/
protected void doCreatePreferences(Composite composite, int numColumns) {
final Group lineWidthGroup= createGroup(numColumns, composite, FormatterMessages.LineWrappingTabPage_width_indent);
createNumberPref(lineWidthGroup, numColumns, FormatterMessages.LineWrappingTabPage_width_indent_option_max_line_width, DefaultCodeFormatterConstants.FORMATTER_LINE_SPLIT, 0, 9999);
createNumberPref(lineWidthGroup, numColumns, FormatterMessages.LineWrappingTabPage_width_indent_option_default_indent_wrapped, DefaultCodeFormatterConstants.FORMATTER_CONTINUATION_INDENTATION, 0, 9999);
// createNumberPref(lineWidthGroup, numColumns, FormatterMessages.LineWrappingTabPage_width_indent_option_default_indent_array, DefaultCodeFormatterConstants.FORMATTER_CONTINUATION_INDENTATION_FOR_ARRAY_INITIALIZER, 0, 9999);
fCategoriesViewer= new TreeViewer(composite /*categoryGroup*/, SWT.MULTI | SWT.BORDER | SWT.READ_ONLY | SWT.V_SCROLL );
fCategoriesViewer.setContentProvider(new ITreeContentProvider() {
public Object[] getElements(Object inputElement) {
return ((Collection)inputElement).toArray();
}
public Object[] getChildren(Object parentElement) {
return ((Category)parentElement).children.toArray();
}
public Object getParent(Object element) { return null; }
public boolean hasChildren(Object element) {
return !((Category)element).children.isEmpty();
}
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {}
public void dispose() {}
});
fCategoriesViewer.setLabelProvider(new LabelProvider());
fCategoriesViewer.setInput(fCategories);
fCategoriesViewer.setExpandedElements(fCategories.toArray());
final GridData gd= createGridData(numColumns, GridData.FILL_BOTH, SWT.DEFAULT);
fCategoriesViewer.getControl().setLayoutData(gd);
fOptionsGroup = createGroup(numColumns, composite, ""); //$NON-NLS-1$
// label "Select split style:"
fWrappingStylePolicy= createLabel(numColumns, fOptionsGroup, FormatterMessages.LineWrappingTabPage_wrapping_policy_label_text);
// combo SplitStyleCombo
fWrappingStyleCombo= new Combo(fOptionsGroup, SWT.SINGLE | SWT.READ_ONLY);
fWrappingStyleCombo.setItems(WRAPPING_NAMES);
fWrappingStyleCombo.setLayoutData(createGridData(numColumns, GridData.HORIZONTAL_ALIGN_FILL, 0));
// label "Select indentation style:"
fIndentStylePolicy= createLabel(numColumns, fOptionsGroup, FormatterMessages.LineWrappingTabPage_indentation_policy_label_text);
// combo SplitStyleCombo
fIndentStyleCombo= new Combo(fOptionsGroup, SWT.SINGLE | SWT.READ_ONLY);
fIndentStyleCombo.setItems(INDENT_NAMES);
fIndentStyleCombo.setLayoutData(createGridData(numColumns, GridData.HORIZONTAL_ALIGN_FILL, 0));
// button "Force split"
fForceSplit= new Button(fOptionsGroup, SWT.CHECK);
fForceSplit.setLayoutData(createGridData(numColumns, GridData.HORIZONTAL_ALIGN_FILL, 0));
fForceSplit.setText(FormatterMessages.LineWrappingTabPage_force_split_checkbox_text);
// selection state object
fSelectionState= new SelectionState();
}
/*
* @see org.eclipse.cdt.internal.ui.preferences.formatter.ModifyDialogTabPage#doCreatePreviewPane(org.eclipse.swt.widgets.Composite, int)
*/
protected Composite doCreatePreviewPane(Composite composite, int numColumns) {
super.doCreatePreviewPane(composite, numColumns);
final NumberPreference previewLineWidth= new NumberPreference(composite, numColumns / 2, fPreviewPreferences, LINE_SPLIT,
0, 9999, FormatterMessages.LineWrappingTabPage_line_width_for_preview_label_text);
fDefaultFocusManager.add(previewLineWidth);
previewLineWidth.addObserver(fUpdater);
previewLineWidth.addObserver(new Observer() {
public void update(Observable o, Object arg) {
fDialogSettings.put(PREF_PREVIEW_LINE_WIDTH, (String)fPreviewPreferences.get(LINE_SPLIT));
}
});
return composite;
}
/*
* @see org.eclipse.cdt.internal.ui.preferences.formatter.ModifyDialogTabPage#doCreateCPreview(org.eclipse.swt.widgets.Composite)
*/
protected CPreview doCreateCPreview(Composite parent) {
fPreview= new TranslationUnitPreview(fWorkingValues, parent);
return fPreview;
}
/*
* @see org.eclipse.cdt.internal.ui.preferences.formatter.ModifyDialogTabPage#initializePage()
*/
protected void initializePage() {
fCategoriesViewer.addSelectionChangedListener(fCategoryListener);
fCategoriesViewer.addDoubleClickListener(fCategoryListener);
fForceSplit.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
forceSplitChanged(fForceSplit.getSelection());
}
});
fIndentStyleCombo.addSelectionListener( new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
indentStyleChanged(((Combo)e.widget).getSelectionIndex());
}
});
fWrappingStyleCombo.addSelectionListener( new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
wrappingStyleChanged(((Combo)e.widget).getSelectionIndex());
}
});
fCategoryListener.restoreSelection();
fDefaultFocusManager.add(fCategoriesViewer.getControl());
fDefaultFocusManager.add(fWrappingStyleCombo);
fDefaultFocusManager.add(fIndentStyleCombo);
fDefaultFocusManager.add(fForceSplit);
}
/*
* @see org.eclipse.cdt.internal.ui.preferences.formatter.ModifyDialogTabPage#doUpdatePreview()
*/
protected void doUpdatePreview() {
final Object normalSetting= fWorkingValues.get(LINE_SPLIT);
fWorkingValues.put(LINE_SPLIT, fPreviewPreferences.get(LINE_SPLIT));
fPreview.update();
fWorkingValues.put(LINE_SPLIT, normalSetting);
}
protected void setPreviewText(String text) {
final Object normalSetting= fWorkingValues.get(LINE_SPLIT);
fWorkingValues.put(LINE_SPLIT, fPreviewPreferences.get(LINE_SPLIT));
fPreview.setPreviewText(text);
fWorkingValues.put(LINE_SPLIT, normalSetting);
}
protected void forceSplitChanged(boolean forceSplit) {
Iterator iterator= fSelectionState.fElements.iterator();
String currentKey;
while (iterator.hasNext()) {
currentKey= ((Category)iterator.next()).key;
try {
changeForceSplit(currentKey, forceSplit);
} catch (IllegalArgumentException e) {
fWorkingValues.put(currentKey, DefaultCodeFormatterConstants.createAlignmentValue(forceSplit, DefaultCodeFormatterConstants.WRAP_NO_SPLIT, DefaultCodeFormatterConstants.INDENT_DEFAULT));
CUIPlugin.getDefault().log(new Status(IStatus.ERROR, CUIPlugin.getPluginId(), IStatus.OK,
Messages.format(FormatterMessages.LineWrappingTabPage_error_invalid_value, currentKey), e));
}
}
fSelectionState.refreshState(fSelection);
}
private void changeForceSplit(String currentKey, boolean forceSplit) throws IllegalArgumentException{
String value= (String)fWorkingValues.get(currentKey);
value= DefaultCodeFormatterConstants.setForceWrapping(value, forceSplit);
if (value == null)
throw new IllegalArgumentException();
fWorkingValues.put(currentKey, value);
}
protected void wrappingStyleChanged(int wrappingStyle) {
Iterator iterator= fSelectionState.fElements.iterator();
String currentKey;
while (iterator.hasNext()) {
currentKey= ((Category)iterator.next()).key;
try {
changeWrappingStyle(currentKey, wrappingStyle);
} catch (IllegalArgumentException e) {
fWorkingValues.put(currentKey, DefaultCodeFormatterConstants.createAlignmentValue(false, wrappingStyle, DefaultCodeFormatterConstants.INDENT_DEFAULT));
CUIPlugin.getDefault().log(new Status(IStatus.ERROR, CUIPlugin.getPluginId(), IStatus.OK,
Messages.format(FormatterMessages.LineWrappingTabPage_error_invalid_value, currentKey), e));
}
}
fSelectionState.refreshState(fSelection);
}
private void changeWrappingStyle(String currentKey, int wrappingStyle) throws IllegalArgumentException {
String value= (String)fWorkingValues.get(currentKey);
value= DefaultCodeFormatterConstants.setWrappingStyle(value, wrappingStyle);
if (value == null)
throw new IllegalArgumentException();
fWorkingValues.put(currentKey, value);
}
protected void indentStyleChanged(int indentStyle) {
Iterator iterator= fSelectionState.fElements.iterator();
String currentKey;
while (iterator.hasNext()) {
currentKey= ((Category)iterator.next()).key;
try {
changeIndentStyle(currentKey, indentStyle);
} catch (IllegalArgumentException e) {
fWorkingValues.put(currentKey, DefaultCodeFormatterConstants.createAlignmentValue(false, DefaultCodeFormatterConstants.WRAP_NO_SPLIT, indentStyle));
CUIPlugin.getDefault().log(new Status(IStatus.ERROR, CUIPlugin.PLUGIN_ID, IStatus.OK,
Messages.format(FormatterMessages.LineWrappingTabPage_error_invalid_value, currentKey), e));
}
}
fSelectionState.refreshState(fSelection);
}
private void changeIndentStyle(String currentKey, int indentStyle) throws IllegalArgumentException{
String value= (String)fWorkingValues.get(currentKey);
value= DefaultCodeFormatterConstants.setIndentStyle(value, indentStyle);
if (value == null)
throw new IllegalArgumentException();
fWorkingValues.put(currentKey, value);
}
protected void updateControlEnablement(boolean inhomogenous, int wrappingStyle) {
boolean doSplit= wrappingStyle != DefaultCodeFormatterConstants.WRAP_NO_SPLIT;
fIndentStylePolicy.setEnabled(true);
fIndentStyleCombo.setEnabled(inhomogenous || doSplit);
fForceSplit.setEnabled(inhomogenous || doSplit);
}
}

View file

@ -1,5 +1,5 @@
/*******************************************************************************
* Copyright (c) 2000, 2005 IBM Corporation and others.
* Copyright (c) 2000, 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
@ -8,38 +8,56 @@
* Contributors:
* IBM Corporation - initial API and implementation
* Sergey Prigogin, Google
* Anton Leherbauer (Wind River Systems)
*******************************************************************************/
package org.eclipse.cdt.internal.ui.preferences.formatter;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.content.IContentType;
import org.eclipse.cdt.internal.ui.preferences.formatter.ModifyDialogTabPage;
import org.eclipse.cdt.internal.ui.preferences.formatter.ProfileManager.CustomProfile;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.StatusDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
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.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.StatusDialog;
import org.eclipse.jface.window.Window;
import org.eclipse.cdt.internal.ui.util.Messages;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.internal.ui.preferences.formatter.ProfileManager.Profile;
public class ModifyDialog extends StatusDialog {
import org.eclipse.cdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.cdt.internal.ui.preferences.formatter.ProfileManager.Profile;
import org.eclipse.cdt.internal.ui.util.ExceptionHandler;
import org.eclipse.cdt.internal.ui.util.Messages;
import org.eclipse.cdt.internal.ui.wizards.dialogfields.DialogField;
import org.eclipse.cdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
import org.eclipse.cdt.internal.ui.wizards.dialogfields.StringDialogField;
public abstract class ModifyDialog extends StatusDialog {
/**
* The keys to retrieve the preferred area from the dialog settings.
@ -54,49 +72,59 @@ public class ModifyDialog extends StatusDialog {
* focus last time.
*/
private static final String DS_KEY_LAST_FOCUS= CUIPlugin.PLUGIN_ID + "formatter_page.modify_dialog.last_focus"; //$NON-NLS-1$
private static final int APPLAY_BUTTON_ID= IDialogConstants.CLIENT_ID;
private static final int SAVE_BUTTON_ID= IDialogConstants.CLIENT_ID + 1;
private final String fTitle;
private final String fKeyPreferredWidth;
private final String fKeyPreferredHight;
private final String fKeyPreferredX;
private final String fKeyPreferredY;
private final String fKeyLastFocus;
private final String fLastSaveLoadPathKey;
private final ProfileStore fProfileStore;
private final boolean fNewProfile;
private Profile fProfile;
private final Map fWorkingValues;
private IStatus fStandardStatus;
protected final List fTabPages;
final IDialogSettings fDialogSettings;
// private TabFolder fTabFolder;
private ProfileManager fProfileManager;
// private Button fApplyButton;
protected ModifyDialog(Shell parentShell, Profile profile, ProfileManager profileManager, boolean newProfile) {
private final List fTabPages;
private final IDialogSettings fDialogSettings;
private TabFolder fTabFolder;
private final ProfileManager fProfileManager;
private Button fApplyButton;
private Button fSaveButton;
private StringDialogField fProfileNameField;
protected ModifyDialog(Shell parentShell, Profile profile, ProfileManager profileManager, ProfileStore profileStore, boolean newProfile, String dialogPreferencesKey, String lastSavePathKey) {
super(parentShell);
fProfileStore= profileStore;
fLastSaveLoadPathKey= lastSavePathKey;
fKeyPreferredWidth= CUIPlugin.PLUGIN_ID + dialogPreferencesKey + DS_KEY_PREFERRED_WIDTH;
fKeyPreferredHight= CUIPlugin.PLUGIN_ID + dialogPreferencesKey + DS_KEY_PREFERRED_HEIGHT;
fKeyPreferredX= CUIPlugin.PLUGIN_ID + dialogPreferencesKey + DS_KEY_PREFERRED_X;
fKeyPreferredY= CUIPlugin.PLUGIN_ID + dialogPreferencesKey + DS_KEY_PREFERRED_Y;
fKeyLastFocus= CUIPlugin.PLUGIN_ID + dialogPreferencesKey + DS_KEY_LAST_FOCUS;
fProfileManager= profileManager;
fNewProfile= newProfile;
setShellStyle(getShellStyle() | SWT.RESIZE | SWT.MAX );
fProfile= profile;
if (fProfile.isBuiltInProfile()) {
fStandardStatus= new Status(IStatus.INFO, CUIPlugin.getPluginId(), IStatus.OK, FormatterMessages.ModifyDialog_dialog_show_warning_builtin, null);
fTitle= Messages.format(FormatterMessages.ModifyDialog_dialog_show_title, profile.getName());
} else {
fStandardStatus= new Status(IStatus.OK, CUIPlugin.getPluginId(), IStatus.OK, "", null); //$NON-NLS-1$
fTitle= Messages.format(FormatterMessages.ModifyDialog_dialog_title, profile.getName());
}
setTitle(Messages.format(FormatterMessages.ModifyDialog_dialog_title, profile.getName()));
fWorkingValues= new HashMap(fProfile.getSettings());
updateStatus(fStandardStatus);
setStatusLineAboveButtons(false);
fTabPages= new ArrayList();
fDialogSettings= CUIPlugin.getDefault().getDialogSettings();
}
protected abstract void addPages(Map values);
public void create() {
super.create();
int lastFocusNr= 0;
try {
lastFocusNr= fDialogSettings.getInt(DS_KEY_LAST_FOCUS);
lastFocusNr= fDialogSettings.getInt(fKeyLastFocus);
if (lastFocusNr < 0) lastFocusNr= 0;
if (lastFocusNr > fTabPages.size() - 1) lastFocusNr= fTabPages.size() - 1;
} catch (NumberFormatException x) {
@ -104,90 +132,100 @@ public class ModifyDialog extends StatusDialog {
}
if (!fNewProfile) {
// fTabFolder.setSelection(lastFocusNr);
// ((ModifyDialogTabPage)fTabFolder.getSelection()[0].getData()).setInitialFocus();
fTabFolder.setSelection(lastFocusNr);
((ModifyDialogTabPage)fTabFolder.getSelection()[0].getData()).setInitialFocus();
}
}
protected void configureShell(Shell shell) {
super.configureShell(shell);
shell.setText(fTitle);
}
protected Control createDialogArea(Composite parent) {
final Composite composite= (Composite)super.createDialogArea(parent);
ModifyDialogTabPage tabPage = new IndentationTabPage(this, fWorkingValues);
tabPage.createContents(composite);
// fTabFolder = new TabFolder(composite, SWT.NONE);
// fTabFolder.setFont(composite.getFont());
// fTabFolder.setLayoutData(new GridData(GridData.FILL_BOTH));
//
// addTabPage(fTabFolder, FormatterMessages.ModifyDialog_tabpage_indentation_title, new IndentationTabPage(this, fWorkingValues));
// addTabPage(fTabFolder, FormatterMessages.ModifyDialog_tabpage_braces_title, new BracesTabPage(this, fWorkingValues));
// addTabPage(fTabFolder, FormatterMessages.ModifyDialog_tabpage_whitespace_title, new WhiteSpaceTabPage(this, fWorkingValues));
// addTabPage(fTabFolder, FormatterMessages.ModifyDialog_tabpage_blank_lines_title, new BlankLinesTabPage(this, fWorkingValues));
// addTabPage(fTabFolder, FormatterMessages.ModifyDialog_tabpage_new_lines_title, new NewLinesTabPage(this, fWorkingValues));
// addTabPage(fTabFolder, FormatterMessages.ModifyDialog_tabpage_control_statements_title, new ControlStatementsTabPage(this, fWorkingValues));
// addTabPage(fTabFolder, FormatterMessages.ModifyDialog_tabpage_line_wrapping_title, new LineWrappingTabPage(this, fWorkingValues));
// addTabPage(fTabFolder, FormatterMessages.ModifyDialog_tabpage_comments_title, new CommentsTabPage(this, fWorkingValues));
Composite nameComposite= new Composite(composite, SWT.NONE);
nameComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
nameComposite.setLayout(new GridLayout(3, false));
fProfileNameField= new StringDialogField();
fProfileNameField.setLabelText(FormatterMessages.ModifyDialog_ProfileName_Label);
fProfileNameField.setText(fProfile.getName());
fProfileNameField.getLabelControl(nameComposite).setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false));
fProfileNameField.getTextControl(nameComposite).setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
fProfileNameField.setDialogFieldListener(new IDialogFieldListener() {
public void dialogFieldChanged(DialogField field) {
doValidate();
}
});
fSaveButton= createButton(nameComposite, SAVE_BUTTON_ID, FormatterMessages.ModifyDialog_Export_Button, false);
fTabFolder = new TabFolder(composite, SWT.NONE);
fTabFolder.setFont(composite.getFont());
fTabFolder.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
addPages(fWorkingValues);
applyDialogFont(composite);
// fTabFolder.addSelectionListener(new SelectionListener() {
// public void widgetDefaultSelected(SelectionEvent e) {}
// public void widgetSelected(SelectionEvent e) {
// final TabItem tabItem= (TabItem)e.item;
// final ModifyDialogTabPage page= (ModifyDialogTabPage)tabItem.getData();
//// page.fSashForm.setWeights();
// fDialogSettings.put(DS_KEY_LAST_FOCUS, fTabPages.indexOf(page));
// page.makeVisible();
// }
// });
fTabFolder.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {}
public void widgetSelected(SelectionEvent e) {
final TabItem tabItem= (TabItem)e.item;
final ModifyDialogTabPage page= (ModifyDialogTabPage)tabItem.getData();
// page.fSashForm.setWeights();
fDialogSettings.put(fKeyLastFocus, fTabPages.indexOf(page));
page.makeVisible();
}
});
doValidate();
return composite;
}
public void updateStatus(IStatus status) {
super.updateStatus(status != null ? status : fStandardStatus);
if (status == null) {
doValidate();
} else {
super.updateStatus(status);
}
}
/* (non-Javadoc)
* @see org.eclipse.jface.window.Window#getInitialSize()
*/
protected Point getInitialSize() {
Point initialSize= super.getInitialSize();
try {
int lastWidth= fDialogSettings.getInt(DS_KEY_PREFERRED_WIDTH);
if (initialSize.x > lastWidth)
lastWidth= initialSize.x;
int lastHeight= fDialogSettings.getInt(DS_KEY_PREFERRED_HEIGHT);
if (initialSize.y > lastHeight)
lastHeight= initialSize.x;
return new Point(lastWidth, lastHeight);
} catch (NumberFormatException ex) {
}
return initialSize;
Point initialSize= super.getInitialSize();
try {
int lastWidth= fDialogSettings.getInt(fKeyPreferredWidth);
if (initialSize.x > lastWidth)
lastWidth= initialSize.x;
int lastHeight= fDialogSettings.getInt(fKeyPreferredHight);
if (initialSize.y > lastHeight)
lastHeight= initialSize.x;
return new Point(lastWidth, lastHeight);
} catch (NumberFormatException ex) {
}
return initialSize;
}
/* (non-Javadoc)
* @see org.eclipse.jface.window.Window#getInitialLocation(org.eclipse.swt.graphics.Point)
*/
protected Point getInitialLocation(Point initialSize) {
try {
return new Point(fDialogSettings.getInt(DS_KEY_PREFERRED_X), fDialogSettings.getInt(DS_KEY_PREFERRED_Y));
} catch (NumberFormatException ex) {
return super.getInitialLocation(initialSize);
}
try {
return new Point(fDialogSettings.getInt(fKeyPreferredX), fDialogSettings.getInt(fKeyPreferredY));
} catch (NumberFormatException ex) {
return super.getInitialLocation(initialSize);
}
}
public boolean close() {
final Rectangle shell= getShell().getBounds();
fDialogSettings.put(DS_KEY_PREFERRED_WIDTH, shell.width);
fDialogSettings.put(DS_KEY_PREFERRED_HEIGHT, shell.height);
fDialogSettings.put(DS_KEY_PREFERRED_X, shell.x);
fDialogSettings.put(DS_KEY_PREFERRED_Y, shell.y);
fDialogSettings.put(fKeyPreferredWidth, shell.width);
fDialogSettings.put(fKeyPreferredHight, shell.height);
fDialogSettings.put(fKeyPreferredX, shell.x);
fDialogSettings.put(fKeyPreferredY, shell.y);
return super.close();
}
@ -201,32 +239,64 @@ public class ModifyDialog extends StatusDialog {
}
protected void buttonPressed(int buttonId) {
if (buttonId == IDialogConstants.CLIENT_ID) {
if (buttonId == APPLAY_BUTTON_ID) {
applyPressed();
setTitle(Messages.format(FormatterMessages.ModifyDialog_dialog_title, fProfile.getName()));
} else if (buttonId == SAVE_BUTTON_ID) {
saveButtonPressed();
} else {
super.buttonPressed(buttonId);
}
}
private void applyPressed() {
if (fProfile.isBuiltInProfile() || fProfile.isSharedProfile()) {
RenameProfileDialog dialog= new RenameProfileDialog(getShell(), fProfile, fProfileManager);
if (dialog.open() != Window.OK) {
return;
}
if (!fProfile.getName().equals(fProfileNameField.getText())) {
fProfile= fProfile.rename(fProfileNameField.getText(), fProfileManager);
}
fProfile.setSettings(new HashMap(fWorkingValues));
fProfileManager.setSelected(fProfile);
doValidate();
}
fProfile= dialog.getRenamedProfile();
fStandardStatus= new Status(IStatus.OK, CUIPlugin.getPluginId(), IStatus.OK, "", null); //$NON-NLS-1$
updateStatus(fStandardStatus);
}
fProfile.setSettings(new HashMap(fWorkingValues));
// fApplyButton.setEnabled(false);
private void saveButtonPressed() {
Profile selected= new CustomProfile(fProfileNameField.getText(), new HashMap(fWorkingValues), fProfile.getVersion(), fProfileManager.getProfileVersioner().getProfileKind());
final FileDialog dialog= new FileDialog(getShell(), SWT.SAVE);
dialog.setText(FormatterMessages.CodingStyleConfigurationBlock_save_profile_dialog_title);
dialog.setFilterExtensions(new String [] {"*.xml"}); //$NON-NLS-1$
final String lastPath= CUIPlugin.getDefault().getDialogSettings().get(fLastSaveLoadPathKey + ".savepath"); //$NON-NLS-1$
if (lastPath != null) {
dialog.setFilterPath(lastPath);
}
final String path= dialog.open();
if (path == null)
return;
CUIPlugin.getDefault().getDialogSettings().put(fLastSaveLoadPathKey + ".savepath", dialog.getFilterPath()); //$NON-NLS-1$
final File file= new File(path);
if (file.exists() && !MessageDialog.openQuestion(getShell(), FormatterMessages.CodingStyleConfigurationBlock_save_profile_overwrite_title, Messages.format(FormatterMessages.CodingStyleConfigurationBlock_save_profile_overwrite_message, path))) {
return;
}
String encoding= ProfileStore.ENCODING;
final IContentType type= Platform.getContentTypeManager().getContentType("org.eclipse.core.runtime.xml"); //$NON-NLS-1$
if (type != null)
encoding= type.getDefaultCharset();
final Collection profiles= new ArrayList();
profiles.add(selected);
try {
fProfileStore.writeProfilesToFile(profiles, file, encoding);
} catch (CoreException e) {
final String title= FormatterMessages.CodingStyleConfigurationBlock_save_profile_error_title;
final String message= FormatterMessages.CodingStyleConfigurationBlock_save_profile_error_message;
ExceptionHandler.handle(e, getShell(), title, message);
}
}
protected void createButtonsForButtonBar(Composite parent) {
// fApplyButton= createButton(parent, IDialogConstants.CLIENT_ID, FormatterMessages.ModifyDialog_apply_button, false);
// fApplyButton.setEnabled(false);
fApplyButton= createButton(parent, APPLAY_BUTTON_ID, FormatterMessages.ModifyDialog_apply_button, false);
fApplyButton.setEnabled(false);
GridLayout layout= (GridLayout) parent.getLayout();
layout.numColumns++;
@ -239,29 +309,85 @@ public class ModifyDialog extends StatusDialog {
}
// private final void addTabPage(TabFolder tabFolder, String title, ModifyDialogTabPage tabPage) {
// final TabItem tabItem= new TabItem(tabFolder, SWT.NONE);
// applyDialogFont(tabItem.getControl());
// tabItem.setText(title);
// tabItem.setData(tabPage);
// tabItem.setControl(tabPage.createContents(tabFolder));
// fTabPages.add(tabPage);
// }
public void valuesModified() {
// if (fApplyButton != null && !fApplyButton.isDisposed()) {
// fApplyButton.setEnabled(hasChanges());
// }
protected final void addTabPage(String title, ModifyDialogTabPage tabPage) {
final TabItem tabItem= new TabItem(fTabFolder, SWT.NONE);
applyDialogFont(tabItem.getControl());
tabItem.setText(title);
tabItem.setData(tabPage);
tabItem.setControl(tabPage.createContents(fTabFolder));
fTabPages.add(tabPage);
}
// private boolean hasChanges() {
// Iterator iter= fProfile.getSettings().entrySet().iterator();
// for (;iter.hasNext();) {
// Map.Entry curr= (Map.Entry) iter.next();
// if (!fWorkingValues.get(curr.getKey()).equals(curr.getValue())) {
// return true;
// }
// }
// return false;
// }
public void valuesModified() {
doValidate();
}
protected void updateButtonsEnableState(IStatus status) {
super.updateButtonsEnableState(status);
if (fApplyButton != null && !fApplyButton.isDisposed()) {
fApplyButton.setEnabled(!status.matches(IStatus.ERROR));
}
if (fSaveButton != null && !fSaveButton.isDisposed()) {
fSaveButton.setEnabled(!validateProfileName().matches(IStatus.ERROR));
}
}
private void doValidate() {
if (!hasChanges()) {
updateStatus(new Status(IStatus.ERROR, CUIPlugin.PLUGIN_ID, "")); //$NON-NLS-1$
return;
}
IStatus status= validateProfileName();
if (status.matches(IStatus.ERROR)) {
updateStatus(status);
return;
}
String name= fProfileNameField.getText().trim();
if (!name.equals(fProfile.getName()) && fProfileManager.containsName(name)) {
updateStatus(new Status(IStatus.ERROR, CUIPlugin.PLUGIN_ID, FormatterMessages.ModifyDialog_Duplicate_Status));
return;
}
if (fProfile.isBuiltInProfile() || fProfile.isSharedProfile()) {
updateStatus(new Status(IStatus.INFO, CUIPlugin.PLUGIN_ID, FormatterMessages.ModifyDialog_NewCreated_Status));
return;
}
updateStatus(StatusInfo.OK_STATUS);
}
private IStatus validateProfileName() {
final String name= fProfileNameField.getText().trim();
if (fProfile.isBuiltInProfile()) {
if (fProfile.getName().equals(name)) {
return new Status(IStatus.ERROR, CUIPlugin.PLUGIN_ID, FormatterMessages.ModifyDialog_BuiltIn_Status);
}
}
if (fProfile.isSharedProfile()) {
if (fProfile.getName().equals(name)) {
return new Status(IStatus.ERROR, CUIPlugin.PLUGIN_ID, FormatterMessages.ModifyDialog_Shared_Status);
}
}
if (name.length() == 0) {
return new Status(IStatus.ERROR, CUIPlugin.PLUGIN_ID, FormatterMessages.ModifyDialog_EmptyName_Status);
}
return StatusInfo.OK_STATUS;
}
private boolean hasChanges() {
Iterator iter= fProfile.getSettings().entrySet().iterator();
for (;iter.hasNext();) {
Map.Entry curr= (Map.Entry) iter.next();
if (!fWorkingValues.get(curr.getKey()).equals(curr.getValue())) {
return true;
}
}
return false;
}
}

View file

@ -1,5 +1,5 @@
/*******************************************************************************
* Copyright (c) 2000, 2005 IBM Corporation and others.
* Copyright (c) 2000, 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
@ -8,6 +8,7 @@
* Contributors:
* IBM Corporation - initial API and implementation
* Sergey Prigogin, Google
* Anton Leherbauer (Wind River Systems)
*******************************************************************************/
package org.eclipse.cdt.internal.ui.preferences.formatter;
@ -20,8 +21,10 @@ import java.util.Observer;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
@ -39,12 +42,8 @@ import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.formatter.DefaultCodeFormatterConstants;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.internal.ui.util.Messages;
@ -562,15 +561,11 @@ public abstract class ModifyDialogTabPage {
fPixelConverter= new PixelConverter(parent);
}
// final SashForm fSashForm = new SashForm(parent, SWT.HORIZONTAL);
// fSashForm.setFont(parent.getFont());
final SashForm fSashForm = new SashForm(parent, SWT.HORIZONTAL);
fSashForm.setFont(parent.getFont());
// final Composite settingsPane= new Composite(fSashForm, SWT.NONE);
// settingsPane.setFont(fSashForm.getFont());
final Composite settingsPane= new Composite(parent, SWT.NONE);
settingsPane.setFont(parent.getFont());
settingsPane.setLayoutData(new GridData(GridData.FILL_BOTH));
final Composite settingsPane= new Composite(fSashForm, SWT.NONE);
settingsPane.setFont(fSashForm.getFont());
final GridLayout layout= new GridLayout(numColumns, false);
layout.verticalSpacing= (int)(1.5 * fPixelConverter.convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING));
@ -580,16 +575,15 @@ public abstract class ModifyDialogTabPage {
settingsPane.setLayout(layout);
doCreatePreferences(settingsPane, numColumns);
return settingsPane;
// final Composite previewPane= new Composite(fSashForm, SWT.NONE);
// previewPane.setLayout(createGridLayout(numColumns, true));
// previewPane.setFont(fSashForm.getFont());
// doCreatePreviewPane(previewPane, numColumns);
//
// initializePage();
//
// fSashForm.setWeights(new int [] {3, 3});
// return fSashForm;
final Composite previewPane= new Composite(fSashForm, SWT.NONE);
previewPane.setLayout(createGridLayout(numColumns, true));
previewPane.setFont(fSashForm.getFont());
doCreatePreviewPane(previewPane, numColumns);
initializePage();
fSashForm.setWeights(new int [] {3, 3});
return fSashForm;
}
/**
@ -797,6 +791,6 @@ public abstract class ModifyDialogTabPage {
* Create a nice javadoc comment for some string.
*/
protected static String createPreviewHeader(String title) {
return "/**\n* " + title + "\n*/\n"; //$NON-NLS-1$ //$NON-NLS-2$
return "/*\n* " + title + "\n*/\n"; //$NON-NLS-1$ //$NON-NLS-2$
}
}

View file

@ -0,0 +1,448 @@
/*******************************************************************************
* Copyright (c) 2000, 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Anton Leherbauer (Wind River Systems)
*******************************************************************************/
package org.eclipse.cdt.internal.ui.preferences.formatter;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ProjectScope;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.preferences.DefaultScope;
import org.eclipse.core.runtime.preferences.IScopeContext;
import org.eclipse.core.runtime.preferences.IEclipsePreferences.IPreferenceChangeListener;
import org.eclipse.core.runtime.preferences.IEclipsePreferences.PreferenceChangeEvent;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.StatusDialog;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
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.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.osgi.service.prefs.BackingStoreException;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.internal.corext.util.Messages;
import org.eclipse.cdt.internal.ui.preferences.PreferencesAccess;
import org.eclipse.cdt.internal.ui.preferences.formatter.ProfileManager.CustomProfile;
import org.eclipse.cdt.internal.ui.preferences.formatter.ProfileManager.Profile;
import org.eclipse.cdt.internal.ui.util.ExceptionHandler;
import org.eclipse.cdt.internal.ui.util.PixelConverter;
import org.eclipse.cdt.internal.ui.util.SWTUtil;
public abstract class ProfileConfigurationBlock {
private class StoreUpdater implements Observer {
public StoreUpdater() {
fProfileManager.addObserver(this);
}
public void update(Observable o, Object arg) {
try {
fPreferenceListenerEnabled= false;
final int value= ((Integer)arg).intValue();
switch (value) {
case ProfileManager.PROFILE_DELETED_EVENT:
case ProfileManager.PROFILE_RENAMED_EVENT:
case ProfileManager.PROFILE_CREATED_EVENT:
case ProfileManager.SETTINGS_CHANGED_EVENT:
try {
fProfileStore.writeProfiles(fProfileManager.getSortedProfiles(), fInstanceScope); // update profile store
fProfileManager.commitChanges(fCurrContext);
} catch (CoreException x) {
CUIPlugin.getDefault().log(x);
}
break;
case ProfileManager.SELECTION_CHANGED_EVENT:
fProfileManager.commitChanges(fCurrContext);
break;
}
} finally {
fPreferenceListenerEnabled= true;
}
}
}
class ProfileComboController implements Observer, SelectionListener {
private final List fSortedProfiles;
public ProfileComboController() {
fSortedProfiles= fProfileManager.getSortedProfiles();
fProfileCombo.addSelectionListener(this);
fProfileManager.addObserver(this);
updateProfiles();
updateSelection();
}
public void widgetSelected(SelectionEvent e) {
final int index= fProfileCombo.getSelectionIndex();
fProfileManager.setSelected((Profile)fSortedProfiles.get(index));
}
public void widgetDefaultSelected(SelectionEvent e) {}
public void update(Observable o, Object arg) {
if (arg == null) return;
final int value= ((Integer)arg).intValue();
switch (value) {
case ProfileManager.PROFILE_CREATED_EVENT:
case ProfileManager.PROFILE_DELETED_EVENT:
case ProfileManager.PROFILE_RENAMED_EVENT:
updateProfiles();
updateSelection();
break;
case ProfileManager.SELECTION_CHANGED_EVENT:
updateSelection();
break;
}
}
private void updateProfiles() {
fProfileCombo.setItems(fProfileManager.getSortedDisplayNames());
}
private void updateSelection() {
fProfileCombo.setText(fProfileManager.getSelected().getName());
}
}
class ButtonController implements Observer, SelectionListener {
public ButtonController() {
fProfileManager.addObserver(this);
fNewButton.addSelectionListener(this);
fEditButton.addSelectionListener(this);
fDeleteButton.addSelectionListener(this);
fLoadButton.addSelectionListener(this);
update(fProfileManager, null);
}
public void update(Observable o, Object arg) {
Profile selected= ((ProfileManager)o).getSelected();
final boolean notBuiltIn= !selected.isBuiltInProfile();
fDeleteButton.setEnabled(notBuiltIn);
}
public void widgetSelected(SelectionEvent e) {
final Button button= (Button)e.widget;
if (button == fEditButton)
modifyButtonPressed();
else if (button == fDeleteButton)
deleteButtonPressed();
else if (button == fNewButton)
newButtonPressed();
else if (button == fLoadButton)
loadButtonPressed();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
private void modifyButtonPressed() {
final StatusDialog modifyDialog= createModifyDialog(fComposite.getShell(), fProfileManager.getSelected(), fProfileManager, fProfileStore, false);
modifyDialog.open();
}
private void deleteButtonPressed() {
if (MessageDialog.openQuestion(
fComposite.getShell(),
FormatterMessages.CodingStyleConfigurationBlock_delete_confirmation_title,
Messages.format(FormatterMessages.CodingStyleConfigurationBlock_delete_confirmation_question, fProfileManager.getSelected().getName()))) {
fProfileManager.deleteSelected();
}
}
private void newButtonPressed() {
final CreateProfileDialog p= new CreateProfileDialog(fComposite.getShell(), fProfileManager, fProfileVersioner);
if (p.open() != Window.OK)
return;
if (!p.openEditDialog())
return;
final StatusDialog modifyDialog= createModifyDialog(fComposite.getShell(), p.getCreatedProfile(), fProfileManager, fProfileStore, true);
modifyDialog.open();
}
private void loadButtonPressed() {
final FileDialog dialog= new FileDialog(fComposite.getShell(), SWT.OPEN);
dialog.setText(FormatterMessages.CodingStyleConfigurationBlock_load_profile_dialog_title);
dialog.setFilterExtensions(new String [] {"*.xml"}); //$NON-NLS-1$
final String lastPath= CUIPlugin.getDefault().getDialogSettings().get(fLastSaveLoadPathKey + ".loadpath"); //$NON-NLS-1$
if (lastPath != null) {
dialog.setFilterPath(lastPath);
}
final String path= dialog.open();
if (path == null)
return;
CUIPlugin.getDefault().getDialogSettings().put(fLastSaveLoadPathKey + ".loadpath", dialog.getFilterPath()); //$NON-NLS-1$
final File file= new File(path);
Collection profiles= null;
try {
profiles= fProfileStore.readProfilesFromFile(file);
} catch (CoreException e) {
final String title= FormatterMessages.CodingStyleConfigurationBlock_load_profile_error_title;
final String message= FormatterMessages.CodingStyleConfigurationBlock_load_profile_error_message;
ExceptionHandler.handle(e, fComposite.getShell(), title, message);
}
if (profiles == null || profiles.isEmpty())
return;
final CustomProfile profile= (CustomProfile)profiles.iterator().next();
if (!fProfileVersioner.getProfileKind().equals(profile.getKind())) {
final String title= FormatterMessages.CodingStyleConfigurationBlock_load_profile_error_title;
final String message= Messages.format(FormatterMessages.ProfileConfigurationBlock_load_profile_wrong_profile_message, new String[] {fProfileVersioner.getProfileKind(), profile.getKind()});
MessageDialog.openError(fComposite.getShell(), title, message);
return;
}
if (profile.getVersion() > fProfileVersioner.getCurrentVersion()) {
final String title= FormatterMessages.CodingStyleConfigurationBlock_load_profile_error_too_new_title;
final String message= FormatterMessages.CodingStyleConfigurationBlock_load_profile_error_too_new_message;
MessageDialog.openWarning(fComposite.getShell(), title, message);
}
if (fProfileManager.containsName(profile.getName())) {
final AlreadyExistsDialog aeDialog= new AlreadyExistsDialog(fComposite.getShell(), profile, fProfileManager);
if (aeDialog.open() != Window.OK)
return;
}
fProfileVersioner.update(profile);
fProfileManager.addProfile(profile);
}
}
/**
* The GUI controls
*/
private Composite fComposite;
private Combo fProfileCombo;
private Button fEditButton;
private Button fDeleteButton;
private Button fNewButton;
private Button fLoadButton;
private PixelConverter fPixConv;
/**
* The ProfileManager, the model of this page.
*/
private final ProfileManager fProfileManager;
private final IScopeContext fCurrContext;
private final IScopeContext fInstanceScope;
private final ProfileStore fProfileStore;
private final IProfileVersioner fProfileVersioner;
private final String fLastSaveLoadPathKey;
private IPreferenceChangeListener fPreferenceListener;
private final PreferencesAccess fPreferenceAccess;
private boolean fPreferenceListenerEnabled;
public ProfileConfigurationBlock(IProject project, final PreferencesAccess access, String lastSaveLoadPathKey) {
fPreferenceAccess= access;
fLastSaveLoadPathKey= lastSaveLoadPathKey;
fProfileVersioner= createProfileVersioner();
fProfileStore= createProfileStore(fProfileVersioner);
fInstanceScope= access.getInstanceScope();
if (project != null) {
fCurrContext= access.getProjectScope(project);
} else {
fCurrContext= fInstanceScope;
}
List profiles= null;
try {
profiles= fProfileStore.readProfiles(fInstanceScope);
} catch (CoreException e) {
CUIPlugin.getDefault().log(e);
}
if (profiles == null) {
try {
// bug 129427
profiles= fProfileStore.readProfiles(new DefaultScope());
} catch (CoreException e) {
CUIPlugin.getDefault().log(e);
}
}
if (profiles == null)
profiles= new ArrayList();
fProfileManager= createProfileManager(profiles, fCurrContext, access, fProfileVersioner);
new StoreUpdater();
fPreferenceListenerEnabled= true;
fPreferenceListener= new IPreferenceChangeListener() {
public void preferenceChange(PreferenceChangeEvent event) {
if (fPreferenceListenerEnabled) {
preferenceChanged(event);
}
}
};
access.getInstanceScope().getNode(CUIPlugin.PLUGIN_ID).addPreferenceChangeListener(fPreferenceListener);
}
protected void preferenceChanged(PreferenceChangeEvent event) {
}
protected abstract IProfileVersioner createProfileVersioner();
protected abstract ProfileStore createProfileStore(IProfileVersioner versioner);
protected abstract ProfileManager createProfileManager(List profiles, IScopeContext context, PreferencesAccess access, IProfileVersioner profileVersioner);
protected abstract ModifyDialog createModifyDialog(Shell shell, Profile profile, ProfileManager profileManager, ProfileStore profileStore, boolean newProfile);
protected abstract void configurePreview(Composite composite, int numColumns, ProfileManager profileManager);
private static Button createButton(Composite composite, String text, final int style) {
final Button button= new Button(composite, SWT.PUSH);
button.setFont(composite.getFont());
button.setText(text);
final GridData gd= new GridData(style);
gd.widthHint= SWTUtil.getButtonWidthHint(button);
button.setLayoutData(gd);
return button;
}
/**
* Create the contents
* @param parent Parent composite
* @return Created control
*/
public Composite createContents(Composite parent) {
final int numColumns = 5;
fPixConv = new PixelConverter(parent);
fComposite = createComposite(parent, numColumns);
fProfileCombo= createProfileCombo(fComposite, 3, fPixConv.convertWidthInCharsToPixels(20));
fEditButton= createButton(fComposite, FormatterMessages.CodingStyleConfigurationBlock_edit_button_desc, GridData.HORIZONTAL_ALIGN_BEGINNING);
fDeleteButton= createButton(fComposite, FormatterMessages.CodingStyleConfigurationBlock_remove_button_desc, GridData.HORIZONTAL_ALIGN_BEGINNING);
fNewButton= createButton(fComposite, FormatterMessages.CodingStyleConfigurationBlock_new_button_desc, GridData.HORIZONTAL_ALIGN_BEGINNING);
fLoadButton= createButton(fComposite, FormatterMessages.CodingStyleConfigurationBlock_load_button_desc, GridData.HORIZONTAL_ALIGN_END);
createLabel(fComposite, "", 3); //$NON-NLS-1$
configurePreview(fComposite, numColumns, fProfileManager);
new ButtonController();
new ProfileComboController();
return fComposite;
}
private static Combo createProfileCombo(Composite composite, int span, int widthHint) {
final GridData gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan = span;
gd.widthHint= widthHint;
final Combo combo= new Combo(composite, SWT.DROP_DOWN | SWT.READ_ONLY );
combo.setFont(composite.getFont());
combo.setLayoutData(gd);
return combo;
}
protected static Label createLabel(Composite composite, String text, int numColumns) {
final GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan = numColumns;
gd.widthHint= 0;
final Label label = new Label(composite, SWT.WRAP);
label.setFont(composite.getFont());
label.setText(text);
label.setLayoutData(gd);
return label;
}
private Composite createComposite(Composite parent, int numColumns) {
final Composite composite = new Composite(parent, SWT.NONE);
composite.setFont(parent.getFont());
final GridLayout layout = new GridLayout(numColumns, false);
layout.marginHeight = 0;
layout.marginWidth = 0;
composite.setLayout(layout);
return composite;
}
public final boolean hasProjectSpecificOptions(IProject project) {
if (project != null) {
return fProfileManager.hasProjectSpecificSettings(new ProjectScope(project));
}
return false;
}
public boolean performOk() {
return true;
}
public void performApply() {
try {
fCurrContext.getNode(CUIPlugin.PLUGIN_ID).flush();
fCurrContext.getNode(CCorePlugin.PLUGIN_ID).flush();
if (fCurrContext != fInstanceScope) {
fInstanceScope.getNode(CUIPlugin.PLUGIN_ID).flush();
fInstanceScope.getNode(CCorePlugin.PLUGIN_ID).flush();
}
} catch (BackingStoreException e) {
CUIPlugin.getDefault().log(e);
}
}
public void performDefaults() {
Profile profile= fProfileManager.getDefaultProfile();
if (profile != null) {
int defaultIndex= fProfileManager.getSortedProfiles().indexOf(profile);
if (defaultIndex != -1) {
fProfileManager.setSelected(profile);
}
}
}
public void dispose() {
if (fPreferenceListener != null) {
fPreferenceAccess.getInstanceScope().getNode(CUIPlugin.PLUGIN_ID).removePreferenceChangeListener(fPreferenceListener);
fPreferenceListener= null;
}
}
public void enableProjectSpecificSettings(boolean useProjectSpecificSettings) {
if (useProjectSpecificSettings) {
fProfileManager.commitChanges(fCurrContext);
} else {
fProfileManager.clearAllSettings(fCurrContext);
}
}
}

View file

@ -8,6 +8,7 @@
* Contributors:
* IBM Corporation - initial API and implementation
* Sergey Prigogin, Google
* Anton Leherbauer (Wind River Systems)
*******************************************************************************/
package org.eclipse.cdt.internal.ui.preferences.formatter;
@ -19,32 +20,46 @@ import java.util.List;
import java.util.Map;
import java.util.Observable;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ProjectScope;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.preferences.DefaultScope;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.core.runtime.preferences.IScopeContext;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ProjectScope;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.formatter.DefaultCodeFormatterConstants;
import org.eclipse.cdt.internal.ui.util.Messages;
import org.eclipse.cdt.internal.ui.preferences.formatter.IProfileVersioner;
import org.osgi.service.prefs.BackingStoreException;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.ui.PreferenceConstants;
import org.eclipse.cdt.internal.ui.preferences.PreferencesAccess;
import org.osgi.service.prefs.BackingStoreException;
import org.eclipse.cdt.internal.ui.util.Messages;
/**
* The model for the set of profiles which are available in the workbench.
*/
public class ProfileManager extends Observable {
public abstract class ProfileManager extends Observable {
public static final class KeySet {
private final List fKeys;
private final String fNodeName;
public KeySet(String nodeName, List keys) {
fNodeName= nodeName;
fKeys= keys;
}
public String getNodeName() {
return fNodeName;
}
public List getKeys() {
return fKeys;
}
}
/**
* A prefix which is prepended to every ID of a user-defined profile, in order
@ -64,9 +79,7 @@ public class ProfileManager extends Observable {
public abstract Map getSettings();
public abstract void setSettings(Map settings);
public int getVersion() {
return ProfileVersioner.CURRENT_VERSION;
}
public abstract int getVersion();
public boolean hasEqualSettings(Map otherMap, List allKeys) {
Map settings= getSettings();
@ -107,12 +120,16 @@ public class ProfileManager extends Observable {
private final String fID;
private final Map fSettings;
private final int fOrder;
private final int fCurrentVersion;
private final String fProfileKind;
protected BuiltInProfile(String ID, String name, Map settings, int order) {
protected BuiltInProfile(String ID, String name, Map settings, int order, int currentVersion, String profileKind) {
fName= name;
fID= ID;
fSettings= settings;
fOrder= order;
fCurrentVersion= currentVersion;
fProfileKind= profileKind;
}
public String getName() {
@ -121,7 +138,7 @@ public class ProfileManager extends Observable {
public Profile rename(String name, ProfileManager manager) {
final String trimmed= name.trim();
CustomProfile newProfile= new CustomProfile(trimmed, fSettings, ProfileVersioner.CURRENT_VERSION);
CustomProfile newProfile= new CustomProfile(trimmed, fSettings, fCurrentVersion, fProfileKind);
manager.addProfile(newProfile);
return newProfile;
}
@ -151,6 +168,10 @@ public class ProfileManager extends Observable {
public boolean isBuiltInProfile() {
return true;
}
public int getVersion() {
return fCurrentVersion;
}
}
@ -162,11 +183,13 @@ public class ProfileManager extends Observable {
private Map fSettings;
protected ProfileManager fManager;
private int fVersion;
private final String fKind;
public CustomProfile(String name, Map settings, int version) {
public CustomProfile(String name, Map settings, int version, String kind) {
fName= name;
fSettings= settings;
fVersion= version;
fKind= kind;
}
public String getName() {
@ -232,16 +255,20 @@ public class ProfileManager extends Observable {
return true;
}
public String getKind() {
return fKind;
}
}
public final static class SharedProfile extends CustomProfile {
public SharedProfile(String oldName, Map options) {
super(oldName, options, ProfileVersioner.CURRENT_VERSION);
public SharedProfile(String oldName, Map options, int version, String profileKind) {
super(oldName, options, version, profileKind);
}
public Profile rename(String name, ProfileManager manager) {
CustomProfile profile= new CustomProfile(name.trim(), getSettings(), getVersion());
CustomProfile profile= new CustomProfile(name.trim(), getSettings(), getVersion(), getKind());
manager.profileReplaced(this, profile);
return profile;
@ -273,25 +300,20 @@ public class ProfileManager extends Observable {
public final static int PROFILE_RENAMED_EVENT= 3;
public final static int PROFILE_CREATED_EVENT= 4;
public final static int SETTINGS_CHANGED_EVENT= 5;
/**
* The key of the preference where the selected profile is stored.
*/
private final static String PROFILE_KEY= PreferenceConstants.FORMATTER_PROFILE;
private final String fProfileKey;
/**
* The key of the preference where the version of the current settings is stored
*/
private final static String FORMATTER_SETTINGS_VERSION= "formatter_settings_version"; //$NON-NLS-1$
private final String fProfileVersionKey;
/**
* The keys of the built-in profiles
*/
public final static String ECLIPSE_PROFILE= "org.eclipse.cdt.ui.default.eclipse_profile"; //$NON-NLS-1$
public final static String SHARED_PROFILE= "org.eclipse.cdt.ui.default.shared"; //$NON-NLS-1$
public final static String DEFAULT_PROFILE= ECLIPSE_PROFILE;
/**
* A map containing the available profiles, using the IDs as keys.
*/
@ -302,7 +324,6 @@ public class ProfileManager extends Observable {
*/
private final List fProfilesByName;
/**
* The currently selected profile.
*/
@ -311,72 +332,76 @@ public class ProfileManager extends Observable {
/**
* The keys of the options to be saved with each profile
*/
private final static List fUIKeys= Collections.EMPTY_LIST;
private final static List fCoreKeys= new ArrayList(DefaultCodeFormatterConstants.getEclipseDefaultSettings().keySet());
private final KeySet[] fKeySets;
/**
* All keys appearing in a profile, sorted alphabetically
*/
private final static List fKeys;
private final PreferencesAccess fPreferencesAccess;
private final IProfileVersioner fProfileVersioner;
static {
fKeys= new ArrayList();
fKeys.addAll(fUIKeys);
fKeys.addAll(fCoreKeys);
Collections.sort(fKeys);
}
/**
* Create and initialize a new profile manager.
* @param profiles Initial custom profiles (List of type <code>CustomProfile</code>)
* @param profileVersioner
*/
public ProfileManager(List profiles, IScopeContext context, PreferencesAccess preferencesAccess) {
public ProfileManager(
List profiles,
IScopeContext context,
PreferencesAccess preferencesAccess,
IProfileVersioner profileVersioner,
KeySet[] keySets,
String profileKey,
String profileVersionKey) {
fPreferencesAccess= preferencesAccess;
fProfileVersioner= profileVersioner;
fKeySets= keySets;
fProfileKey= profileKey;
fProfileVersionKey= profileVersionKey;
fProfiles= new HashMap();
fProfilesByName= new ArrayList();
addBuiltinProfiles(fProfiles, fProfilesByName);
for (final Iterator iter = profiles.iterator(); iter.hasNext();) {
final CustomProfile profile= (CustomProfile) iter.next();
profile.setManager(this);
final Profile profile= (Profile) iter.next();
if (profile instanceof CustomProfile) {
((CustomProfile)profile).setManager(this);
}
fProfiles.put(profile.getID(), profile);
fProfilesByName.add(profile);
}
Collections.sort(fProfilesByName);
IScopeContext instanceScope= fPreferencesAccess.getInstanceScope();
String profileId= instanceScope.getNode(CUIPlugin.PLUGIN_ID).get(PROFILE_KEY, null);
if (profileId == null) {
profileId= new DefaultScope().getNode(CUIPlugin.PLUGIN_ID).get(PROFILE_KEY, null);
}
String profileId= getSelectedProfileId(fPreferencesAccess.getInstanceScope());
Profile profile= (Profile) fProfiles.get(profileId);
if (profile == null) {
profile= (Profile) fProfiles.get(DEFAULT_PROFILE);
profile= getDefaultProfile();
}
fSelected= profile;
if (context.getName() == ProjectScope.SCOPE && hasProjectSpecificSettings(context)) {
Map map= readFromPreferenceStore(context, profile);
if (map != null) {
List allKeys= new ArrayList();
for (int i= 0; i < fKeySets.length; i++) {
allKeys.addAll(fKeySets[i].getKeys());
}
Collections.sort(allKeys);
Profile matching= null;
String projProfileId= context.getNode(CUIPlugin.PLUGIN_ID).get(PROFILE_KEY, null);
String projProfileId= context.getNode(CUIPlugin.PLUGIN_ID).get(fProfileKey, null);
if (projProfileId != null) {
Profile curr= (Profile) fProfiles.get(projProfileId);
if (curr != null && (curr.isBuiltInProfile() || curr.hasEqualSettings(map, getKeys()))) {
if (curr != null && (curr.isBuiltInProfile() || curr.hasEqualSettings(map, allKeys))) {
matching= curr;
}
} else {
// old version: look for similar
for (final Iterator iter = fProfilesByName.iterator(); iter.hasNext();) {
Profile curr= (Profile) iter.next();
if (curr.hasEqualSettings(map, getKeys())) {
if (curr.hasEqualSettings(map, allKeys)) {
matching= curr;
break;
}
@ -390,7 +415,7 @@ public class ProfileManager extends Observable {
name= FormatterMessages.ProfileManager_unmanaged_profile;
}
// current settings do not correspond to any profile -> create a 'team' profile
SharedProfile shared= new SharedProfile(name, map);
SharedProfile shared= new SharedProfile(name, map, fProfileVersioner.getCurrentVersion(), fProfileVersioner.getProfileKind());
shared.setManager(this);
fProfiles.put(shared.getID(), shared);
fProfilesByName.add(shared); // add last
@ -401,9 +426,14 @@ public class ProfileManager extends Observable {
}
}
protected String getSelectedProfileId(IScopeContext instanceScope) {
String profileId= instanceScope.getNode(CUIPlugin.PLUGIN_ID).get(fProfileKey, null);
if (profileId == null) {
// request from bug 129427
profileId= new DefaultScope().getNode(CUIPlugin.PLUGIN_ID).get(fProfileKey, null);
}
return profileId;
}
/**
* Notify observers with a message. The message must be one of the following:
@ -420,28 +450,25 @@ public class ProfileManager extends Observable {
notifyObservers(new Integer(message));
}
public static boolean hasProjectSpecificSettings(IScopeContext context) {
IEclipsePreferences corePrefs= context.getNode(CCorePlugin.PLUGIN_ID);
for (final Iterator keyIter = fCoreKeys.iterator(); keyIter.hasNext(); ) {
final String key= (String) keyIter.next();
Object val= corePrefs.get(key, null);
if (val != null) {
return true;
}
}
IEclipsePreferences uiPrefs= context.getNode(CUIPlugin.PLUGIN_ID);
for (final Iterator keyIter = fUIKeys.iterator(); keyIter.hasNext(); ) {
final String key= (String) keyIter.next();
Object val= uiPrefs.get(key, null);
if (val != null) {
return true;
}
}
public static boolean hasProjectSpecificSettings(IScopeContext context, KeySet[] keySets) {
for (int i= 0; i < keySets.length; i++) {
KeySet keySet= keySets[i];
IEclipsePreferences preferences= context.getNode(keySet.getNodeName());
for (final Iterator keyIter= keySet.getKeys().iterator(); keyIter.hasNext();) {
final String key= (String)keyIter.next();
Object val= preferences.get(key, null);
if (val != null) {
return true;
}
}
}
return false;
}
public boolean hasProjectSpecificSettings(IScopeContext context) {
return hasProjectSpecificSettings(context, fKeySets);
}
/**
* Only to read project specific settings to find out to what profile it matches.
* @param context The project context
@ -449,38 +476,33 @@ public class ProfileManager extends Observable {
public Map readFromPreferenceStore(IScopeContext context, Profile workspaceProfile) {
final Map profileOptions= new HashMap();
IEclipsePreferences uiPrefs= context.getNode(CUIPlugin.PLUGIN_ID);
IEclipsePreferences corePrefs= context.getNode(CCorePlugin.PLUGIN_ID);
int version= uiPrefs.getInt(FORMATTER_SETTINGS_VERSION, ProfileVersioner.VERSION_1);
if (version != ProfileVersioner.CURRENT_VERSION) {
int version= uiPrefs.getInt(fProfileVersionKey, fProfileVersioner.getFirstVersion());
if (version != fProfileVersioner.getCurrentVersion()) {
Map allOptions= new HashMap();
addAll(uiPrefs, allOptions);
addAll(corePrefs, allOptions);
return ProfileVersioner.updateAndComplete(allOptions, version);
for (int i= 0; i < fKeySets.length; i++) {
addAll(context.getNode(fKeySets[i].getNodeName()), allOptions);
}
CustomProfile profile= new CustomProfile("tmp", allOptions, version, fProfileVersioner.getProfileKind()); //$NON-NLS-1$
fProfileVersioner.update(profile);
return profile.getSettings();
}
boolean hasValues= false;
for (final Iterator keyIter = fCoreKeys.iterator(); keyIter.hasNext(); ) {
final String key= (String) keyIter.next();
Object val= corePrefs.get(key, null);
if (val != null) {
hasValues= true;
} else {
val= workspaceProfile.getSettings().get(key);
for (int i= 0; i < fKeySets.length; i++) {
KeySet keySet= fKeySets[i];
IEclipsePreferences preferences= context.getNode(keySet.getNodeName());
for (final Iterator keyIter = keySet.getKeys().iterator(); keyIter.hasNext(); ) {
final String key= (String) keyIter.next();
Object val= preferences.get(key, null);
if (val != null) {
hasValues= true;
} else {
val= workspaceProfile.getSettings().get(key);
}
profileOptions.put(key, val);
}
profileOptions.put(key, val);
}
for (final Iterator keyIter = fUIKeys.iterator(); keyIter.hasNext(); ) {
final String key= (String) keyIter.next();
Object val= uiPrefs.get(key, null);
if (val != null) {
hasValues= true;
} else {
val= workspaceProfile.getSettings().get(key);
}
profileOptions.put(key, val);
}
}
if (!hasValues) {
return null;
@ -536,55 +558,22 @@ public class ProfileManager extends Observable {
private void writeToPreferenceStore(Profile profile, IScopeContext context) {
final Map profileOptions= profile.getSettings();
final IEclipsePreferences corePrefs= context.getNode(CCorePlugin.PLUGIN_ID);
updatePreferences(corePrefs, fCoreKeys, profileOptions);
for (int i= 0; i < fKeySets.length; i++) {
updatePreferences(context.getNode(fKeySets[i].getNodeName()), fKeySets[i].getKeys(), profileOptions);
}
final IEclipsePreferences uiPrefs= context.getNode(CUIPlugin.PLUGIN_ID);
updatePreferences(uiPrefs, fUIKeys, profileOptions);
if (uiPrefs.getInt(FORMATTER_SETTINGS_VERSION, 0) != ProfileVersioner.CURRENT_VERSION) {
uiPrefs.putInt(FORMATTER_SETTINGS_VERSION, ProfileVersioner.CURRENT_VERSION);
if (uiPrefs.getInt(fProfileVersionKey, 0) != fProfileVersioner.getCurrentVersion()) {
uiPrefs.putInt(fProfileVersionKey, fProfileVersioner.getCurrentVersion());
}
if (context.getName() == InstanceScope.SCOPE) {
uiPrefs.put(PROFILE_KEY, profile.getID());
uiPrefs.put(fProfileKey, profile.getID());
} else if (context.getName() == ProjectScope.SCOPE && !profile.isSharedProfile()) {
uiPrefs.put(PROFILE_KEY, profile.getID());
uiPrefs.put(fProfileKey, profile.getID());
}
}
/**
* Add all the built-in profiles to the map and to the list.
* @param profiles The map to add the profiles to
* @param profilesByName List of profiles by
*/
private void addBuiltinProfiles(Map profiles, List profilesByName) {
final Profile eclipseProfile= new BuiltInProfile(ECLIPSE_PROFILE, FormatterMessages.ProfileManager_default_profile_name, getEclipseSettings(), 2);
profiles.put(eclipseProfile.getID(), eclipseProfile);
profilesByName.add(eclipseProfile);
}
/**
* @return Returns the settings for the new eclipse profile.
*/
public static Map getEclipseSettings() {
return DefaultCodeFormatterConstants.getEclipseDefaultSettings();
}
/**
* @return Returns the default settings.
*/
public static Map getDefaultSettings() {
return getEclipseSettings();
}
/**
* @return All keys appearing in a profile, sorted alphabetically.
*/
public static List getKeys() {
return fKeys;
}
/**
* Get an immutable list as view on all profiles, sorted alphabetically. Unless the set
* of profiles has been modified between the two calls, the sequence is guaranteed to
@ -634,13 +623,12 @@ public class ProfileManager extends Observable {
}
public void clearAllSettings(IScopeContext context) {
final IEclipsePreferences corePrefs= context.getNode(CCorePlugin.PLUGIN_ID);
updatePreferences(corePrefs, fCoreKeys, Collections.EMPTY_MAP);
for (int i= 0; i < fKeySets.length; i++) {
updatePreferences(context.getNode(fKeySets[i].getNodeName()), fKeySets[i].getKeys(), Collections.EMPTY_MAP);
}
final IEclipsePreferences uiPrefs= context.getNode(CUIPlugin.PLUGIN_ID);
updatePreferences(uiPrefs, fUIKeys, Collections.EMPTY_MAP);
uiPrefs.remove(PROFILE_KEY);
uiPrefs.remove(fProfileKey);
}
/**
@ -707,26 +695,28 @@ public class ProfileManager extends Observable {
if (!(fSelected instanceof CustomProfile))
return false;
Profile removedProfile= fSelected;
return deleteProfile((CustomProfile)fSelected);
}
public boolean deleteProfile(CustomProfile profile) {
int index= fProfilesByName.indexOf(profile);
int index= fProfilesByName.indexOf(removedProfile);
fProfiles.remove(profile.getID());
fProfilesByName.remove(profile);
fProfiles.remove(removedProfile.getID());
fProfilesByName.remove(removedProfile);
((CustomProfile)removedProfile).setManager(null);
profile.setManager(null);
if (index >= fProfilesByName.size())
index--;
fSelected= (Profile) fProfilesByName.get(index);
if (!removedProfile.isSharedProfile()) {
updateProfilesWithName(removedProfile.getID(), null, false);
if (!profile.isSharedProfile()) {
updateProfilesWithName(profile.getID(), null, false);
}
notifyObservers(PROFILE_DELETED_EVENT);
return true;
}
}
public void profileRenamed(CustomProfile profile, String oldID) {
fProfiles.remove(oldID);
@ -770,15 +760,15 @@ public class ProfileManager extends Observable {
for (int i= 0; i < projects.length; i++) {
IScopeContext projectScope= fPreferencesAccess.getProjectScope(projects[i]);
IEclipsePreferences node= projectScope.getNode(CUIPlugin.PLUGIN_ID);
String profileId= node.get(PROFILE_KEY, null);
String profileId= node.get(fProfileKey, null);
if (oldName.equals(profileId)) {
if (newProfile == null) {
node.remove(PROFILE_KEY);
node.remove(fProfileKey);
} else {
if (applySettings) {
writeToPreferenceStore(newProfile, projectScope);
} else {
node.put(PROFILE_KEY, newProfile.getID());
node.put(fProfileKey, newProfile.getID());
}
}
}
@ -786,8 +776,14 @@ public class ProfileManager extends Observable {
IScopeContext instanceScope= fPreferencesAccess.getInstanceScope();
final IEclipsePreferences uiPrefs= instanceScope.getNode(CUIPlugin.PLUGIN_ID);
if (newProfile != null && oldName.equals(uiPrefs.get(PROFILE_KEY, null))) {
if (newProfile != null && oldName.equals(uiPrefs.get(fProfileKey, null))) {
writeToPreferenceStore(newProfile, instanceScope);
}
}
public abstract Profile getDefaultProfile();
public IProfileVersioner getProfileVersioner() {
return fProfileVersioner;
}
}

View file

@ -17,14 +17,12 @@ import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
@ -46,20 +44,7 @@ import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.core.runtime.preferences.IScopeContext;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.internal.ui.CUIException;
import org.eclipse.cdt.internal.ui.CUIStatus;
import org.eclipse.cdt.internal.ui.preferences.PreferencesAccess;
import org.eclipse.cdt.internal.ui.preferences.formatter.ProfileManager.CustomProfile;
import org.eclipse.cdt.internal.ui.preferences.formatter.ProfileManager.Profile;
import org.osgi.service.prefs.BackingStoreException;
import org.eclipse.cdt.internal.ui.preferences.formatter.ProfileManager;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.Attributes;
@ -67,9 +52,21 @@ import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.internal.ui.CUIException;
import org.eclipse.cdt.internal.ui.CUIStatus;
import org.eclipse.cdt.internal.ui.preferences.formatter.ProfileManager.CustomProfile;
import org.eclipse.cdt.internal.ui.preferences.formatter.ProfileManager.Profile;
public class ProfileStore {
/** The default encoding to use */
public static final String ENCODING= "UTF-8"; //$NON-NLS-1$
protected static final String VERSION_KEY_SUFFIX= ".version"; //$NON-NLS-1$
/**
* A SAX event handler to parse the xml format for profiles.
@ -81,7 +78,7 @@ public class ProfileStore {
private String fName;
private Map fSettings;
private String fKind;
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
@ -94,6 +91,10 @@ public class ProfileStore {
} else if (qName.equals(XML_NODE_PROFILE)) {
fName= attributes.getValue(XML_ATTRIBUTE_NAME);
fKind= attributes.getValue(XML_ATTRIBUTE_PROFILE_KIND);
if (fKind == null) //Can only be an CodeFormatterProfile created pre 20061106
fKind= ProfileVersioner.CODE_FORMATTER_PROFILE_KIND;
fSettings= new HashMap(200);
}
@ -111,9 +112,10 @@ public class ProfileStore {
public void endElement(String uri, String localName, String qName) {
if (qName.equals(XML_NODE_PROFILE)) {
fProfiles.add(new CustomProfile(fName, fSettings, fVersion));
fProfiles.add(new CustomProfile(fName, fSettings, fVersion, fKind));
fName= null;
fSettings= null;
fKind= null;
}
}
@ -123,17 +125,6 @@ public class ProfileStore {
}
/**
* Preference key where all profiles are stored
*/
private static final String PREF_FORMATTER_PROFILES= "org.eclipse.cdt.ui.formatterprofiles"; //$NON-NLS-1$
/**
* Preference key where all profiles are stored
*/
private static final String PREF_FORMATTER_PROFILES_VERSION= "org.eclipse.cdt.ui.formatterprofiles.version"; //$NON-NLS-1$
/**
* Identifiers for the XML file.
*/
@ -144,58 +135,62 @@ public class ProfileStore {
private final static String XML_ATTRIBUTE_VERSION= "version"; //$NON-NLS-1$
private final static String XML_ATTRIBUTE_ID= "id"; //$NON-NLS-1$
private final static String XML_ATTRIBUTE_NAME= "name"; //$NON-NLS-1$
private final static String XML_ATTRIBUTE_PROFILE_KIND= "kind"; //$NON-NLS-1$
private final static String XML_ATTRIBUTE_VALUE= "value"; //$NON-NLS-1$
private final IProfileVersioner fProfileVersioner;
private final String fProfilesKey;
private final String fProfilesVersionKey;
private ProfileStore() {
public ProfileStore(String profilesKey, IProfileVersioner profileVersioner) {
fProfilesKey= profilesKey;
fProfileVersioner= profileVersioner;
fProfilesVersionKey= profilesKey + VERSION_KEY_SUFFIX;
}
/**
* @return Returns the collection of profiles currently stored in the preference store or
* <code>null</code> if the loading failed. The elements are of type {@link CustomProfile}
* <code>null</code> if the loading failed. The elements are of type {@link ProfileManager.CustomProfile}
* and are all updated to the latest version.
* @throws CoreException
*/
public static List readProfiles(IScopeContext scope) throws CoreException {
List res= readProfilesFromPreferences(scope);
if (res == null) {
return readOldForCompatibility(scope);
}
return res;
public List readProfiles(IScopeContext scope) throws CoreException {
return readProfilesFromString(scope.getNode(CUIPlugin.PLUGIN_ID).get(fProfilesKey, null));
}
public static void writeProfiles(Collection profiles, IScopeContext instanceScope) throws CoreException {
public void writeProfiles(Collection profiles, IScopeContext instanceScope) throws CoreException {
ByteArrayOutputStream stream= new ByteArrayOutputStream(2000);
try {
writeProfilesToStream(profiles, stream);
writeProfilesToStream(profiles, stream, ENCODING, fProfileVersioner);
String val;
try {
val= stream.toString("UTF-8"); //$NON-NLS-1$
val= stream.toString(ENCODING);
} catch (UnsupportedEncodingException e) {
val= stream.toString();
}
IEclipsePreferences uiPreferences = instanceScope.getNode(CUIPlugin.PLUGIN_ID);
uiPreferences.put(PREF_FORMATTER_PROFILES, val);
uiPreferences.putInt(PREF_FORMATTER_PROFILES_VERSION, ProfileVersioner.CURRENT_VERSION);
uiPreferences.put(fProfilesKey, val);
uiPreferences.putInt(fProfilesVersionKey, fProfileVersioner.getCurrentVersion());
} finally {
try { stream.close(); } catch (IOException e) { /* ignore */ }
}
}
public static List readProfilesFromPreferences(IScopeContext scope) throws CoreException {
String string= scope.getNode(CUIPlugin.PLUGIN_ID).get(PREF_FORMATTER_PROFILES, null);
if (string != null && string.length() > 0) {
public List readProfilesFromString(String profiles) throws CoreException {
if (profiles != null && profiles.length() > 0) {
byte[] bytes;
try {
bytes= string.getBytes("UTF-8"); //$NON-NLS-1$
bytes= profiles.getBytes(ENCODING);
} catch (UnsupportedEncodingException e) {
bytes= string.getBytes();
bytes= profiles.getBytes();
}
InputStream is= new ByteArrayInputStream(bytes);
try {
List res= readProfilesFromStream(new InputSource(is));
if (res != null) {
for (int i= 0; i < res.size(); i++) {
ProfileVersioner.updateAndComplete((CustomProfile) res.get(i));
fProfileVersioner.update((CustomProfile) res.get(i));
}
}
return res;
@ -206,45 +201,6 @@ public class ProfileStore {
return null;
}
/**
* Read the available profiles from the internal XML file and return them
* as collection.
* @return returns a list of <code>CustomProfile</code> or <code>null</code>
*/
private static List readOldForCompatibility(IScopeContext instanceScope) {
// in 3.0 M9 and less the profiles were stored in a file in the plugin's meta data
final String STORE_FILE= "code_formatter_profiles.xml"; //$NON-NLS-1$
File file= CUIPlugin.getDefault().getStateLocation().append(STORE_FILE).toFile();
if (!file.exists())
return null;
try {
// note that it's wrong to use a file reader when XML declares UTF-8: Kept for compatibility
final FileReader reader= new FileReader(file);
try {
List res= readProfilesFromStream(new InputSource(reader));
if (res != null) {
for (int i= 0; i < res.size(); i++) {
ProfileVersioner.updateAndComplete((CustomProfile) res.get(i));
}
writeProfiles(res, instanceScope);
}
file.delete(); // remove after successful write
return res;
} finally {
reader.close();
}
} catch (CoreException e) {
CUIPlugin.getDefault().log(e); // log but ignore
} catch (IOException e) {
CUIPlugin.getDefault().log(e); // log but ignore
}
return null;
}
/**
* Read the available profiles from the internal XML file and return them
* as collection or <code>null</code> if the file is not a profile file.
@ -252,7 +208,7 @@ public class ProfileStore {
* @return returns a list of <code>CustomProfile</code> or <code>null</code>
* @throws CoreException
*/
public static List readProfilesFromFile(File file) throws CoreException {
public List readProfilesFromFile(File file) throws CoreException {
try {
final FileInputStream reader= new FileInputStream(file);
try {
@ -271,7 +227,7 @@ public class ProfileStore {
* @return returns a list of <code>CustomProfile</code> or <code>null</code>
* @throws CoreException
*/
private static List readProfilesFromStream(InputSource inputSource) throws CoreException {
protected static List readProfilesFromStream(InputSource inputSource) throws CoreException {
final ProfileDefaultHandler handler= new ProfileDefaultHandler();
try {
@ -292,16 +248,17 @@ public class ProfileStore {
* Write the available profiles to the internal XML file.
* @param profiles List of <code>CustomProfile</code>
* @param file File to write
* @param encoding the encoding to use
* @throws CoreException
*/
public static void writeProfilesToFile(Collection profiles, File file) throws CoreException {
final OutputStream writer;
public void writeProfilesToFile(Collection profiles, File file, String encoding) throws CoreException {
final OutputStream stream;
try {
writer= new FileOutputStream(file);
stream= new FileOutputStream(file);
try {
writeProfilesToStream(profiles, writer);
writeProfilesToStream(profiles, stream, encoding, fProfileVersioner);
} finally {
try { writer.close(); } catch (IOException e) { /* ignore */ }
try { stream.close(); } catch (IOException e) { /* ignore */ }
}
} catch (IOException e) {
throw createException(e, FormatterMessages.CodingStyleConfigurationBlock_error_serializing_xml_message);
@ -312,9 +269,11 @@ public class ProfileStore {
* Save profiles to an XML stream
* @param profiles List of <code>CustomProfile</code>
* @param stream Stream to write
* @param encoding the encoding to use
* @throws CoreException
*/
private static void writeProfilesToStream(Collection profiles, OutputStream stream) throws CoreException {
private static void writeProfilesToStream(Collection profiles, OutputStream stream, String encoding, IProfileVersioner profileVersioner) throws CoreException {
try {
final DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
@ -322,21 +281,21 @@ public class ProfileStore {
final Document document= builder.newDocument();
final Element rootElement = document.createElement(XML_NODE_ROOT);
rootElement.setAttribute(XML_ATTRIBUTE_VERSION, Integer.toString(ProfileVersioner.CURRENT_VERSION));
rootElement.setAttribute(XML_ATTRIBUTE_VERSION, Integer.toString(profileVersioner.getCurrentVersion()));
document.appendChild(rootElement);
for(final Iterator iter= profiles.iterator(); iter.hasNext();) {
final Profile profile= (Profile)iter.next();
if (profile.isProfileToSave()) {
final Element profileElement= createProfileElement(profile, document);
final Element profileElement= createProfileElement(profile, document, profileVersioner);
rootElement.appendChild(profileElement);
}
}
Transformer transformer=TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //$NON-NLS-1$
transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
transformer.transform(new DOMSource(document), new StreamResult(stream));
} catch (TransformerException e) {
@ -351,12 +310,13 @@ public class ProfileStore {
* Create a new profile element in the specified document. The profile is not added
* to the document by this method.
*/
private static Element createProfileElement(Profile profile, Document document) {
private static Element createProfileElement(Profile profile, Document document, IProfileVersioner profileVersioner) {
final Element element= document.createElement(XML_NODE_PROFILE);
element.setAttribute(XML_ATTRIBUTE_NAME, profile.getName());
element.setAttribute(XML_ATTRIBUTE_VERSION, Integer.toString(profile.getVersion()));
element.setAttribute(XML_ATTRIBUTE_PROFILE_KIND, profileVersioner.getProfileKind());
final Iterator keyIter= ProfileManager.getKeys().iterator();
final Iterator keyIter= profile.getSettings().keySet().iterator();
while (keyIter.hasNext()) {
final String key= (String)keyIter.next();
@ -373,51 +333,6 @@ public class ProfileStore {
return element;
}
public static void checkCurrentOptionsVersion() {
PreferencesAccess access= PreferencesAccess.getOriginalPreferences();
IScopeContext instanceScope= access.getInstanceScope();
IEclipsePreferences uiPreferences= instanceScope.getNode(CUIPlugin.PLUGIN_ID);
int version= uiPreferences.getInt(PREF_FORMATTER_PROFILES_VERSION, 0);
if (version >= ProfileVersioner.CURRENT_VERSION) {
return; // is up to date
}
try {
List profiles= ProfileStore.readProfiles(instanceScope);
if (profiles == null) {
profiles= Collections.EMPTY_LIST;
}
ProfileManager manager= new ProfileManager(profiles, instanceScope, access);
if (manager.getSelected() instanceof CustomProfile) {
manager.commitChanges(instanceScope); // updates CCorePlugin options
}
uiPreferences.putInt(PREF_FORMATTER_PROFILES_VERSION, ProfileVersioner.CURRENT_VERSION);
savePreferences(instanceScope);
IProject[] projects= ResourcesPlugin.getWorkspace().getRoot().getProjects();
for (int i= 0; i < projects.length; i++) {
IScopeContext scope= access.getProjectScope(projects[i]);
if (ProfileManager.hasProjectSpecificSettings(scope)) {
manager= new ProfileManager(profiles, scope, access);
manager.commitChanges(scope); // updates CCorePlugin project options
savePreferences(scope);
}
}
} catch (CoreException e) {
CUIPlugin.getDefault().log(e);
} catch (BackingStoreException e) {
CUIPlugin.getDefault().log(e);
}
}
private static void savePreferences(final IScopeContext context) throws BackingStoreException {
try {
context.getNode(CUIPlugin.PLUGIN_ID).flush();
} finally {
context.getNode(CCorePlugin.PLUGIN_ID).flush();
}
}
/*
* Creates a UI exception for logging purposes
*/

View file

@ -18,12 +18,37 @@ import java.util.Map;
import org.eclipse.cdt.internal.ui.preferences.formatter.ProfileManager.CustomProfile;
public class ProfileVersioner {
public class ProfileVersioner implements IProfileVersioner {
public static final int VERSION_1= 1; // < 20040113 (includes M6)
public static final String CODE_FORMATTER_PROFILE_KIND= "CodeFormatterProfile"; //$NON-NLS-1$
public static final int VERSION_1= 1; // < 20061106 (pre CDT 4.0M3)
public static final int CURRENT_VERSION= VERSION_1;
public int getFirstVersion() {
return VERSION_1;
}
public int getCurrentVersion() {
return CURRENT_VERSION;
}
/**
* {@inheritDoc}
*/
public String getProfileKind() {
return CODE_FORMATTER_PROFILE_KIND;
}
public void update(CustomProfile profile) {
final Map oldSettings= profile.getSettings();
Map newSettings= updateAndComplete(oldSettings, profile.getVersion());
profile.setVersion(CURRENT_VERSION);
profile.setSettings(newSettings);
}
public static int getVersionStatus(CustomProfile profile) {
final int version= profile.getVersion();
if (version < CURRENT_VERSION)
@ -42,7 +67,7 @@ public class ProfileVersioner {
}
public static Map updateAndComplete(Map oldSettings, int version) {
final Map newSettings= ProfileManager.getDefaultSettings();
final Map newSettings= FormatterProfileManager.getDefaultSettings();
switch (version) {

View file

@ -1,142 +0,0 @@
/*******************************************************************************
* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Aaron Luchko, aluchko@redhat.com - 105926 [Formatter] Exporting Unnamed profile fails silently
* Sergey Prigogin, Google
*******************************************************************************/
package org.eclipse.cdt.internal.ui.preferences.formatter;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
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.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.StatusDialog;
import org.eclipse.cdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.cdt.internal.ui.preferences.formatter.ProfileManager.Profile;
import org.eclipse.cdt.internal.ui.preferences.formatter.ProfileManager.SharedProfile;
/**
* The dialog to rename a new profile.
*/
public class RenameProfileDialog extends StatusDialog {
private Label fNameLabel;
private Text fNameText;
private final StatusInfo fOk;
private final StatusInfo fEmpty;
private final StatusInfo fDuplicate;
private final StatusInfo fNoMessage;
private final Profile fProfile;
private final ProfileManager fManager;
private Profile fRenamedProfile;
public RenameProfileDialog(Shell parentShell, Profile profile, ProfileManager manager) {
super(parentShell);
fManager= manager;
setTitle(FormatterMessages.RenameProfileDialog_dialog_title);
fProfile= profile;
fOk= new StatusInfo();
fDuplicate= new StatusInfo(IStatus.ERROR, FormatterMessages.RenameProfileDialog_status_message_profile_with_this_name_already_exists);
fEmpty= new StatusInfo(IStatus.ERROR, FormatterMessages.RenameProfileDialog_status_message_profile_name_empty);
fNoMessage= new StatusInfo(IStatus.ERROR, new String());
}
public Control createDialogArea(Composite parent) {
final int numColumns= 2;
GridLayout layout= new GridLayout();
layout.marginHeight= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
layout.marginWidth= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
layout.verticalSpacing= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
layout.horizontalSpacing= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
layout.numColumns= numColumns;
final Composite composite= new Composite(parent, SWT.NULL);
composite.setLayout(layout);
// Create "Please enter a new name:" label
GridData gd = new GridData();
gd.horizontalSpan = numColumns;
gd.widthHint= convertWidthInCharsToPixels(60);
fNameLabel = new Label(composite, SWT.NONE);
fNameLabel.setText(FormatterMessages.RenameProfileDialog_dialog_label_enter_a_new_name);
fNameLabel.setLayoutData(gd);
// Create text field to enter name
gd = new GridData( GridData.FILL_HORIZONTAL);
gd.horizontalSpan= numColumns;
fNameText= new Text(composite, SWT.SINGLE | SWT.BORDER);
if (fProfile instanceof SharedProfile) {
fNameText.setText(fProfile.getName());
}
fNameText.setSelection(0, fProfile.getName().length());
fNameText.setLayoutData(gd);
fNameText.addModifyListener( new ModifyListener() {
public void modifyText(ModifyEvent e) {
doValidation();
}
});
fNameText.setText(fProfile.getName());
fNameText.selectAll();
applyDialogFont(composite);
return composite;
}
/**
* Validate the current settings.
*/
protected void doValidation() {
final String name= fNameText.getText().trim();
if (name.length() == 0) {
updateStatus(fEmpty);
return;
}
if (name.equals(fProfile.getName())) {
updateStatus(fNoMessage);
return;
}
if (fManager.containsName(name)) {
updateStatus(fDuplicate);
return;
}
updateStatus(fOk);
}
public Profile getRenamedProfile() {
return fRenamedProfile;
}
protected void okPressed() {
if (!getStatus().isOK())
return;
fRenamedProfile= fProfile.rename(fNameText.getText(), fManager);
super.okPressed();
}
}

View file

@ -1,5 +1,5 @@
/*******************************************************************************
* Copyright (c) 2000, 2005 IBM Corporation and others.
* Copyright (c) 2000, 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
@ -8,32 +8,34 @@
* Contributors:
* IBM Corporation - initial API and implementation
* Sergey Prigogin, Google
* Anton Leherbauer (Wind River Systems)
*******************************************************************************/
package org.eclipse.cdt.internal.ui.preferences.formatter;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.formatter.FormattingContextProperties;
import org.eclipse.jface.text.formatter.IContentFormatter;
import org.eclipse.jface.text.formatter.IContentFormatterExtension;
import org.eclipse.jface.text.formatter.IFormattingContext;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.cdt.core.CCorePreferenceConstants;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.internal.ui.ICStatusConstants;
import org.eclipse.cdt.internal.ui.text.comment.CommentFormattingContext;
import org.eclipse.cdt.ui.CUIPlugin;
public class TranslationUnitPreview extends CPreview {
private String fPreviewText;
private String fFormatterId;
/**
* @param workingValues
@ -56,7 +58,12 @@ public class TranslationUnitPreview extends CPreview {
final IContentFormatter formatter = fViewerConfiguration.getContentFormatter(fSourceViewer);
if (formatter instanceof IContentFormatterExtension) {
final IContentFormatterExtension extension = (IContentFormatterExtension) formatter;
context.setProperty(FormattingContextProperties.CONTEXT_PREFERENCES, fWorkingValues);
Map prefs= fWorkingValues;
if (fFormatterId != null) {
prefs= new HashMap(fWorkingValues);
prefs.put(CCorePreferenceConstants.CODE_FORMATTER, fFormatterId);
}
context.setProperty(FormattingContextProperties.CONTEXT_PREFERENCES, prefs);
context.setProperty(FormattingContextProperties.CONTEXT_DOCUMENT, Boolean.valueOf(true));
extension.format(fPreviewDocument, context);
} else
@ -72,8 +79,14 @@ public class TranslationUnitPreview extends CPreview {
}
public void setPreviewText(String previewText) {
// if (previewText == null) throw new IllegalArgumentException();
fPreviewText= previewText;
update();
}
/**
* @param formatterId
*/
public void setFormatterId(String formatterId) {
fFormatterId= formatterId;
}
}

View file

@ -7,23 +7,12 @@
*
* Contributors:
* QNX Software Systems - Initial API and implementation
* Anton Leherbauer (Wind River Systems)
*******************************************************************************/
package org.eclipse.cdt.internal.ui.text;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.formatter.CodeFormatter;
import org.eclipse.cdt.core.formatter.DefaultCodeFormatterConstants;
import org.eclipse.cdt.core.model.CoreModel;
import org.eclipse.cdt.core.parser.ParserLanguage;
import org.eclipse.cdt.internal.corext.util.CodeFormatterUtil;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.jface.text.Assert;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.TextUtilities;
@ -33,9 +22,11 @@ import org.eclipse.jface.text.formatter.FormattingContextProperties;
import org.eclipse.jface.text.formatter.IFormattingContext;
import org.eclipse.text.edits.MalformedTreeException;
import org.eclipse.text.edits.TextEdit;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.cdt.core.formatter.CodeFormatter;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.internal.corext.util.CodeFormatterUtil;
/**
* @author AChapiro
@ -66,32 +57,30 @@ public class CFormattingStrategy extends ContextBasedFormattingStrategy {
if (document != null && partition != null) {
try {
final TextEdit edit= CodeFormatterUtil.format(CodeFormatter.K_COMPILATION_UNIT,
document.get(),
partition.getOffset(),
partition.getLength(),
0,
TextUtilities.getDefaultLineDelimiter(document),
final TextEdit edit = CodeFormatterUtil.format(
CodeFormatter.K_COMPILATION_UNIT, document.get(),
partition.getOffset(), partition.getLength(), 0,
TextUtilities.getDefaultLineDelimiter(document),
getPreferences());
if (edit != null)
edit.apply(document);
} catch (MalformedTreeException exception) {
CUIPlugin.getDefault().log(exception);
} catch (BadLocationException exception) {
// Can only happen on concurrent document modification - log and bail out
// Can only happen on concurrent document modification - log and
// bail out
CUIPlugin.getDefault().log(exception);
}
}
}
}
/*
* @see org.eclipse.jface.text.formatter.ContextBasedFormattingStrategy#formatterStarts(org.eclipse.jface.text.formatter.IFormattingContext)
*/
public void formatterStarts(final IFormattingContext context) {
prepareFormattingContext(context);
super.formatterStarts(context);
fPartitions.addLast(context.getProperty(FormattingContextProperties.CONTEXT_PARTITION));
@ -108,47 +97,4 @@ public class CFormattingStrategy extends ContextBasedFormattingStrategy {
fDocuments.clear();
}
private IFile getActiveFile() {
IFile file = null;
IEditorPart editor =
CUIPlugin.getDefault().getWorkbench().
getActiveWorkbenchWindow().
getActivePage().getActiveEditor();
IEditorInput input = editor.getEditorInput();
if(input instanceof IFileEditorInput) {
file = ((IFileEditorInput)input).getFile();
}
return file;
}
private void prepareFormattingContext(final IFormattingContext context) {
Map preferences;
ParserLanguage language = ParserLanguage.CPP;
IFile activeFile = getActiveFile();
if(null != activeFile) {
IProject currentProject = activeFile.getProject();
Assert.isNotNull(currentProject);
String filename = activeFile.getFullPath().lastSegment();
// pick the language
if (CoreModel.isValidCXXHeaderUnitName(currentProject, filename)
|| CoreModel.isValidCXXSourceUnitName(currentProject, filename)) {
language = ParserLanguage.CPP;
} else {
// for C project try to guess.
language = ParserLanguage.C;
}
preferences= new HashMap(CoreModel.getDefault().create(
activeFile.getProject()).getOptions(true));
} else
preferences= new HashMap(CCorePlugin.getOptions());
preferences.put(DefaultCodeFormatterConstants.FORMATTER_LANGUAGE, language);
preferences.put(DefaultCodeFormatterConstants.FORMATTER_CURRENT_FILE, activeFile);
context.storeToMap(CUIPlugin.getDefault().getPreferenceStore(), preferences, false);
context.setProperty(FormattingContextProperties.CONTEXT_PREFERENCES, preferences);
return;
}
}

View file

@ -14,9 +14,7 @@ package org.eclipse.cdt.internal.ui.text;
import java.util.Arrays;
import org.eclipse.cdt.ui.text.ICPartitions;
import org.eclipse.jface.text.Assert;
import org.eclipse.core.runtime.Assert;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
@ -25,6 +23,8 @@ import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.TextUtilities;
import org.eclipse.jface.text.TypedRegion;
import org.eclipse.cdt.ui.text.ICPartitions;
/**
* Utility methods for heuristic based C manipulations in an incomplete C source file.
*

View file

@ -12,16 +12,17 @@
*******************************************************************************/
package org.eclipse.cdt.internal.ui.text;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.formatter.DefaultCodeFormatterConstants;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.internal.corext.util.CodeFormatterUtil;
import org.eclipse.jface.text.Assert;
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.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.formatter.DefaultCodeFormatterConstants;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.internal.corext.util.CodeFormatterUtil;
/**
* Uses the {@link org.eclipse.cdt.internal.ui.text.CHeuristicScanner} to

View file

@ -1,5 +1,5 @@
/*******************************************************************************
* Copyright (c) 2000, 2005 IBM Corporation and others.
* Copyright (c) 2000, 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
@ -8,45 +8,17 @@
* Contributors:
* IBM Corporation - initial API and implementation
* Sergey Prigogin, Google
* Anton Leherbauer (Wind River Systems)
*******************************************************************************/
package org.eclipse.cdt.internal.ui.text.comment;
import org.eclipse.jface.text.formatter.FormattingContext;
import org.eclipse.cdt.core.formatter.DefaultCodeFormatterConstants;
/**
* Formatting context for the comment formatter.
*
* @since 4.0
*/
public class CommentFormattingContext extends FormattingContext {
/*
* @see org.eclipse.jface.text.formatter.IFormattingContext#getPreferenceKeys()
*/
public String[] getPreferenceKeys() {
return new String[] {
DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT,
DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_HEADER,
DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_SOURCE,
DefaultCodeFormatterConstants.FORMATTER_COMMENT_LINE_LENGTH,
DefaultCodeFormatterConstants.FORMATTER_COMMENT_CLEAR_BLANK_LINES};
}
/*
* @see org.eclipse.jface.text.formatter.IFormattingContext#isBooleanPreference(java.lang.String)
*/
public boolean isBooleanPreference(String key) {
return !key.equals(DefaultCodeFormatterConstants.FORMATTER_COMMENT_LINE_LENGTH);
}
/*
* @see org.eclipse.jface.text.formatter.IFormattingContext#isIntegerPreference(java.lang.String)
*/
public boolean isIntegerPreference(String key) {
return key.equals(DefaultCodeFormatterConstants.FORMATTER_COMMENT_LINE_LENGTH);
}
}

View file

@ -7,11 +7,15 @@
*
* Contributors:
* QNX Software Systems - Initial API and implementation
* Anton Leherbauer (Wind River Systems)
*******************************************************************************/
package org.eclipse.cdt.utils.ui.controls;
import java.util.StringTokenizer;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.CheckboxTableViewer;
import org.eclipse.jface.viewers.ColumnWeightData;
@ -19,6 +23,8 @@ import org.eclipse.jface.viewers.TableLayout;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
@ -94,6 +100,56 @@ public class ControlFactory {
return separator;
}
/**
* Creates a composite with a highlighted Note entry and a message text.
* This is designed to take up the full width of the page.
*
* @param font the font to use
* @param composite the parent composite
* @param title the title of the note
* @param message the message for the note
* @return the composite for the note
*/
public static Composite createNoteComposite(Font font, Composite composite,
String title, String message) {
Composite messageComposite = new Composite(composite, SWT.NONE);
GridLayout messageLayout = new GridLayout();
messageLayout.numColumns = 2;
messageLayout.marginWidth = 0;
messageLayout.marginHeight = 0;
messageComposite.setLayout(messageLayout);
messageComposite.setLayoutData(new GridData(
GridData.HORIZONTAL_ALIGN_FILL));
messageComposite.setFont(font);
final Label noteLabel = new Label(messageComposite, SWT.BOLD);
noteLabel.setText(title);
noteLabel.setFont(JFaceResources.getFontRegistry().getBold(
JFaceResources.DEFAULT_FONT));
noteLabel
.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING));
final IPropertyChangeListener fontListener = new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
if (JFaceResources.BANNER_FONT.equals(event.getProperty())) {
noteLabel.setFont(JFaceResources
.getFont(JFaceResources.BANNER_FONT));
}
}
};
JFaceResources.getFontRegistry().addListener(fontListener);
noteLabel.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent event) {
JFaceResources.getFontRegistry().removeListener(fontListener);
}
});
Label messageLabel = new Label(messageComposite, SWT.WRAP);
messageLabel.setText(message);
messageLabel.setFont(font);
return messageComposite;
}
/**
* Creates a separator.
*