eclipse plugin: Apply the formatting rules & organize import

This commit is contained in:
Timotei Dolean 2011-08-06 21:10:03 +00:00
parent 06aeb27b84
commit 020800ef20
157 changed files with 13332 additions and 12234 deletions

View file

@ -1,4 +1,4 @@
#Sat Aug 06 15:40:55 EEST 2011
#Sat Aug 06 15:51:03 EEST 2011
eclipse.preferences.version=1
org.eclipse.jdt.core.codeComplete.argumentPrefixes=
org.eclipse.jdt.core.codeComplete.argumentSuffixes=
@ -303,21 +303,21 @@ org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declara
org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=insert
org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=insert
org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=insert
org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert

View file

@ -8,6 +8,8 @@ import java.util.List;
import org.antlr.runtime.ANTLRStringStream;
import org.antlr.runtime.CharStream;
import org.antlr.runtime.Token;
import org.junit.Ignore;
import org.eclipse.xtext.ParserRule;
import org.eclipse.xtext.junit.AbstractXtextTests;
import org.eclipse.xtext.nodemodel.INode;
@ -16,7 +18,7 @@ import org.eclipse.xtext.parser.IParser;
import org.eclipse.xtext.parser.antlr.ITokenDefProvider;
import org.eclipse.xtext.parser.antlr.Lexer;
import org.eclipse.xtext.parser.antlr.XtextTokenStream;
import org.junit.Ignore;
import org.wesnoth.WMLStandaloneSetup;
import org.wesnoth.services.WMLGrammarAccess;
import org.wesnoth.utils.StringUtils;
@ -47,7 +49,8 @@ public abstract class WMLTests extends AbstractXtextTests
return parser;
}
Class getStandaloneSetupClass() {
Class getStandaloneSetupClass( )
{
return WMLStandaloneSetup.class;
}
@ -63,8 +66,10 @@ public abstract class WMLTests extends AbstractXtextTests
// get the wesnoth data path from the user
dataPath_ = System.getProperty( "wesnothDataDir" );
if ( StringUtils.isNullOrEmpty( dataPath_ ) || ! new File( dataPath_ ).exists( ) ) {
System.out.println( "Please set the wesnoth data dir before testing!." );
if( StringUtils.isNullOrEmpty( dataPath_ )
|| ! new File( dataPath_ ).exists( ) ) {
System.out
.println( "Please set the wesnoth data dir before testing!." );
assertTrue( false );
}
}
@ -88,7 +93,8 @@ public abstract class WMLTests extends AbstractXtextTests
{
CharStream stream = new ANTLRStringStream( input );
getLexer( ).setCharStream( stream );
XtextTokenStream tokenStream = new XtextTokenStream( getLexer( ), getTokenDefProvider( ) );
XtextTokenStream tokenStream = new XtextTokenStream( getLexer( ),
getTokenDefProvider( ) );
List< Token > tokens = tokenStream.getTokens( );
return tokens;
}
@ -104,7 +110,8 @@ public abstract class WMLTests extends AbstractXtextTests
/**
* check whether an input is chopped into a list of expected token types
*/
protected void checkTokenisation( String input, String... expectedTokenTypes )
protected void checkTokenisation( String input,
String... expectedTokenTypes )
{
List< Token > tokens = getTokens( input );
assertEquals( input, expectedTokenTypes.length, tokens.size( ) );
@ -158,7 +165,8 @@ public abstract class WMLTests extends AbstractXtextTests
*/
protected void checkParsing( Reader reader )
{
IParseResult la = getParser( ).parse( reader );;
IParseResult la = getParser( ).parse( reader );
;
for( INode node: la.getSyntaxErrors( ) ) {
System.out.println( node.getSyntaxErrorMessage( ).getMessage( ) );
}
@ -231,7 +239,8 @@ public abstract class WMLTests extends AbstractXtextTests
}
@Ignore
public void testFile( String path ) {
public void testFile( String path )
{
}
}

View file

@ -10,17 +10,14 @@ package org.wesnoth.tests;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.wesnoth.tests.grammar.WMLFilesTests;
import org.wesnoth.tests.grammar.WMLGrammarTokensTests;
import org.wesnoth.tests.plugin.WMLParsingCampaignsConfigs;
@RunWith( Suite.class )
@Suite.SuiteClasses(
{
WMLGrammarTokensTests.class,
WMLFilesTests.class,
WMLParsingCampaignsConfigs.class,
} )
@Suite.SuiteClasses( { WMLGrammarTokensTests.class, WMLFilesTests.class,
WMLParsingCampaignsConfigs.class, } )
public class WMLTestsSuite
{
}

View file

@ -12,6 +12,7 @@ import java.io.FileNotFoundException;
import java.io.FileReader;
import org.junit.Ignore;
import org.wesnoth.tests.WMLTests;
/**
@ -127,8 +128,7 @@ public class WMLFilesTests extends WMLTests
try {
checkParsing( new FileReader( path ) );
System.out.print( " OK" );
}
catch ( FileNotFoundException e ) {
} catch( FileNotFoundException e ) {
e.printStackTrace( );
// should not reach here.
assertTrue( false );

View file

@ -20,6 +20,7 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.wesnoth.tests.WMLTests;
import org.wesnoth.utils.StringUtils;
import org.wesnoth.wml.SimpleWMLParser;
@ -42,8 +43,7 @@ public class WMLParsingCampaignsConfigs extends WMLTests
{
try {
setUp( );
}
catch ( Exception e ) {
} catch( Exception e ) {
e.printStackTrace( );
assertTrue( false );
}
@ -71,7 +71,8 @@ public class WMLParsingCampaignsConfigs extends WMLTests
return;
try {
SimpleWMLParser wmlParser = new SimpleWMLParser( new File( path ), getParser( ) );
SimpleWMLParser wmlParser = new SimpleWMLParser( new File( path ),
getParser( ) );
wmlParser.parse( );
WMLConfig config = wmlParser.getParsedConfig( );
@ -81,8 +82,7 @@ public class WMLParsingCampaignsConfigs extends WMLTests
if( ! StringUtils.isNullOrEmpty( config.CampaignId ) )
parsedCampaignIds_.add( config.CampaignId );
}
catch ( FileNotFoundException e ) {
} catch( FileNotFoundException e ) {
e.printStackTrace( );
assertTrue( false );
}
@ -110,8 +110,15 @@ public class WMLParsingCampaignsConfigs extends WMLTests
public static Collection< Object[] > data( )
{
return Arrays.asList( new Object[][] {
{ new String[]{ "An_Orcish_Incursion", "An_Orcish_Incursion", "01_Defend_the_Forest", "02_Assassins", "03_Wasteland", "04_Valley_of_Trolls", "05_Linaera_the_Quick", "06_A_Detour_through_the_Swamp", "07_Showdown" } },
{ new String[]{ "Dead_Water", "Dead_Water", "01_Invasion", "02_Flight", "03_Wolf_Coast", "04_Slavers", "05_Tirigaz", "06_Uncharted_Islands", "07_Bilheld", "08_Talking_to_Tyegea", "09_The_Mage", "10_The_Flaming_Sword", "11_Getting_Help", "12_Revenge", "13_Epilogue" } }
} );
{ new String[] { "An_Orcish_Incursion", "An_Orcish_Incursion",
"01_Defend_the_Forest", "02_Assassins", "03_Wasteland",
"04_Valley_of_Trolls", "05_Linaera_the_Quick",
"06_A_Detour_through_the_Swamp", "07_Showdown" } },
{ new String[] { "Dead_Water", "Dead_Water", "01_Invasion",
"02_Flight", "03_Wolf_Coast", "04_Slavers",
"05_Tirigaz", "06_Uncharted_Islands", "07_Bilheld",
"08_Talking_to_Tyegea", "09_The_Mage",
"10_The_Flaming_Sword", "11_Getting_Help",
"12_Revenge", "13_Epilogue" } } } );
}
}

View file

@ -1,4 +1,4 @@
#Sat Aug 06 15:40:55 EEST 2011
#Sat Aug 06 15:51:03 EEST 2011
eclipse.preferences.version=1
org.eclipse.jdt.core.codeComplete.argumentPrefixes=
org.eclipse.jdt.core.codeComplete.argumentSuffixes=
@ -303,21 +303,21 @@ org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declara
org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=insert
org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=insert
org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=insert
org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert

View file

@ -32,8 +32,7 @@ public class Messages extends NLS
public static String WMLHighlightingConfiguration_8;
public static String WMLHighlightingConfiguration_9;
public static String WMLHyperlinkHelper_0;
static
{
static {
// initialize resource bundle
NLS.initializeMessages( BUNDLE_NAME, Messages.class );
}

View file

@ -8,6 +8,9 @@
*******************************************************************************/
package org.wesnoth.ui;
import com.google.inject.Binder;
import com.google.inject.Provider;
import org.eclipse.jface.text.hyperlink.IHyperlinkDetector;
import org.eclipse.jface.text.source.ICharacterPairMatcher;
import org.eclipse.jface.viewers.ILabelProvider;
@ -25,6 +28,7 @@ import org.eclipse.xtext.ui.editor.syntaxcoloring.AbstractAntlrTokenToAttributeI
import org.eclipse.xtext.ui.editor.syntaxcoloring.IHighlightingConfiguration;
import org.eclipse.xtext.ui.editor.syntaxcoloring.IHighlightingHelper;
import org.eclipse.xtext.ui.editor.syntaxcoloring.ISemanticHighlightingCalculator;
import org.wesnoth.ui.autoedit.WMLAutoEditStrategy;
import org.wesnoth.ui.contentassist.WMLContentAssistContext;
import org.wesnoth.ui.contentassist.WMLProposalComparator;
@ -40,16 +44,14 @@ import org.wesnoth.ui.syntax.WMLCharacterPairMatcher;
import org.wesnoth.ui.syntax.WMLHighlightingConfiguration;
import org.wesnoth.ui.syntax.WMLSemanticHighlightingCalculator;
import com.google.inject.Binder;
import com.google.inject.Provider;
/**
* Use this class to register components to be used within the IDE.
*/
@SuppressWarnings( "all" )
public class WMLUiModule extends org.wesnoth.ui.AbstractWMLUiModule
{
public WMLUiModule(AbstractUIPlugin plugin) {
public WMLUiModule( AbstractUIPlugin plugin )
{
super( plugin );
}
@ -83,7 +85,8 @@ public class WMLUiModule extends org.wesnoth.ui.AbstractWMLUiModule
@Override
public ICharacterPairMatcher bindICharacterPairMatcher( )
{
return new WMLCharacterPairMatcher( new char[] { '(', ')', '{', '}', '[', ']' } );
return new WMLCharacterPairMatcher( new char[] { '(', ')', '{', '}',
'[', ']' } );
}
public Class< ? extends XtextEditor > bindEditor( )

View file

@ -19,6 +19,7 @@ import org.eclipse.xtext.resource.XtextResource;
import org.eclipse.xtext.ui.editor.XtextEditor;
import org.eclipse.xtext.ui.editor.utils.EditorUtils;
import org.eclipse.xtext.util.concurrent.IUnitOfWork;
import org.wesnoth.utils.StringUtils;
import org.wesnoth.wml.WMLTag;
@ -30,36 +31,41 @@ public class ClosingEndTagAutoEditStrategy implements IAutoEditStrategy
public void customizeDocumentCommand( final IDocument document,
final DocumentCommand command )
{
try
{
try {
if( command.text.equals( "/" ) && document.get( command.offset - 1, 1 ).equals( "[" ) ) //$NON-NLS-1$ //$NON-NLS-2$
{
XtextEditor editor = EditorUtils.getActiveXtextEditor( );
if( editor == null )
return;
editor.getDocument().readOnly(new IUnitOfWork.Void<XtextResource>(){
editor.getDocument( ).readOnly(
new IUnitOfWork.Void< XtextResource >( ) {
@Override
public void process(XtextResource state) throws Exception
public void process( XtextResource state )
throws Exception
{
ILeafNode currentNode = NodeModelUtils.findLeafNodeAtOffset(
state.getParseResult( ).getRootNode( ), command.offset);
ILeafNode currentNode = NodeModelUtils
.findLeafNodeAtOffset( state
.getParseResult( )
.getRootNode( ), command.offset );
if( currentNode == null )
return;
EObject semanticElement = currentNode.getSemanticElement( );
EObject semanticElement = currentNode
.getSemanticElement( );
if( semanticElement == null )
return;
String tagName = ""; //$NON-NLS-1$
EObject container = semanticElement.eContainer( );
EObject container = semanticElement
.eContainer( );
if( container instanceof WMLTag ) {
tagName = ( ( WMLTag ) container ).getName( );
tagName = ( ( WMLTag ) container )
.getName( );
}
if ( !StringUtils.isNullOrEmpty( tagName ) )
{
if( ! StringUtils.isNullOrEmpty( tagName ) ) {
command.shiftsCaret = true;
command.text = ( "/" + tagName ); //$NON-NLS-1$ //$NON-NLS-2$
}

View file

@ -8,10 +8,10 @@
*******************************************************************************/
package org.wesnoth.ui.contentassist;
import org.eclipse.xtext.ui.editor.contentassist.ContentAssistContext;
import com.google.inject.Inject;
import org.eclipse.xtext.ui.editor.contentassist.ContentAssistContext;
public class WMLContentAssistContext extends ContentAssistContext
{
@Inject

View file

@ -16,9 +16,8 @@ public class WMLProposalComparator implements ICompletionProposalComparator
{
public int compare( ICompletionProposal arg0, ICompletionProposal arg1 )
{
if (arg0 instanceof ConfigurableCompletionProposal &&
arg1 instanceof ConfigurableCompletionProposal)
{
if( arg0 instanceof ConfigurableCompletionProposal
&& arg1 instanceof ConfigurableCompletionProposal ) {
ConfigurableCompletionProposal tmp0 = ( ConfigurableCompletionProposal ) arg0;
ConfigurableCompletionProposal tmp1 = ( ConfigurableCompletionProposal ) arg1;
return tmp0.compareTo( tmp1 );

View file

@ -8,6 +8,10 @@
*******************************************************************************/
package org.wesnoth.ui.contentassist;
import com.google.common.base.Function;
import com.google.common.base.Predicates;
import com.google.common.collect.Collections2;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@ -24,6 +28,7 @@ import org.eclipse.xtext.nodemodel.ICompositeNode;
import org.eclipse.xtext.nodemodel.util.NodeModelUtils;
import org.eclipse.xtext.ui.editor.contentassist.ContentAssistContext;
import org.eclipse.xtext.ui.editor.contentassist.ICompletionProposalAcceptor;
import org.wesnoth.installs.WesnothInstallsUtils;
import org.wesnoth.preprocessor.Define;
import org.wesnoth.projects.ProjectCache;
@ -42,10 +47,6 @@ import org.wesnoth.wml.WMLTag;
import org.wesnoth.wml.WMLVariable;
import org.wesnoth.wml.WMLVariable.Scope;
import com.google.common.base.Function;
import com.google.common.base.Predicates;
import com.google.common.collect.Collections2;
public class WMLProposalProvider extends AbstractWMLProposalProvider
{
protected SchemaParser schemaParser_;
@ -63,10 +64,8 @@ public class WMLProposalProvider extends AbstractWMLProposalProvider
private static Image WML_TAG_IMAGE = null;
/**
* For priorities, see:
* {@link #KEY_NAME_PRIORITY}
* {@link #KEY_VALUE_PRIORITY}
* {@link #TAG_PRIORITY}
* For priorities, see: {@link #KEY_NAME_PRIORITY}
* {@link #KEY_VALUE_PRIORITY} {@link #TAG_PRIORITY}
* {@link #MACRO_CALL_PRIORITY}
*/
public WMLProposalProvider( )
@ -92,7 +91,8 @@ public class WMLProposalProvider extends AbstractWMLProposalProvider
projectCache_ = ProjectUtils.getCacheForProject( file.getProject( ) );
// load the schema so we know what to suggest for autocomplete
schemaParser_ = SchemaParser.getInstance( WesnothInstallsUtils.getInstallNameForResource( file ) );
schemaParser_ = SchemaParser.getInstance( WesnothInstallsUtils
.getInstallNameForResource( file ) );
dependencyIndex_ = ResourceUtils.getDependencyIndex( file );
}
@ -138,8 +138,9 @@ public class WMLProposalProvider extends AbstractWMLProposalProvider
}
@Override
public void completeWMLMacroCall_Name(EObject model, Assignment assignment,
ContentAssistContext context, ICompletionProposalAcceptor acceptor)
public void completeWMLMacroCall_Name( EObject model,
Assignment assignment, ContentAssistContext context,
ICompletionProposalAcceptor acceptor )
{
super.completeWMLMacroCall_Name( model, assignment, context, acceptor );
refresh( );
@ -160,8 +161,8 @@ public class WMLProposalProvider extends AbstractWMLProposalProvider
private void addMacroCallProposals( EObject model, boolean ruleProposal,
ContentAssistContext context, ICompletionProposalAcceptor acceptor )
{
for(Entry<String, Define> define : projectCache_.getDefines().entrySet())
{
for( Entry< String, Define > define: projectCache_.getDefines( )
.entrySet( ) ) {
StringBuilder proposal = new StringBuilder( 10 );
if( ruleProposal == true )
proposal.append( "{" ); //$NON-NLS-1$
@ -171,8 +172,9 @@ public class WMLProposalProvider extends AbstractWMLProposalProvider
proposal.append( " " + arg ); //$NON-NLS-1$
proposal.append( "}" ); //$NON-NLS-1$
acceptor.accept(createCompletionProposal(proposal.toString(), define.getKey(),
MACRO_CALL_IMAGE, context, MACRO_CALL_PRIORITY)); //$NON-NLS-1$
acceptor.accept( createCompletionProposal( proposal.toString( ),
define.getKey( ), MACRO_CALL_IMAGE, context,
MACRO_CALL_PRIORITY ) ); //$NON-NLS-1$
}
}
@ -188,8 +190,7 @@ public class WMLProposalProvider extends AbstractWMLProposalProvider
if( keyName.equals( "next_scenario" ) || //$NON-NLS-1$
keyName.equals( "first_scenario" ) ) //$NON-NLS-1$
{
for(WMLConfig config : projectCache_.getWMLConfigs().values())
{
for( WMLConfig config: projectCache_.getWMLConfigs( ).values( ) ) {
if( StringUtils.isNullOrEmpty( config.ScenarioId ) )
continue;
acceptor.accept( createCompletionProposal( config.ScenarioId,
@ -197,18 +198,15 @@ public class WMLProposalProvider extends AbstractWMLProposalProvider
context, KEY_VALUE_PRIORITY ) );
}
}
else if (model.eContainer() != null && model.eContainer() instanceof WMLTag)
{
else if( model.eContainer( ) != null
&& model.eContainer( ) instanceof WMLTag ) {
WMLTag parent = ( WMLTag ) model.eContainer( );
String tagName = parent.getName( );
WMLTag tag = schemaParser_.getTags( ).get( tagName );
if (tag != null)
{
if( tag != null ) {
WMLKey tagKey = WMLUtils.getKeyByName( tag, keyName );
if ( tagKey != null && tagKey.is_Enum() )
{
for(WMLKeyValue val : tagKey.getValues( ) )
{
if( tagKey != null && tagKey.is_Enum( ) ) {
for( WMLKeyValue val: tagKey.getValues( ) ) {
acceptor.accept( createCompletionProposal(
val.toString( ), context, KEY_VALUE_PRIORITY ) );
}
@ -219,18 +217,22 @@ public class WMLProposalProvider extends AbstractWMLProposalProvider
&& keyName.equals( "name" ) ) {
// add events
List< String > events = new ArrayList< String >( );
events.addAll( TemplateProvider.getInstance( ).getCAC( "events" ) );
events.addAll( TemplateProvider.getInstance( )
.getCAC( "events" ) );
events.addAll( projectCache_.getEvents( ) );
for( String event: events ) {
acceptor.accept( createCompletionProposal( event, context ) );
}
} else {
final int nodeOffset = NodeModelUtils.getNode( model ).getTotalOffset( );
}
else {
final int nodeOffset = NodeModelUtils.getNode( model )
.getTotalOffset( );
List< String > variables = new ArrayList< String >( );
// add CAC variables
variables.addAll( TemplateProvider.getInstance( ).getCAC( "variables" ) );
variables.addAll( TemplateProvider.getInstance( ).getCAC(
"variables" ) );
// filter variables by index
Collection< String > projectVariables = Collections2.transform(
@ -241,7 +243,8 @@ public class WMLProposalProvider extends AbstractWMLProposalProvider
public String apply( WMLVariable from )
{
for( Scope scope: from.getScopes( ) ) {
if ( scope.contains( dependencyIndex_, nodeOffset ) )
if( scope.contains( dependencyIndex_,
nodeOffset ) )
return from.getName( );
}
@ -253,7 +256,8 @@ public class WMLProposalProvider extends AbstractWMLProposalProvider
Predicates.notNull( ) ) );
for( String variable: variables ) {
acceptor.accept( createCompletionProposal( "$" + variable, context ) );
acceptor.accept( createCompletionProposal( "$" + variable,
context ) );
}
}
}
@ -268,18 +272,15 @@ public class WMLProposalProvider extends AbstractWMLProposalProvider
else if( model.eContainer( ) instanceof WMLTag )
tag = ( WMLTag ) model.eContainer( );
if (tag != null)
{
if( tag != null ) {
WMLTag schemaTag = schemaParser_.getTags( ).get( tag.getName( ) );
// try getting the custom ones
if( schemaTag == null ) {
schemaTag = projectCache_.getWMLTags( ).get( tag.getName( ) );
}
if ( schemaTag != null)
{
for( WMLKey key : schemaTag.getWMLKeys( ) )
{
if( schemaTag != null ) {
for( WMLKey key: schemaTag.getWMLKeys( ) ) {
// skip forbidden keys
if( key.is_Forbidden( ) )
continue;
@ -292,8 +293,10 @@ public class WMLProposalProvider extends AbstractWMLProposalProvider
}
if( toAdd )
acceptor.accept(createCompletionProposal(key.getName() + "=", //$NON-NLS-1$
key.getName(), WML_KEY_IMAGE, context, KEY_NAME_PRIORITY));
acceptor.accept( createCompletionProposal(
key.getName( ) + "=", //$NON-NLS-1$
key.getName( ), WML_KEY_IMAGE, context,
KEY_NAME_PRIORITY ) );
}
}
}
@ -308,8 +311,7 @@ public class WMLProposalProvider extends AbstractWMLProposalProvider
else if( model.eContainer( ) instanceof WMLTag )
parentTag = ( WMLTag ) model.eContainer( );
if (parentTag != null)
{
if( parentTag != null ) {
ICompositeNode node = NodeModelUtils.getNode( model );
String parentIndent = ""; //$NON-NLS-1$
@ -322,12 +324,11 @@ public class WMLProposalProvider extends AbstractWMLProposalProvider
// remove ugly new lines that break indentation
parentIndent = parentIndent.replace( "\r", "" ).replace( "\n", "" ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
WMLTag tagChildren = schemaParser_.getTags().get(parentTag.getName());
if (tagChildren != null)
{
WMLTag tagChildren = schemaParser_.getTags( ).get(
parentTag.getName( ) );
if( tagChildren != null ) {
boolean toAdd = true;
for( WMLTag tag : tagChildren.getWMLTags( ) )
{
for( WMLTag tag: tagChildren.getWMLTags( ) ) {
// skip forbidden tags
if( tag.is_Forbidden( ) )
continue;
@ -335,38 +336,41 @@ public class WMLProposalProvider extends AbstractWMLProposalProvider
toAdd = true;
// check only non-repeatable tags
if ( ! tag.is_Repeatable() )
{
toAdd = ( WMLUtils.getTagByName( parentTag, tag.getName( ) ) == null );
if( ! tag.is_Repeatable( ) ) {
toAdd = ( WMLUtils.getTagByName( parentTag,
tag.getName( ) ) == null );
}
if( toAdd )
acceptor.accept(createTagProposal( tag.asWMLTag( ), parentIndent,
ruleProposal, context));
acceptor.accept( createTagProposal( tag.asWMLTag( ),
parentIndent, ruleProposal, context ) );
}
}
}
else // we are at the root
{
WMLTag rootTag = schemaParser_.getTags( ).get( "root" ); //$NON-NLS-1$
for( WMLTag tag : rootTag.getWMLTags( ) )
{
acceptor.accept( createTagProposal( tag, "", ruleProposal, context ) ); //$NON-NLS-1$
for( WMLTag tag: rootTag.getWMLTags( ) ) {
acceptor.accept( createTagProposal( tag,
"", ruleProposal, context ) ); //$NON-NLS-1$
}
}
// parsed custom tags
for( WMLTag tag : projectCache_.getWMLTags( ).values( ) )
{
for( WMLTag tag: projectCache_.getWMLTags( ).values( ) ) {
acceptor.accept( createTagProposal( tag, "", ruleProposal, context ) ); //$NON-NLS-1$
}
}
/**
* Returns the proposal for the specified tag, usign the specified indent
* @param tag The tag from which to construct the proposal
* @param indent The indent used to indent the tag and subsequent keys
* @param ruleProposal Whether this is a proposal for an entire rule or not
*
* @param tag
* The tag from which to construct the proposal
* @param indent
* The indent used to indent the tag and subsequent keys
* @param ruleProposal
* Whether this is a proposal for an entire rule or not
* @param context
* @return
*/
@ -378,8 +382,7 @@ public class WMLProposalProvider extends AbstractWMLProposalProvider
proposal.append( "[" ); //$NON-NLS-1$
proposal.append( tag.getName( ) );
proposal.append( "]\n" ); //$NON-NLS-1$
for( WMLKey key : tag.getWMLKeys( ) )
{
for( WMLKey key: tag.getWMLKeys( ) ) {
if( key.is_Required( ) )
proposal.append( String.format( "\t%s%s=\n", //$NON-NLS-1$
indent, key.getName( ) ) );
@ -396,10 +399,12 @@ public class WMLProposalProvider extends AbstractWMLProposalProvider
context.getPrefix( ), context );
}
public ICompletionProposal createCompletionProposal(String proposal, String displayString, Image image,
public ICompletionProposal createCompletionProposal( String proposal,
String displayString, Image image,
ContentAssistContext contentAssistContext, int priority )
{
return createCompletionProposal(proposal, new StyledString(displayString),
image, priority, contentAssistContext.getPrefix(), contentAssistContext);
return createCompletionProposal( proposal, new StyledString(
displayString ), image, priority,
contentAssistContext.getPrefix( ), contentAssistContext );
}
}

View file

@ -10,8 +10,11 @@ package org.wesnoth.ui.editor;
import org.eclipse.jface.action.IMenuManager;
public class DefaultExtXtextEditorCustomizer implements IExtXtextEditorCustomizer {
public void customizeEditorContextMenu(IMenuManager menuManager) {
public class DefaultExtXtextEditorCustomizer implements
IExtXtextEditorCustomizer
{
public void customizeEditorContextMenu( IMenuManager menuManager )
{
// do nothing
}
}

View file

@ -8,15 +8,16 @@
package org.wesnoth.ui.editor;
import org.eclipse.jface.action.IMenuManager;
import com.google.inject.ImplementedBy;
import org.eclipse.jface.action.IMenuManager;
/**
*
*
*/
@ImplementedBy( DefaultExtXtextEditorCustomizer.class )
public interface IExtXtextEditorCustomizer {
public interface IExtXtextEditorCustomizer
{
public void customizeEditorContextMenu( IMenuManager menuManager );
}

View file

@ -32,22 +32,20 @@ public class LinkedFileEditorInput extends FileEditorInput
return true;
}
String targetUri = ""; //$NON-NLS-1$
if (!(obj instanceof IFileEditorInput))
{
if (obj instanceof FileStoreEditorInput)
{
if( ! ( obj instanceof IFileEditorInput ) ) {
if( obj instanceof FileStoreEditorInput ) {
FileStoreEditorInput other = ( FileStoreEditorInput ) obj;
targetUri = other.getURI( ).toString( );
}
}
else
{
else {
IFileEditorInput other = ( IFileEditorInput ) obj;
targetUri = other.getFile( ).getLocationURI( ).toString( );
}
if( targetUri.isEmpty( ) )
return false;
return getFile().getLocationURI().toString().toLowerCase(Locale.ENGLISH).
equals(targetUri.toLowerCase(Locale.ENGLISH));
return getFile( ).getLocationURI( ).toString( )
.toLowerCase( Locale.ENGLISH )
.equals( targetUri.toLowerCase( Locale.ENGLISH ) );
}
}

View file

@ -15,7 +15,8 @@ import org.eclipse.xtext.ui.editor.XtextEditor;
* We use this class to suppress the default one which asks for adding
* a xtext nature on non-xtext project. We don't want that (yet)
*/
public class WMLAbstractDirtyEditorCallback extends AbstractDirtyStateAwareEditorCallback
public class WMLAbstractDirtyEditorCallback extends
AbstractDirtyStateAwareEditorCallback
{
@Override
public void afterCreatePartControl( XtextEditor editor )

View file

@ -8,11 +8,11 @@
*******************************************************************************/
package org.wesnoth.ui.editor;
import com.google.inject.Inject;
import java.io.File;
import org.wesnoth.Logger;
import org.wesnoth.WesnothPlugin;
import org.wesnoth.ui.Messages;
import org.apache.log4j.Level;
import org.eclipse.core.filesystem.EFS;
import org.eclipse.core.filesystem.IFileStore;
@ -54,9 +54,9 @@ import org.eclipse.xtext.ui.editor.XtextEditor;
import org.eclipse.xtext.ui.editor.syntaxcoloring.HighlightingHelper;
import org.eclipse.xtext.ui.editor.utils.EditorUtils;
import org.apache.log4j.Level;
import com.google.inject.Inject;
import org.wesnoth.Logger;
import org.wesnoth.WesnothPlugin;
import org.wesnoth.ui.Messages;
public class WMLEditor extends XtextEditor
{
@ -74,7 +74,8 @@ public class WMLEditor extends XtextEditor
{
super( );
if( DEBUG )
org.apache.log4j.Logger.getLogger(XtextEditor.class).setLevel(Level.DEBUG);
org.apache.log4j.Logger.getLogger( XtextEditor.class ).setLevel(
Level.DEBUG );
// activate the wesnoth plugin
WesnothPlugin.getDefault( );
}
@ -95,11 +96,12 @@ public class WMLEditor extends XtextEditor
{
if( ( obj instanceof XtextEditor ) == false )
return false;
if (getEditorInput() == null ||
((XtextEditor)obj).getEditorInput() == null)
if( getEditorInput( ) == null
|| ( ( XtextEditor ) obj ).getEditorInput( ) == null )
return false;
java.net.URI u1 = ( ( IURIEditorInput ) getEditorInput( ) ).getURI( );
java.net.URI u2 = ((IURIEditorInput)((XtextEditor)obj).getEditorInput()).getURI();
java.net.URI u2 = ( ( IURIEditorInput ) ( ( XtextEditor ) obj )
.getEditorInput( ) ).getURI( );
if( u1 == null || u2 == null )
return false;
return u1.toString( ).equals( u2.toString( ) );
@ -108,6 +110,7 @@ public class WMLEditor extends XtextEditor
/**
* Gets current edited file.
*
* @return An IFile instance
*/
public static IFile getActiveEditorFile( )
@ -117,7 +120,9 @@ public class WMLEditor extends XtextEditor
/**
* Gets the edited file from the specified editor
* @param editor The editor to get the file from
*
* @param editor
* The editor to get the file from
* @return An IFile instance
*/
public static IFile getEditorFile( XtextEditor editor )
@ -140,14 +145,17 @@ public class WMLEditor extends XtextEditor
* such license is available at www.eclipse.org.
*/
private void createLink(IProject project, IFile linkFile, java.net.URI uri) throws CoreException {
private void createLink( IProject project, IFile linkFile, java.net.URI uri )
throws CoreException
{
IPath path = linkFile.getFullPath( );
IPath folders = path.removeLastSegments( 1 ).removeFirstSegments( 1 );
IPath checkPath = Path.ROOT;
int segmentCount = folders.segmentCount( );
for( int i = 0; i < segmentCount; i++ ) {
checkPath = checkPath.addTrailingSeparator().append(folders.segment(i));
checkPath = checkPath.addTrailingSeparator( ).append(
folders.segment( i ) );
IFolder folder = project.getFolder( checkPath );
if( ! folder.exists( ) )
folder.create( true, true, null );
@ -156,7 +164,8 @@ public class WMLEditor extends XtextEditor
}
@Override
public void dispose() {
public void dispose( )
{
// Unlink the input if it was linked
IEditorInput input = getEditorInput( );
if( input instanceof IFileEditorInput ) {
@ -164,13 +173,15 @@ public class WMLEditor extends XtextEditor
if( file.isLinked( ) ) {
file.getProject( ).getName( ).equals( AUTOLINK_PROJECT_NAME );
try {
// if the editor is disposed because workbench is shutting down, it is NOT a good
// if the editor is disposed because workbench is shutting
// down, it is NOT a good
// idea to delete the link
if(PlatformUI.isWorkbenchRunning() && !PlatformUI.getWorkbench().isClosing())
if( PlatformUI.isWorkbenchRunning( )
&& ! PlatformUI.getWorkbench( ).isClosing( ) )
file.delete( true, null );
}
catch(CoreException e) {
// Nothing to do really, it will be recreated/refreshed later if ever used - some garbage may stay behind...
} catch( CoreException e ) {
// Nothing to do really, it will be recreated/refreshed
// later if ever used - some garbage may stay behind...
Logger.getInstance( ).logException( e );
}
}
@ -179,57 +190,75 @@ public class WMLEditor extends XtextEditor
}
/**
* Overridden to allow customization of editor context menu via injected handler
* Overridden to allow customization of editor context menu via injected
* handler
*
* @see org.eclipse.ui.editors.text.TextEditor#editorContextMenuAboutToShow(org.eclipse.jface.action.IMenuManager)
*/
@Override
protected void editorContextMenuAboutToShow(IMenuManager menu) {
protected void editorContextMenuAboutToShow( IMenuManager menu )
{
super.editorContextMenuAboutToShow( menu );
editorCustomizer.customizeEditorContextMenu( menu );
}
private IFile getWorkspaceFile(IFileStore fileStore) {
IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
IFile[] files = workspaceRoot.findFilesForLocationURI(fileStore.toURI());
private IFile getWorkspaceFile( IFileStore fileStore )
{
IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace( )
.getRoot( );
IFile[] files = workspaceRoot.findFilesForLocationURI( fileStore
.toURI( ) );
if( files != null && files.length == 1 )
return files[0];
return null;
}
/**
* Translates an incoming IEditorInput being an FilestoreEditorInput, or IURIEditorInput
* Translates an incoming IEditorInput being an FilestoreEditorInput, or
* IURIEditorInput
* that is not also a IFileEditorInput.
* FilestoreEditorInput is used when opening external files in an IDE environment.
* The result is that the regular XtextEditor gets an IEFSEditorInput which is also an
* FilestoreEditorInput is used when opening external files in an IDE
* environment.
* The result is that the regular XtextEditor gets an IEFSEditorInput which
* is also an
* IStorageEditorInput.
*/
@Override
public void init(IEditorSite site, IEditorInput input) throws PartInitException {
public void init( IEditorSite site, IEditorInput input )
throws PartInitException
{
// THE ISSUE HERE:
// In the IDE, the File Open Dialog (and elsewhere) uses a FilestoreEditorInput class
// In the IDE, the File Open Dialog (and elsewhere) uses a
// FilestoreEditorInput class
// which is an IDE specific implementation.
// The state at this point:
// 1. When creating a file, the IEditorInput is an IURIEditorInput
// 2. The only (non IDE specific) interface implemented by FilestoreEditorInput is IURIEditorInput
// 2. The only (non IDE specific) interface implemented by
// FilestoreEditorInput is IURIEditorInput
// 3. The creation of a file is however also an IFileEditorInput
//
// Remedy:
if(input instanceof IURIEditorInput && !(input instanceof IFileEditorInput)) {
if( input instanceof IURIEditorInput
&& ! ( input instanceof IFileEditorInput ) ) {
java.net.URI uri = ( ( IURIEditorInput ) input ).getURI( );
String name = ( ( IURIEditorInput ) input ).getName( );
// Check if this is linkable input
if( uri.getScheme( ).equals( "file" ) ) { //$NON-NLS-1$
IFile linkedFile = obtainLink( uri );
IFileEditorInput linkedInput = new LinkedFileEditorInput(linkedFile);
IFileEditorInput linkedInput = new LinkedFileEditorInput(
linkedFile );
super.init( site, linkedInput );
}
else {
// use EMF URI (readonly) input - will open without validation though...
// (Could be improved, i.e. perform a download, make readonly, and keep in project,
// or stored in tmp, and processed as the other linked resources..
URIEditorInput uriInput = new URIEditorInput(URI.createURI(uri.toString()), name);
// use EMF URI (readonly) input - will open without validation
// though...
// (Could be improved, i.e. perform a download, make readonly,
// and keep in project,
// or stored in tmp, and processed as the other linked
// resources..
URIEditorInput uriInput = new URIEditorInput(
URI.createURI( uri.toString( ) ), name );
super.init( site, uriInput );
return;
}
@ -244,7 +273,8 @@ public class WMLEditor extends XtextEditor
* @param uri
* @return
*/
private IFile obtainLink(java.net.URI uri) {
private IFile obtainLink( java.net.URI uri )
{
try {
IWorkspace ws = ResourcesPlugin.getWorkspace( );
// get, or create project if non existing
@ -260,45 +290,53 @@ public class WMLEditor extends XtextEditor
}
if( newProject )
project.setDefaultCharset(ENCODING_UTF8, new NullProgressMonitor());
project.setDefaultCharset( ENCODING_UTF8,
new NullProgressMonitor( ) );
// path in project that is the same as the external file's path
IFile linkFile = project.getFile( uri.getPath( ) );
if( linkFile.exists( ) )
linkFile.refreshLocal(1, null); // don't know if needed (or should be avoided...)
linkFile.refreshLocal( 1, null ); // don't know if needed (or
// should be avoided...)
else {
// create the link
createLink( project, linkFile, uri );
// linkFile.createLink(uri, IResource.ALLOW_MISSING_LOCAL, null);
// linkFile.createLink(uri, IResource.ALLOW_MISSING_LOCAL,
// null);
}
return linkFile;
// IPath location = new Path(name);
// IFile file = project.getFile(location.lastSegment());
// file.createLink(location, IResource.NONE, null);
}
catch(CoreException e) {
} catch( CoreException e ) {
throw new WrappedException( e );
}
}
// SaveAs support for linked files - saves them on local disc, not to workspace if file is in special
// SaveAs support for linked files - saves them on local disc, not to
// workspace if file is in special
// hidden external file link project.
@Override
protected void performSaveAs(IProgressMonitor progressMonitor) {
protected void performSaveAs( IProgressMonitor progressMonitor )
{
Shell shell = getSite( ).getShell( );
final IEditorInput input = getEditorInput( );
// Customize save as if the file is linked, and it is in the special external link project
// Customize save as if the file is linked, and it is in the special
// external link project
//
if(input instanceof IFileEditorInput && ((IFileEditorInput) input).getFile().isLinked() &&
((IFileEditorInput) input).getFile().getProject().getName().equals(AUTOLINK_PROJECT_NAME)) {
if( input instanceof IFileEditorInput
&& ( ( IFileEditorInput ) input ).getFile( ).isLinked( )
&& ( ( IFileEditorInput ) input ).getFile( ).getProject( )
.getName( ).equals( AUTOLINK_PROJECT_NAME ) ) {
final IEditorInput newInput;
IDocumentProvider provider = getDocumentProvider( );
FileDialog dialog = new FileDialog( shell, SWT.SAVE );
IPath oldPath = URIUtil.toPath(((IURIEditorInput) input).getURI());
IPath oldPath = URIUtil.toPath( ( ( IURIEditorInput ) input )
.getURI( ) );
if( oldPath != null ) {
dialog.setFileName( oldPath.lastSegment( ) );
dialog.setFilterPath( oldPath.toOSString( ) );
@ -315,9 +353,12 @@ public class WMLEditor extends XtextEditor
// Check whether file exists and if so, confirm overwrite
final File localFile = new File( path );
if( localFile.exists( ) ) {
MessageDialog overwriteDialog = new MessageDialog(shell, Messages.WMLEditor_0, null, path +
Messages.WMLEditor_1, MessageDialog.WARNING, new String[] {
IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL }, 1); // 'No' is the default
MessageDialog overwriteDialog = new MessageDialog( shell,
Messages.WMLEditor_0, null,
path + Messages.WMLEditor_1, MessageDialog.WARNING,
new String[] { IDialogConstants.YES_LABEL,
IDialogConstants.NO_LABEL }, 1 ); // 'No' is the
// default
if( overwriteDialog.open( ) != Window.OK ) {
if( progressMonitor != null ) {
progressMonitor.setCanceled( true );
@ -329,8 +370,7 @@ public class WMLEditor extends XtextEditor
IFileStore fileStore;
try {
fileStore = EFS.getStore( localFile.toURI( ) );
}
catch(CoreException ex) {
} catch( CoreException ex ) {
Logger.getInstance( ).logException( ex );
String title = Messages.WMLEditor_2;
String msg = Messages.WMLEditor_3 + ex.getMessage( );
@ -350,7 +390,8 @@ public class WMLEditor extends XtextEditor
}
if( provider == null ) {
// editor has programmatically been closed while the dialog was open
// editor has programmatically been closed while the dialog was
// open
return;
}
@ -358,11 +399,11 @@ public class WMLEditor extends XtextEditor
try {
provider.aboutToChange( newInput );
provider.saveDocument(progressMonitor, newInput, provider.getDocument(input), true);
provider.saveDocument( progressMonitor, newInput,
provider.getDocument( input ), true );
success = true;
}
catch(CoreException x) {
} catch( CoreException x ) {
Logger.getInstance( ).logException( x );
final IStatus status = x.getStatus( );
if( status == null || status.getSeverity( ) != IStatus.CANCEL ) {
@ -370,8 +411,7 @@ public class WMLEditor extends XtextEditor
String msg = Messages.WMLEditor_5 + x.getMessage( );
MessageDialog.openError( shell, title, msg );
}
}
finally {
} finally {
provider.changed( newInput );
if( success )
setInput( newInput );

View file

@ -8,18 +8,19 @@
*******************************************************************************/
package org.wesnoth.ui.folding;
import com.google.inject.Inject;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.xtext.resource.ILocationInFileProvider;
import org.eclipse.xtext.ui.editor.folding.DefaultFoldingRegionProvider;
import org.eclipse.xtext.ui.editor.folding.IFoldingRegionAcceptor;
import org.eclipse.xtext.util.ITextRegion;
import org.wesnoth.wml.WMLKey;
import org.wesnoth.wml.WMLMacroDefine;
import org.wesnoth.wml.WMLPreprocIF;
import org.wesnoth.wml.WMLTextdomain;
import com.google.inject.Inject;
public class WMLFoldingRegionProvider extends DefaultFoldingRegionProvider
{
@Inject
@ -40,14 +41,17 @@ public class WMLFoldingRegionProvider extends DefaultFoldingRegionProvider
}
@Override
protected void computeObjectFolding( EObject eObject, IFoldingRegionAcceptor<ITextRegion> foldingRegionAcceptor )
protected void computeObjectFolding( EObject eObject,
IFoldingRegionAcceptor< ITextRegion > foldingRegionAcceptor )
{
// copied from "DefaultFoldingRegionProvider
ITextRegion region = locationInFileProvider.getFullTextRegion( eObject );
if( region != null ) {
ITextRegion significant = locationInFileProvider.getSignificantTextRegion(eObject);
ITextRegion significant = locationInFileProvider
.getSignificantTextRegion( eObject );
if( significant == null )
throw new NullPointerException("significant region may not be null");
throw new NullPointerException(
"significant region may not be null" );
int offset = region.getOffset( );
int length = region.getLength( );

View file

@ -13,20 +13,23 @@ import org.eclipse.xtext.ui.label.DefaultDescriptionLabelProvider;
/**
* Provides labels for a IEObjectDescriptions and IResourceDescriptions.
*
* see http://www.eclipse.org/Xtext/documentation/latest/xtext.html#labelProvider
* see
* http://www.eclipse.org/Xtext/documentation/latest/xtext.html#labelProvider
*/
public class WMLDescriptionLabelProvider extends DefaultDescriptionLabelProvider {
public class WMLDescriptionLabelProvider extends
DefaultDescriptionLabelProvider
{
/*
//Labels and icons can be computed like this:
String text(IEObjectDescription ele) {
return "my "+ele.getName();
}
String image(IEObjectDescription ele) {
return ele.getEClass().getName() + ".gif";
}
* //Labels and icons can be computed like this:
*
* String text(IEObjectDescription ele) {
* return "my "+ele.getName();
* }
*
* String image(IEObjectDescription ele) {
* return ele.getEClass().getName() + ".gif";
* }
*/
}

View file

@ -8,6 +8,8 @@
*******************************************************************************/
package org.wesnoth.ui.labeling;
import com.google.inject.Inject;
import java.util.Locale;
import org.eclipse.emf.ecore.EClass;
@ -16,19 +18,19 @@ import org.eclipse.swt.graphics.Image;
import org.eclipse.xtext.ui.editor.model.XtextDocument;
import org.eclipse.xtext.ui.label.DefaultEObjectLabelProvider;
import com.google.inject.Inject;
/**
* Provides labels for a EObjects.
*
* see http://www.eclipse.org/Xtext/documentation/latest/xtext.html#labelProvider
* see
* http://www.eclipse.org/Xtext/documentation/latest/xtext.html#labelProvider
*/
public class WMLLabelProvider extends DefaultEObjectLabelProvider
{
private static WMLLabelProvider instance_;
@Inject
public WMLLabelProvider(AdapterFactoryLabelProvider delegate) {
public WMLLabelProvider( AdapterFactoryLabelProvider delegate )
{
super( delegate );
instance_ = this;
}
@ -36,12 +38,12 @@ public class WMLLabelProvider extends DefaultEObjectLabelProvider
@Override
protected Object doGetImage( Object element )
{
if (element instanceof EClass)
{
return ((EClass)element).getName().toLowerCase(Locale.ENGLISH) + ".png"; //$NON-NLS-1$
if( element instanceof EClass ) {
return ( ( EClass ) element ).getName( ).toLowerCase(
Locale.ENGLISH )
+ ".png"; //$NON-NLS-1$
}
else if (element instanceof String)
{
else if( element instanceof String ) {
return element;
}
return super.doGetImage( element );

View file

@ -17,22 +17,29 @@ public interface IWMLDocProvider
{
/**
* Gets the title of the wmldoc dialog
*
* @return
*/
public String getTitle( );
/**
* Gets the text to be written in the info statusbar
*
* @return
*/
public String getInfoText( );
/**
* Gets the contents to be written into the
* styledtext control of the wmldoc dialog
*
* @return
*/
public String getContents( );
/**
* Gets an array of StyleRange used to style the contents
*
* @return
*/
public StyleRange[] getStyleRanges( );

View file

@ -8,15 +8,6 @@
*******************************************************************************/
package org.wesnoth.ui.labeling.wmldoc;
import org.wesnoth.Logger;
import org.wesnoth.installs.WesnothInstallsUtils;
import org.wesnoth.preprocessor.Define;
import org.wesnoth.projects.ProjectUtils;
import org.wesnoth.ui.editor.WMLEditor;
import org.wesnoth.utils.WMLUtils;
import org.wesnoth.wml.WMLMacroCall;
import org.wesnoth.wml.WMLTag;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
@ -29,6 +20,15 @@ import org.eclipse.xtext.ui.editor.XtextEditor;
import org.eclipse.xtext.ui.editor.utils.EditorUtils;
import org.eclipse.xtext.util.concurrent.IUnitOfWork;
import org.wesnoth.Logger;
import org.wesnoth.installs.WesnothInstallsUtils;
import org.wesnoth.preprocessor.Define;
import org.wesnoth.projects.ProjectUtils;
import org.wesnoth.ui.editor.WMLEditor;
import org.wesnoth.utils.WMLUtils;
import org.wesnoth.wml.WMLMacroCall;
import org.wesnoth.wml.WMLTag;
/**
* A handler that handles pressing F2 on a resource in the editor
*/
@ -36,53 +36,62 @@ public class WMLDocHandler extends AbstractHandler
{
public Object execute( ExecutionEvent event ) throws ExecutionException
{
try
{
try {
final XtextEditor editor = EditorUtils.getActiveXtextEditor( event );
final IFile editedFile = WMLEditor.getEditorFile( editor );
final String installName = WesnothInstallsUtils.getInstallNameForResource( editedFile );
final String installName = WesnothInstallsUtils
.getInstallNameForResource( editedFile );
editor.getDocument().readOnly(new IUnitOfWork.Void<XtextResource>()
{
editor.getDocument( ).readOnly(
new IUnitOfWork.Void< XtextResource >( ) {
@Override
public void process(XtextResource resource) throws Exception
public void process( XtextResource resource )
throws Exception
{
WMLDocInformationPresenter presenter_ = null;
ITextSelection selection = (ITextSelection) editor.getSelectionProvider().getSelection();
Point positionRelative = editor.getInternalSourceViewer().getTextWidget().getLocationAtOffset(selection.getOffset());
Point positionAbsolute = editor.getInternalSourceViewer().getTextWidget().toDisplay(positionRelative);
ITextSelection selection = ( ITextSelection ) editor
.getSelectionProvider( ).getSelection( );
Point positionRelative = editor
.getInternalSourceViewer( )
.getTextWidget( )
.getLocationAtOffset( selection.getOffset( ) );
Point positionAbsolute = editor
.getInternalSourceViewer( ).getTextWidget( )
.toDisplay( positionRelative );
positionAbsolute.y += 20;
EObject grammarElement = WMLUtils.resolveElementAt( resource, selection.getOffset( ) );
EObject grammarElement = WMLUtils.resolveElementAt(
resource, selection.getOffset( ) );
if( grammarElement == null )
return;
if ( grammarElement instanceof WMLMacroCall )
{
if( grammarElement instanceof WMLMacroCall ) {
WMLMacroCall macro = ( WMLMacroCall ) grammarElement;
Define define = ProjectUtils.getCacheForProject(
editedFile.getProject()).getDefines().get(macro.getName());
if (define != null)
{
if (presenter_ == null)
{
Define define = ProjectUtils
.getCacheForProject(
editedFile.getProject( ) )
.getDefines( ).get( macro.getName( ) );
if( define != null ) {
if( presenter_ == null ) {
presenter_ = new WMLDocInformationPresenter(
editor.getSite().getShell(), new WMLDocMacro(define),
editor.getSite( ).getShell( ),
new WMLDocMacro( define ),
positionAbsolute );
presenter_.create( );
}
presenter_.open( );
}
}
else if ( grammarElement instanceof WMLTag)
{
if (presenter_ == null)
{
else if( grammarElement instanceof WMLTag ) {
if( presenter_ == null ) {
presenter_ = new WMLDocInformationPresenter(
editor.getSite( ).getShell( ),
new WMLDocTag( editedFile, installName,
( ( WMLTag ) grammarElement ).getName() ),
new WMLDocTag(
editedFile,
installName,
( ( WMLTag ) grammarElement )
.getName( ) ),
positionAbsolute );
presenter_.create( );
}
@ -90,8 +99,7 @@ public class WMLDocHandler extends AbstractHandler
}
}
} );
}
catch (Exception e) {
} catch( Exception e ) {
Logger.getInstance( ).logException( e );
}
return null;

View file

@ -27,12 +27,12 @@ public class WMLDocInformationPresenter extends PopupDialog
/**
* Creates a new WMLDocumentation information presenter
*/
public WMLDocInformationPresenter(Shell parent, IWMLDocProvider docProvider,
Point bounds)
public WMLDocInformationPresenter( Shell parent,
IWMLDocProvider docProvider, Point bounds )
{
super(parent, PopupDialog.INFOPOPUPRESIZE_SHELLSTYLE, true, true, true,
false, false, docProvider.getTitle( ),
docProvider.getInfoText( ) );
super( parent, PopupDialog.INFOPOPUPRESIZE_SHELLSTYLE, true, true,
true, false, false, docProvider.getTitle( ), docProvider
.getInfoText( ) );
bounds_ = bounds;
currentDocProvider_ = docProvider;
@ -42,8 +42,10 @@ public class WMLDocInformationPresenter extends PopupDialog
protected Control createDialogArea( Composite parent )
{
panel_ = new Composite( parent, SWT.None );
panel_.setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_INFO_BACKGROUND));
panel_.setForeground(parent.getDisplay().getSystemColor(SWT.COLOR_INFO_FOREGROUND));
panel_.setBackground( parent.getDisplay( ).getSystemColor(
SWT.COLOR_INFO_BACKGROUND ) );
panel_.setForeground( parent.getDisplay( ).getSystemColor(
SWT.COLOR_INFO_FOREGROUND ) );
GridLayout grid = new GridLayout( );
grid.numColumns = 5;
@ -59,7 +61,8 @@ public class WMLDocInformationPresenter extends PopupDialog
return panel_;
}
private GridData createDefaultGridData(int columnspan) {
private GridData createDefaultGridData( int columnspan )
{
GridData gd = new GridData( );
gd.horizontalSpan = columnspan;
gd.verticalAlignment = SWT.BEGINNING;
@ -74,4 +77,3 @@ public class WMLDocInformationPresenter extends PopupDialog
return bounds_;
}
}

View file

@ -11,13 +11,13 @@ package org.wesnoth.ui.labeling.wmldoc;
import java.util.ArrayList;
import java.util.List;
import org.wesnoth.preprocessor.Define;
import org.wesnoth.ui.Messages;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.widgets.Display;
import org.wesnoth.preprocessor.Define;
import org.wesnoth.ui.Messages;
/**
* Provides WMLDoc info for a macro
@ -53,16 +53,14 @@ public class WMLDocMacro implements IWMLDocProvider
content.append( macro_.getValue( ) );
content.append( '\n' );
if (macro_.getArguments().isEmpty() == false)
{
if( macro_.getArguments( ).isEmpty( ) == false ) {
int len = content.length( ) - 1;
content.append( Messages.WMLDocMacro_2 );
addStyleRange( len, content.length( ) - len - 1, SWT.BOLD );
len = content.length( ) - 1;
for(String arg : macro_.getArguments())
{
for( String arg: macro_.getArguments( ) ) {
content.append( '\t' + arg + '\n' );
}
addStyleRange( len, content.length( ) - len - 1, SWT.ITALIC );
@ -75,15 +73,16 @@ public class WMLDocMacro implements IWMLDocProvider
/**
* Adds a style range to current list
*
* @param offset
* @param length
* @param style
*/
private void addStyleRange( int offset, int length, int style )
{
styleRanges_.add(new StyleRange(offset, length,
Display.getDefault().getSystemColor(SWT.COLOR_INFO_FOREGROUND),
Display.getDefault().getSystemColor(SWT.COLOR_INFO_BACKGROUND),
styleRanges_.add( new StyleRange( offset, length, Display.getDefault( )
.getSystemColor( SWT.COLOR_INFO_FOREGROUND ), Display
.getDefault( ).getSystemColor( SWT.COLOR_INFO_BACKGROUND ),
style ) );
}
@ -107,6 +106,7 @@ public class WMLDocMacro implements IWMLDocProvider
/**
* Gets the associated macro
*
* @return
*/
public Define getMacro( )
@ -118,6 +118,7 @@ public class WMLDocMacro implements IWMLDocProvider
{
if( macro_.getLocation( ) == null )
return null;
return "Defined in: " + macro_.getLocation( ) + " : " + macro_.getLineNum( );
return "Defined in: " + macro_.getLocation( ) + " : "
+ macro_.getLineNum( );
}
}

View file

@ -11,17 +11,17 @@ package org.wesnoth.ui.labeling.wmldoc;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IFile;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.widgets.Display;
import org.wesnoth.projects.ProjectUtils;
import org.wesnoth.schema.SchemaParser;
import org.wesnoth.ui.Messages;
import org.wesnoth.wml.WMLTag;
import org.wesnoth.wml.WmlFactory2;
import org.eclipse.core.resources.IFile;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.widgets.Display;
/**
* Displays wml doc for a tag [tag] or [/tag]
*/
@ -40,8 +40,8 @@ public class WMLDocTag implements IWMLDocProvider
// try to get it from the Project Cache ( lua parsed ones )
if( tag_ == null ) {
tag_ = ProjectUtils.getCacheForProject( currentFile.getProject( ) ).
getWMLTags( ).get( name );
tag_ = ProjectUtils.getCacheForProject( currentFile.getProject( ) )
.getWMLTags( ).get( name );
}
// Create a default one
@ -86,7 +86,10 @@ public class WMLDocTag implements IWMLDocProvider
*/
private void addStyleRange( int offset, int length, int style )
{
styleRanges_.add( new StyleRange( offset, length, Display.getDefault( ).getSystemColor( SWT.COLOR_INFO_FOREGROUND ), Display.getDefault( ).getSystemColor( SWT.COLOR_INFO_BACKGROUND ), style ) );
styleRanges_.add( new StyleRange( offset, length, Display.getDefault( )
.getSystemColor( SWT.COLOR_INFO_FOREGROUND ), Display
.getDefault( ).getSystemColor( SWT.COLOR_INFO_BACKGROUND ),
style ) );
}
public String getTitle( )

View file

@ -13,6 +13,7 @@ import org.eclipse.jface.text.IDocument;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.xtext.ui.editor.hyperlinking.XtextHyperlink;
import org.wesnoth.utils.EditorUtils;
@ -29,19 +30,16 @@ public class FileLocationOpenerHyperlink extends XtextHyperlink
public void open( )
{
IEditorPart part = EditorUtils.openEditor( filePath_ );
if (part != null)
{
if( part != null ) {
ITextEditor editor = EditorUtils.getTextEditor( part );
IDocument doc = editor.getDocumentProvider().
getDocument(editor.getEditorInput());
IDocument doc = editor.getDocumentProvider( ).getDocument(
editor.getEditorInput( ) );
int offset = 0;
try
{
try {
// compute offset based on linenum_
offset = doc.getLineOffset( linenum_ );
}
catch (BadLocationException e) {
} catch( BadLocationException e ) {
// ignore
}
EditorUtils.getTextEditor( part ).selectAndReveal( offset, 0 );
@ -52,14 +50,17 @@ public class FileLocationOpenerHyperlink extends XtextHyperlink
{
linenum_ = linenum;
}
public int getLinenumber( )
{
return linenum_;
}
public void setFilePath( String filePath )
{
filePath_ = filePath;
}
public String getFilePath( )
{
return filePath_;

View file

@ -14,6 +14,7 @@ import java.io.IOException;
import org.eclipse.swt.SWT;
import org.eclipse.xtext.ui.editor.hyperlinking.XtextHyperlink;
import org.wesnoth.Logger;
import org.wesnoth.templates.TemplateProvider;
import org.wesnoth.utils.GUIUtils;
@ -37,9 +38,9 @@ public class MapOpenerHyperlink extends XtextHyperlink
@Override
public void open( )
{
if ( !new File(location_).exists() )
{
if ( GUIUtils.showMessageBox(
if( ! new File( location_ ).exists( ) ) {
if( GUIUtils
.showMessageBox(
"The map doesn't exist. Do you want to create a default one and open that?",
SWT.YES | SWT.NO ) == SWT.NO )
return;
@ -48,10 +49,10 @@ public class MapOpenerHyperlink extends XtextHyperlink
FileWriter writer;
try {
writer = new FileWriter( location_ );
writer.write( TemplateProvider.getInstance( ).getTemplate( "map" ) );
writer.write( TemplateProvider.getInstance( ).getTemplate(
"map" ) );
writer.close( );
}
catch ( IOException e ) {
} catch( IOException e ) {
Logger.getInstance( ).logException( e );
}
}

View file

@ -8,6 +8,15 @@
*******************************************************************************/
package org.wesnoth.ui.navigation;
import org.eclipse.core.resources.IFile;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.jface.text.Region;
import org.eclipse.xtext.nodemodel.ICompositeNode;
import org.eclipse.xtext.nodemodel.util.NodeModelUtils;
import org.eclipse.xtext.resource.XtextResource;
import org.eclipse.xtext.ui.editor.hyperlinking.HyperlinkHelper;
import org.eclipse.xtext.ui.editor.hyperlinking.IHyperlinkAcceptor;
import org.wesnoth.Logger;
import org.wesnoth.installs.WesnothInstallsUtils;
import org.wesnoth.preferences.Preferences;
@ -19,15 +28,6 @@ import org.wesnoth.utils.WMLUtils;
import org.wesnoth.wml.WMLKey;
import org.wesnoth.wml.WMLMacroCall;
import org.eclipse.core.resources.IFile;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.jface.text.Region;
import org.eclipse.xtext.nodemodel.ICompositeNode;
import org.eclipse.xtext.nodemodel.util.NodeModelUtils;
import org.eclipse.xtext.resource.XtextResource;
import org.eclipse.xtext.ui.editor.hyperlinking.HyperlinkHelper;
import org.eclipse.xtext.ui.editor.hyperlinking.IHyperlinkAcceptor;
public class WMLHyperlinkHelper extends HyperlinkHelper
{
@Override
@ -43,11 +43,13 @@ public class WMLHyperlinkHelper extends HyperlinkHelper
IFile file = WMLEditor.getActiveEditorFile( );
if( file == null ) {
Logger.getInstance().logError( "FATAL! file is null (and it shouldn't) ");
Logger.getInstance( ).logError(
"FATAL! file is null (and it shouldn't) " );
return;
}
Paths paths = Preferences.getPaths( WesnothInstallsUtils.getInstallNameForResource( file ) );
Paths paths = Preferences.getPaths( WesnothInstallsUtils
.getInstallNameForResource( file ) );
ICompositeNode node = NodeModelUtils.getNode( object );
@ -57,11 +59,17 @@ public class WMLHyperlinkHelper extends HyperlinkHelper
/**
* Creates a hyperlink for opening the macro definition
* @param paths The paths variable for the current install
* @param file The current edited file
* @param object The current object
* @param acceptor The hyperlink acceptor
* @param node The node model representation of the macro
*
* @param paths
* The paths variable for the current install
* @param file
* The current edited file
* @param object
* The current object
* @param acceptor
* The hyperlink acceptor
* @param node
* The node model representation of the macro
*/
private void createMacroHyperlink( Paths paths, IFile file, EObject object,
IHyperlinkAcceptor acceptor, ICompositeNode node )
@ -72,10 +80,9 @@ public class WMLHyperlinkHelper extends HyperlinkHelper
WMLMacroCall macro = ( WMLMacroCall ) object;
// get the define for the macro
Define define = ProjectUtils.getCacheForProject(
file.getProject() ).getDefines().get( macro.getName() );
if ( define == null ||
define.getLocation( ).length( ) <= 2 )
Define define = ProjectUtils.getCacheForProject( file.getProject( ) )
.getDefines( ).get( macro.getName( ) );
if( define == null || define.getLocation( ).length( ) <= 2 )
return;
String filePath = define.getLocation( );
@ -83,13 +90,15 @@ public class WMLHyperlinkHelper extends HyperlinkHelper
if( filePath.charAt( 0 ) == '~' ) {
// expand the '~' character to user data dir
filePath = filePath.replaceFirst( "~", paths.getUserDataDir( ) );
} else if ( filePath.startsWith( "core/" ) ) {
}
else if( filePath.startsWith( "core/" ) ) {
// expand the data/core path
filePath = filePath.replaceFirst( "core/", paths.getCoreDir( ) );
}
FileLocationOpenerHyperlink macroTarget = new FileLocationOpenerHyperlink( );
macroTarget.setHyperlinkRegion( new Region( node.getOffset( ), node.getLength( ) ) );
macroTarget.setHyperlinkRegion( new Region( node.getOffset( ), node
.getLength( ) ) );
macroTarget.setFilePath( filePath );
macroTarget.setLinenumber( define.getLineNum( ) );
acceptor.accept( macroTarget );
@ -97,18 +106,23 @@ public class WMLHyperlinkHelper extends HyperlinkHelper
/**
* Creates a hyperlink for opening the map ( if applying )
* @param paths The paths variable for the current install
* @param object The current object
* @param acceptor The hyperlink acceptor
* @param node The node model representation of the macro
*
* @param paths
* The paths variable for the current install
* @param object
* The current object
* @param acceptor
* The hyperlink acceptor
* @param node
* The node model representation of the macro
*/
private void createMapHyperlink( Paths paths, EObject object,
IHyperlinkAcceptor acceptor, ICompositeNode node )
{
EObject container = object.eContainer( );
if ( !( container instanceof WMLKey ) ||
!( ( WMLKey ) container ).getName( ).equals( "map_data" ) )
if( ! ( container instanceof WMLKey )
|| ! ( ( WMLKey ) container ).getName( ).equals( "map_data" ) )
return;
String mapLocation = node.getText( );
@ -141,14 +155,18 @@ public class WMLHyperlinkHelper extends HyperlinkHelper
if( mapLocation.charAt( 0 ) == '~' ) {
// expand the '~' character to user data dir
mapLocation = mapLocation.replaceFirst( "~", paths.getUserDataDir( ) );
} else if ( mapLocation.startsWith( "campaigns/" ) ) {
mapLocation = mapLocation
.replaceFirst( "~", paths.getUserDataDir( ) );
}
else if( mapLocation.startsWith( "campaigns/" ) ) {
// expand the campaigns path
mapLocation = mapLocation.replaceFirst( "campaigns/", paths.getCampaignDir( ) );
mapLocation = mapLocation.replaceFirst( "campaigns/",
paths.getCampaignDir( ) );
}
MapOpenerHyperlink hyperlink = new MapOpenerHyperlink( );
hyperlink.setHyperlinkRegion( new Region(node.getOffset( ), node.getLength( ) ) );
hyperlink.setHyperlinkRegion( new Region( node.getOffset( ), node
.getLength( ) ) );
hyperlink.setLocation( mapLocation );
acceptor.accept( hyperlink );
}

View file

@ -3,15 +3,16 @@
*/
package org.wesnoth.ui.outline;
import org.wesnoth.wml.WMLRoot;
import org.eclipse.xtext.ui.editor.outline.impl.DefaultOutlineTreeProvider;
import org.wesnoth.wml.WMLRoot;
/**
* customization of the default outline structure
*
*/
public class WMLOutlineTreeProvider extends DefaultOutlineTreeProvider {
public class WMLOutlineTreeProvider extends DefaultOutlineTreeProvider
{
@Override
protected Object _text( Object modelElement )
{

View file

@ -10,12 +10,16 @@ package org.wesnoth.ui.quickfix;
import org.eclipse.xtext.ui.editor.quickfix.DefaultQuickfixProvider;
public class WMLQuickfixProvider extends DefaultQuickfixProvider {
public class WMLQuickfixProvider extends DefaultQuickfixProvider
{
// @Fix(MyJavaValidator.INVALID_NAME)
// public void capitalizeName(final Issue issue, IssueResolutionAcceptor acceptor) {
// acceptor.accept(issue, "Capitalize name", "Capitalize the name.", "upcase.png", new IModification() {
// public void apply(IModificationContext context) throws BadLocationException {
// public void capitalizeName(final Issue issue, IssueResolutionAcceptor
// acceptor) {
// acceptor.accept(issue, "Capitalize name", "Capitalize the name.",
// "upcase.png", new IModification() {
// public void apply(IModificationContext context) throws
// BadLocationException {
// IXtextDocument xtextDocument = context.getXtextDocument();
// String firstLetter = xtextDocument.get(issue.getOffset(), 1);
// xtextDocument.replace(issue.getOffset(), 1, firstLetter.toUpperCase());

View file

@ -10,21 +10,19 @@ package org.wesnoth.ui.syntax;
import org.eclipse.xtext.ui.editor.syntaxcoloring.DefaultAntlrTokenToAttributeIdMapper;
public class WMLAntlrTokenToAttributeIdMapper extends DefaultAntlrTokenToAttributeIdMapper
public class WMLAntlrTokenToAttributeIdMapper extends
DefaultAntlrTokenToAttributeIdMapper
{
@Override
protected String calculateId( String tokenName, int tokenType )
{
if ( tokenName.equals( "'+'" ) ||
tokenName.equals("'['") ||
tokenName.equals("'[/'") ||
tokenName.equals("']'")) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
if( tokenName.equals( "'+'" ) || tokenName.equals( "'['" )
|| tokenName.equals( "'[/'" ) || tokenName.equals( "']'" ) ) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
{
return WMLHighlightingConfiguration.RULE_WML_TAG;
}
if ( tokenName.equals( "'~'" ) ||
tokenName.equals("'{'") ||
tokenName.equals("'}'") ) //$NON-NLS-1$ //$NON-NLS-2$
if( tokenName.equals( "'~'" ) || tokenName.equals( "'{'" )
|| tokenName.equals( "'}'" ) ) //$NON-NLS-1$ //$NON-NLS-2$
{
return WMLHighlightingConfiguration.RULE_WML_MACRO_CALL;
}

View file

@ -10,10 +10,6 @@ package org.wesnoth.ui.syntax;
import java.util.Iterator;
import org.wesnoth.ui.editor.WMLEditor;
import org.wesnoth.utils.WMLUtils;
import org.wesnoth.wml.WMLTag;
import org.eclipse.emf.common.notify.Adapter;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.jface.text.IDocument;
@ -24,6 +20,10 @@ import org.eclipse.xtext.ui.editor.model.XtextDocument;
import org.eclipse.xtext.ui.editor.utils.EditorUtils;
import org.eclipse.xtext.util.concurrent.IUnitOfWork;
import org.wesnoth.ui.editor.WMLEditor;
import org.wesnoth.utils.WMLUtils;
import org.wesnoth.wml.WMLTag;
public class WMLCharacterPairMatcher extends DefaultCharacterPairMatcher
{
private WMLTag currentTag_;
@ -42,15 +42,18 @@ public class WMLCharacterPairMatcher extends DefaultCharacterPairMatcher
++matchCnt;
IRegion region = super.match( doc, offset );
if ( region == null && doc instanceof XtextDocument &&
doc.getLength( ) > 0 ) {
if( region == null && doc instanceof XtextDocument
&& doc.getLength( ) > 0 ) {
if( matchCnt == 2 ) {
matchCnt = 0;
} else {
( ( XtextDocument ) doc ).readOnly( new IUnitOfWork<Boolean, XtextResource>(){
}
else {
( ( XtextDocument ) doc )
.readOnly( new IUnitOfWork< Boolean, XtextResource >( ) {
@Override
public Boolean exec( XtextResource state ) throws Exception
public Boolean exec( XtextResource state )
throws Exception
{
computeMatchingRegion( state, offset );
return true;
@ -58,18 +61,22 @@ public class WMLCharacterPairMatcher extends DefaultCharacterPairMatcher
} );
// refresh the highlighting
WMLEditor currentEditor = ( WMLEditor ) EditorUtils.getActiveXtextEditor( );
if ( currentEditor != null &&
currentEditor.getHighlightingHelper( ) != null &&
currentEditor.getHighlightingHelper( ).getReconciler( ) != null )
currentEditor.getHighlightingHelper( ).getReconciler( ).refresh( );
WMLEditor currentEditor = ( WMLEditor ) EditorUtils
.getActiveXtextEditor( );
if( currentEditor != null
&& currentEditor.getHighlightingHelper( ) != null
&& currentEditor.getHighlightingHelper( )
.getReconciler( ) != null )
currentEditor.getHighlightingHelper( ).getReconciler( )
.refresh( );
}
}
return region;
}
public synchronized void computeMatchingRegion(XtextResource state, int offset)
public synchronized void computeMatchingRegion( XtextResource state,
int offset )
{
EObject object = WMLUtils.resolveElementAt( state, offset );
@ -89,9 +96,11 @@ public class WMLCharacterPairMatcher extends DefaultCharacterPairMatcher
}
}
state.eAdapters( ).add( new WMLSyntaxColoringAdapter(
state.eAdapters( )
.add( new WMLSyntaxColoringAdapter(
WMLHighlightingConfiguration.RULE_MATCH_TAG, object ) );
} else {
}
else {
// nothing new selected, just remove current adapter
Iterator< Adapter > itor = state.eAdapters( ).iterator( );
while( itor.hasNext( ) ) {

View file

@ -13,9 +13,11 @@ import org.eclipse.swt.graphics.RGB;
import org.eclipse.xtext.ui.editor.syntaxcoloring.DefaultHighlightingConfiguration;
import org.eclipse.xtext.ui.editor.syntaxcoloring.IHighlightingConfigurationAcceptor;
import org.eclipse.xtext.ui.editor.utils.TextStyle;
import org.wesnoth.ui.Messages;
public class WMLHighlightingConfiguration extends DefaultHighlightingConfiguration
public class WMLHighlightingConfiguration extends
DefaultHighlightingConfiguration
{
public static final String RULE_WML_TAG = "wmlTag"; //$NON-NLS-1$
public static final String RULE_WML_KEY = "wmlKey"; //$NON-NLS-1$
@ -31,17 +33,23 @@ public class WMLHighlightingConfiguration extends DefaultHighlightingConfigurati
public void configure( IHighlightingConfigurationAcceptor acceptor )
{
super.configure( acceptor );
acceptor.acceptDefaultHighlighting(RULE_WML_TAG, Messages.WMLHighlightingConfiguration_7, tagTextStyle());
acceptor.acceptDefaultHighlighting(RULE_WML_KEY, Messages.WMLHighlightingConfiguration_8, keyTextStyle());
acceptor.acceptDefaultHighlighting(RULE_WML_MACRO_CALL, Messages.WMLHighlightingConfiguration_9, macroTextStyle());
acceptor.acceptDefaultHighlighting( RULE_WML_TAG,
Messages.WMLHighlightingConfiguration_7, tagTextStyle( ) );
acceptor.acceptDefaultHighlighting( RULE_WML_KEY,
Messages.WMLHighlightingConfiguration_8, keyTextStyle( ) );
acceptor.acceptDefaultHighlighting( RULE_WML_MACRO_CALL,
Messages.WMLHighlightingConfiguration_9, macroTextStyle( ) );
acceptor.acceptDefaultHighlighting( RULE_MATCH_TAG,
Messages.WMLHighlightingConfiguration_10, startEndTextStyle( ) );
// preproc
acceptor.acceptDefaultHighlighting(RULE_WML_MACRO_DEFINE, Messages.WMLHighlightingConfiguration_11, preprocTextStyle());
acceptor.acceptDefaultHighlighting(RULE_WML_IF, Messages.WMLHighlightingConfiguration_12, preprocTextStyle());
acceptor.acceptDefaultHighlighting(RULE_WML_TEXTDOMAIN, Messages.WMLHighlightingConfiguration_13, preprocTextStyle());
acceptor.acceptDefaultHighlighting( RULE_WML_MACRO_DEFINE,
Messages.WMLHighlightingConfiguration_11, preprocTextStyle( ) );
acceptor.acceptDefaultHighlighting( RULE_WML_IF,
Messages.WMLHighlightingConfiguration_12, preprocTextStyle( ) );
acceptor.acceptDefaultHighlighting( RULE_WML_TEXTDOMAIN,
Messages.WMLHighlightingConfiguration_13, preprocTextStyle( ) );
}
public TextStyle preprocTextStyle( )

View file

@ -22,6 +22,7 @@ import org.eclipse.xtext.nodemodel.util.NodeModelUtils;
import org.eclipse.xtext.resource.XtextResource;
import org.eclipse.xtext.ui.editor.syntaxcoloring.IHighlightedPositionAcceptor;
import org.eclipse.xtext.ui.editor.syntaxcoloring.ISemanticHighlightingCalculator;
import org.wesnoth.utils.Pair;
import org.wesnoth.wml.WMLKey;
import org.wesnoth.wml.WMLMacroCall;
@ -31,10 +32,12 @@ import org.wesnoth.wml.WMLTag;
import org.wesnoth.wml.WMLTextdomain;
import org.wesnoth.wml.WmlPackage;
public class WMLSemanticHighlightingCalculator implements ISemanticHighlightingCalculator
public class WMLSemanticHighlightingCalculator implements
ISemanticHighlightingCalculator
{
@Override
public void provideHighlightingFor(XtextResource resource, IHighlightedPositionAcceptor acceptor)
public void provideHighlightingFor( XtextResource resource,
IHighlightedPositionAcceptor acceptor )
{
if( resource == null )
return;
@ -47,48 +50,60 @@ public class WMLSemanticHighlightingCalculator implements ISemanticHighlightingC
if( current instanceof WMLTag ) {
toColor.add( Pair.create(
getFirstFeatureNode( current, WmlPackage.Literals.WML_EXPRESSION__NAME ),
getFirstFeatureNode( current,
WmlPackage.Literals.WML_EXPRESSION__NAME ),
WMLHighlightingConfiguration.RULE_WML_TAG ) );
toColor.add( Pair.create(
getFirstFeatureNode( current, WmlPackage.Literals.WML_TAG__END_NAME ),
getFirstFeatureNode( current,
WmlPackage.Literals.WML_TAG__END_NAME ),
WMLHighlightingConfiguration.RULE_WML_TAG ) );
}
else if( current instanceof WMLKey ) {
toColor.add( Pair.create(
getFirstFeatureNode( current, WmlPackage.Literals.WML_EXPRESSION__NAME ),
getFirstFeatureNode( current,
WmlPackage.Literals.WML_EXPRESSION__NAME ),
WMLHighlightingConfiguration.RULE_WML_KEY ) );
}
else if( current instanceof WMLMacroCall ) {
toColor.add( Pair.create(
getFirstFeatureNode( current, WmlPackage.Literals.WML_EXPRESSION__NAME ),
getFirstFeatureNode( current,
WmlPackage.Literals.WML_EXPRESSION__NAME ),
WMLHighlightingConfiguration.RULE_WML_MACRO_CALL ) );
}
else if( current instanceof WMLTextdomain ) {
toColor.add( Pair.create(
getFirstFeatureNode( current, WmlPackage.Literals.WML_EXPRESSION__NAME ),
getFirstFeatureNode( current,
WmlPackage.Literals.WML_EXPRESSION__NAME ),
WMLHighlightingConfiguration.RULE_WML_TEXTDOMAIN ) );
}
else if( current instanceof WMLPreprocIF ) {
toColor.add( Pair.create(
getFirstFeatureNode( current, WmlPackage.Literals.WML_EXPRESSION__NAME ),
getFirstFeatureNode( current,
WmlPackage.Literals.WML_EXPRESSION__NAME ),
WMLHighlightingConfiguration.RULE_WML_IF ) );
toColor.add( Pair.create(
getFirstFeatureNode( current, WmlPackage.Literals.WML_EXPRESSION__NAME ),
getFirstFeatureNode( current,
WmlPackage.Literals.WML_EXPRESSION__NAME ),
WMLHighlightingConfiguration.RULE_WML_IF ) );
}
else if( current instanceof WMLMacroDefine ) {
toColor.add( Pair.create(
getFirstFeatureNode( current, WmlPackage.Literals.WML_EXPRESSION__NAME ),
getFirstFeatureNode( current,
WmlPackage.Literals.WML_EXPRESSION__NAME ),
WMLHighlightingConfiguration.RULE_WML_MACRO_DEFINE ) );
toColor.add( Pair.create(
getFirstFeatureNode( current, WmlPackage.Literals.WML_MACRO_DEFINE__END_NAME ),
toColor.add( Pair
.create(
getFirstFeatureNode(
current,
WmlPackage.Literals.WML_MACRO_DEFINE__END_NAME ),
WMLHighlightingConfiguration.RULE_WML_MACRO_DEFINE ) );
}
// check if we have any information specific information for highlighting
// check if we have any information specific information for
// highlighting
for( Adapter adapter: resource.eAdapters( ) ) {
if( adapter instanceof WMLSyntaxColoringAdapter ) {
WMLSyntaxColoringAdapter wmlAdapter = ( WMLSyntaxColoringAdapter ) adapter;
@ -112,35 +127,51 @@ public class WMLSemanticHighlightingCalculator implements ISemanticHighlightingC
}
/**
* Copied from org.eclipse.xtext.xtext.ui.editor.syntaxcoloring.SemanticHighlightingCalculator
* @param node The node to highlight
* @param id The id of the coloring
* @param acceptor The acceptor to add the node to
* Copied from org.eclipse.xtext.xtext.ui.editor.syntaxcoloring.
* SemanticHighlightingCalculator
*
* @param node
* The node to highlight
* @param id
* The id of the coloring
* @param acceptor
* The acceptor to add the node to
*/
private void highlightNode(INode node, String id, IHighlightedPositionAcceptor acceptor) {
private void highlightNode( INode node, String id,
IHighlightedPositionAcceptor acceptor )
{
if( node == null )
return;
if( node instanceof ILeafNode ) {
acceptor.addPosition( node.getOffset( ), node.getLength( ), id );
} else {
}
else {
for( ILeafNode leaf: node.getLeafNodes( ) ) {
if( ! leaf.isHidden( ) ) {
acceptor.addPosition(leaf.getOffset(), leaf.getLength(), id);
acceptor.addPosition( leaf.getOffset( ), leaf.getLength( ),
id );
}
}
}
}
/**
* Copied from org.eclipse.xtext.xtext.ui.editor.syntaxcoloring.SemanticHighlightingCalculator
* @param semantic The object to search in
* @param feature The feature to search for
* Copied from org.eclipse.xtext.xtext.ui.editor.syntaxcoloring.
* SemanticHighlightingCalculator
*
* @param semantic
* The object to search in
* @param feature
* The feature to search for
* @return Null if there is no feature, or an {@link INode} node
*/
public INode getFirstFeatureNode(EObject semantic, EStructuralFeature feature) {
public INode getFirstFeatureNode( EObject semantic,
EStructuralFeature feature )
{
if( feature == null )
return NodeModelUtils.findActualNodeFor( semantic );
List<INode> nodes = NodeModelUtils.findNodesForFeature(semantic, feature);
List< INode > nodes = NodeModelUtils.findNodesForFeature( semantic,
feature );
if( ! nodes.isEmpty( ) )
return nodes.get( 0 );
return null;

View file

@ -17,7 +17,8 @@ import org.eclipse.emf.ecore.EObject;
public class WMLSyntaxColoringAdapter extends AdapterImpl
{
/**
* A color id from the {@link org.wesnoth.ui.syntax.WMLHighlightingConfiguration}
* A color id from the
* {@link org.wesnoth.ui.syntax.WMLHighlightingConfiguration}
*/
public String ColorId;

View file

@ -1,4 +1,4 @@
#Sat Aug 06 15:40:55 EEST 2011
#Sat Aug 06 15:51:03 EEST 2011
eclipse.preferences.version=1
org.eclipse.jdt.core.codeComplete.argumentPrefixes=
org.eclipse.jdt.core.codeComplete.argumentSuffixes=
@ -303,21 +303,21 @@ org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declara
org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=insert
org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=insert
org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=insert
org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert

View file

@ -18,22 +18,26 @@ import org.eclipse.xtext.ui.XtextProjectHelper;
public class Constants
{
/** Plugin related */
public static final String PLUGIN_FULL_PATH =
Constants.class.getProtectionDomain().getCodeSource().getLocation().getPath() + "/"; //$NON-NLS-1$
public static final String PLUGIN_FULL_PATH = Constants.class
.getProtectionDomain( )
.getCodeSource( )
.getLocation( )
.getPath( )
+ "/"; //$NON-NLS-1$
public static final String PLUGIN_ID = "org.wesnoth"; //$NON-NLS-1$
public static final String MACHINE_OS =
System.getProperty("os.name").toLowerCase(Locale.ENGLISH); //$NON-NLS-1$
public static final String MACHINE_OS = System.getProperty(
"os.name" ).toLowerCase( Locale.ENGLISH ); //$NON-NLS-1$
/**
* The boolean value whether this machine is running windows or not
*/
public static final boolean IS_WINDOWS_MACHINE =
MACHINE_OS.contains("windows"); //$NON-NLS-1$ //$NON-NLS-2$
public static final boolean IS_WINDOWS_MACHINE = MACHINE_OS
.contains( "windows" ); //$NON-NLS-1$ //$NON-NLS-2$
/**
* The boolean value whether this machine is running Machintosh or not
*/
public static final boolean IS_MAC_MACHINE =
MACHINE_OS.contains("mac"); //$NON-NLS-1$ //$NON-NLS-2$
public static final boolean IS_MAC_MACHINE = MACHINE_OS
.contains( "mac" ); //$NON-NLS-1$ //$NON-NLS-2$
/** Preferences Constants **/
public static final String P_WESNOTH_EXEC_PATH = "wesnoth_exec_path"; //$NON-NLS-1$

View file

@ -20,19 +20,24 @@ import java.util.Date;
import javax.swing.JOptionPane;
import org.eclipse.core.runtime.IStatus;
import org.wesnoth.utils.GUIUtils;
import org.wesnoth.utils.WorkspaceUtils;
/**
* A class that logs activities in a file
*/
public class Logger {
public class Logger
{
private static class LoggerInstance{
private static class LoggerInstance
{
private static Logger instance_ = new Logger( );
}
private Logger() { }
private Logger( )
{
}
private BufferedWriter logWriter_;
private BufferedWriter toolLaunchLogWriter_;
@ -49,15 +54,18 @@ public class Logger {
{
if( logWriter_ != null )
return;
try
{
try {
if( WorkspaceUtils.getTemporaryFolder( ) == null )
throw new IOException( "Could not create the temporary folder." ); //$NON-NLS-1$
String logFilePath = String.format("%s/logs/log%s.txt", //$NON-NLS-1$
WorkspaceUtils.getTemporaryFolder(), WorkspaceUtils.getCurrentDateTime());
String toolsLogFilePath = String.format("%s/logs/tools_log%s.txt", //$NON-NLS-1$
WorkspaceUtils.getTemporaryFolder(), WorkspaceUtils.getCurrentDateTime());
String logFilePath = String.format(
"%s/logs/log%s.txt", //$NON-NLS-1$
WorkspaceUtils.getTemporaryFolder( ),
WorkspaceUtils.getCurrentDateTime( ) );
String toolsLogFilePath = String.format(
"%s/logs/tools_log%s.txt", //$NON-NLS-1$
WorkspaceUtils.getTemporaryFolder( ),
WorkspaceUtils.getCurrentDateTime( ) );
new File( WorkspaceUtils.getTemporaryFolder( ) + "/logs/" ).mkdirs( ); //$NON-NLS-1$
@ -65,13 +73,16 @@ public class Logger {
log( "Logging started." ); //$NON-NLS-1$
log( "Error codes: 1 - INFO, 2 - WARNING, 4 - ERROR" ); //$NON-NLS-1$
toolLaunchLogWriter_ = new BufferedWriter( new FileWriter( toolsLogFilePath ) );
toolLaunchLogWriter_ = new BufferedWriter( new FileWriter(
toolsLogFilePath ) );
logTool( "Logging started." ); //$NON-NLS-1$
logTool( "Error codes: 1 - INFO, 2 - WARNING, 4 - ERROR" ); //$NON-NLS-1$
} catch (IOException e)
{
JOptionPane.showMessageDialog(null, "There was an error trying to open the log." + e.getMessage()); //$NON-NLS-1$
} catch( IOException e ) {
JOptionPane
.showMessageDialog(
null,
"There was an error trying to open the log." + e.getMessage( ) ); //$NON-NLS-1$
e.printStackTrace( );
}
}
@ -83,21 +94,21 @@ public class Logger {
{
if( logWriter_ == null )
return;
try
{
try {
log( "Logging ended." ); //$NON-NLS-1$
logTool( "Logging Ended" );
logWriter_.close( );
toolLaunchLogWriter_.close( );
} catch (IOException e)
{
} catch( IOException e ) {
e.printStackTrace( );
}
}
/**
* Prints a message to the error log (severity: info)
* @param message The message to log
*
* @param message
* The message to log
*/
public void log( String message )
{
@ -106,15 +117,20 @@ public class Logger {
/**
* Logs a warning message
* @param message The message to log
*
* @param message
* The message to log
*/
public void logWarn( String message )
{
log( message, IStatus.WARNING );
}
/**
* Logs an error message
* @param message The message to log
*
* @param message
* The message to log
*/
public void logError( String message )
{
@ -123,7 +139,9 @@ public class Logger {
/**
* Logs the specified exception, providing the stacktrace to the console
* @param e The exception to log
*
* @param e
* The exception to log
*/
public void logException( Exception e )
{
@ -132,7 +150,9 @@ public class Logger {
/**
* Logs the specified exception, providing the stacktrace to the console
* @param e The exception to log
*
* @param e
* The exception to log
*/
public void logToolException( Exception e )
{
@ -155,8 +175,11 @@ public class Logger {
/**
* Logs the message (severity: info) showing also a messagebox to the user
* @param message The message to log
* @param guiMessage The message to show to the user
*
* @param message
* The message to log
* @param guiMessage
* The message to show to the user
*/
public void log( String message, String guiMessage )
{
@ -166,8 +189,11 @@ public class Logger {
/**
* Prints a message to the error log with the specified severity
* @param message the message to log
* @param severity the severity level from IStatus enum
*
* @param message
* the message to log
* @param severity
* the severity level from IStatus enum
*/
public void log( String message, int severity )
{
@ -176,32 +202,34 @@ public class Logger {
/**
* Prints a message to the tool launch log (severity: info)
* @param message The message to log
*
* @param message
* The message to log
*/
public void logTool( String message )
{
logToWriter( toolLaunchLogWriter_, message, IStatus.INFO );
}
private void logToWriter( BufferedWriter writer, String message, int severity )
private void logToWriter( BufferedWriter writer, String message,
int severity )
{
if (writer != null)
{
try
{
writer.write(String.format("%s | %d | %s\n", //$NON-NLS-1$
if( writer != null ) {
try {
writer.write( String
.format(
"%s | %d | %s\n", //$NON-NLS-1$
new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" ).format( new Date( ) ), //$NON-NLS-1$
severity, message ) );
writer.flush( );
} catch (IOException e)
{
} catch( IOException e ) {
e.printStackTrace( );
}
}
// don't print to console the tools if there was no error/warning
if ( writer != toolLaunchLogWriter_ ||
( writer == toolLaunchLogWriter_ && severity != IStatus.INFO ) )
if( writer != toolLaunchLogWriter_
|| ( writer == toolLaunchLogWriter_ && severity != IStatus.INFO ) )
System.out.println( message );
}
}

View file

@ -315,8 +315,7 @@ public class Messages extends NLS
public static String WorkspaceUtils_33;
public static String WorkspaceUtils_7;
public static String WorkspaceUtils_9;
static
{
static {
// initialize resource bundle
NLS.initializeMessages( BUNDLE_NAME, Messages.class );
}

View file

@ -9,6 +9,7 @@
package org.wesnoth;
import org.antlr.runtime.CharStream;
import org.wesnoth.parser.antlr.internal.InternalWMLLexer;
public class WMLLexer extends InternalWMLLexer

View file

@ -11,9 +11,11 @@ package org.wesnoth;
import org.eclipse.xtext.parser.antlr.Lexer;
/**
* Use this class to register components to be used at runtime / without the Equinox extension registry.
* Use this class to register components to be used at runtime / without the
* Equinox extension registry.
*/
public class WMLRuntimeModule extends org.wesnoth.AbstractWMLRuntimeModule {
public class WMLRuntimeModule extends org.wesnoth.AbstractWMLRuntimeModule
{
@Override
public Class< ? extends Lexer > bindLexer( )
{

View file

@ -16,10 +16,10 @@ import org.wesnoth.schema.SchemaParser;
*/
public class WMLStandaloneSetup extends WMLStandaloneSetupGenerated
{
public static void doSetup() {
public static void doSetup( )
{
new WMLStandaloneSetup( ).createInjectorAndDoEMFRegistration( );
SchemaParser.reloadSchemas( false );
}
}

View file

@ -10,6 +10,8 @@ package org.wesnoth;
import java.util.Map.Entry;
import org.osgi.framework.BundleContext;
import org.eclipse.core.resources.IProject;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.wizard.WizardDialog;
@ -17,7 +19,7 @@ import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
import org.wesnoth.preprocessor.PreprocessorUtils;
import org.wesnoth.projects.ProjectCache;
import org.wesnoth.projects.ProjectUtils;
@ -34,7 +36,8 @@ public class WesnothPlugin extends AbstractUIPlugin
/**
* The constructor
*/
public WesnothPlugin() {
public WesnothPlugin( )
{
}
@Override
@ -45,8 +48,7 @@ public class WesnothPlugin extends AbstractUIPlugin
Logger.getInstance( ).startLogger( );
if( PlatformUI.isWorkbenchRunning( ) ) {
if (WorkspaceUtils.checkPathsAreSet( null, false) == false)
{
if( WorkspaceUtils.checkPathsAreSet( null, false ) == false ) {
Display.getDefault( ).asyncExec( new Runnable( ) {
@Override
public void run( )
@ -64,9 +66,8 @@ public class WesnothPlugin extends AbstractUIPlugin
public void stop( BundleContext context ) throws Exception
{
// save the caches of the projects on disk
for(Entry<IProject, ProjectCache> cache :
ProjectUtils.getProjectCaches().entrySet())
{
for( Entry< IProject, ProjectCache > cache: ProjectUtils
.getProjectCaches( ).entrySet( ) ) {
cache.getValue( ).saveCache( );
}
PreprocessorUtils.getInstance( ).saveTimestamps( );
@ -91,7 +92,8 @@ public class WesnothPlugin extends AbstractUIPlugin
* Returns an image descriptor for the image file at the given plug-in
* relative path
*
* @param path the path
* @param path
* the path
* @return the image descriptor
*/
public static ImageDescriptor getImageDescriptor( String path )

View file

@ -9,6 +9,7 @@
package org.wesnoth.action;
import org.eclipse.jface.action.IAction;
import org.wesnoth.utils.MapUtils;
public class ImportMap extends ObjectActionDelegate

View file

@ -9,6 +9,7 @@
package org.wesnoth.action;
import org.eclipse.jface.action.IAction;
import org.wesnoth.utils.GameUtils;

View file

@ -9,6 +9,7 @@
package org.wesnoth.action;
import org.eclipse.jface.action.IAction;
import org.wesnoth.utils.GameUtils;
import org.wesnoth.utils.WorkspaceUtils;

View file

@ -9,6 +9,7 @@
package org.wesnoth.action;
import org.eclipse.jface.action.IAction;
import org.wesnoth.utils.GameUtils;

View file

@ -8,6 +8,7 @@ import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.jface.action.IAction;
import org.wesnoth.Logger;
import org.wesnoth.templates.ReplaceableParameter;
import org.wesnoth.templates.TemplateProvider;
@ -16,7 +17,9 @@ import org.wesnoth.utils.ResourceUtils;
public class RegenerateBuildFiles extends ObjectActionDelegate
{
public RegenerateBuildFiles() { }
public RegenerateBuildFiles( )
{
}
@SuppressWarnings( "rawtypes" )
@Override
@ -25,22 +28,22 @@ public class RegenerateBuildFiles extends ObjectActionDelegate
if( structuredSelection_ == null )
return;
for (Iterator it = structuredSelection_.iterator(); it.hasNext();)
{
for( Iterator it = structuredSelection_.iterator( ); it.hasNext( ); ) {
Object element = it.next( );
if (element instanceof IProject)
{
if( element instanceof IProject ) {
ArrayList< ReplaceableParameter > param = new ArrayList< ReplaceableParameter >( );
param.add(new ReplaceableParameter("$$project_name", (((IProject)element).getName()))); //$NON-NLS-1$
param.add(new ReplaceableParameter("$$project_dir_name", ((IProject)element).getName())); //$NON-NLS-1$
ResourceUtils.createFile((IProject)element, "build.xml", //$NON-NLS-1$
TemplateProvider.getInstance().getProcessedTemplate("build_xml", param), true); //$NON-NLS-1$
try
{
((IProject)element).refreshLocal(IResource.DEPTH_ONE, new NullProgressMonitor());
}
catch (CoreException e)
{
param.add( new ReplaceableParameter(
"$$project_name", ( ( ( IProject ) element ).getName( ) ) ) ); //$NON-NLS-1$
param.add( new ReplaceableParameter(
"$$project_dir_name", ( ( IProject ) element ).getName( ) ) ); //$NON-NLS-1$
ResourceUtils.createFile( ( IProject ) element,
"build.xml", //$NON-NLS-1$
TemplateProvider.getInstance( ).getProcessedTemplate(
"build_xml", param ), true ); //$NON-NLS-1$
try {
( ( IProject ) element ).refreshLocal( IResource.DEPTH_ONE,
new NullProgressMonitor( ) );
} catch( CoreException e ) {
Logger.getInstance( ).logException( e );
}
}

View file

@ -9,6 +9,7 @@
package org.wesnoth.action;
import org.eclipse.jface.action.IAction;
import org.wesnoth.utils.WMLTools;
import org.wesnoth.utils.WMLTools.Tools;

View file

@ -9,6 +9,7 @@
package org.wesnoth.action;
import org.eclipse.jface.action.IAction;
import org.wesnoth.utils.WMLTools;
import org.wesnoth.utils.WMLTools.Tools;

View file

@ -9,6 +9,7 @@
package org.wesnoth.action;
import org.eclipse.jface.action.IAction;
import org.wesnoth.utils.WMLTools;
import org.wesnoth.utils.WMLTools.Tools;

View file

@ -9,6 +9,7 @@
package org.wesnoth.action;
import org.eclipse.jface.action.IAction;
import org.wesnoth.preprocessor.PreprocessorUtils;
import org.wesnoth.utils.WorkspaceUtils;
@ -19,7 +20,7 @@ public class ShowPlainPreprocessedConfig extends ObjectActionDelegate
public void run( IAction action )
{
PreprocessorUtils.getInstance( ).openPreprocessedFileInEditor(
WorkspaceUtils.getSelectedFile(WorkspaceUtils.getWorkbenchWindow()),
true);
WorkspaceUtils.getSelectedFile( WorkspaceUtils
.getWorkbenchWindow( ) ), true );
}
}

View file

@ -9,6 +9,7 @@
package org.wesnoth.action;
import org.eclipse.jface.action.IAction;
import org.wesnoth.preprocessor.PreprocessorUtils;
import org.wesnoth.utils.WorkspaceUtils;
@ -18,6 +19,7 @@ public class ShowPreprocessedConfig extends ObjectActionDelegate
@Override
public void run( IAction action )
{
PreprocessorUtils.getInstance().openPreprocessedFileInEditor(WorkspaceUtils.getSelectedFile(), false);
PreprocessorUtils.getInstance( ).openPreprocessedFileInEditor(
WorkspaceUtils.getSelectedFile( ), false );
}
}

View file

@ -15,9 +15,10 @@ import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.wesnoth.WesnothPlugin;
import org.wesnoth.Logger;
import org.wesnoth.Messages;
import org.wesnoth.WesnothPlugin;
import org.wesnoth.utils.GUIUtils;
import org.wesnoth.utils.WMLTools;
import org.wesnoth.utils.WorkspaceUtils;
@ -28,10 +29,11 @@ public class UploadAddon extends ObjectActionDelegate
@Override
public void run( IAction action )
{
final String fullPath = WorkspaceUtils.getSelectedResource().getLocation().toOSString();
ProgressMonitorDialog dialog = new ProgressMonitorDialog(WesnothPlugin.getShell());
try
{
final String fullPath = WorkspaceUtils.getSelectedResource( )
.getLocation( ).toOSString( );
ProgressMonitorDialog dialog = new ProgressMonitorDialog(
WesnothPlugin.getShell( ) );
try {
dialog.run( false, false, new IRunnableWithProgress( ) {
@Override
public void run( IProgressMonitor monitor )
@ -39,19 +41,19 @@ public class UploadAddon extends ObjectActionDelegate
{
monitor.beginTask( Messages.UploadAddon_0, 50 );
monitor.worked( 10 );
OutputStream consoleStream = GUIUtils.
createConsole(Messages.UploadAddon_1, null, true).newOutputStream();
OutputStream consoleStream = GUIUtils.createConsole(
Messages.UploadAddon_1, null, true )
.newOutputStream( );
WMLTools.uploadWesnothAddon( fullPath,
new OutputStream[] { consoleStream }, new OutputStream[] { consoleStream });
new OutputStream[] { consoleStream },
new OutputStream[] { consoleStream } );
monitor.worked( 40 );
monitor.done( );
}
} );
} catch (InvocationTargetException e)
{
} catch( InvocationTargetException e ) {
Logger.getInstance( ).logException( e );
} catch (InterruptedException e)
{
} catch( InterruptedException e ) {
}
}
}

View file

@ -13,6 +13,7 @@ import java.io.File;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IProject;
import org.eclipse.jface.action.IAction;
import org.wesnoth.Messages;
import org.wesnoth.utils.GUIUtils;
import org.wesnoth.utils.WorkspaceUtils;
@ -24,8 +25,7 @@ public class WesnothProjectReport extends ObjectActionDelegate
public void run( IAction action )
{
IProject project = WorkspaceUtils.getSelectedProject( );
if (project == null)
{
if( project == null ) {
GUIUtils.showWarnMessageBox( Messages.WesnothProjectReport_0 );
return;
}
@ -35,6 +35,7 @@ public class WesnothProjectReport extends ObjectActionDelegate
/**
* Gets the report for specified container (sceanarios, maps, units)
*
* @param container
* @return
*/
@ -42,19 +43,22 @@ public class WesnothProjectReport extends ObjectActionDelegate
{
int[] statistics = new int[3];
File scenariosFolder = new File(container.getLocation().toOSString() + "/scenarios"); //$NON-NLS-1$
File scenariosFolder = new File( container.getLocation( ).toOSString( )
+ "/scenarios" ); //$NON-NLS-1$
if( scenariosFolder.exists( ) )
statistics[0] = scenariosFolder.listFiles( ).length;
File mapsFolder = new File(container.getLocation().toOSString() + "/maps"); //$NON-NLS-1$
File mapsFolder = new File( container.getLocation( ).toOSString( )
+ "/maps" ); //$NON-NLS-1$
if( mapsFolder.exists( ) )
statistics[1] = mapsFolder.listFiles( ).length;
File unitsFolder = new File(container.getLocation().toOSString() + "/units"); //$NON-NLS-1$
File unitsFolder = new File( container.getLocation( ).toOSString( )
+ "/units" ); //$NON-NLS-1$
if( unitsFolder.exists( ) )
statistics[2] = unitsFolder.listFiles( ).length;
return String.format(Messages.WesnothProjectReport_4,
statistics[0],statistics[1], statistics[2]);
return String.format( Messages.WesnothProjectReport_4, statistics[0],
statistics[1], statistics[2] );
}
}

View file

@ -22,6 +22,7 @@ import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.wesnoth.Logger;
import org.wesnoth.utils.ResourceUtils;
import org.wesnoth.utils.ResourceUtils.WMLFilesComparator;
@ -68,14 +69,17 @@ public class DependencyListBuilder implements Serializable
/**
* Create the whole dependency list from scratch.
* @param force True for force re-creating the list even if it
*
* @param force
* True for force re-creating the list even if it
* was previously created
*/
public void createDependencyList( boolean force )
{
if( isCreated_ && ! force ) {
Logger.getInstance( ).log( "Skipping depedency list for project " +
project_.getName( ) );
Logger.getInstance( )
.log( "Skipping depedency list for project "
+ project_.getName( ) );
return;
}
@ -91,7 +95,9 @@ public class DependencyListBuilder implements Serializable
/**
* Adds a new node in the PDL
* @param file The file to add
*
* @param file
* The file to add
* @return The newly created node
*/
public DependencyListNode addNode( IFile file )
@ -99,7 +105,8 @@ public class DependencyListBuilder implements Serializable
// TODO: create better heuristics for the indexes
// in case we need to add multiple subsequent files...
DependencyListNode backupPrevious = previous_, newNode = null;
String fileParentProjectPath = file.getParent( ).getProjectRelativePath( ).toString( );
String fileParentProjectPath = file.getParent( )
.getProjectRelativePath( ).toString( );
// we add a file in an existing processed directory.
if( directories_.contains( fileParentProjectPath ) ) {
@ -113,7 +120,8 @@ public class DependencyListBuilder implements Serializable
if( tmpNode != null ) {
String fileName = file.getName( );
/* check if the file is _main.cfg. If yes,
/*
* check if the file is _main.cfg. If yes,
* all current nodes from this directory need to be erased
* and processed by the includes from other _main.cfg
*/
@ -126,14 +134,15 @@ public class DependencyListBuilder implements Serializable
// create the node
newNode = internal_addNode( file );
} else {
}
else {
// search for the correct place in current dir
DependencyListNode prevTmpNode = null;
while( tmpNode != null ) {
// we found the place?
if ( ResourceUtils.wmlFileNameCompare(
tmpNode.getFile( ).getName( ), fileName ) > 0 ) {
if( ResourceUtils.wmlFileNameCompare( tmpNode.getFile( )
.getName( ), fileName ) > 0 ) {
previous_ = tmpNode.getPrevious( );
@ -151,7 +160,8 @@ public class DependencyListBuilder implements Serializable
newNode = internal_addNode( file );
}
}
} else {
}
else {
// previous_ should be the first non-null node in previous
// directories.
@ -167,7 +177,8 @@ public class DependencyListBuilder implements Serializable
// now, parse the file to check if we should include other dirs
internal_addContainers( newNode.getIncludes( true ) );
} else {
}
else {
// didn't found any place to put it. where shall we?
// the place should be dictated by other cfg,
// by getting the included directory
@ -181,7 +192,9 @@ public class DependencyListBuilder implements Serializable
/**
* Adds the containers and their contents to the list
* @param containerList The list of container paths
*
* @param containerList
* The list of container paths
*/
private void internal_addContainers( Collection< String > containerList )
{
@ -192,7 +205,9 @@ public class DependencyListBuilder implements Serializable
/**
* Add the container and it's contents to the list
* @param containerPath The path of the container
*
* @param containerPath
* The path of the container
*/
private void internal_addContainer( String containerPath )
{
@ -209,13 +224,13 @@ public class DependencyListBuilder implements Serializable
// add any included containers
internal_addContainers( newNode.getIncludes( true ) );
}else {
}
else {
// no main.cfg, just follow WML reading rules
List< IResource > members = null;
try {
members = Arrays.asList( container.members( ) );
}
catch ( CoreException e ) {
} catch( CoreException e ) {
Logger.getInstance( ).logException( e );
return;
}
@ -225,13 +240,15 @@ public class DependencyListBuilder implements Serializable
boolean toAddDirectoryEntry = false;
if( ! directories_.contains( containerPath ) ) {
directories_.add( containerPath );
directoriesEntries_.add( new ListDirectoryEntry( containerPath, null, null ) );
directoriesEntries_.add( new ListDirectoryEntry( containerPath,
null, null ) );
toAddDirectoryEntry = true;
} else {
}
else {
// update the includes
directoriesEntries_.get( directoriesEntries_.indexOf( containerPath ) )
.Includes ++ ;
directoriesEntries_.get( directoriesEntries_
.indexOf( containerPath ) ).Includes++;
}
if( members.isEmpty( ) )
@ -242,7 +259,8 @@ public class DependencyListBuilder implements Serializable
for( IResource resource: members ) {
if( resource instanceof IContainer )
internal_addContainer( resource.getProjectRelativePath( ).toString( ) );
internal_addContainer( resource.getProjectRelativePath( )
.toString( ) );
else {
// just config files.
if( ! ResourceUtils.isConfigFile( resource ) )
@ -258,24 +276,26 @@ public class DependencyListBuilder implements Serializable
if( toAddDirectoryEntry ) {
// update the first directory node
directoriesEntries_.set( directories_.size( ) - 1,
new ListDirectoryEntry( containerPath, firstNewNode, lastNode ));
} else {
new ListDirectoryEntry( containerPath,
firstNewNode, lastNode ) );
}
else {
// if the current entry has null nodes
// or the indexes are greater/lower than the current ones
// we need to update the references nodes
ListDirectoryEntry entry = directoriesEntries_.get(
directories_.indexOf( containerPath ) );
ListDirectoryEntry entry = directoriesEntries_
.get( directories_.indexOf( containerPath ) );
if ( entry.FirstNode == null ||
( entry.FirstNode != null &&
firstNewNode.getIndex( ) < entry.FirstNode.getIndex( ) ) ) {
if( entry.FirstNode == null
|| ( entry.FirstNode != null && firstNewNode
.getIndex( ) < entry.FirstNode.getIndex( ) ) ) {
entry.FirstNode = firstNewNode;
}
if ( entry.LastNode == null ||
( entry.LastNode != null &&
lastNode.getIndex( ) > entry.LastNode.getIndex( ) ) ) {
if( entry.LastNode == null
|| ( entry.LastNode != null && lastNode.getIndex( ) > entry.LastNode
.getIndex( ) ) ) {
entry.LastNode = lastNode;
}
}
@ -285,7 +305,9 @@ public class DependencyListBuilder implements Serializable
/**
* Adds a new node to this list
* @param file The file to add
*
* @param file
* The file to add
* @return The newly created node
*/
private DependencyListNode internal_addNode( IFile file )
@ -296,24 +318,28 @@ public class DependencyListBuilder implements Serializable
// inserting is done between 2 nodes
if( previous_.getNext( ) != null ) {
int newIndex = (previous_.getIndex( ) +
previous_.getNext( ).getIndex( )) / 2;
int newIndex = ( previous_.getIndex( ) + previous_.getNext( )
.getIndex( ) ) / 2;
if ( newIndex > previous_.getIndex( ) + DependencyListNode.INDEX_STEP )
newIndex = previous_.getIndex( ) + DependencyListNode.INDEX_STEP ;
if( newIndex > previous_.getIndex( )
+ DependencyListNode.INDEX_STEP )
newIndex = previous_.getIndex( )
+ DependencyListNode.INDEX_STEP;
newNode.setIndex( newIndex );
newNode.setNext( previous_.getNext( ) );
previous_.getNext( ).setPrevious( newNode );
} else {
}
else {
newNode.setIndex( currentIndex_ );
currentIndex_ += DependencyListNode.INDEX_STEP;
}
previous_.setNext( newNode );
newNode.setPrevious( previous_ );
} else {
}
else {
// no previous yet (== null)
// so we're making this the root node for this list
@ -323,8 +349,10 @@ public class DependencyListBuilder implements Serializable
root.setPrevious( newNode );
newNode.setNext( root );
newNode.setIndex( root.getIndex( ) - DependencyListNode.INDEX_STEP );
} else {
newNode.setIndex( root.getIndex( )
- DependencyListNode.INDEX_STEP );
}
else {
newNode.setIndex( currentIndex_ );
currentIndex_ += DependencyListNode.INDEX_STEP;
}
@ -339,7 +367,9 @@ public class DependencyListBuilder implements Serializable
/**
* Removes a node specified by the file
* @param file The file to remove from the list
*
* @param file
* The file to remove from the list
*/
public void removeNode( IFile file )
{
@ -348,7 +378,9 @@ public class DependencyListBuilder implements Serializable
/**
* Removes the specified node from the list
* @param node The node to remove from the list
*
* @param node
* The node to remove from the list
*/
public void removeNode( DependencyListNode node )
{
@ -361,14 +393,17 @@ public class DependencyListBuilder implements Serializable
if( node.getNext( ) != null )
node.getNext( ).setPrevious( node.getPrevious( ) );
String fileParentProjectPath = node.getFile( ).getParent( ).getProjectRelativePath( ).toString( );
String fileParentProjectPath = node.getFile( ).getParent( )
.getProjectRelativePath( ).toString( );
list_.remove( node.getFile( ).getProjectRelativePath( ).toString( ) );
// if we're at last node, decrease currentIndex_ to make economy on indexes
// if we're at last node, decrease currentIndex_ to make economy on
// indexes
if( node.getNext( ) == null ) {
if( node.getPrevious( ) != null )
currentIndex_ = node.getPrevious( ).getIndex( ) + DependencyListNode.INDEX_STEP;
currentIndex_ = node.getPrevious( ).getIndex( )
+ DependencyListNode.INDEX_STEP;
}
// removing a _main.cfg, add the parent container
@ -385,7 +420,9 @@ public class DependencyListBuilder implements Serializable
/**
* Removes the container and all it's contents from the list
* @param path The container's path
*
* @param path
* The container's path
*/
private void internal_removeContainer( String path )
{
@ -420,7 +457,9 @@ public class DependencyListBuilder implements Serializable
/**
* Updates the current node in the list
* @param node The node to update
*
* @param node
* The node to update
*/
public void updateNode( DependencyListNode node )
{
@ -433,8 +472,8 @@ public class DependencyListBuilder implements Serializable
List< String > processedIncludes = new ArrayList< String >( );
for ( int prevIndex = 0, newIndex = 0
; prevIndex < prevLength && newIndex < newLength; ) {
for( int prevIndex = 0, newIndex = 0; prevIndex < prevLength
&& newIndex < newLength; ) {
String prevIncl = previousIncludes.get( prevIndex );
String newIncl = newIncludes.get( prevIndex );
@ -449,7 +488,8 @@ public class DependencyListBuilder implements Serializable
boolean prevDeleted = ! newIncludes.contains( prevIncl );
if( newIsNew ) {
// add the new directory before the previous included dir (if any)
// add the new directory before the previous included dir (if
// any)
DependencyListNode backupPrevious = previous_;
@ -457,8 +497,9 @@ public class DependencyListBuilder implements Serializable
// get the directory entry for the previous include
if( newIndex > 0 ) {
ListDirectoryEntry entry = directoriesEntries_.get(
directories_.indexOf( newIncludes.get( newIndex - 1 ) ) );
ListDirectoryEntry entry = directoriesEntries_
.get( directories_.indexOf( newIncludes
.get( newIndex - 1 ) ) );
if( entry != null )
previous_ = entry.FirstNode;
@ -468,24 +509,28 @@ public class DependencyListBuilder implements Serializable
previous_ = backupPrevious;
++newIndex;
} else {
}
else {
if( prevDeleted ) {
// the previous include was deleted
internal_removeContainer( prevIncl );
} else {
// the previous included has changed it's index (in the includes list)
}
else {
// the previous included has changed it's index (in the
// includes list)
// don't reprocess this pair if we already did
if( ! processedIncludes.contains( prevIncl ) ) {
ListDirectoryEntry prevEntry = directoriesEntries_.get(
directories_.indexOf( prevIncl ) );
ListDirectoryEntry newEntry = directoriesEntries_.get(
directories_.indexOf( newIncl ) );
ListDirectoryEntry prevEntry = directoriesEntries_
.get( directories_.indexOf( prevIncl ) );
ListDirectoryEntry newEntry = directoriesEntries_
.get( directories_.indexOf( newIncl ) );
if ( prevEntry != null && newEntry != null &&
prevEntry.FirstNode != null && newEntry.FirstNode != null) {
if( prevEntry != null && newEntry != null
&& prevEntry.FirstNode != null
&& newEntry.FirstNode != null ) {
// create a list for easier swap
List< DependencyListNode > nodes = new ArrayList< DependencyListNode >( );
@ -530,9 +575,11 @@ public class DependencyListBuilder implements Serializable
processedIncludes.add( prevIncl );
processedIncludes.add( newIncl );
} else {
Logger.getInstance( ).log( "Null directory entry for" +
"includes: " + prevIncl + " and " + newIncl );
}
else {
Logger.getInstance( ).log(
"Null directory entry for" + "includes: "
+ prevIncl + " and " + newIncl );
}
}
}
@ -545,7 +592,9 @@ public class DependencyListBuilder implements Serializable
/**
* Returns the node specified by the file
* @param file The file to get the depedency node for
*
* @param file
* The file to get the depedency node for
* @return An instance of {@link DependencyListNode}
*/
public DependencyListNode getNode( IFile file )
@ -557,7 +606,9 @@ public class DependencyListBuilder implements Serializable
* Returns the node specified by the key. The keys are
* usually project-relative paths for project's files, or
* the {@link #ROOT_NODE_KEY}
* @param key The key to get the node by
*
* @param key
* The key to get the node by
* @return An instance of {@link DependencyListNode}
*/
public DependencyListNode getNode( String key )
@ -567,6 +618,7 @@ public class DependencyListBuilder implements Serializable
/**
* Returns true if the list was already created, false otherwise
*
* @return A boolean value
*/
public boolean getIsCreated( )

View file

@ -15,6 +15,7 @@ import java.util.List;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.QualifiedName;
import org.wesnoth.Constants;
import org.wesnoth.Logger;
import org.wesnoth.utils.ResourceUtils;
@ -39,7 +40,9 @@ public class DependencyListNode implements Serializable
*/
public static final int INDEX_STEP = 100000;
public static final QualifiedName PDL_INDEX = new QualifiedName( Constants.PLUGIN_ID, "pdl_index" ); //$NON-NLS-1$
public static final QualifiedName PDL_INDEX = new QualifiedName(
Constants.PLUGIN_ID,
"pdl_index" ); //$NON-NLS-1$
private DependencyListNode previous_;
private DependencyListNode next_;
@ -63,6 +66,7 @@ public class DependencyListNode implements Serializable
/**
* Gets this node's file
*
* @return A IFile resource
*/
public IFile getFile( )
@ -72,14 +76,17 @@ public class DependencyListNode implements Serializable
/**
* Gets the includes from this node
* @param refresh True to force reloading the current file and return
*
* @param refresh
* True to force reloading the current file and return
* the newly parsed ones
* @return A set with string paths for included directories
*/
public List< String > getIncludes( boolean refresh )
{
if( includes_ == null || refresh ) {
includes_ = new ArrayList<String>( ResourceUtils.getContainers( file_ ) );
includes_ = new ArrayList< String >(
ResourceUtils.getContainers( file_ ) );
}
return includes_;
@ -87,6 +94,7 @@ public class DependencyListNode implements Serializable
/**
* Returns the index of this node in the whole dependency list
*
* @return
*/
public int getIndex( )
@ -96,7 +104,9 @@ public class DependencyListNode implements Serializable
/**
* Sets a new index for this node
* @param index The index to set
*
* @param index
* The index to set
*/
protected void setIndex( int index )
{
@ -104,14 +114,14 @@ public class DependencyListNode implements Serializable
try {
file_.setPersistentProperty( PDL_INDEX, Integer.toString( index ) );
}
catch ( CoreException e ) {
} catch( CoreException e ) {
Logger.getInstance( ).logException( e );
}
}
/**
* Gets the node before the current node
*
* @return A node or null if there is no parent
*/
public DependencyListNode getPrevious( )
@ -121,7 +131,9 @@ public class DependencyListNode implements Serializable
/**
* Sets a new previous node for this node
* @param previous The new previous node to set
*
* @param previous
* The new previous node to set
*/
public void setPrevious( DependencyListNode previous )
{
@ -130,6 +142,7 @@ public class DependencyListNode implements Serializable
/**
* Gets the node after the current node
*
* @return A node or null if there is no parent
*/
public DependencyListNode getNext( )
@ -139,7 +152,9 @@ public class DependencyListNode implements Serializable
/**
* Sets a new next node for this node
* @param next The new next node to set
*
* @param next
* The new next node to set
*/
public void setNext( DependencyListNode next )
{

View file

@ -17,6 +17,7 @@ import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.jface.action.IAction;
import org.wesnoth.Constants;
import org.wesnoth.Logger;
import org.wesnoth.action.ObjectActionDelegate;
@ -29,20 +30,17 @@ public class ToggleWesnothNatureAction extends ObjectActionDelegate
{
if( structuredSelection_ == null )
return;
for (Iterator it = structuredSelection_.iterator(); it.hasNext();)
{
for( Iterator it = structuredSelection_.iterator( ); it.hasNext( ); ) {
Object element = it.next( );
IProject project = null;
if (element instanceof IProject)
{
if( element instanceof IProject ) {
project = ( IProject ) element;
}
else if (element instanceof IAdaptable)
{
project = (IProject) ((IAdaptable) element).getAdapter(IProject.class);
else if( element instanceof IAdaptable ) {
project = ( IProject ) ( ( IAdaptable ) element )
.getAdapter( IProject.class );
}
if (project != null)
{
if( project != null ) {
toggleNature( project );
}
}
@ -51,26 +49,27 @@ public class ToggleWesnothNatureAction extends ObjectActionDelegate
/**
* Toggles sample nature on a project
*
* @param project to have sample nature added or removed
* @param project
* to have sample nature added or removed
*/
public void toggleNature( IProject project )
{
try
{
try {
IProjectDescription description = project.getDescription( );
String[] natures = description.getNatureIds( );
for (int i = 0; i < natures.length; ++i)
{
if (Constants.NATURE_WESNOTH.equals(natures[i]))
{
for( int i = 0; i < natures.length; ++i ) {
if( Constants.NATURE_WESNOTH.equals( natures[i] ) ) {
// Remove the nature
String[] newNatures = new String[natures.length - 1];
System.arraycopy( natures, 0, newNatures, 0, i );
System.arraycopy(natures, i + 1, newNatures, i, natures.length - i - 1);
System.arraycopy( natures, i + 1, newNatures, i,
natures.length - i - 1 );
description.setNatureIds( newNatures );
project.setDescription(description, new NullProgressMonitor());
project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
project.setDescription( description,
new NullProgressMonitor( ) );
project.refreshLocal( IResource.DEPTH_INFINITE,
new NullProgressMonitor( ) );
return;
}
}
@ -81,9 +80,9 @@ public class ToggleWesnothNatureAction extends ObjectActionDelegate
newNatures[natures.length] = Constants.NATURE_WESNOTH;
description.setNatureIds( newNatures );
project.setDescription( description, new NullProgressMonitor( ) );
project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
} catch (CoreException e)
{
project.refreshLocal( IResource.DEPTH_INFINITE,
new NullProgressMonitor( ) );
} catch( CoreException e ) {
Logger.getInstance( ).logException( e );
}
}

View file

@ -17,6 +17,7 @@ import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.jface.action.IAction;
import org.wesnoth.Constants;
import org.wesnoth.Logger;
import org.wesnoth.action.ObjectActionDelegate;
@ -29,20 +30,17 @@ public class ToggleXtextNatureAction extends ObjectActionDelegate
{
if( structuredSelection_ == null )
return;
for (Iterator it = structuredSelection_.iterator(); it.hasNext();)
{
for( Iterator it = structuredSelection_.iterator( ); it.hasNext( ); ) {
Object element = it.next( );
IProject project = null;
if (element instanceof IProject)
{
if( element instanceof IProject ) {
project = ( IProject ) element;
}
else if (element instanceof IAdaptable)
{
project = (IProject) ((IAdaptable) element).getAdapter(IProject.class);
else if( element instanceof IAdaptable ) {
project = ( IProject ) ( ( IAdaptable ) element )
.getAdapter( IProject.class );
}
if (project != null)
{
if( project != null ) {
toggleNature( project );
}
}
@ -51,26 +49,27 @@ public class ToggleXtextNatureAction extends ObjectActionDelegate
/**
* Toggles sample nature on a project
*
* @param project to have sample nature added or removed
* @param project
* to have sample nature added or removed
*/
public void toggleNature( IProject project )
{
try
{
try {
IProjectDescription description = project.getDescription( );
String[] natures = description.getNatureIds( );
for (int i = 0; i < natures.length; ++i)
{
if (Constants.NATURE_XTEXT.equals(natures[i]))
{
for( int i = 0; i < natures.length; ++i ) {
if( Constants.NATURE_XTEXT.equals( natures[i] ) ) {
// Remove the nature
String[] newNatures = new String[natures.length - 1];
System.arraycopy( natures, 0, newNatures, 0, i );
System.arraycopy(natures, i + 1, newNatures, i, natures.length - i - 1);
System.arraycopy( natures, i + 1, newNatures, i,
natures.length - i - 1 );
description.setNatureIds( newNatures );
project.setDescription(description, new NullProgressMonitor());
project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
project.setDescription( description,
new NullProgressMonitor( ) );
project.refreshLocal( IResource.DEPTH_INFINITE,
new NullProgressMonitor( ) );
return;
}
}
@ -81,9 +80,9 @@ public class ToggleXtextNatureAction extends ObjectActionDelegate
newNatures[natures.length] = Constants.NATURE_XTEXT;
description.setNatureIds( newNatures );
project.setDescription( description, new NullProgressMonitor( ) );
project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
} catch (CoreException e)
{
project.refreshLocal( IResource.DEPTH_INFINITE,
new NullProgressMonitor( ) );
} catch( CoreException e ) {
Logger.getInstance( ).logException( e );
}
}

View file

@ -19,6 +19,14 @@ import java.util.Map;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingDeque;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.wesnoth.Constants;
import org.wesnoth.Logger;
import org.wesnoth.Messages;
@ -37,14 +45,6 @@ import org.wesnoth.utils.WorkspaceUtils;
import org.wesnoth.wml.SimpleWMLParser;
import org.wesnoth.wml.WMLConfig;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
/**
* The builder does the following steps in order to create and ensure
* a correct PDL (Project Dependency Lits)
@ -71,10 +71,14 @@ public class WesnothProjectBuilder extends IncrementalProjectBuilder
if( projectCache_ == null )
projectCache_ = ProjectUtils.getCacheForProject( project_ );
Logger.getInstance().log( "Building project " + getProject( ).getName( ) + " ..." ); //$NON-NLS-1$
monitor.beginTask(String.format(Messages.WesnothProjectBuilder_1, project_.getName()), 100);
Logger.getInstance( ).log(
"Building project " + getProject( ).getName( ) + " ..." ); //$NON-NLS-1$
monitor.beginTask(
String.format( Messages.WesnothProjectBuilder_1,
project_.getName( ) ), 100 );
String installName = WesnothInstallsUtils.getInstallNameForResource( project_ );
String installName = WesnothInstallsUtils
.getInstallNameForResource( project_ );
Paths paths = Preferences.getPaths( installName );
monitor.subTask( Messages.WesnothProjectBuilder_3 );
@ -101,8 +105,7 @@ public class WesnothProjectBuilder extends IncrementalProjectBuilder
if( kind == FULL_BUILD )
readDefines = fullBuild( monitor );
else
{
else {
IResourceDelta delta = getDelta( project_ );
if( delta == null )
readDefines = fullBuild( monitor );
@ -110,8 +113,7 @@ public class WesnothProjectBuilder extends IncrementalProjectBuilder
readDefines = incrementalBuild( delta, monitor );
}
if (readDefines)
{
if( readDefines ) {
// we read the defines at the end of the build
// to speed up things (and only if we had any .cfg files processed)
projectCache_.readDefines( true );
@ -121,28 +123,34 @@ public class WesnothProjectBuilder extends IncrementalProjectBuilder
}
monitor.done( );
Logger.getInstance( ).log( "Done building project " + getProject( ).getName( ) );
Logger.getInstance( ).log(
"Done building project " + getProject( ).getName( ) );
return null;
}
/**
* Does a full build on this project
* @param monitor The monitor used to signal progress
*
* @param monitor
* The monitor used to signal progress
* @return True if there were config files processed
* @throws CoreException
*/
protected boolean fullBuild(final IProgressMonitor monitor) throws CoreException
protected boolean fullBuild( final IProgressMonitor monitor )
throws CoreException
{
// clean all project cache
projectCache_.clear( );
PreprocessorUtils.getInstance( ).clearTimestampsForPath( project_.getLocation( ).toOSString( ) );
PreprocessorUtils.getInstance( ).clearTimestampsForPath(
project_.getLocation( ).toOSString( ) );
projectCache_.getDependencyList( ).createDependencyList( true );
boolean foundCfg = false;
DependencyListNode node = null;
node = projectCache_.getDependencyList( ).getNode( DependencyListBuilder.ROOT_NODE_KEY );
node = projectCache_.getDependencyList( ).getNode(
DependencyListBuilder.ROOT_NODE_KEY );
if( node != null ) {
@ -160,13 +168,16 @@ public class WesnothProjectBuilder extends IncrementalProjectBuilder
/**
* Does an incremental build on this project
* @param delta The delta which contains the project modifications
* @param monitor The monitor used to signal progress
*
* @param delta
* The delta which contains the project modifications
* @param monitor
* The monitor used to signal progress
* @return True if there were config files processed
* @throws CoreException
*/
protected boolean incrementalBuild(IResourceDelta delta, IProgressMonitor monitor)
throws CoreException
protected boolean incrementalBuild( IResourceDelta delta,
IProgressMonitor monitor ) throws CoreException
{
boolean foundCfg = false;
@ -191,38 +202,49 @@ public class WesnothProjectBuilder extends IncrementalProjectBuilder
if( deltaKind == IResourceDelta.REMOVED ) {
projectCache_.getDependencyList( ).removeNode( file );
projectCache_.getWMLConfigs().remove( file.getProjectRelativePath( ).toString( ) );
projectCache_.getWMLConfigs( ).remove(
file.getProjectRelativePath( ).toString( ) );
} else if ( deltaKind == IResourceDelta.ADDED ){
}
else if( deltaKind == IResourceDelta.ADDED ) {
DependencyListNode newNode = list.addNode( file );
if( newNode == null )
Logger.getInstance( ).logError( "Couldn't create a new" +
"PDL node for file: " + file.getFullPath( ).toString( ) );
Logger.getInstance( ).logError(
"Couldn't create a new" + "PDL node for file: "
+ file.getFullPath( ).toString( ) );
else {
nodesToProcess.add( newNode );
}
} else if ( deltaKind == IResourceDelta.CHANGED ) {
}
else if( deltaKind == IResourceDelta.CHANGED ) {
DependencyListNode node = list.getNode( file );
if( node == null )
Logger.getInstance( ).logError( "Couldn't find file "
+ file.getFullPath( ).toString( ) + " in PDL!." );
Logger.getInstance( ).logError(
"Couldn't find file "
+ file.getFullPath( ).toString( )
+ " in PDL!." );
else {
nodesToProcess.add( node );
list.updateNode( node );
}
} else {
Logger.getInstance( ).log( "unknown delta kind: " + deltaKind );
}
else {
Logger.getInstance( ).log(
"unknown delta kind: " + deltaKind );
}
}
deltasQueue.addAll( Arrays.asList( deltaItem.getAffectedChildren( ) ) );
deltasQueue
.addAll( Arrays.asList( deltaItem.getAffectedChildren( ) ) );
}
// sort the list by index (ascending)
Collections.sort( nodesToProcess, new Comparator<DependencyListNode> () {
Collections.sort( nodesToProcess,
new Comparator< DependencyListNode >( ) {
@Override
public int compare( DependencyListNode o1, DependencyListNode o2 )
public int compare( DependencyListNode o1,
DependencyListNode o2 )
{
if( o1.getIndex( ) < o2.getIndex( ) )
return - 1;
@ -244,17 +266,20 @@ public class WesnothProjectBuilder extends IncrementalProjectBuilder
/**
* Runs the ant job that copies the project in user add-ons directory
* @param paths The paths instance which contains the paths to wesnoth
*
* @param paths
* The paths instance which contains the paths to wesnoth
* utilities
* @param monitor The monitor used to signal progress
* @param monitor
* The monitor used to signal progress
* @return true or false whether the job completed successfully
*/
private boolean runAntJob( Paths paths, IProgressMonitor monitor )
{
String buildXMLPath = project_.getLocation().toOSString() + "/build.xml";
String buildXMLPath = project_.getLocation( ).toOSString( )
+ "/build.xml";
// check for 'build.xml' existance
if ( new File( buildXMLPath ).exists() == true )
{
if( new File( buildXMLPath ).exists( ) == true ) {
// run the ant job to copy the whole project
// in the user add-ons directory (incremental)
monitor.subTask( Messages.WesnothProjectBuilder_8 );
@ -266,8 +291,7 @@ public class WesnothProjectBuilder extends IncrementalProjectBuilder
Logger.getInstance( ).logTool( result );
monitor.worked( 10 );
if (result == null)
{
if( result == null ) {
Logger.getInstance( ).log( "error running the ant job", //$NON-NLS-1$
Messages.WesnothProjectBuilder_13 );
return false;
@ -278,25 +302,25 @@ public class WesnothProjectBuilder extends IncrementalProjectBuilder
return true;
}
protected boolean checkResource( IResource resource, IProgressMonitor monitor )
protected boolean checkResource( IResource resource,
IProgressMonitor monitor )
{
monitor.worked( 5 );
if ( resource.exists() == false ||
monitor.isCanceled() )
if( resource.exists( ) == false || monitor.isCanceled( ) )
return false;
// config files
if ( ResourceUtils.isConfigFile( resource ) )
{
if( ResourceUtils.isConfigFile( resource ) ) {
IFile file = ( IFile ) resource;
String filePath = file.getProjectRelativePath( ).toString( );
String macrosFilePath = PreprocessorUtils.getInstance( ).getMacrosLocation( file );
String macrosFilePath = PreprocessorUtils.getInstance( )
.getMacrosLocation( file );
Logger.getInstance( ).log( "Resource: " + filePath ); //$NON-NLS-1$
try
{
monitor.subTask( String.format( Messages.WesnothProjectBuilder_19 ,filePath ) );
try {
monitor.subTask( String.format(
Messages.WesnothProjectBuilder_19, filePath ) );
List< String > defines = new ArrayList< String >( );
// parse the core only if we don't have any macros file
@ -304,20 +328,23 @@ public class WesnothProjectBuilder extends IncrementalProjectBuilder
defines.add( "SKIP_CORE" ); //$NON-NLS-1$
// we use a single _MACROS_.cfg file for each project
PreprocessorUtils.getInstance().preprocessFile(file, macrosFilePath, defines);
PreprocessorUtils.getInstance( ).preprocessFile( file,
macrosFilePath, defines );
monitor.worked( 5 );
// process the AST ( Abstract Syntax Tree ) to get info for the file
monitor.subTask( String.format( Messages.WesnothProjectBuilder_22, filePath ) );
// process the AST ( Abstract Syntax Tree ) to get info for the
// file
monitor.subTask( String.format(
Messages.WesnothProjectBuilder_22, filePath ) );
WMLConfig config = projectCache_.getWMLConfig( filePath );
SimpleWMLParser parser = new SimpleWMLParser( file, config, projectCache_ );
SimpleWMLParser parser = new SimpleWMLParser( file, config,
projectCache_ );
parser.parse( );
monitor.worked( 10 );
} catch (Exception e)
{
} catch( Exception e ) {
Logger.getInstance( ).logException( e );
}
}
@ -325,17 +352,19 @@ public class WesnothProjectBuilder extends IncrementalProjectBuilder
}
@SuppressWarnings( "unused" )
private void runWMLLint( String installName, IProgressMonitor monitor, IFile file )
private void runWMLLint( String installName, IProgressMonitor monitor,
IFile file )
{
monitor.subTask( String.format( "Running WMLlint on file %s ...", file.getName( ) ) );
ExternalToolInvoker tool = WMLTools.runWMLLint( installName,
file.getLocation().toOSString(), false, false );
monitor.subTask( String.format( "Running WMLlint on file %s ...",
file.getName( ) ) );
ExternalToolInvoker tool = WMLTools.runWMLLint( installName, file
.getLocation( ).toOSString( ), false, false );
tool.waitForTool( );
try {
file.deleteMarkers(Constants.MARKER_WMLLINT, false, IResource.DEPTH_INFINITE);
}
catch ( CoreException e ) {
file.deleteMarkers( Constants.MARKER_WMLLINT, false,
IResource.DEPTH_INFINITE );
} catch( CoreException e ) {
Logger.getInstance( ).logException( e );
}
@ -348,22 +377,25 @@ public class WesnothProjectBuilder extends IncrementalProjectBuilder
/**
* Run the wmlscope for the specified file
*
* @param monitor
* @param file
* @throws CoreException
*/
@SuppressWarnings( "unused" )
private void runWMLScope( String installName, IProgressMonitor monitor, IFile file )
private void runWMLScope( String installName, IProgressMonitor monitor,
IFile file )
{
monitor.subTask( String.format( "Running WMLScope on file %s ...", file.getName( ) ) );
ExternalToolInvoker tool = WMLTools.runWMLScope( installName,
file.getLocation().toOSString(), false );
monitor.subTask( String.format( "Running WMLScope on file %s ...",
file.getName( ) ) );
ExternalToolInvoker tool = WMLTools.runWMLScope( installName, file
.getLocation( ).toOSString( ), false );
tool.waitForTool( );
try {
file.deleteMarkers(Constants.MARKER_WMLSCOPE, false, IResource.DEPTH_INFINITE);
}
catch ( CoreException e ) {
file.deleteMarkers( Constants.MARKER_WMLSCOPE, false,
IResource.DEPTH_INFINITE );
} catch( CoreException e ) {
Logger.getInstance( ).logException( e );
}

View file

@ -13,6 +13,7 @@ import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IProjectNature;
import org.eclipse.core.runtime.CoreException;
import org.wesnoth.Constants;
@ -29,15 +30,13 @@ public class WesnothProjectNature implements IProjectNature
boolean wesnothConfigured = false;
boolean xtextConfigured = false;
int configured = 0;
for (int i = 0; i < commands.length; ++i)
{
if (commands[i].getBuilderName().equals(Constants.BUIILDER_WESNOTH))
{
for( int i = 0; i < commands.length; ++i ) {
if( commands[i].getBuilderName( ).equals(
Constants.BUIILDER_WESNOTH ) ) {
wesnothConfigured = true;
configured++;
}
if (commands[i].getBuilderName().equals(Constants.BUILDER_XTEXT))
{
if( commands[i].getBuilderName( ).equals( Constants.BUILDER_XTEXT ) ) {
xtextConfigured = true;
configured++;
}
@ -45,16 +44,15 @@ public class WesnothProjectNature implements IProjectNature
if( configured == 2 )
return;
ICommand[] newCommands = new ICommand[commands.length + (2 - configured)];
ICommand[] newCommands = new ICommand[commands.length
+ ( 2 - configured )];
System.arraycopy( commands, 0, newCommands, 0, commands.length );
if (wesnothConfigured == false)
{
if( wesnothConfigured == false ) {
ICommand command = desc.newCommand( );
command.setBuilderName( Constants.BUIILDER_WESNOTH );
newCommands[newCommands.length - 1] = command;
}
if (xtextConfigured == false)
{
if( xtextConfigured == false ) {
ICommand command = desc.newCommand( );
command.setBuilderName( Constants.BUILDER_XTEXT );
newCommands[newCommands.length - ( 2 - configured )] = command;
@ -68,11 +66,11 @@ public class WesnothProjectNature implements IProjectNature
{
IProjectDescription description = getProject( ).getDescription( );
ICommand[] commands = description.getBuildSpec( );
for (int i = 0; i < commands.length; ++i)
{
if (commands[i].getBuilderName().equals(Constants.BUIILDER_WESNOTH) ||
commands[i].getBuilderName().equals(Constants.BUILDER_XTEXT))
{
for( int i = 0; i < commands.length; ++i ) {
if( commands[i].getBuilderName( ).equals(
Constants.BUIILDER_WESNOTH )
|| commands[i].getBuilderName( ).equals(
Constants.BUILDER_XTEXT ) ) {
ICommand[] newCommands = new ICommand[commands.length - 1];
System.arraycopy( commands, 0, newCommands, 0, i );
System.arraycopy( commands, i + 1, newCommands, i,

View file

@ -2,6 +2,7 @@ package org.wesnoth.editors;
import org.eclipse.core.runtime.IPath;
import org.eclipse.ui.IEditorLauncher;
import org.wesnoth.utils.GameUtils;
public class MapFileEditor implements IEditorLauncher

View file

@ -17,7 +17,8 @@ import org.eclipse.xtext.formatting.impl.FormattingConfig;
* see : http://www.eclipse.org/Xtext/documentation/latest/xtext.html#formatting
* on how and when to use it
*
* Also see {@link org.eclipse.xtext.xtext.XtextFormattingTokenSerializer} as an example
* Also see {@link org.eclipse.xtext.xtext.XtextFormattingTokenSerializer} as an
* example
*/
public class WMLFormatter extends AbstractDeclarativeFormatter
{
@ -36,21 +37,27 @@ public class WMLFormatter extends AbstractDeclarativeFormatter
c.setAutoLinewrap( 500 );
// no space after '[' and '[/'
c.setNoSpace().after(f.getWMLTagAccess().getLeftSquareBracketKeyword_0());
c.setNoSpace().after(f.getWMLTagAccess().getLeftSquareBracketSolidusKeyword_5());
c.setNoSpace( ).after(
f.getWMLTagAccess( ).getLeftSquareBracketKeyword_0( ) );
c.setNoSpace( ).after(
f.getWMLTagAccess( ).getLeftSquareBracketSolidusKeyword_5( ) );
// no space before and after ']'
c.setNoSpace().around(f.getWMLTagAccess().getRightSquareBracketKeyword_3());
c.setNoSpace().around(f.getWMLTagAccess().getRightSquareBracketKeyword_7());
c.setNoSpace( ).around(
f.getWMLTagAccess( ).getRightSquareBracketKeyword_3( ) );
c.setNoSpace( ).around(
f.getWMLTagAccess( ).getRightSquareBracketKeyword_7( ) );
// no space before and after the '=' in 'key=value'
c.setNoSpace( ).around( f.getWMLKeyAccess( ).getEqualsSignKeyword_1( ) );
// one indentation after tag ...
c.setIndentationIncrement().before(f.getWMLTagAccess().getExpressionsAssignment_4( ));
c.setIndentationIncrement( ).before(
f.getWMLTagAccess( ).getExpressionsAssignment_4( ) );
// but get back the [/<tagname>]
c.setIndentationDecrement().before(f.getWMLTagAccess().getLeftSquareBracketSolidusKeyword_5());
c.setIndentationDecrement( ).before(
f.getWMLTagAccess( ).getLeftSquareBracketSolidusKeyword_5( ) );
c.setLinewrap( 0, 1, 2 ).before( f.getSL_COMMENTRule( ) );
}

View file

@ -12,6 +12,7 @@ import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.resources.IFolder;
import org.eclipse.swt.SWT;
import org.wesnoth.Logger;
import org.wesnoth.Messages;
import org.wesnoth.utils.GUIUtils;
@ -25,9 +26,9 @@ public class ImportMapHandler extends AbstractHandler
public Object execute( ExecutionEvent event )
{
IFolder selectedFolder = WorkspaceUtils.getSelectedFolder( );
if (selectedFolder == null)
{
Logger.getInstance().log("no directory selected (importMapHandler)", //$NON-NLS-1$
if( selectedFolder == null ) {
Logger.getInstance( ).log(
"no directory selected (importMapHandler)", //$NON-NLS-1$
Messages.ImportMapHandler_1 );
return null;
}

View file

@ -10,6 +10,7 @@ package org.wesnoth.handlers;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.wesnoth.utils.GameUtils;

View file

@ -10,6 +10,7 @@ package org.wesnoth.handlers;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.wesnoth.utils.GameUtils;

View file

@ -11,6 +11,7 @@ package org.wesnoth.handlers;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.resources.IFile;
import org.wesnoth.Logger;
import org.wesnoth.Messages;
import org.wesnoth.utils.GameUtils;
@ -23,8 +24,7 @@ public class OpenMapInEditorHandler extends AbstractHandler
public Object execute( ExecutionEvent event )
{
IFile selectedFile = WorkspaceUtils.getSelectedFile( );
if (selectedFile == null)
{
if( selectedFile == null ) {
Logger.getInstance( ).log( "file null (open map handler)", //$NON-NLS-1$
Messages.OpenMapInEditorHandler_1 );
return null;
@ -32,7 +32,8 @@ public class OpenMapInEditorHandler extends AbstractHandler
if( ! selectedFile.getName( ).endsWith( ".map" ) ) //$NON-NLS-1$
{
Logger.getInstance().log("non-map file selected: "+selectedFile.getName(), //$NON-NLS-1$
Logger.getInstance( ).log(
"non-map file selected: " + selectedFile.getName( ), //$NON-NLS-1$
Messages.OpenMapInEditorHandler_4 );
return null;
}

View file

@ -13,6 +13,7 @@ import java.util.Map.Entry;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.resources.IProject;
import org.wesnoth.Messages;
import org.wesnoth.projects.ProjectCache;
import org.wesnoth.projects.ProjectUtils;
@ -30,9 +31,8 @@ public class ReloadFilesHandler extends AbstractHandler
TemplateProvider.getInstance( ).loadTemplates( );
// reload the cache only for already loaded files
for(Entry<IProject, ProjectCache> cache :
ProjectUtils.getProjectCaches().entrySet())
{
for( Entry< IProject, ProjectCache > cache: ProjectUtils
.getProjectCaches( ).entrySet( ) ) {
cache.getValue( ).readDefines( true );
}

View file

@ -10,13 +10,15 @@ package org.wesnoth.handlers;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.wesnoth.utils.WorkspaceUtils;
public class SetupWorkspaceHandler extends AbstractHandler
{
@Override
public Object execute(ExecutionEvent event) {
public Object execute( ExecutionEvent event )
{
WorkspaceUtils.setupWorkspace( true );
return null;
}

View file

@ -12,6 +12,7 @@ import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IFile;
import org.wesnoth.utils.ResourceUtils;
import org.wesnoth.utils.WorkspaceUtils;
@ -27,10 +28,13 @@ public class TestHandler extends AbstractHandler
IFile file = WorkspaceUtils.getSelectedFile( );
System.out.println( ResourceUtils.getWMLRoot( file ) );
// IFile file = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(new Path("E:\\work\\java\\runtime-EclipseApplication\\A_Simple_Campaign\\scenarios\\atemplate.cfg"));
// IFile file =
// ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(new
// Path("E:\\work\\java\\runtime-EclipseApplication\\A_Simple_Campaign\\scenarios\\atemplate.cfg"));
// try
// {
// file.deleteMarkers(Constants.MARKER_WMLSCOPE, false, IResource.DEPTH_INFINITE);
// file.deleteMarkers(Constants.MARKER_WMLSCOPE, false,
// IResource.DEPTH_INFINITE);
// IMarker a= file.createMarker(Constants.MARKER_WMLLINT);
// a.setAttribute(IMarker.LINE_NUMBER, 3);
// a.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING);
@ -53,17 +57,21 @@ public class TestHandler extends AbstractHandler
// {
// e.printStackTrace();
// }
// IWorkingSet set = WorkspaceUtils.getWorkingSetManager().getWorkingSet("Default");
// WorkingSetFilterActionGroup action = new WorkingSetFilterActionGroup(Activator.getShell(),
// IWorkingSet set =
// WorkspaceUtils.getWorkingSetManager().getWorkingSet("Default");
// WorkingSetFilterActionGroup action = new
// WorkingSetFilterActionGroup(Activator.getShell(),
// null);
// action.setWorkingSet(set);
// DefinesSAXHandler handler = (DefinesSAXHandler) ResourceUtils.getWMLSAXHandlerFromResource(
// DefinesSAXHandler handler = (DefinesSAXHandler)
// ResourceUtils.getWMLSAXHandlerFromResource(
// "d:/tmp/wesnoth_plugin/a/_MACROS_.cfg",
// new DefinesSAXHandler());
// System.out.println(handler.getDefines().size());
// try
// {
// BuildCommand c = ((BuildCommand)WorkspaceUtils.getSelectedProject().getDescription().getBuildSpec()[1]);
// BuildCommand c =
// ((BuildCommand)WorkspaceUtils.getSelectedProject().getDescription().getBuildSpec()[1]);
// System.out.println(c);
// }
// catch (CoreException e)
@ -73,14 +81,16 @@ public class TestHandler extends AbstractHandler
// IFile sel = WorkspaceUtils.getSelectedFile();
// if (sel == null)
// return null;
// ExternalToolInvoker parser = WMLTools.runWMLParser2(sel.getLocation().toOSString());
// ExternalToolInvoker parser =
// WMLTools.runWMLParser2(sel.getLocation().toOSString());
// parser.waitForTool();
// ///System.out.println(parser.getOutputContent());
// try
// {
// SAXParser saxparser = SAXParserFactory.newInstance().newSAXParser();
// WMLSaxHandler handler = new WMLSaxHandler();
// saxparser.parse(new InputSource(new StringReader(parser.getOutputContent())), handler);
// saxparser.parse(new InputSource(new
// StringReader(parser.getOutputContent())), handler);
//
// // GUIUtils.showInfoMessageBox("AA: ");
// }
@ -117,7 +127,8 @@ public class TestHandler extends AbstractHandler
// // }
// // else
// // {
//// IMarker[] marks = proj.findMarkers("sett", true, IResource.DEPTH_INFINITE);
// // IMarker[] marks = proj.findMarkers("sett", true,
// IResource.DEPTH_INFINITE);
// // System.out.println(marks.length);
// // }
// // }
@ -147,7 +158,8 @@ public class TestHandler extends AbstractHandler
// tool.waitForTool();
// System.out.println("Exitt");
// String stdin = EditorUtils.getEditorDocument().get();
//EditorUtils.replaceEditorText(WMLTools.runWMLIndent(null, stdin, false, false, false));
// EditorUtils.replaceEditorText(WMLTools.runWMLIndent(null, stdin,
// false, false, false));
// IEditorReference[] files =
// Activator.getDefault().getWorkbench().getActiveWorkbenchWindow().getPages()[0].getEditorReferences();
// for (IEditorReference file : files)
@ -155,7 +167,8 @@ public class TestHandler extends AbstractHandler
// if (file.isDirty())
// file.getEditor(false).doSave(null);
// }
// ProgressMonitorDialog dialog = new ProgressMonitorDialog(Activator.getShell());
// ProgressMonitorDialog dialog = new
// ProgressMonitorDialog(Activator.getShell());
// try
// {
// dialog.run(true, true, new IRunnableWithProgress() {
@ -221,7 +234,8 @@ public class TestHandler extends AbstractHandler
// job2.schedule();
// new WorkspaceJob("My new job") {
// @Override
// public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException
// public IStatus runInWorkspace(IProgressMonitor monitor) throws
// CoreException
// {
// monitor.beginTask("Some nice progress message here ...", 100);
// // execute the task ...try
@ -240,4 +254,3 @@ public class TestHandler extends AbstractHandler
return null;
}
}

View file

@ -19,6 +19,7 @@ import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.wesnoth.installs.WesnothInstallsUtils;
import org.wesnoth.wizards.WizardPageTemplate;
@ -55,34 +56,39 @@ public class ImportProjectPage extends WizardPageTemplate
projectPathField_ = new DirectoryFieldEditor( "project_path",
"Directory to import:", container );
projectPathField_.getTextControl( container ).addModifyListener( listener );
projectPathField_.getTextControl( container ).addModifyListener(
listener );
Label lblNewLabel = new Label( container, SWT.NONE );
lblNewLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
lblNewLabel.setLayoutData( new GridData( SWT.RIGHT, SWT.CENTER, false,
false, 1, 1 ) );
lblNewLabel.setText( "Project Name:" );
txtProjectName_ = new Text( container, SWT.BORDER );
txtProjectName_.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false, 2, 1));
txtProjectName_.setLayoutData( new GridData( SWT.FILL, SWT.TOP, true,
false, 2, 1 ) );
txtProjectName_.addModifyListener( listener );
Label lblWesnothInstall = new Label( container, SWT.NONE );
lblWesnothInstall.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
lblWesnothInstall.setLayoutData( new GridData( SWT.RIGHT, SWT.CENTER,
false, false, 1, 1 ) );
lblWesnothInstall.setText( "Wesnoth install:" );
cmbInstalls_ = new Combo( container, SWT.READ_ONLY );
cmbInstalls_.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
cmbInstalls_.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true,
false, 2, 1 ) );
WesnothInstallsUtils.fillComboWithInstalls( cmbInstalls_ );
}
protected void updatePageIsComplete( )
{
setPageComplete(
! txtProjectName_.getText( ).isEmpty( ) &&
new File( projectPathField_.getStringValue( ) ).exists( ) );
setPageComplete( ! txtProjectName_.getText( ).isEmpty( )
&& new File( projectPathField_.getStringValue( ) ).exists( ) );
}
/**
* Returns the imported project's path
*
* @return A string with the project path
*/
public String getProjectPath( )
@ -92,6 +98,7 @@ public class ImportProjectPage extends WizardPageTemplate
/**
* Returns the imported project's name
*
* @return A string with the imported project's name
*/
public String getProjectName( )
@ -101,6 +108,7 @@ public class ImportProjectPage extends WizardPageTemplate
/**
* Returns the selected install name
*
* @return A string with the selected install name
*/
public String getSelectedInstallName( )

View file

@ -5,11 +5,13 @@ import java.lang.reflect.InvocationTargetException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.ui.IImportWizard;
import org.wesnoth.Logger;
import org.wesnoth.projects.ProjectUtils;
import org.wesnoth.wizards.WizardTemplate;
public class ImportProjectWizard extends WizardTemplate implements IImportWizard
public class ImportProjectWizard extends WizardTemplate implements
IImportWizard
{
private ImportProjectPage page0_;
@ -35,19 +37,16 @@ public class ImportProjectWizard extends WizardTemplate implements IImportWizard
public void run( IProgressMonitor monitor )
{
ProjectUtils.createWesnothProject( page0_.getProjectName( ),
page0_.getProjectPath( ), page0_.getSelectedInstallName(),
monitor );
page0_.getProjectPath( ),
page0_.getSelectedInstallName( ), monitor );
monitor.done( );
}
};
try
{
try {
getContainer( ).run( false, false, op );
} catch (InterruptedException e)
{
} catch( InterruptedException e ) {
return false;
} catch (InvocationTargetException e)
{
} catch( InvocationTargetException e ) {
Logger.getInstance( ).logException( e );
}
return true;

View file

@ -43,11 +43,13 @@ public class SelectWesnothInstallDialog extends Dialog
composite.setLayout( new GridLayout( 2, false ) );
Label lblWesnothInstall = new Label( composite, SWT.NONE );
lblWesnothInstall.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
lblWesnothInstall.setLayoutData( new GridData( SWT.RIGHT, SWT.CENTER,
false, false, 1, 1 ) );
lblWesnothInstall.setText( "Wesnoth Install:" );
cmbInstall_ = new Combo( composite, SWT.READ_ONLY );
GridData gd_cmbInstall_ = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
GridData gd_cmbInstall_ = new GridData( SWT.FILL, SWT.CENTER, true,
false, 1, 1 );
gd_cmbInstall_.widthHint = 163;
cmbInstall_.setLayoutData( gd_cmbInstall_ );
@ -57,15 +59,18 @@ public class SelectWesnothInstallDialog extends Dialog
}
@Override
protected Point getInitialSize() {
protected Point getInitialSize( )
{
return new Point( 291, 123 );
}
/**
* Gets the install selected by the user
*
* @return A string with the name of the install selected
*/
public String getSelectedInstallName( ){
public String getSelectedInstallName( )
{
return cmbInstall_.getText( );
}
}

View file

@ -19,15 +19,18 @@ public class WesnothInstall
version_ = version;
}
public String getName( ){
public String getName( )
{
return name_;
}
public String getVersion( ) {
public String getVersion( )
{
return version_;
}
public void setVersion( String newVersion ){
public void setVersion( String newVersion )
{
version_ = newVersion;
}
}

View file

@ -16,6 +16,7 @@ import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Combo;
import org.wesnoth.Constants;
import org.wesnoth.Logger;
import org.wesnoth.Messages;
@ -30,13 +31,15 @@ public class WesnothInstallsUtils
/**
* Returns a list of the current wesnoth installations available
* in the preferences store
*
* @return A list with Wesnoth Installs
*/
public static List< WesnothInstall > getInstalls( )
{
List< WesnothInstall > installsList = new ArrayList< WesnothInstall >( );
// unpack installs
String[] installs = Preferences.getString( Constants.P_INST_INSTALL_LIST ).split( ";" ); //$NON-NLS-1$
String[] installs = Preferences.getString(
Constants.P_INST_INSTALL_LIST ).split( ";" ); //$NON-NLS-1$
for( String str: installs ) {
if( str.isEmpty( ) )
continue;
@ -44,7 +47,8 @@ public class WesnothInstallsUtils
String[] tokens = str.split( ":" ); //$NON-NLS-1$
if( tokens.length != 2 ) {
Logger.getInstance().logError( "invalid install [" + str + "] in installs list." ); //$NON-NLS-1$ //$NON-NLS-2$
Logger.getInstance( ).logError(
"invalid install [" + str + "] in installs list." ); //$NON-NLS-1$ //$NON-NLS-2$
continue;
}
@ -56,7 +60,9 @@ public class WesnothInstallsUtils
/**
* Sets the specified Installs list in the preferences store
* @param installsList The list to replace / set the installs list
*
* @param installsList
* The list to replace / set the installs list
*/
public static void setInstalls( Collection< WesnothInstall > installsList )
{
@ -70,12 +76,15 @@ public class WesnothInstallsUtils
installs.append( ":" ); //$NON-NLS-1$
installs.append( install.getVersion( ) );
}
Preferences.getPreferences().setValue( Constants.P_INST_INSTALL_LIST, installs.toString() );
Preferences.getPreferences( ).setValue( Constants.P_INST_INSTALL_LIST,
installs.toString( ) );
}
/**
* Returns the install name for the specified resource
* @param resourcePath The path to the resource
*
* @param resourcePath
* The path to the resource
* @return The install name for the resource
*/
public static String getInstallNameForResource( String resourcePath )
@ -83,13 +92,15 @@ public class WesnothInstallsUtils
if( StringUtils.isNullOrEmpty( resourcePath ) )
return "";
return getInstallNameForResource( ResourcesPlugin.getWorkspace( ).getRoot( ).
findMember( resourcePath ) );
return getInstallNameForResource( ResourcesPlugin.getWorkspace( )
.getRoot( ).findMember( resourcePath ) );
}
/**
* Returns the install name for the specified resource
* @param resource The resource
*
* @param resource
* The resource
* @return The install name for the resource
*/
public static String getInstallNameForResource( IResource resource )
@ -97,26 +108,34 @@ public class WesnothInstallsUtils
if( resource == null || ! resource.exists( ) )
return ""; //$NON-NLS-1$
return ProjectUtils.getCacheForProject( resource.getProject( ) ).getInstallName( );
return ProjectUtils.getCacheForProject( resource.getProject( ) )
.getInstallName( );
}
/**
* Sets the install name for the specified resource
* @param resource The resource to set the install to
* @param newInstallName The new install name
*
* @param resource
* The resource to set the install to
* @param newInstallName
* The new install name
*/
public static void setInstallNameForResource( IResource resource, String newInstallName )
public static void setInstallNameForResource( IResource resource,
String newInstallName )
{
if( resource == null )
return;
ProjectUtils.getCacheForProject( resource.getProject( ) ).setInstallName( newInstallName );
ProjectUtils.getCacheForProject( resource.getProject( ) )
.setInstallName( newInstallName );
}
/**
* Fills the specified combo box with all the current installs
* and selects the default or the first ( if no default exists )
* @param comboBox The combobox to fill
*
* @param comboBox
* The combobox to fill
*/
public static void fillComboWithInstalls( Combo comboBox )
{
@ -134,8 +153,8 @@ public class WesnothInstallsUtils
}
// select the first if there is no other selected
if ( comboBox.getSelectionIndex( ) == -1 &&
comboBox.getItemCount( ) > 0 )
if( comboBox.getSelectionIndex( ) == - 1
&& comboBox.getItemCount( ) > 0 )
comboBox.select( 0 );
}
@ -144,7 +163,8 @@ public class WesnothInstallsUtils
* for the specified resource. If it is not, it will guide the user
* through selecting a proper install (if any).
*
* @param resource True if the installation is valid, false
* @param resource
* True if the installation is valid, false
* otherwise
* @return Boolean flag whether the setup was successfull or failed.
*/
@ -158,8 +178,10 @@ public class WesnothInstallsUtils
if( Preferences.getDefaultInstallName( ).isEmpty( ) )
return false;
if ( GUIUtils.showMessageBox( String.format(
Messages.WesnothInstallsUtils_1, resource.getProject( ).getName( ) ),
if( GUIUtils
.showMessageBox( String.format(
Messages.WesnothInstallsUtils_1, resource
.getProject( ).getName( ) ),
SWT.ICON_QUESTION | SWT.YES | SWT.NO ) == SWT.NO )
return false; // no hope :(

View file

@ -33,7 +33,9 @@ public class DoubleInputDialog extends Dialog
private String resStr1 = "", resStr2 = ""; //$NON-NLS-1$ //$NON-NLS-2$
private String val1String = "", val2String = ""; //$NON-NLS-1$ //$NON-NLS-2$
public DoubleInputDialog(Shell parentShell, String value1String, String value2String) {
public DoubleInputDialog( Shell parentShell, String value1String,
String value2String )
{
super( parentShell );
setShellStyle( SWT.DIALOG_TRIM );
val1String = value1String + ":"; //$NON-NLS-1$
@ -50,18 +52,22 @@ public class DoubleInputDialog extends Dialog
lblValue1 = new Label( container, SWT.NONE );
lblValue1.setText( val1String );
Label label = new Label( container, SWT.NONE );
label.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
label.setLayoutData( new GridData( SWT.RIGHT, SWT.CENTER, false, false,
1, 1 ) );
txtValue1_ = new Text( container, SWT.BORDER );
txtValue1_.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
txtValue1_.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true,
false, 1, 1 ) );
lblValue2 = new Label( container, SWT.NONE );
lblValue2.setText( val2String );
Label label_3 = new Label( container, SWT.NONE );
label_3.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
label_3.setLayoutData( new GridData( SWT.RIGHT, SWT.CENTER, false,
false, 1, 1 ) );
txtValue2_ = new Text( container, SWT.BORDER );
txtValue2_.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
txtValue2_.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true,
false, 1, 1 ) );
return container;
}
@ -69,8 +75,10 @@ public class DoubleInputDialog extends Dialog
@Override
protected void createButtonsForButtonBar( Composite parent )
{
createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true);
createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false);
createButton( parent, IDialogConstants.OK_ID,
IDialogConstants.OK_LABEL, true );
createButton( parent, IDialogConstants.CANCEL_ID,
IDialogConstants.CANCEL_LABEL, false );
}
@Override

View file

@ -18,12 +18,15 @@ public class RegexStringFieldEditor extends StringFieldEditor
/**
* An regex matcher string field editor.
* @param regex The regex to match this textbox's string
* @param errorMessage The message to show as error when field's text
*
* @param regex
* The regex to match this textbox's string
* @param errorMessage
* The message to show as error when field's text
* doesn't match the regex
*/
public RegexStringFieldEditor(String name, String labelText,
String regex, String errorMessage, Composite parent)
public RegexStringFieldEditor( String name, String labelText, String regex,
String errorMessage, Composite parent )
{
super( name, labelText, parent );
regex_ = regex;

View file

@ -13,13 +13,14 @@ import org.eclipse.jface.preference.FieldEditorPreferencePage;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
public abstract class AbstractPreferencePage extends FieldEditorPreferencePage implements
IWorkbenchPreferencePage
public abstract class AbstractPreferencePage extends FieldEditorPreferencePage
implements IWorkbenchPreferencePage
{
public AbstractPreferencePage( int style )
{
super( style );
}
public AbstractPreferencePage( )
{
super( );
@ -27,12 +28,14 @@ public abstract class AbstractPreferencePage extends FieldEditorPreferencePage i
/**
* Adds the specified field editor with the specified tooltip
*
* @param editor
* @param tooltip
*/
protected void addField( FieldEditor editor, String tooltip )
{
editor.getLabelControl(getFieldEditorParent()).setToolTipText(tooltip);
editor.getLabelControl( getFieldEditorParent( ) ).setToolTipText(
tooltip );
super.addField( editor );
}

View file

@ -15,6 +15,7 @@ import java.util.Map.Entry;
import org.eclipse.jface.preference.BooleanFieldEditor;
import org.eclipse.jface.preference.StringFieldEditor;
import org.eclipse.xtext.ui.editor.preferences.fields.LabelFieldEditor;
import org.wesnoth.Constants;
import org.wesnoth.Messages;
import org.wesnoth.WesnothPlugin;
@ -51,14 +52,19 @@ public class AddonUploadPreferencePage extends AbstractPreferencePage
@Override
protected void createFieldEditors( )
{
addField(new StringFieldEditor(Constants.P_WAU_PASSWORD,
Messages.AddonUploadPreferencePage_11, getFieldEditorParent()),
addField(
new StringFieldEditor( Constants.P_WAU_PASSWORD,
Messages.AddonUploadPreferencePage_11,
getFieldEditorParent( ) ),
Messages.AddonUploadPreferencePage_12 );
addField( new BooleanFieldEditor( Constants.P_WAU_VERBOSE,
Messages.AddonUploadPreferencePage_13, 1, getFieldEditorParent()));
Messages.AddonUploadPreferencePage_13, 1,
getFieldEditorParent( ) ) );
addField(new RegexStringFieldEditor(Constants.P_WAU_ADDRESS,
Messages.AddonUploadPreferencePage_14, Messages.AddonUploadPreferencePage_15,
addField(
new RegexStringFieldEditor( Constants.P_WAU_ADDRESS,
Messages.AddonUploadPreferencePage_14,
Messages.AddonUploadPreferencePage_15,
Messages.AddonUploadPreferencePage_16,
getFieldEditorParent( ) ),
Messages.AddonUploadPreferencePage_17 );
@ -66,20 +72,23 @@ public class AddonUploadPreferencePage extends AbstractPreferencePage
StringBuilder ports = new StringBuilder( );
StringBuilder portsRegex = new StringBuilder( );
portsRegex.append( "(" ); //$NON-NLS-1$
for (Entry<String, String> item : ADDON_SERVER_PORTS.entrySet())
{
for( Entry< String, String > item: ADDON_SERVER_PORTS.entrySet( ) ) {
portsRegex.append( item.getKey( ) + "|" ); //$NON-NLS-1$
ports.append(String.format("\t%s - %s\n", item.getKey(), item.getValue())); //$NON-NLS-1$
ports.append( String.format(
"\t%s - %s\n", item.getKey( ), item.getValue( ) ) ); //$NON-NLS-1$
}
portsRegex.deleteCharAt( portsRegex.length( ) - 1 );
portsRegex.append( ")*" ); //$NON-NLS-1$
// System.out.println(portsRegex.toString());
addField(new RegexStringFieldEditor(Constants.P_WAU_PORT,
Messages.AddonUploadPreferencePage_22, portsRegex.toString(),
Messages.AddonUploadPreferencePage_23, getFieldEditorParent()),
addField(
new RegexStringFieldEditor( Constants.P_WAU_PORT,
Messages.AddonUploadPreferencePage_22,
portsRegex.toString( ),
Messages.AddonUploadPreferencePage_23,
getFieldEditorParent( ) ),
Messages.AddonUploadPreferencePage_24 );
addField(new LabelFieldEditor(Messages.AddonUploadPreferencePage_25 +
ports.toString(), getFieldEditorParent()));
addField( new LabelFieldEditor( Messages.AddonUploadPreferencePage_25
+ ports.toString( ), getFieldEditorParent( ) ) );
}
}

View file

@ -8,12 +8,12 @@
*******************************************************************************/
package org.wesnoth.preferences;
import org.eclipse.jface.preference.BooleanFieldEditor;
import org.wesnoth.Constants;
import org.wesnoth.Messages;
import org.wesnoth.WesnothPlugin;
import org.eclipse.jface.preference.BooleanFieldEditor;
public class AdvancedPreferencePage extends AbstractPreferencePage
{
public AdvancedPreferencePage( )
@ -27,17 +27,15 @@ public class AdvancedPreferencePage extends AbstractPreferencePage
@Override
protected void createFieldEditors( )
{
addField( new BooleanFieldEditor(
Constants.P_NO_TERRAIN_GFX, Messages.AdvancedPreferencePage_1,
BooleanFieldEditor.SEPARATE_LABEL,
getFieldEditorParent( ) ),
addField( new BooleanFieldEditor( Constants.P_NO_TERRAIN_GFX,
Messages.AdvancedPreferencePage_1,
BooleanFieldEditor.SEPARATE_LABEL, getFieldEditorParent( ) ),
Messages.AdvancedPreferencePage_2 );
addField( new BooleanFieldEditor(
Constants.P_WML_VALIDATION, "WML Validation, parent",
BooleanFieldEditor.SEPARATE_LABEL,
addField( new BooleanFieldEditor( Constants.P_WML_VALIDATION,
"WML Validation, parent", BooleanFieldEditor.SEPARATE_LABEL,
getFieldEditorParent( ) ),
"If checked, the WML Editor will validate some of the " +
"written WML to check for semantic errors." );
"If checked, the WML Editor will validate some of the "
+ "written WML to check for semantic errors." );
}
}

View file

@ -11,14 +11,14 @@ package org.wesnoth.preferences;
import java.util.HashMap;
import java.util.Map;
import org.wesnoth.Constants;
import org.wesnoth.WesnothPlugin;
import org.wesnoth.utils.StringUtils;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
import org.eclipse.jface.preference.IPreferenceStore;
import org.wesnoth.Constants;
import org.wesnoth.WesnothPlugin;
import org.wesnoth.utils.StringUtils;
/**
* Class used to initialize default preference values.
*/
@ -27,12 +27,12 @@ public class Preferences extends AbstractPreferenceInitializer
/**
* A map for storing the paths for the current session
*/
protected final static Map< String, Paths > paths_ =
new HashMap< String, Paths > ();
protected final static Map< String, Paths > paths_ = new HashMap< String, Paths >( );
public static void initializeToDefault( )
{
IPreferenceStore store = WesnothPlugin.getDefault().getPreferenceStore();
IPreferenceStore store = WesnothPlugin.getDefault( )
.getPreferenceStore( );
// general settings
store.setDefault( Constants.P_WESNOTH_EXEC_PATH, "" ); //$NON-NLS-1$
store.setDefault( Constants.P_WESNOTH_WORKING_DIR, "" ); //$NON-NLS-1$
@ -97,6 +97,7 @@ public class Preferences extends AbstractPreferenceInitializer
{
return getPreferences( ).getInt( prefName );
}
/**
* Returns the contents of the specified preference as a boolean
* or false if there is no such preference set
@ -109,7 +110,8 @@ public class Preferences extends AbstractPreferenceInitializer
/**
* Gets the install preference prefix for the specified install name.
*
* @param installName The name of the install. If the parameter is null,
* @param installName
* The name of the install. If the parameter is null,
* the default install prefix is returned
*/
public static String getInstallPrefix( String installName )
@ -122,6 +124,7 @@ public class Preferences extends AbstractPreferenceInitializer
/**
* Returns the name of the default install
*
* @return Returns the name of the default install
*/
public static String getDefaultInstallName( )
@ -131,16 +134,21 @@ public class Preferences extends AbstractPreferenceInitializer
/**
* Sets the default install name
* @param newInstallName The new install name
*
* @param newInstallName
* The new install name
*/
public static void setDefaultInstallName( String newInstallName )
{
getPreferences( ).setValue( Constants.P_INST_DEFAULT_INSTALL, newInstallName );
getPreferences( ).setValue( Constants.P_INST_DEFAULT_INSTALL,
newInstallName );
}
/**
* Returns a new Paths object based on the specified install name
* @param installName The install name used for the paths
*
* @param installName
* The install name used for the paths
* @return A new Paths object
*/
public static Paths getPaths( String installName )
@ -175,6 +183,7 @@ public class Preferences extends AbstractPreferenceInitializer
/**
* Returns the install name associated with this instance
*
* @return A string representing the install name
*/
public String getInstallName( )
@ -184,6 +193,7 @@ public class Preferences extends AbstractPreferenceInitializer
/**
* Returns the addons directory
*
* @return Returns the addons directory
*/
public String getAddonsDir( )
@ -193,6 +203,7 @@ public class Preferences extends AbstractPreferenceInitializer
/**
* Returns the data user directory
*
* @return Returns the data user directory
*/
public String getUserDataDir( )
@ -202,6 +213,7 @@ public class Preferences extends AbstractPreferenceInitializer
/**
* Returns the campaign directory
*
* @return Returns the campaign directory
*/
public String getCampaignDir( )
@ -211,6 +223,7 @@ public class Preferences extends AbstractPreferenceInitializer
/**
* Returns the 'data/core' directory
*
* @return Returns the 'data/core' directory
*/
public String getCoreDir( )
@ -220,6 +233,7 @@ public class Preferences extends AbstractPreferenceInitializer
/**
* Returns the <b>schema.cfg</b> file path
*
* @return Returns the schema.cfg file path
*/
public String getSchemaPath( )
@ -229,6 +243,7 @@ public class Preferences extends AbstractPreferenceInitializer
/**
* Returns the user's directory
*
* @return Returns the user's directory
*/
public String getUserDir( )
@ -240,6 +255,7 @@ public class Preferences extends AbstractPreferenceInitializer
/**
* Returns the working directory that contains the
* <b>data</b> folder
*
* @return Returns the working directory
*/
public String getWorkingDir( )
@ -251,6 +267,7 @@ public class Preferences extends AbstractPreferenceInitializer
/**
* Returns the directory that contains the wml tools
* ( wmlscope, wmllint, wmlindent, wesnoth_addons_manager, etc)
*
* @return Returns the directory that contains the wml tools
*/
public String getWMLToolsDir( )
@ -261,6 +278,7 @@ public class Preferences extends AbstractPreferenceInitializer
/**
* Returns the path to the wesnoth executable
*
* @return Returns the path to the wesnoth executable
*/
public String getWesnothExecutablePath( )

View file

@ -11,9 +11,10 @@ package org.wesnoth.preferences;
import org.eclipse.jface.preference.BooleanFieldEditor;
import org.eclipse.jface.preference.ScaleFieldEditor;
import org.eclipse.xtext.ui.editor.preferences.fields.LabelFieldEditor;
import org.wesnoth.WesnothPlugin;
import org.wesnoth.Constants;
import org.wesnoth.Messages;
import org.wesnoth.WesnothPlugin;
public class WMLToolsPreferencePage extends AbstractPreferencePage
{
@ -28,27 +29,32 @@ public class WMLToolsPreferencePage extends AbstractPreferencePage
@Override
protected void createFieldEditors( )
{
addField(new LabelFieldEditor(Messages.WMLToolsPreferencePage_1, getFieldEditorParent()));
addField(new BooleanFieldEditor(Constants.P_WMLINDENT_DRYRUN, Messages.WMLToolsPreferencePage_2, 1,
getFieldEditorParent()));
addField(new BooleanFieldEditor(Constants.P_WMLINDENT_VERBOSE, Messages.WMLToolsPreferencePage_3, 1,
addField( new LabelFieldEditor( Messages.WMLToolsPreferencePage_1,
getFieldEditorParent( ) ) );
addField( new BooleanFieldEditor( Constants.P_WMLINDENT_DRYRUN,
Messages.WMLToolsPreferencePage_2, 1, getFieldEditorParent( ) ) );
addField( new BooleanFieldEditor( Constants.P_WMLINDENT_VERBOSE,
Messages.WMLToolsPreferencePage_3, 1, getFieldEditorParent( ) ) );
addField( new LabelFieldEditor( "", getFieldEditorParent( ) ) ); //$NON-NLS-1$
addField(new LabelFieldEditor(Messages.WMLToolsPreferencePage_5, getFieldEditorParent()));
addField(new ScaleFieldEditor(Constants.P_WMLSCOPE_VERBOSE_LEVEL, Messages.WMLToolsPreferencePage_6,
getFieldEditorParent(), 0, 2, 1, 1));
addField(new BooleanFieldEditor(Constants.P_WMLSCOPE_COLLISIONS, Messages.WMLToolsPreferencePage_7, 1,
addField( new LabelFieldEditor( Messages.WMLToolsPreferencePage_5,
getFieldEditorParent( ) ) );
addField( new ScaleFieldEditor( Constants.P_WMLSCOPE_VERBOSE_LEVEL,
Messages.WMLToolsPreferencePage_6, getFieldEditorParent( ), 0,
2, 1, 1 ) );
addField( new BooleanFieldEditor( Constants.P_WMLSCOPE_COLLISIONS,
Messages.WMLToolsPreferencePage_7, 1, getFieldEditorParent( ) ) );
addField( new LabelFieldEditor( "", getFieldEditorParent( ) ) ); //$NON-NLS-1$
addField(new LabelFieldEditor(Messages.WMLToolsPreferencePage_9, getFieldEditorParent()));
addField(new BooleanFieldEditor(Constants.P_WMLLINT_DRYRUN, Messages.WMLToolsPreferencePage_10, 1,
addField( new LabelFieldEditor( Messages.WMLToolsPreferencePage_9,
getFieldEditorParent( ) ) );
addField(new BooleanFieldEditor(Constants.P_WMLLINT_SPELL_CHECK, Messages.WMLToolsPreferencePage_11, 1,
getFieldEditorParent()));
addField(new ScaleFieldEditor(Constants.P_WMLLINT_VERBOSE_LEVEL, Messages.WMLToolsPreferencePage_12,
getFieldEditorParent(), 0, 3, 1, 1));
addField( new BooleanFieldEditor( Constants.P_WMLLINT_DRYRUN,
Messages.WMLToolsPreferencePage_10, 1, getFieldEditorParent( ) ) );
addField( new BooleanFieldEditor( Constants.P_WMLLINT_SPELL_CHECK,
Messages.WMLToolsPreferencePage_11, 1, getFieldEditorParent( ) ) );
addField( new ScaleFieldEditor( Constants.P_WMLLINT_VERBOSE_LEVEL,
Messages.WMLToolsPreferencePage_12, getFieldEditorParent( ), 0,
3, 1, 1 ) );
addField( new LabelFieldEditor( "", getFieldEditorParent( ) ) ); //$NON-NLS-1$
}
}

View file

@ -50,6 +50,7 @@ import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
import org.eclipse.xtext.ui.editor.preferences.fields.LabelFieldEditor;
import org.wesnoth.Constants;
import org.wesnoth.Messages;
import org.wesnoth.WesnothPlugin;
@ -93,8 +94,7 @@ public class WesnothInstallsPage extends AbstractPreferencePage
installs_ = new HashMap< String, WesnothInstall >( );
List< WesnothInstall > installs = WesnothInstallsUtils.getInstalls( );
for ( WesnothInstall wesnothInstall : installs )
{
for( WesnothInstall wesnothInstall: installs ) {
installs_.put( wesnothInstall.getName( ), wesnothInstall );
}
}
@ -114,20 +114,21 @@ public class WesnothInstallsPage extends AbstractPreferencePage
wesnothExecutableField_ = new FileFieldEditor( "", //$NON-NLS-1$
Messages.WesnothPreferencesPage_5, getFieldEditorParent( ) );
wesnothExecutableField_.getTextControl(getFieldEditorParent()).
addFocusListener(new FocusListener() {
wesnothExecutableField_.getTextControl( getFieldEditorParent( ) )
.addFocusListener( new FocusListener( ) {
@Override
public void focusLost( FocusEvent e )
{
checkState( );
}
@Override
public void focusGained( FocusEvent e )
{
}
} );
wesnothExecutableField_.getTextControl(getFieldEditorParent()).
addModifyListener(new ModifyListener() {
wesnothExecutableField_.getTextControl( getFieldEditorParent( ) )
.addModifyListener( new ModifyListener( ) {
@Override
public void modifyText( ModifyEvent e )
@ -139,8 +140,8 @@ public class WesnothInstallsPage extends AbstractPreferencePage
wesnothWorkingDirField_ = new DirectoryFieldEditor( "", //$NON-NLS-1$
Messages.WesnothPreferencesPage_7, getFieldEditorParent( ) );
wesnothWorkingDirField_.getTextControl(getFieldEditorParent()).
addModifyListener(listener);
wesnothWorkingDirField_.getTextControl( getFieldEditorParent( ) )
.addModifyListener( listener );
addField( wesnothWorkingDirField_, Messages.WesnothPreferencesPage_8 );
wesnothUserDirField_ = new DirectoryFieldEditor( "", //$NON-NLS-1$
@ -167,10 +168,12 @@ public class WesnothInstallsPage extends AbstractPreferencePage
{
Composite installComposite = new Composite( parent, 0 );
installComposite.setLayout( new GridLayout( 2, false ) );
installComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
installComposite.setLayoutData( new GridData( SWT.FILL, SWT.FILL, true,
true, 1, 1 ) );
// create install manager
installsTableViewer_ = new TableViewer(installComposite, SWT.BORDER | SWT.FULL_SELECTION);
installsTableViewer_ = new TableViewer( installComposite, SWT.BORDER
| SWT.FULL_SELECTION );
installsTable_ = installsTableViewer_.getTable( );
installsTable_.addMouseListener( new MouseAdapter( ) {
@Override
@ -180,17 +183,20 @@ public class WesnothInstallsPage extends AbstractPreferencePage
}
} );
installsTable_.setHeaderVisible( true );
installsTable_.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
installsTable_.setLayoutData( new GridData( SWT.FILL, SWT.FILL, true,
true, 1, 1 ) );
TableColumn tblclmnName = new TableColumn( installsTable_, SWT.NONE );
tblclmnName.setWidth( 150 );
tblclmnName.setText( Messages.WesnothInstallsPage_5 );
TableColumn tblclmnWesnothVersion = new TableColumn(installsTable_, SWT.NONE);
TableColumn tblclmnWesnothVersion = new TableColumn( installsTable_,
SWT.NONE );
tblclmnWesnothVersion.setWidth( 70 );
tblclmnWesnothVersion.setText( Messages.WesnothInstallsPage_6 );
TableColumn tblclmnIsDefault = new TableColumn(installsTable_, SWT.NONE);
TableColumn tblclmnIsDefault = new TableColumn( installsTable_,
SWT.NONE );
tblclmnIsDefault.setWidth( 70 );
tblclmnIsDefault.setText( Messages.WesnothInstallsPage_7 );
@ -203,14 +209,16 @@ public class WesnothInstallsPage extends AbstractPreferencePage
fl_composite.spacing = 10;
fl_composite.marginHeight = 10;
composite.setLayout( fl_composite );
GridData gd_composite = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
GridData gd_composite = new GridData( SWT.FILL, SWT.CENTER, true,
false, 1, 1 );
gd_composite.widthHint = 80;
composite.setLayoutData( gd_composite );
Button btnNew = new Button( composite, SWT.NONE );
btnNew.addSelectionListener( new SelectionAdapter( ) {
@Override
public void widgetSelected(SelectionEvent e) {
public void widgetSelected( SelectionEvent e )
{
newInstall( );
}
} );
@ -219,7 +227,8 @@ public class WesnothInstallsPage extends AbstractPreferencePage
Button btnRemove = new Button( composite, SWT.NONE );
btnRemove.addSelectionListener( new SelectionAdapter( ) {
@Override
public void widgetSelected(SelectionEvent e) {
public void widgetSelected( SelectionEvent e )
{
removeInstall( getSelectedInstall( ) );
}
} );
@ -228,7 +237,8 @@ public class WesnothInstallsPage extends AbstractPreferencePage
Button btnSetAsDefault = new Button( composite, SWT.NONE );
btnSetAsDefault.addSelectionListener( new SelectionAdapter( ) {
@Override
public void widgetSelected(SelectionEvent e) {
public void widgetSelected( SelectionEvent e )
{
setInstallAsDefault( getSelectedInstall( ) );
}
} );
@ -240,21 +250,21 @@ public class WesnothInstallsPage extends AbstractPreferencePage
txtInstallName_ = new Text( parent, SWT.SINGLE );
txtInstallName_.setText( Messages.WesnothInstallsPage_12 );
txtInstallName_.setEditable( false );
txtInstallName_.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
txtInstallName_.setLayoutData( new GridData( SWT.FILL, SWT.CENTER,
false, false, 1, 1 ) );
txtInstallName_.addVerifyListener( new VerifyListener( ) {
private boolean isCharOk( char character )
{
return ( character >= 'a' && character <= 'z' ) ||
( character >= 'A' && character <= 'Z' ) ||
( character >= '0' && character <= '9' );
return ( character >= 'a' && character <= 'z' )
|| ( character >= 'A' && character <= 'Z' )
|| ( character >= '0' && character <= '9' );
}
@Override
public void verifyText( VerifyEvent e )
{
if ( e.character == 0 )
{
if( e.character == 0 ) {
// we got a text copied. Check for invalid chars.
for( int index = e.text.length( ) - 1; index >= 0; --index ) {
if( isCharOk( e.text.charAt( index ) ) == false ) {
@ -263,12 +273,12 @@ public class WesnothInstallsPage extends AbstractPreferencePage
}
}
} else {
e.doit = isCharOk( e.character ) ||
e.keyCode == SWT.BS ||
e.keyCode == SWT.ARROW_LEFT ||
e.keyCode == SWT.ARROW_RIGHT ||
e.keyCode == SWT.DEL;
}
else {
e.doit = isCharOk( e.character ) || e.keyCode == SWT.BS
|| e.keyCode == SWT.ARROW_LEFT
|| e.keyCode == SWT.ARROW_RIGHT
|| e.keyCode == SWT.DEL;
}
}
} );
@ -277,7 +287,8 @@ public class WesnothInstallsPage extends AbstractPreferencePage
lblVersion.setText( Messages.WesnothInstallsPage_13 );
cmbVersion_ = new Combo( parent, SWT.READ_ONLY );
cmbVersion_.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
cmbVersion_.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true,
false, 1, 1 ) );
cmbVersion_.add( "1.9.x" ); //$NON-NLS-1$
cmbVersion_.add( "trunk" ); //$NON-NLS-1$
@ -310,20 +321,24 @@ public class WesnothInstallsPage extends AbstractPreferencePage
// unset all settings.
IPreferenceStore prefs = Preferences.getPreferences( );
String installPrefix = Preferences.getInstallPrefix( install.getName( ) );
String installPrefix = Preferences.getInstallPrefix( install
.getName( ) );
prefs.setToDefault( installPrefix + Constants.P_WESNOTH_EXEC_PATH );
prefs.setToDefault( installPrefix + Constants.P_WESNOTH_USER_DIR );
prefs.setToDefault( installPrefix + Constants.P_WESNOTH_WMLTOOLS_DIR );
prefs.setToDefault( installPrefix
+ Constants.P_WESNOTH_WMLTOOLS_DIR );
prefs.setToDefault( installPrefix + Constants.P_WESNOTH_WORKING_DIR );
// unset the default install if this was that
// and select another one (the first) - if any - as default
if ( install.getName( ).equals( Preferences.getDefaultInstallName( ) ) ) {
if( install.getName( )
.equals( Preferences.getDefaultInstallName( ) ) ) {
Preferences.setDefaultInstallName( "" ); //$NON-NLS-1$
if( ! installs_.isEmpty( ) ) {
// get the first item from the iterator
Iterator<WesnothInstall> itor = installs_.values( ).iterator( );
Iterator< WesnothInstall > itor = installs_.values( )
.iterator( );
setInstallAsDefault( itor.next( ) );
}
}
@ -342,7 +357,9 @@ public class WesnothInstallsPage extends AbstractPreferencePage
/**
* Updates the interface with the specified install
* @param install The install
*
* @param install
* The install
*/
private void updateInterface( WesnothInstall install )
{
@ -358,18 +375,26 @@ public class WesnothInstallsPage extends AbstractPreferencePage
/**
* Sets the fields's internal preference name based on the installPrefix
* @param installPrefix The install prefix
* @param loadPreferences True to load the current stored preference
*
* @param installPrefix
* The install prefix
* @param loadPreferences
* True to load the current stored preference
*/
private void setFieldsPreferenceName( String installPrefix, boolean loadPreferences )
private void setFieldsPreferenceName( String installPrefix,
boolean loadPreferences )
{
wesnothExecutableField_.setPreferenceName( installPrefix + Constants.P_WESNOTH_EXEC_PATH );
wesnothExecutableField_.setPreferenceName( installPrefix
+ Constants.P_WESNOTH_EXEC_PATH );
wesnothUserDirField_.setPreferenceName( installPrefix + Constants.P_WESNOTH_USER_DIR );
wesnothUserDirField_.setPreferenceName( installPrefix
+ Constants.P_WESNOTH_USER_DIR );
wesnothWorkingDirField_.setPreferenceName( installPrefix + Constants.P_WESNOTH_WORKING_DIR );
wesnothWorkingDirField_.setPreferenceName( installPrefix
+ Constants.P_WESNOTH_WORKING_DIR );
wmlToolsField_.setPreferenceName( installPrefix + Constants.P_WESNOTH_WMLTOOLS_DIR );
wmlToolsField_.setPreferenceName( installPrefix
+ Constants.P_WESNOTH_WMLTOOLS_DIR );
if( loadPreferences ) {
wesnothUserDirField_.setStringValue( "" ); //$NON-NLS-1$
@ -394,13 +419,13 @@ public class WesnothInstallsPage extends AbstractPreferencePage
if( new File( wesnothExec ).exists( ) ) {
String wesnothExecName = new File( wesnothExec ).getName( );
if (wesnothWorkingDirField_.getStringValue().isEmpty() &&
!wesnothExec.isEmpty() &&
new File(wesnothExec.substring(0,
wesnothExec.lastIndexOf(wesnothExecName))).exists())
{
wesnothWorkingDirField_.setStringValue(wesnothExec.substring(0,
wesnothExec.lastIndexOf(wesnothExecName)));
if( wesnothWorkingDirField_.getStringValue( ).isEmpty( )
&& ! wesnothExec.isEmpty( )
&& new File( wesnothExec.substring( 0,
wesnothExec.lastIndexOf( wesnothExecName ) ) )
.exists( ) ) {
wesnothWorkingDirField_.setStringValue( wesnothExec.substring(
0, wesnothExec.lastIndexOf( wesnothExecName ) ) );
}
}
@ -420,39 +445,40 @@ public class WesnothInstallsPage extends AbstractPreferencePage
os = "windows"; //$NON-NLS-1$
List< ReplaceableParameter > params = new ArrayList< ReplaceableParameter >( );
params.add(new ReplaceableParameter("$$home_path", System.getProperty("user.home"))); //$NON-NLS-1$ //$NON-NLS-2$
params.add( new ReplaceableParameter(
"$$home_path", System.getProperty( "user.home" ) ) ); //$NON-NLS-1$ //$NON-NLS-2$
testPaths(StringUtils.getLines(
TemplateProvider.getInstance().getProcessedTemplate(os + "_exec", params)), //$NON-NLS-1$
testPaths( StringUtils.getLines( TemplateProvider.getInstance( )
.getProcessedTemplate( os + "_exec", params ) ), //$NON-NLS-1$
wesnothExecutableField_ );
testPaths(StringUtils.getLines(
TemplateProvider.getInstance().getProcessedTemplate(os + "_data", params)), //$NON-NLS-1$
testPaths( StringUtils.getLines( TemplateProvider.getInstance( )
.getProcessedTemplate( os + "_data", params ) ), //$NON-NLS-1$
wesnothWorkingDirField_ );
testPaths(StringUtils.getLines(
TemplateProvider.getInstance().getProcessedTemplate(os + "_user", params)), //$NON-NLS-1$
testPaths( StringUtils.getLines( TemplateProvider.getInstance( )
.getProcessedTemplate( os + "_user", params ) ), //$NON-NLS-1$
wesnothUserDirField_ );
// guess the working dir based on executable's path
Text textControl = wesnothWorkingDirField_.getTextControl(
getFieldEditorParent());
Text textControl = wesnothWorkingDirField_
.getTextControl( getFieldEditorParent( ) );
String workingDirValue = wesnothWorkingDirField_.getStringValue( );
String wesnothExecValue = wesnothExecutableField_.getStringValue( );
if ( workingDirValue.isEmpty() &&
! wesnothExecValue.isEmpty() &&
new File(wesnothExecValue.substring(0,
wesnothExecValue.lastIndexOf(new File(wesnothExecValue).getName()))).exists())
{
if( workingDirValue.isEmpty( )
&& ! wesnothExecValue.isEmpty( )
&& new File(
wesnothExecValue.substring( 0, wesnothExecValue
.lastIndexOf( new File( wesnothExecValue )
.getName( ) ) ) ).exists( ) ) {
textControl.setText( wesnothExecValue.substring( 0,
wesnothExecValue.lastIndexOf(new File(wesnothExecValue).getName()))
);
wesnothExecValue.lastIndexOf( new File( wesnothExecValue )
.getName( ) ) ) );
}
// guess the wmltools path
if ( wmlToolsField_.getStringValue().isEmpty() &&
! workingDirValue.isEmpty() )
{
if( wmlToolsField_.getStringValue( ).isEmpty( )
&& ! workingDirValue.isEmpty( ) ) {
String path = workingDirValue + "/data/tools"; //$NON-NLS-1$
if( testWMLToolsPath( path ) ) {
wmlToolsField_.setStringValue( path );
@ -461,9 +487,7 @@ public class WesnothInstallsPage extends AbstractPreferencePage
String userDirValue = wesnothUserDirField_.getStringValue( );
// guess the userdata path
if ( userDirValue.isEmpty() &&
! workingDirValue.isEmpty() )
{
if( userDirValue.isEmpty( ) && ! workingDirValue.isEmpty( ) ) {
String path = workingDirValue + "/userdata"; //$NON-NLS-1$
testPaths( new String[] { path }, wesnothUserDirField_ );
}
@ -473,17 +497,16 @@ public class WesnothInstallsPage extends AbstractPreferencePage
/**
* Tests for wmltools in the specified path
*
* @param path
* @return
*/
private boolean testWMLToolsPath( String path )
{
for(String tool : wmlToolsList_)
{
if (!(new File(path + Path.SEPARATOR + tool).exists()))
{
setErrorMessage(String.format(Messages.WesnothPreferencesPage_24,
tool));
for( String tool: wmlToolsList_ ) {
if( ! ( new File( path + Path.SEPARATOR + tool ).exists( ) ) ) {
setErrorMessage( String.format(
Messages.WesnothPreferencesPage_24, tool ) );
return false;
}
}
@ -494,18 +517,19 @@ public class WesnothInstallsPage extends AbstractPreferencePage
* Tests the list of paths and if any path exists it will
* set it as the string value to the field editor
* if the field editor value is empty
* @param list The list to search in
* @param field The field to put the path in
*
* @param list
* The list to search in
* @param field
* The field to put the path in
*/
private void testPaths( String[] list, StringFieldEditor field )
{
if( ! ( field.getStringValue( ).isEmpty( ) ) )
return;
for(String path : list)
{
if (new File(path).exists())
{
for( String path: list ) {
if( new File( path ).exists( ) ) {
field.setStringValue( path );
return;
}
@ -516,19 +540,21 @@ public class WesnothInstallsPage extends AbstractPreferencePage
* Checks whether the fields are empty (contain no text)
* and the combobox/name don't have any values also
* (the user doesn't create a new install)
*
* @return
*/
private boolean isFieldsEmpty( )
{
return wmlToolsField_.getStringValue( ).isEmpty( ) &&
wesnothExecutableField_.getStringValue( ).isEmpty( ) &&
wesnothUserDirField_.getStringValue( ).isEmpty( ) &&
wesnothWorkingDirField_.getStringValue( ).isEmpty( ) &&
txtInstallName_.getText( ).isEmpty( );
return wmlToolsField_.getStringValue( ).isEmpty( )
&& wesnothExecutableField_.getStringValue( ).isEmpty( )
&& wesnothUserDirField_.getStringValue( ).isEmpty( )
&& wesnothWorkingDirField_.getStringValue( ).isEmpty( )
&& txtInstallName_.getText( ).isEmpty( );
}
/**
* Saves the current install
*
* @return true if the save was successfully, false otherwise
*/
private boolean saveInstall( )
@ -556,7 +582,8 @@ public class WesnothInstallsPage extends AbstractPreferencePage
}
// update the fields preferences names
setFieldsPreferenceName( Preferences.getInstallPrefix( installName ), false );
setFieldsPreferenceName(
Preferences.getInstallPrefix( installName ), false );
WesnothInstall newInstall = new WesnothInstall( installName,
cmbVersion_.getText( ) );
@ -570,7 +597,8 @@ public class WesnothInstallsPage extends AbstractPreferencePage
// we are creating a new install. Clear the editable
// flag after we save it, to prevent renaming.
txtInstallName_.setEditable( false );
} else if ( getSelectedInstall( ) != null ) { // just saving
}
else if( getSelectedInstall( ) != null ) { // just saving
// the fields are automatically saved by Eclipse.
// we just need to save the new version.
getSelectedInstall( ).setVersion( cmbVersion_.getText( ) );
@ -617,21 +645,29 @@ public class WesnothInstallsPage extends AbstractPreferencePage
checkState( );
}
private static class TableLabelProvider extends LabelProvider implements ITableLabelProvider {
public Image getColumnImage(Object element, int columnIndex) {
private static class TableLabelProvider extends LabelProvider implements
ITableLabelProvider
{
public Image getColumnImage( Object element, int columnIndex )
{
return null;
}
public String getColumnText(Object element, int columnIndex) {
public String getColumnText( Object element, int columnIndex )
{
if( element instanceof WesnothInstall ) {
WesnothInstall install = ( WesnothInstall ) element;
if( columnIndex == 0 ) { // name
return install.getName( );
} else if (columnIndex == 1) { // version
}
else if( columnIndex == 1 ) { // version
return install.getVersion( );
} else if ( columnIndex == 2 ) { // is Default ?
}
else if( columnIndex == 2 ) { // is Default ?
if ( install.getName( ).equals( Preferences.getDefaultInstallName( ) ) )
if( install.getName( ).equals(
Preferences.getDefaultInstallName( ) ) )
return Messages.WesnothInstallsPage_21;
return ""; //$NON-NLS-1$

View file

@ -10,12 +10,7 @@ package org.wesnoth.preferences;
import java.io.File;
import org.wesnoth.Logger;
import org.wesnoth.Messages;
import org.wesnoth.WesnothPlugin;
import org.wesnoth.utils.GUIUtils;
import org.wesnoth.utils.ResourceUtils;
import org.wesnoth.utils.WorkspaceUtils;
import org.osgi.service.prefs.BackingStoreException;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
@ -28,11 +23,17 @@ import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.osgi.service.prefs.BackingStoreException;
import org.wesnoth.Logger;
import org.wesnoth.Messages;
import org.wesnoth.WesnothPlugin;
import org.wesnoth.utils.GUIUtils;
import org.wesnoth.utils.ResourceUtils;
import org.wesnoth.utils.WorkspaceUtils;
public class WesnothPreferencesPage extends AbstractPreferencePage
{
public WesnothPreferencesPage() {
public WesnothPreferencesPage( )
{
super( GRID );
setPreferenceStore( WesnothPlugin.getDefault( ).getPreferenceStore( ) );
@ -60,28 +61,31 @@ public class WesnothPreferencesPage extends AbstractPreferencePage
@Override
public void widgetSelected( SelectionEvent e )
{
if ( GUIUtils.showMessageBox(
if( GUIUtils
.showMessageBox(
"Are you sure you want to clear the plugin preferences?",
SWT.YES | SWT.NO ) == SWT.NO )
return;
// clear the preferences
IEclipsePreferences root = Platform.getPreferencesService( ).getRootNode( );
IEclipsePreferences root = Platform.getPreferencesService( )
.getRootNode( );
try {
for( String rootName: root.childrenNames( ) ) {
org.osgi.service.prefs.Preferences childNode = root.node( rootName );
org.osgi.service.prefs.Preferences childNode = root
.node( rootName );
for( String childName: childNode.childrenNames( ) ) {
org.osgi.service.prefs.Preferences node = childNode.node( childName );
org.osgi.service.prefs.Preferences node = childNode
.node( childName );
if( childName.startsWith( "org.wesnoth" ) ) {
try {
node.clear( );
node.flush( );
node.sync( );
}
catch ( BackingStoreException e1 ) {
} catch( BackingStoreException e1 ) {
Logger.getInstance( ).logException( e1 );
}
}
@ -90,22 +94,21 @@ public class WesnothPreferencesPage extends AbstractPreferencePage
}
Preferences.initializeToDefault( );
}
catch ( BackingStoreException e1 ) {
} catch( BackingStoreException e1 ) {
e1.printStackTrace( );
}
// clear the plugin's dirs
File pluginDir = WesnothPlugin.getDefault( ).
getStateLocation( ).toFile( ).getParentFile( );
ResourceUtils.deleteDirectory(
pluginDir.getAbsolutePath( ) + "/org.wesnoth" );
ResourceUtils.deleteDirectory(
pluginDir.getAbsolutePath( ) + "/org.wesnoth.ui" );
File pluginDir = WesnothPlugin.getDefault( ).getStateLocation( )
.toFile( ).getParentFile( );
ResourceUtils.deleteDirectory( pluginDir.getAbsolutePath( )
+ "/org.wesnoth" );
ResourceUtils.deleteDirectory( pluginDir.getAbsolutePath( )
+ "/org.wesnoth.ui" );
// clear the temporary files
File[] files =
new File( WorkspaceUtils.getTemporaryFolder( ) ).listFiles( );
File[] files = new File( WorkspaceUtils.getTemporaryFolder( ) )
.listFiles( );
for( File file: files ) {
// don't remove the logs

View file

@ -35,8 +35,8 @@ public class Define
private String location_;
private List< String > args_;
public Define(String name, String value, String textdomain,
int linenum, String location, List<String> args)
public Define( String name, String value, String textdomain, int linenum,
String location, List< String > args )
{
name_ = name;
value_ = value;
@ -54,18 +54,22 @@ public class Define
{
return lineNum_;
}
public String getLocation( )
{
return location_;
}
public String getName( )
{
return name_;
}
public String getTextdomain( )
{
return textdomain_;
}
public String getValue( )
{
return value_;
@ -73,6 +77,7 @@ public class Define
/**
* Gets the arguments of this macro
*
* @return
*/
public List< String > getArguments( )
@ -82,6 +87,7 @@ public class Define
/**
* Returns a string containing the current define, formatted
*
* @return The string value of the define
*/
@Override
@ -100,21 +106,25 @@ public class Define
/**
* Reads the defines from the specified file
*
* @param file
* @return Returns a map of defines
*/
public static Map<String, Define> readDefines( String installName, String file )
public static Map< String, Define > readDefines( String installName,
String file )
{
DefinesSAXHandler handler = (DefinesSAXHandler) ResourceUtils.
getWMLSAXHandlerFromResource( installName, file,
DefinesSAXHandler handler = ( DefinesSAXHandler ) ResourceUtils
.getWMLSAXHandlerFromResource( installName, file,
new DefinesSAXHandler( ) );
if( handler != null ) {
Logger.getInstance().log("loaded " + handler.getDefines().size() + " defines for file:" + file); //$NON-NLS-1$ //$NON-NLS-1$ //$NON-NLS-2$
Logger.getInstance( )
.log( "loaded " + handler.getDefines( ).size( ) + " defines for file:" + file ); //$NON-NLS-1$ //$NON-NLS-1$ //$NON-NLS-2$
return handler.getDefines( );
}
Logger.getInstance().log("There was an error on creating the Defines SAX handler"); //$NON-NLS-1$
Logger.getInstance( ).log(
"There was an error on creating the Defines SAX handler" ); //$NON-NLS-1$
return new HashMap< String, Define >( 0 );
}
}

View file

@ -82,8 +82,7 @@ public class DefinesSAXHandler extends DefaultHandler
{
arguments_.add( new String( ch, start, length ) );
}
else
{
else {
name_ = new String( ch, start, length );
}
}
@ -120,6 +119,7 @@ public class DefinesSAXHandler extends DefaultHandler
/**
* Gets the map of defines parsed
*
* @return
*/
public Map< String, Define > getDefines( )

View file

@ -24,6 +24,7 @@ import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.dialogs.DialogSettings;
import org.wesnoth.Constants;
import org.wesnoth.Logger;
import org.wesnoth.Messages;
@ -38,7 +39,8 @@ import org.wesnoth.utils.WorkspaceUtils;
public class PreprocessorUtils
{
private static class PreprocessorUtilsInstance{
private static class PreprocessorUtilsInstance
{
private static PreprocessorUtils instance_ = new PreprocessorUtils( );
}
@ -58,9 +60,14 @@ public class PreprocessorUtils
/**
* preprocesses a file using the wesnoth's executable, only
* if the file was modified since last time checked.
* The target directory is the temporary directory + files's path relative to project
* @param file the file to process
* @param defines the list of additional defines to be added when preprocessing the file
* The target directory is the temporary directory + files's path relative
* to project
*
* @param file
* the file to process
* @param defines
* the list of additional defines to be added when preprocessing
* the file
* @return
*/
public int preprocessFile( IFile file, List< String > defines )
@ -72,25 +79,40 @@ public class PreprocessorUtils
/**
* preprocesses a file using the wesnoth's executable, only
* if the file was modified since last time checked.
* The target directory is the temporary directory + files's path relative to project
* @param file the file to process
* @param macrosFile The file where macros are stored
* @param defines the list of additional defines to be added when preprocessing the file
* The target directory is the temporary directory + files's path relative
* to project
*
* @param file
* the file to process
* @param macrosFile
* The file where macros are stored
* @param defines
* the list of additional defines to be added when preprocessing
* the file
* @return
*/
public int preprocessFile(IFile file, String macrosFile, List<String> defines)
public int preprocessFile( IFile file, String macrosFile,
List< String > defines )
{
return preprocessFile(file, getTemporaryLocation(file), macrosFile, defines, true);
return preprocessFile( file, getTemporaryLocation( file ), macrosFile,
defines, true );
}
/**
* preprocesses a file using the wesnoth's executable, only
* if the file was modified since last time checked.
* @param file the file to process
* @param targetDirectory target directory where should be put the results
* @param macrosFile The file where macros are stored
* @param defines the list of additional defines to be added when preprocessing the file
* @param waitForIt true to wait for the preprocessing to finish
*
* @param file
* the file to process
* @param targetDirectory
* target directory where should be put the results
* @param macrosFile
* The file where macros are stored
* @param defines
* the list of additional defines to be added when preprocessing
* the file
* @param waitForIt
* true to wait for the preprocessing to finish
* @return
* -1 - we skipped preprocessing - file was already preprocessed
* 0 - preprocessed succesfully
@ -100,10 +122,11 @@ public class PreprocessorUtils
String macrosFile, List< String > defines, boolean waitForIt )
{
String filePath = file.getLocation( ).toOSString( );
if (filesTimeStamps_.containsKey(filePath) &&
filesTimeStamps_.get(filePath) >= new File(filePath).lastModified())
{
Logger.getInstance().logTool("skipped preprocessing a non-modified file: " + filePath); //$NON-NLS-1$
if( filesTimeStamps_.containsKey( filePath )
&& filesTimeStamps_.get( filePath ) >= new File( filePath )
.lastModified( ) ) {
Logger.getInstance( ).logTool(
"skipped preprocessing a non-modified file: " + filePath ); //$NON-NLS-1$
return - 1;
}
@ -111,8 +134,9 @@ public class PreprocessorUtils
try {
Paths paths = Preferences.getPaths(
ProjectUtils.getCacheForProject( file.getProject( ) ).getInstallName( ) );
Paths paths = Preferences
.getPaths( ProjectUtils.getCacheForProject(
file.getProject( ) ).getInstallName( ) );
List< String > arguments = new ArrayList< String >( );
@ -122,8 +146,7 @@ public class PreprocessorUtils
arguments.add( "--data-dir" ); //$NON-NLS-1$
arguments.add( paths.getWorkingDir( ) );
if (macrosFile != null && macrosFile.isEmpty() == false)
{
if( macrosFile != null && macrosFile.isEmpty( ) == false ) {
ResourceUtils.createNewFile( macrosFile );
// add the _MACROS_.cfg file
@ -135,8 +158,7 @@ public class PreprocessorUtils
arguments.add( macrosFile );
}
if (Preferences.getBool(Constants.P_NO_TERRAIN_GFX))
{
if( Preferences.getBool( Constants.P_NO_TERRAIN_GFX ) ) {
if( defines == null )
defines = new ArrayList< String >( );
defines.add( "NO_TERRAIN_GFX" ); //$NON-NLS-1$
@ -148,13 +170,12 @@ public class PreprocessorUtils
arguments.add( targetDirectory );
// --preprocess-defines
if (defines != null && !defines.isEmpty())
{
if( defines != null && ! defines.isEmpty( ) ) {
arguments.add( "--preprocess-defines" ); //$NON-NLS-1$
StringBuilder definesArg = new StringBuilder( );
for( Iterator<String> itor = defines.iterator(); itor.hasNext(); )
{
for( Iterator< String > itor = defines.iterator( ); itor
.hasNext( ); ) {
if( definesArg.length( ) > 0 )
definesArg.append( "," ); //$NON-NLS-1$
@ -166,14 +187,12 @@ public class PreprocessorUtils
Logger.getInstance( ).logTool( "preprocessing file: " + filePath ); //$NON-NLS-1$
ExternalToolInvoker wesnoth = new ExternalToolInvoker(
paths.getWesnothExecutablePath( ),
arguments);
paths.getWesnothExecutablePath( ), arguments );
wesnoth.runTool( );
if( waitForIt )
return wesnoth.waitForTool( );
return 0;
}
catch (Exception e) {
} catch( Exception e ) {
Logger.getInstance( ).logException( e );
return 1;
}
@ -181,35 +200,43 @@ public class PreprocessorUtils
/**
* Opens the preprocessed version of the specified file
* @param file the file to show preprocessed output
* @param openPlain true if it should open the plain preprocessed version
*
* @param file
* the file to show preprocessed output
* @param openPlain
* true if it should open the plain preprocessed version
* or false for the normal one
*/
public void openPreprocessedFileInEditor( IFile file, boolean openPlain )
{
if (file == null || !file.exists())
{
if( file == null || ! file.exists( ) ) {
Logger.getInstance( ).log( "file null or non existent.", //$NON-NLS-1$
Messages.PreprocessorUtils_12 );
return;
}
EditorUtils.openEditor(getPreprocessedFilePath(file, openPlain, true));
EditorUtils
.openEditor( getPreprocessedFilePath( file, openPlain, true ) );
}
/**
* Returns the path of the preprocessed file of the specified file
* @param file The file whom preprocessed file to get
* @param plain True to return the plain version file's file
* @param create if this is true, if the target preprocessed file
*
* @param file
* The file whom preprocessed file to get
* @param plain
* True to return the plain version file's file
* @param create
* if this is true, if the target preprocessed file
* doesn't exist it will be created.
* @return
*/
public IFileStore getPreprocessedFilePath( IFile file, boolean plain,
boolean create )
{
IFileStore preprocFile =
EFS.getLocalFileSystem().getStore(new Path(getTemporaryLocation(file)));
preprocFile = preprocFile.getChild(file.getName() + (plain == true? ".plain" : "") ); //$NON-NLS-1$ //$NON-NLS-2$
IFileStore preprocFile = EFS.getLocalFileSystem( ).getStore(
new Path( getTemporaryLocation( file ) ) );
preprocFile = preprocFile.getChild( file.getName( )
+ ( plain == true ? ".plain": "" ) ); //$NON-NLS-1$ //$NON-NLS-2$
if( create && ! preprocFile.fetchInfo( ).exists( ) )
preprocessFile( file, null );
return preprocFile;
@ -217,6 +244,7 @@ public class PreprocessorUtils
/**
* Gets the temporary location where that file should be preprocessed
*
* @param file
* @return
*/
@ -224,7 +252,9 @@ public class PreprocessorUtils
{
String targetDirectory = WorkspaceUtils.getTemporaryFolder( );
targetDirectory += file.getProject( ).getName( ) + "/"; //$NON-NLS-1$
targetDirectory += file.getParent().getProjectRelativePath().toOSString() + "/"; //$NON-NLS-1$
targetDirectory += file.getParent( ).getProjectRelativePath( )
.toOSString( )
+ "/"; //$NON-NLS-1$
return targetDirectory;
}
@ -233,13 +263,16 @@ public class PreprocessorUtils
* specified resource.
*
* Currently we store just a defines file per project.
* @param resource The resource to get the location for
*
* @param resource
* The resource to get the location for
* @return A string that points to the macros file.
*/
public String getMacrosLocation( IResource resource )
{
return WorkspaceUtils.getProjectTemporaryFolder( resource.getProject( ) ) +
"/_MACROS_.cfg"; //$NON-NLS-1$
return WorkspaceUtils
.getProjectTemporaryFolder( resource.getProject( ) )
+ "/_MACROS_.cfg"; //$NON-NLS-1$
}
/**
@ -248,21 +281,20 @@ public class PreprocessorUtils
*/
public void saveTimestamps( )
{
String filename = WorkspaceUtils.getTemporaryFolder( ) + "preprocessed.txt"; //$NON-NLS-1$
String filename = WorkspaceUtils.getTemporaryFolder( )
+ "preprocessed.txt"; //$NON-NLS-1$
DialogSettings settings = new DialogSettings( "preprocessed" ); //$NON-NLS-1$
try
{
settings.put("files", filesTimeStamps_.keySet().toArray(new String[0])); //$NON-NLS-1$
try {
settings.put(
"files", filesTimeStamps_.keySet( ).toArray( new String[0] ) ); //$NON-NLS-1$
List< String > timestamps = new ArrayList< String >( );
for(Long timestamp : filesTimeStamps_.values())
{
for( Long timestamp: filesTimeStamps_.values( ) ) {
timestamps.add( timestamp.toString( ) );
}
settings.put("timestamps", timestamps.toArray(new String[timestamps.size( )])); //$NON-NLS-1$
settings.put(
"timestamps", timestamps.toArray( new String[timestamps.size( )] ) ); //$NON-NLS-1$
settings.save( filename );
}
catch (Exception e)
{
} catch( Exception e ) {
Logger.getInstance( ).logException( e );
}
}
@ -278,8 +310,7 @@ public class PreprocessorUtils
DialogSettings settings = new DialogSettings( "preprocessed" ); //$NON-NLS-1$
filesTimeStamps_.clear( );
try
{
try {
// ensure the creation of a valid file if it doesn't exist
if( new File( filename ).exists( ) == false )
settings.save( filename );
@ -287,28 +318,28 @@ public class PreprocessorUtils
settings.load( filename );
String[] timestamps = settings.getArray( "timestamps" ); //$NON-NLS-1$
String[] files = settings.getArray( "files" ); //$NON-NLS-1$
if (timestamps != null && files != null &&
timestamps.length == files.length)
{
for(int index = 0 ;index < files.length; ++index)
{
filesTimeStamps_.put(files[index], Long.valueOf(timestamps[index]));
if( timestamps != null && files != null
&& timestamps.length == files.length ) {
for( int index = 0; index < files.length; ++index ) {
filesTimeStamps_.put( files[index],
Long.valueOf( timestamps[index] ) );
}
}
}
catch (IOException e)
{
} catch( IOException e ) {
Logger.getInstance( ).logException( e );
}
}
/**
* Clears all timestamps cached for files that are located in that path
* @param path The path to match the files to clear their timestamp
*
* @param path
* The path to match the files to clear their timestamp
*/
public void clearTimestampsForPath( String path )
{
Iterator<Entry<String, Long>> itor = filesTimeStamps_.entrySet( ).iterator( );
Iterator< Entry< String, Long >> itor = filesTimeStamps_.entrySet( )
.iterator( );
while( itor.hasNext( ) ) {
Entry< String, Long > entry = itor.next( );

View file

@ -17,6 +17,7 @@ import org.eclipse.ui.IStartup;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.wesnoth.Messages;
public class ActionWiper implements IStartup, IPerspectiveListener
@ -38,12 +39,11 @@ public class ActionWiper implements IStartup, IPerspectiveListener
public void earlyStartup( )
{
IWorkbenchWindow[] windows = PlatformUI.getWorkbench().getWorkbenchWindows();
for (int i = 0; i < windows.length; i++)
{
IWorkbenchWindow[] windows = PlatformUI.getWorkbench( )
.getWorkbenchWindows( );
for( int i = 0; i < windows.length; i++ ) {
IWorkbenchPage page = windows[i].getActivePage( );
if (page != null)
{
if( page != null ) {
wipeActions( page );
}
windows[i].addPerspectiveListener( this );
@ -57,16 +57,13 @@ public class ActionWiper implements IStartup, IPerspectiveListener
{
// remove the run menu
Menu menu = page.getWorkbenchWindow( ).getShell( ).getMenuBar( );
for (MenuItem item : menu.getItems())
{
if (item.getText().equals(Messages.ActionWiper_6))
{
for( MenuItem item: menu.getItems( ) ) {
if( item.getText( ).equals( Messages.ActionWiper_6 ) ) {
item.dispose( );
}
}
for (int i = 0; i < ACTIONS_2_WIPE.length; i++)
{
for( int i = 0; i < ACTIONS_2_WIPE.length; i++ ) {
page.hideActionSet( ACTIONS_2_WIPE[i] );
}
}

View file

@ -12,6 +12,7 @@ import org.eclipse.ui.IFolderLayout;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPerspectiveFactory;
import org.eclipse.ui.console.IConsoleConstants;
import org.wesnoth.views.AddonsView;
import org.wesnoth.views.WesnothProjectsExplorer;
@ -33,17 +34,20 @@ public class WMLPerspective implements IPerspectiveFactory
layout.setEditorAreaVisible( true );
// Place navigator and outline to left of editor area.
IFolderLayout left = layout.createFolder("left", IPageLayout.LEFT, (float) 0.26, editorArea); //$NON-NLS-1$
IFolderLayout left = layout.createFolder(
"left", IPageLayout.LEFT, ( float ) 0.26, editorArea ); //$NON-NLS-1$
left.addView( WesnothProjectsExplorer.ID_PROJECTS_EXPLORER );
IFolderLayout bottom = layout.createFolder("bottom", IPageLayout.BOTTOM, 0.76f, editorArea); //$NON-NLS-1$
IFolderLayout bottom = layout.createFolder(
"bottom", IPageLayout.BOTTOM, 0.76f, editorArea ); //$NON-NLS-1$
bottom.addView( IPageLayout.ID_PROBLEM_VIEW );
bottom.addView( IPageLayout.ID_PROGRESS_VIEW );
bottom.addView( IConsoleConstants.ID_CONSOLE_VIEW );
bottom.addView( AddonsView.ID_ADDONS_VIEW );
bottom.addView( "org.eclipse.pde.runtime.LogView" ); //$NON-NLS-1$
IFolderLayout right = layout.createFolder("right", IPageLayout.RIGHT, 0.68f, editorArea); //$NON-NLS-1$
IFolderLayout right = layout.createFolder(
"right", IPageLayout.RIGHT, 0.68f, editorArea ); //$NON-NLS-1$
right.addView( IPageLayout.ID_OUTLINE );
layout.addPerspectiveShortcut( WMLPERSPECTIVE_ID );

View file

@ -13,6 +13,7 @@ import org.eclipse.equinox.app.IApplicationContext;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;
import org.wesnoth.Logger;
public class WesnothApplication implements IApplication
@ -23,17 +24,16 @@ public class WesnothApplication implements IApplication
Display display = PlatformUI.createDisplay( );
Logger.getInstance( ).startLogger( );
try {
int returnCode = PlatformUI.createAndRunWorkbench(display, new WesnothWorkbenchAdvisor());
int returnCode = PlatformUI.createAndRunWorkbench( display,
new WesnothWorkbenchAdvisor( ) );
if( returnCode == PlatformUI.RETURN_RESTART )
return IApplication.EXIT_RESTART;
else
return IApplication.EXIT_OK;
}
catch(Exception e){
} catch( Exception e ) {
Logger.getInstance( ).logException( e );
return IApplication.EXIT_OK;
}
finally {
} finally {
display.dispose( );
}
}
@ -47,7 +47,8 @@ public class WesnothApplication implements IApplication
final IWorkbench workbench = PlatformUI.getWorkbench( );
final Display display = workbench.getDisplay( );
display.syncExec( new Runnable( ) {
public void run() {
public void run( )
{
if( ! display.isDisposed( ) )
workbench.close( );
}

View file

@ -12,20 +12,25 @@ import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.ui.application.IWorkbenchWindowConfigurer;
import org.eclipse.ui.application.WorkbenchWindowAdvisor;
import org.eclipse.ui.ide.IDE;
import org.wesnoth.utils.WorkspaceUtils;
import org.wesnoth.views.WesnothProjectsExplorer;
public class WesnothWorkbenchAdvisor extends WorkbenchAdvisorHack {
public class WesnothWorkbenchAdvisor extends WorkbenchAdvisorHack
{
private static final String PERSPECTIVE_ID = "org.wesnoth.product.WMLPerspective"; //$NON-NLS-1$
@Override
public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer) {
public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor(
IWorkbenchWindowConfigurer configurer )
{
return new WesnothWorkbenchWindowAdvisor( configurer );
}
@Override
public String getInitialWindowPerspectiveId() {
public String getInitialWindowPerspectiveId( )
{
return PERSPECTIVE_ID;
}
@ -44,8 +49,7 @@ public class WesnothWorkbenchAdvisor extends WorkbenchAdvisorHack {
@Override
public void postStartup( )
{
if (WorkspaceUtils.checkPathsAreSet( null, false ) == false)
{
if( WorkspaceUtils.checkPathsAreSet( null, false ) == false ) {
WorkspaceUtils.setupWorkspace( true );
}
}

View file

@ -15,21 +15,27 @@ import org.eclipse.ui.application.ActionBarAdvisor;
import org.eclipse.ui.application.IActionBarConfigurer;
import org.eclipse.ui.application.IWorkbenchWindowConfigurer;
import org.eclipse.ui.application.WorkbenchWindowAdvisor;
import org.wesnoth.Logger;
public class WesnothWorkbenchWindowAdvisor extends WorkbenchWindowAdvisor {
public class WesnothWorkbenchWindowAdvisor extends WorkbenchWindowAdvisor
{
public WesnothWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer) {
public WesnothWorkbenchWindowAdvisor( IWorkbenchWindowConfigurer configurer )
{
super( configurer );
}
@Override
public ActionBarAdvisor createActionBarAdvisor(IActionBarConfigurer configurer) {
public ActionBarAdvisor createActionBarAdvisor(
IActionBarConfigurer configurer )
{
return new WesnothActionBarAdvisor( configurer );
}
@Override
public void preWindowOpen() {
public void preWindowOpen( )
{
super.preWindowOpen( );
IWorkbenchWindowConfigurer configurer = getWindowConfigurer( );
configurer.setShowMenuBar( true );
@ -43,16 +49,17 @@ public class WesnothWorkbenchWindowAdvisor extends WorkbenchWindowAdvisor {
@Override
public void postWindowCreate( )
{
getWindowConfigurer().getWindow().getActivePage().hideActionSet("org.eclipse.ui.run"); //$NON-NLS-1$
getWindowConfigurer( ).getWindow( ).getActivePage( )
.hideActionSet( "org.eclipse.ui.run" ); //$NON-NLS-1$
}
@Override
public boolean preWindowShellClose( )
{
try {
ResourcesPlugin.getWorkspace( ).save( true , new NullProgressMonitor() );
}
catch ( CoreException e ) {
ResourcesPlugin.getWorkspace( ).save( true,
new NullProgressMonitor( ) );
} catch( CoreException e ) {
Logger.getInstance( ).logException( e );
}
return true;

View file

@ -2,6 +2,8 @@ package org.wesnoth.product;
import java.net.URL;
import org.osgi.framework.Bundle;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
@ -11,7 +13,6 @@ import org.eclipse.ui.application.WorkbenchAdvisor;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.internal.ide.IDEInternalWorkbenchImages;
import org.eclipse.ui.internal.ide.IDEWorkbenchPlugin;
import org.osgi.framework.Bundle;
/**
* Methods copied from {@link org.eclipse.ui.internal.ide.IDEWorkbenchAdvisor}
@ -55,7 +56,8 @@ public abstract class WorkbenchAdvisorHack extends WorkbenchAdvisor
final String PATH_EVIEW = ICONS_PATH + "eview16/"; //$NON-NLS-1$
Bundle ideBundle = Platform.getBundle(IDEWorkbenchPlugin.IDE_WORKBENCH);
Bundle ideBundle = Platform
.getBundle( IDEWorkbenchPlugin.IDE_WORKBENCH );
declareWorkbenchImage( ideBundle,
IDEInternalWorkbenchImages.IMG_ETOOL_BUILD_EXEC, PATH_ETOOL
@ -143,8 +145,8 @@ public abstract class WorkbenchAdvisorHack extends WorkbenchAdvisor
IDEInternalWorkbenchImages.IMG_OBJS_FIXABLE_WARNING,
PATH_OBJECT + "quickfix_warning_obj.gif", true ); //$NON-NLS-1$
declareWorkbenchImage( ideBundle,
IDEInternalWorkbenchImages.IMG_OBJS_FIXABLE_ERROR,
PATH_OBJECT + "quickfix_error_obj.gif", true); //$NON-NLS-1$
IDEInternalWorkbenchImages.IMG_OBJS_FIXABLE_ERROR, PATH_OBJECT
+ "quickfix_error_obj.gif", true ); //$NON-NLS-1$
// task objects
@ -193,8 +195,8 @@ public abstract class WorkbenchAdvisorHack extends WorkbenchAdvisor
PATH_ETOOL + "problem_category.gif", true ); //$NON-NLS-1$
declareWorkbenchImage( ideBundle,
IDEInternalWorkbenchImages.IMG_ETOOL_PROBLEMS_VIEW,
PATH_EVIEW + "problems_view.gif", true); //$NON-NLS-1$
IDEInternalWorkbenchImages.IMG_ETOOL_PROBLEMS_VIEW, PATH_EVIEW
+ "problems_view.gif", true ); //$NON-NLS-1$
declareWorkbenchImage( ideBundle,
IDEInternalWorkbenchImages.IMG_ETOOL_PROBLEMS_VIEW_ERROR,
PATH_EVIEW + "problems_view_error.gif", true ); //$NON-NLS-1$
@ -217,8 +219,8 @@ public abstract class WorkbenchAdvisorHack extends WorkbenchAdvisor
* <code>false</code> if this is not a shared image
* @see org.eclipse.ui.internal.ide.IDEWorkbenchAdvisor#declareImage
*/
private void declareWorkbenchImage(Bundle ideBundle, String symbolicName, String path,
boolean shared)
private void declareWorkbenchImage( Bundle ideBundle, String symbolicName,
String path, boolean shared )
{
URL url = FileLocator.find( ideBundle, new Path( path ), null );
ImageDescriptor desc = ImageDescriptor.createFromURL( url );

View file

@ -21,6 +21,8 @@ import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.eclipse.core.resources.IProject;
import org.wesnoth.Constants;
import org.wesnoth.Logger;
import org.wesnoth.builder.DependencyListBuilder;
@ -32,12 +34,11 @@ import org.wesnoth.wml.WMLConfig;
import org.wesnoth.wml.WMLTag;
import org.wesnoth.wml.WMLVariable;
import org.eclipse.core.resources.IProject;
/**
* A class that stores some project specific infos
* for current session.
* Some of the fields of this cache can be saved to disk
*
* @see ProjectCache#saveCache()
*/
public class ProjectCache implements Serializable
@ -71,12 +72,15 @@ public class ProjectCache implements Serializable
definesTimestamp_ = - 1;
wesnothFile_ = new File ( project.getLocation().toOSString() + "/.wesnoth" ); //$NON-NLS-1$
definesFile_ = new File ( PreprocessorUtils.getInstance().getMacrosLocation( project ));
wesnothFile_ = new File( project.getLocation( ).toOSString( )
+ "/.wesnoth" ); //$NON-NLS-1$
definesFile_ = new File( PreprocessorUtils.getInstance( )
.getMacrosLocation( project ) );
}
/**
* Gets the properties map for this project.
*
* @return A map with properties of the project
*/
public Map< String, String > getProperties( )
@ -88,6 +92,7 @@ public class ProjectCache implements Serializable
* Gets the map with the WMLConfigs
* The key represent the filenames of the files
* and the value the scenarioId from that file
*
* @return A map with key the file path and value the WMLConfig
*/
public Map< String, WMLConfig > getWMLConfigs( )
@ -98,7 +103,9 @@ public class ProjectCache implements Serializable
/**
* Gets the WMLConfig by the specified file project-relative path.
* If the WMLConfig doesn't exist it will be created
* @param path The project-relative path for the file.
*
* @param path
* The project-relative path for the file.
* @return
*/
public WMLConfig getWMLConfig( String path )
@ -114,6 +121,7 @@ public class ProjectCache implements Serializable
/**
* Returns the variables found in this project
*
* @return A multimap containing all the variables
*/
public Map< String, WMLVariable > getVariables( )
@ -127,14 +135,14 @@ public class ProjectCache implements Serializable
*/
public void loadCache( )
{
ResourceUtils.createWesnothFile( wesnothFile_.getAbsolutePath(), false );
ResourceUtils
.createWesnothFile( wesnothFile_.getAbsolutePath( ), false );
try
{
try
{
try {
try {
FileInputStream inputStream = new FileInputStream( wesnothFile_ );
ObjectInputStream deserializer = new ObjectInputStream( inputStream );
ObjectInputStream deserializer = new ObjectInputStream(
inputStream );
ProjectCache cache = ( ProjectCache ) deserializer.readObject( );
properties_ = cache.properties_;
@ -147,16 +155,12 @@ public class ProjectCache implements Serializable
// invalid file contents. just save this instance to it.
catch( EOFException e ) {
saveCache( );
}
catch (StreamCorruptedException e) {
} catch( StreamCorruptedException e ) {
saveCache( );
} catch( ClassCastException ex ) {
saveCache( );
}
catch(ClassCastException ex) {
saveCache( );
}
}
catch (Exception e)
{
} catch( Exception e ) {
Logger.getInstance( ).logException( e );
}
@ -168,22 +172,22 @@ public class ProjectCache implements Serializable
* Saves:
* - properties
* - existing scenarios
*
* @return
*/
public boolean saveCache( )
{
ResourceUtils.createWesnothFile(wesnothFile_.getAbsolutePath(), false);
ResourceUtils
.createWesnothFile( wesnothFile_.getAbsolutePath( ), false );
try
{
try {
FileOutputStream outputStream = new FileOutputStream( wesnothFile_ );
ObjectOutputStream serializer = new ObjectOutputStream( outputStream );
ObjectOutputStream serializer = new ObjectOutputStream(
outputStream );
serializer.writeObject( this );
return true;
}
catch (Exception e)
{
} catch( Exception e ) {
Logger.getInstance( ).logException( e );
return false;
}
@ -191,24 +195,27 @@ public class ProjectCache implements Serializable
/**
* Reads the defines files for this project
* @param force Read the defines even if the defines file's contents
*
* @param force
* Read the defines even if the defines file's contents
* haven't changed since last time read.
*/
public void readDefines( boolean force )
{
if (force == false &&
definesFile_.lastModified() <= definesTimestamp_)
if( force == false && definesFile_.lastModified( ) <= definesTimestamp_ )
return;
if( definesFile_.exists( ) == false )
return;
defines_ = Define.readDefines( getInstallName( ), definesFile_.getAbsolutePath( ) );
defines_ = Define.readDefines( getInstallName( ),
definesFile_.getAbsolutePath( ) );
definesTimestamp_ = definesFile_.lastModified( );
}
/**
* Returns the defines associated with this project
*
* @return
*/
public Map< String, Define > getDefines( )
@ -218,6 +225,7 @@ public class ProjectCache implements Serializable
/**
* Returns the list of events available in the project
*
* @return A set with events as strings
*/
public Set< String > getEvents( )
@ -230,12 +238,15 @@ public class ProjectCache implements Serializable
*/
public String getInstallName( )
{
return Preferences.getString( Constants.P_INST_NAME_PREFIX + project_.getName( ) );
return Preferences.getString( Constants.P_INST_NAME_PREFIX
+ project_.getName( ) );
}
/**
* Sets the new install used in the project
* @param newInstallName The new install name
*
* @param newInstallName
* The new install name
*/
public void setInstallName( String newInstallName )
{
@ -246,6 +257,7 @@ public class ProjectCache implements Serializable
/**
* Returns the current dependency tree builder for this project
*
* @return A dependency tree
*/
public DependencyListBuilder getDependencyList( )
@ -271,6 +283,7 @@ public class ProjectCache implements Serializable
/**
* Returns the parsed WML Tags from all configs of this project
*
* @return A list of Tags
*/
public Map< String, WMLTag > getWMLTags( )

View file

@ -12,6 +12,14 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.wesnoth.Constants;
import org.wesnoth.Logger;
import org.wesnoth.Messages;
@ -22,22 +30,13 @@ import org.wesnoth.templates.TemplateProvider;
import org.wesnoth.utils.ResourceUtils;
import org.wesnoth.utils.StringUtils;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;
public class ProjectUtils
{
/**
* A map which stores the caches for each project.
* The properties are stored in '.wesnoth' file
*/
private static Map<IProject, ProjectCache> projectCache_ =
new HashMap<IProject, ProjectCache>();
private static Map< IProject, ProjectCache > projectCache_ = new HashMap< IProject, ProjectCache >( );
public static Map< IProject, ProjectCache > getProjectCaches( )
{
@ -46,15 +45,18 @@ public class ProjectUtils
/**
* Gets the properties map for this project.
*
* @return A map with properties of the project
*/
public static Map<String, String> getPropertiesForProject(IProject project)
public static Map< String, String > getPropertiesForProject(
IProject project )
{
return getCacheForProject( project ).getProperties( );
}
/**
* Gets the cache for the specified project
*
* @param project
* @return
*/
@ -62,8 +64,7 @@ public class ProjectUtils
{
ProjectCache cache = projectCache_.get( project );
if (cache == null)
{
if( cache == null ) {
cache = new ProjectCache( project );
cache.loadCache( );
projectCache_.put( project, cache );
@ -74,9 +75,13 @@ public class ProjectUtils
/**
* Creates a new wesnoth project with the specified name
* and on the specified location on disk
* @param name The name of the new project
* @param location The location of the new project
* @param installName The name of the install this project belongs to
*
* @param name
* The name of the new project
* @param location
* The location of the new project
* @param installName
* The name of the install this project belongs to
* @return A project handle
* @throws CoreException
*/
@ -87,10 +92,11 @@ public class ProjectUtils
IProject newProject = root.getProject( name );
IProjectDescription description = null;
// set the path only if the project's location is outside the workspace root
if ( ! location.equals( root.getLocation( ).toOSString( ) ) )
{
description = ResourcesPlugin.getWorkspace().newProjectDescription( name );
// set the path only if the project's location is outside the workspace
// root
if( ! location.equals( root.getLocation( ).toOSString( ) ) ) {
description = ResourcesPlugin.getWorkspace( )
.newProjectDescription( name );
description.setLocation( new Path( location ) );
}
@ -103,14 +109,20 @@ public class ProjectUtils
* Creates a project that has associated the wesnoth nature using
* the specified handle. If the project is created there will be
* no modifications done by this method.
* @param handle the handle to the project
* @param description the default description used when the project is created
* @param installName The name of the install this project belongs to
* @param monitor the monitor will do a 30 worked amount in the method
*
* @param handle
* the handle to the project
* @param description
* the default description used when the project is created
* @param installName
* The name of the install this project belongs to
* @param monitor
* the monitor will do a 30 worked amount in the method
* @throws CoreException
*/
public static int createWesnothProject( IProject handle, IProjectDescription description,
String installName, IProgressMonitor monitor)
public static int createWesnothProject( IProject handle,
IProjectDescription description, String installName,
IProgressMonitor monitor )
{
if( handle == null || handle.exists( ) )
return - 1;
@ -119,12 +131,14 @@ public class ProjectUtils
String projectPath = null;
if( handle.getLocation( ) == null && description != null )
projectPath = description.getLocationURI().getPath( ).toString( ).substring( 1 );
projectPath = description.getLocationURI( ).getPath( )
.toString( ).substring( 1 );
else if( handle.getLocation( ) != null )
projectPath = handle.getLocation( ).toOSString( );
else // project is in workspace
projectPath =
ResourcesPlugin.getWorkspace( ).getRoot( ).getLocation( ).toOSString( )
else
// project is in workspace
projectPath = ResourcesPlugin.getWorkspace( ).getRoot( )
.getLocation( ).toOSString( )
+ "/" + handle.getProject( ).getName( );
monitor.subTask( Messages.ProjectUtils_0 );
@ -135,7 +149,8 @@ public class ProjectUtils
ResourceUtils.removeFile( projectPath + "/.build.xml" ); //$NON-NLS-1$
monitor.worked( 5 );
monitor.subTask(String.format(Messages.ProjectUtils_4, handle.getName()));
monitor.subTask( String.format( Messages.ProjectUtils_4,
handle.getName( ) ) );
// create the project
if( description == null )
@ -149,8 +164,13 @@ public class ProjectUtils
monitor.subTask( Messages.ProjectUtils_6 );
// add wesnoth nature
IProjectDescription tmpDescription = handle.getDescription( );
tmpDescription.setNatureIds(new String[] { Constants.NATURE_WESNOTH /*,
Constants.NATURE_XTEXT */ });
tmpDescription
.setNatureIds( new String[] { Constants.NATURE_WESNOTH /*
* ,
* Constants
* .
* NATURE_XTEXT
*/} );
handle.setDescription( tmpDescription, monitor );
monitor.worked( 5 );
@ -158,21 +178,25 @@ public class ProjectUtils
// into the data/campaigns or user's /addons directory
Paths paths = Preferences.getPaths( installName );
String normalizedPath = StringUtils.normalizePath( projectPath );
if ( ! normalizedPath.contains( StringUtils.normalizePath( paths.getCampaignDir( ) ) ) &&
! normalizedPath.contains( StringUtils.normalizePath( paths.getAddonsDir( ) ) ) )
{
if( ! normalizedPath.contains( StringUtils.normalizePath( paths
.getCampaignDir( ) ) )
&& ! normalizedPath.contains( StringUtils
.normalizePath( paths.getAddonsDir( ) ) ) ) {
ArrayList< ReplaceableParameter > param = new ArrayList< ReplaceableParameter >( );
param.add(new ReplaceableParameter("$$project_name", handle.getName())); //$NON-NLS-1$
param.add(new ReplaceableParameter("$$project_dir_name", handle.getName())); //$NON-NLS-1$
ResourceUtils.createFile(handle, "build.xml", //$NON-NLS-1$
TemplateProvider.getInstance().getProcessedTemplate("build_xml", param), true); //$NON-NLS-1$
param.add( new ReplaceableParameter(
"$$project_name", handle.getName( ) ) ); //$NON-NLS-1$
param.add( new ReplaceableParameter(
"$$project_dir_name", handle.getName( ) ) ); //$NON-NLS-1$
ResourceUtils.createFile( handle,
"build.xml", //$NON-NLS-1$
TemplateProvider.getInstance( ).getProcessedTemplate(
"build_xml", param ), true ); //$NON-NLS-1$
}
monitor.worked( 10 );
// save the install name
getCacheForProject( handle ).setInstallName( installName );
}
catch (CoreException e) {
} catch( CoreException e ) {
Logger.getInstance( ).logException( e );
return 1;
}

View file

@ -14,6 +14,7 @@ import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.dialogs.PropertyPage;
import org.wesnoth.Messages;
import org.wesnoth.installs.WesnothInstall;
import org.wesnoth.installs.WesnothInstallsUtils;
@ -51,11 +52,13 @@ public class WesnothProjectPage extends PropertyPage
grpGeneral.setLayout( new GridLayout( 2, false ) );
Label lblNewLabel = new Label( grpGeneral, SWT.NONE );
lblNewLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
lblNewLabel.setLayoutData( new GridData( SWT.RIGHT, SWT.CENTER, false,
false, 1, 1 ) );
lblNewLabel.setText( Messages.WesnothProjectPage_1 );
cmbInstall_ = new Combo( grpGeneral, SWT.READ_ONLY );
cmbInstall_.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
cmbInstall_.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true,
false, 1, 1 ) );
// fill the installs
List< WesnothInstall > installs = WesnothInstallsUtils.getInstalls( );
@ -63,13 +66,11 @@ public class WesnothProjectPage extends PropertyPage
boolean foundInstallInList = false;
String installName = currProjectCache_.getInstallName( );
for ( WesnothInstall wesnothInstall : installs )
{
for( WesnothInstall wesnothInstall: installs ) {
cmbInstall_.add( wesnothInstall.getName( ) );
// current install is default?
if ( wesnothInstall.getName( ).equalsIgnoreCase( installName ) )
{
if( wesnothInstall.getName( ).equalsIgnoreCase( installName ) ) {
cmbInstall_.select( cmbInstall_.getItemCount( ) - 1 );
foundInstallInList = true;
}
@ -87,8 +88,7 @@ public class WesnothProjectPage extends PropertyPage
public boolean performOk( )
{
// save settings.
if ( currProjectCache_ != null &&
!cmbInstall_.getText( ).isEmpty( ) ) {
if( currProjectCache_ != null && ! cmbInstall_.getText( ).isEmpty( ) ) {
currProjectCache_.setInstallName( cmbInstall_.getText( ) );
}

View file

@ -32,12 +32,13 @@ import org.wesnoth.wml.WmlFactory2;
*/
public class SchemaParser
{
protected final static Map< String, SchemaParser > parsers_ =
new HashMap<String, SchemaParser>();
protected final static Map< String, SchemaParser > parsers_ = new HashMap< String, SchemaParser >( );
/**
* Returns a SchemaParser instance based on the specified install
* @param installName The name of the install
*
* @param installName
* The name of the install
* @return A SchemaParser singleton instance
*/
public static SchemaParser getInstance( String installName )
@ -58,7 +59,9 @@ public class SchemaParser
/**
* Reloads all currently stored schemas
* @param force True to force reloading schemas
*
* @param force
* True to force reloading schemas
*/
public static void reloadSchemas( boolean force )
{
@ -84,45 +87,50 @@ public class SchemaParser
/**
* Parses the schema
*
* @param installName The install to use. It will get the default schema
* @param installName
* The install to use. It will get the default schema
* path based on that
*
* @param force True to force parsing the schema, skipping the existing cache
* @param force
* True to force parsing the schema, skipping the existing cache
*/
public void parseSchema( boolean force )
{
parseSchemaFile( force, Preferences.getPaths( installName_ ).getSchemaPath( ) );
parseSchemaFile( force, Preferences.getPaths( installName_ )
.getSchemaPath( ) );
}
/**
* Parses the schema
* @param force True to force parsing the schema, skipping the existing cache
* @param schemaPath The path to the 'schema.cfg' file
*
* @param force
* True to force parsing the schema, skipping the existing cache
* @param schemaPath
* The path to the 'schema.cfg' file
*/
public void parseSchemaFile( boolean force, String schemaPath )
{
if (parsingDone_ && !force)
{
Logger.getInstance().log("schema not parsed since there is already in cache."); //$NON-NLS-1$
if( parsingDone_ && ! force ) {
Logger.getInstance( ).log(
"schema not parsed since there is already in cache." ); //$NON-NLS-1$
return;
}
parsingDone_ = false;
if (force)
{
if( force ) {
primitives_.clear( );
tags_.clear( );
}
Logger.getInstance().log("parsing schema " + (force == true ? "forced" : "")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
Logger.getInstance( ).log(
"parsing schema " + ( force == true ? "forced": "" ) ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
File schemaFile = new File( schemaPath );
String res = ResourceUtils.getFileContents( schemaFile );
String[] lines = StringUtils.getLines( res );
Stack< String > tagStack = new Stack< String >( );
WMLTag currentTag = null;
for (int index = 0; index < lines.length; index++)
{
for( int index = 0; index < lines.length; index++ ) {
String line = lines[index];
// skip comments and empty lines
if( StringUtils.startsWith( line, "#" ) || line.matches( "^[\t ]*$" ) ) //$NON-NLS-1$ //$NON-NLS-2$
@ -135,21 +143,23 @@ public class SchemaParser
{
// propagate the 'needsexpanding' property to upper levels
boolean expand = false;
if (!tagStack.isEmpty() &&
tags_.containsKey(tagStack.peek()))
expand = tags_.get(tagStack.peek()).is_NeedingExpansion();
if( ! tagStack.isEmpty( )
&& tags_.containsKey( tagStack.peek( ) ) )
expand = tags_.get( tagStack.peek( ) )
.is_NeedingExpansion( );
tagStack.pop( );
if (!tagStack.isEmpty() &&
tags_.containsKey(tagStack.peek()) &&
expand == true)
tags_.get(tagStack.peek()).set_NeedingExpansion(expand);
if( ! tagStack.isEmpty( )
&& tags_.containsKey( tagStack.peek( ) )
&& expand == true )
tags_.get( tagStack.peek( ) ).set_NeedingExpansion(
expand );
}
// opening tag
else
{
String tagName = line.substring(line.indexOf("[") + 1, line.indexOf("]")); //$NON-NLS-1$ //$NON-NLS-2$
else {
String tagName = line.substring(
line.indexOf( "[" ) + 1, line.indexOf( "]" ) ); //$NON-NLS-1$ //$NON-NLS-2$
String simpleTagName = tagName;
String extendedTagName = ""; //$NON-NLS-1$
if( tagName.split( ":" ).length > 1 ) //$NON-NLS-1$
@ -161,32 +171,31 @@ public class SchemaParser
if( ! tagName.equals( "description" ) ) //$NON-NLS-1$
{
if (tags_.containsKey(simpleTagName))
{
if( tags_.containsKey( simpleTagName ) ) {
// this tags was already refered in the schema
// before they were declared
currentTag = tags_.get( simpleTagName );
currentTag.set_InhertedTagName( extendedTagName );
currentTag.set_NeedingExpansion(!extendedTagName.isEmpty());
currentTag.set_NeedingExpansion( ! extendedTagName
.isEmpty( ) );
}
else
{
WMLTag tag = WmlFactory2.eINSTANCE.createWMLTag( simpleTagName, extendedTagName );
tag.set_NeedingExpansion( ! extendedTagName.isEmpty( ) );
else {
WMLTag tag = WmlFactory2.eINSTANCE.createWMLTag(
simpleTagName, extendedTagName );
tag.set_NeedingExpansion( ! extendedTagName
.isEmpty( ) );
currentTag = tag;
tags_.put( simpleTagName, tag );
}
}
}
}
else
{
else {
// top level - primitives defined
if( tagStack.peek( ).equals( "schema" ) ) //$NON-NLS-1$
{
String[] tokens = line.split( "=" ); //$NON-NLS-1$
if (tokens.length != 2)
{
if( tokens.length != 2 ) {
Logger.getInstance( ).logError(
"Error. invalid primitive on line :" + index ); //$NON-NLS-1$
continue;
@ -202,78 +211,76 @@ public class SchemaParser
// this *should* happen only in [description]
// multi-line string
if (StringUtils.countOf(tokens[1], '"') % 2 != 0)
{
if( StringUtils.countOf( tokens[1], '"' ) % 2 != 0 ) {
value.append( tokens[1] + "\n" ); //$NON-NLS-1$
++index;
while (StringUtils.countOf(lines[index], '"') % 2 == 0 &&
!StringUtils.startsWith(lines[index], "#") && //$NON-NLS-1$
index < lines.length)
{
while( StringUtils.countOf( lines[index], '"' ) % 2 == 0
&& ! StringUtils.startsWith( lines[index], "#" ) && //$NON-NLS-1$
index < lines.length ) {
value.append( lines[index] + "\n" ); //$NON-NLS-1$
++index;
}
value.append( lines[index] );
}
else
{
else {
value.append( tokens[1] );
}
// get rid of the quotes
if (value.length() >= 2)
{
value = new StringBuilder(value.substring(1, value.length() - 1));
if( value.length( ) >= 2 ) {
value = new StringBuilder( value.substring( 1,
value.length( ) - 1 ) );
}
if( currentTag != null ) {
currentTag.set_Description( value.toString( ) );
}else {
}
else {
System.out.println( "Tag shouldn't have been null!" ); //$NON-NLS-1$
}
}
else
{
else {
String tmpLine = line.trim( );
if( line.contains( "#" ) ) //$NON-NLS-1$
tmpLine = line.substring(0, line.lastIndexOf("#")).trim(); //$NON-NLS-1$
tmpLine = line
.substring( 0, line.lastIndexOf( "#" ) ).trim( ); //$NON-NLS-1$
String[] tokens = tmpLine.split( "=" ); //$NON-NLS-1$
if (tokens.length != 2)
{
if( tokens.length != 2 ) {
Logger.getInstance( ).logError(
"Error. invalid attribute on line :" + index ); //$NON-NLS-1$
continue;
}
String[] value = tokens[1].substring(1, tokens[1].length() - 1).split(" "); //$NON-NLS-1$
if (value.length != 2)
{
Logger.getInstance().logError(
String[] value = tokens[1].substring( 1,
tokens[1].length( ) - 1 ).split( " " ); //$NON-NLS-1$
if( value.length != 2 ) {
Logger.getInstance( )
.logError(
"Error. invalid attribute value on line:" + index ); //$NON-NLS-1$
continue;
}
if (currentTag != null)
{
if( currentTag != null ) {
if( tokens[0].startsWith( "_" ) ) // reference to another tag //$NON-NLS-1$
{
WMLTag targetTag = null;
targetTag = tags_.get( value[1] );
// tag wasn't created yet
if ( targetTag == null )
{
targetTag = WmlFactory2.eINSTANCE.createWMLTag( value[1], "", getCardinality( value[0] ) );
if( targetTag == null ) {
targetTag = WmlFactory2.eINSTANCE
.createWMLTag( value[1], "",
getCardinality( value[0] ) );
tags_.put( value[1], targetTag );
}
currentTag.getExpressions( ).add( targetTag );
}
else
{
else {
if( primitives_.get( value[1] ) == null )
Logger.getInstance().logError(
Logger.getInstance( )
.logError(
"Undefined primitive type in schema.cfg for: " + value[1] ); //$NON-NLS-1$
currentTag.getExpressions( ).add(
@ -284,9 +291,9 @@ public class SchemaParser
value[1].equals( "tstring" ) ) );
}
}
else
{
//System.err.println("can't find entry for: " + tagStack.peek());
else {
// System.err.println("can't find entry for: " +
// tagStack.peek());
}
}
}
@ -309,8 +316,7 @@ public class SchemaParser
*/
private void expandTag( WMLTag tag )
{
if (tag.is_NeedingExpansion())
{
if( tag.is_NeedingExpansion( ) ) {
tag.set_NeedingExpansion( false );
for( WMLTag subTag: tag.getWMLTags( ) ) {
@ -326,11 +332,14 @@ public class SchemaParser
/**
* Sorts all tag's children by using the cardinality comparator
* @param tag The tag to whom to sort the children
*
* @param tag
* The tag to whom to sort the children
*/
private void sortChildren( WMLTag tag )
{
WMLExpression[] expressions = ( WMLExpression[] ) tag.getExpressions( ).toArray( );
WMLExpression[] expressions = ( WMLExpression[] ) tag.getExpressions( )
.toArray( );
Arrays.sort( expressions, new CardinalityComparator( ) );
tag.getExpressions( ).clear( );
@ -357,7 +366,9 @@ public class SchemaParser
* optional = ?
* repeated = *
* forbidden = -
* @param value The value the parse
*
* @param value
* The value the parse
*/
public char getCardinality( String value )
{
@ -376,7 +387,8 @@ public class SchemaParser
* A WML Expression comparator that sorts just after required cardinality.
* That is, after the sort the required wmlexpressions will be first
*/
public static class CardinalityComparator implements Comparator< WMLExpression >, Serializable
public static class CardinalityComparator implements
Comparator< WMLExpression >, Serializable
{
private static final long serialVersionUID = 6103884038547449868L;

View file

@ -17,6 +17,7 @@ import org.eclipse.xtext.scoping.impl.AbstractDeclarativeScopeProvider;
* on how and when to use it
*
*/
public class WMLScopeProvider extends AbstractDeclarativeScopeProvider {
public class WMLScopeProvider extends AbstractDeclarativeScopeProvider
{
}

View file

@ -8,9 +8,11 @@
*******************************************************************************/
package org.wesnoth.templates;
public class ReplaceableParameter{
public class ReplaceableParameter
{
public String paramName;
public String paramValue;
public ReplaceableParameter( String name, String value )
{
paramName = name;

Some files were not shown because too many files have changed in this diff Show more