eclipse plugin: Refactor the SchemaParser to take in account the install

This commit is contained in:
Timotei Dolean 2011-06-29 18:48:33 +00:00
parent c9c7cd882a
commit 0bcb25ec22
9 changed files with 106 additions and 87 deletions

View File

@ -22,8 +22,9 @@ import org.eclipse.xtext.parsetree.LeafNode;
import org.eclipse.xtext.parsetree.NodeUtil; import org.eclipse.xtext.parsetree.NodeUtil;
import org.eclipse.xtext.ui.editor.contentassist.ContentAssistContext; import org.eclipse.xtext.ui.editor.contentassist.ContentAssistContext;
import org.eclipse.xtext.ui.editor.contentassist.ICompletionProposalAcceptor; import org.eclipse.xtext.ui.editor.contentassist.ICompletionProposalAcceptor;
import org.wesnoth.Logger; import org.wesnoth.installs.WesnothInstallsUtils;
import org.wesnoth.preprocessor.Define; import org.wesnoth.preprocessor.Define;
import org.wesnoth.projects.ProjectCache;
import org.wesnoth.projects.ProjectUtils; import org.wesnoth.projects.ProjectUtils;
import org.wesnoth.schema.SchemaParser; import org.wesnoth.schema.SchemaParser;
import org.wesnoth.schema.Tag; import org.wesnoth.schema.Tag;
@ -40,20 +41,31 @@ import org.wesnoth.wml.impl.WmlFactoryImpl;
@SuppressWarnings("unused") @SuppressWarnings("unused")
public class WMLProposalProvider extends AbstractWMLProposalProvider public class WMLProposalProvider extends AbstractWMLProposalProvider
{ {
/** protected SchemaParser schemaParser_;
* We have the following priorities: protected ProjectCache projectCache_;
*
* 1700 - key values
* 1500 - key names
* 1000 - tags
* 100 - macro calls
*/
protected static final int KEY_VALUE_PRIORITY = 1700;
protected static final int KEY_NAME_PRIORITY = 1500;
protected static final int TAG_PRIORITY = 1000;
protected static final int MACRO_CALL_PRIORITY = 100;
/**
* For priorities, see:
* {@link #KEY_NAME_PRIORITY}
* {@link #KEY_VALUE_PRIORITY}
* {@link #TAG_PRIORITY}
* {@link #MACRO_CALL_PRIORITY}
*/
public WMLProposalProvider() public WMLProposalProvider()
{ {
super(); super();
IFile file = WMLUtil.getActiveEditorFile();
projectCache_ = ProjectUtils.getCacheForProject( file.getProject( ) );
// load the schema so we know what to suggest for autocomplete // load the schema so we know what to suggest for autocomplete
SchemaParser.getInstance().parseSchema(false); SchemaParser.reloadSchemas( false );
schemaParser_ = SchemaParser.getInstance( WesnothInstallsUtils.getInstallNameForResource( file ) );
} }
@Override @Override
@ -113,15 +125,7 @@ public class WMLProposalProvider extends AbstractWMLProposalProvider
private void addMacroCallProposals(EObject model, boolean ruleProposal, private void addMacroCallProposals(EObject model, boolean ruleProposal,
ContentAssistContext context, ICompletionProposalAcceptor acceptor) ContentAssistContext context, ICompletionProposalAcceptor acceptor)
{ {
IFile file = WMLUtil.getActiveEditorFile(); for(Entry<String, Define> define : projectCache_.getDefines().entrySet())
if (file == null)
{
Logger.getInstance().logError("FATAL! file is null (and it shouldn't)"); //$NON-NLS-1$
return;
}
for(Entry<String, Define> define : ProjectUtils.getCacheForProject(
file.getProject()).getDefines().entrySet())
{ {
StringBuilder proposal = new StringBuilder(10); StringBuilder proposal = new StringBuilder(10);
if (ruleProposal == true) if (ruleProposal == true)
@ -133,7 +137,7 @@ public class WMLProposalProvider extends AbstractWMLProposalProvider
proposal.append("}"); //$NON-NLS-1$ proposal.append("}"); //$NON-NLS-1$
acceptor.accept(createCompletionProposal(proposal.toString(), define.getKey(), acceptor.accept(createCompletionProposal(proposal.toString(), define.getKey(),
WMLLabelProvider.getImageByName("macrocall.png"), context, 100)); //$NON-NLS-1$ WMLLabelProvider.getImageByName("macrocall.png"), context, MACRO_CALL_PRIORITY)); //$NON-NLS-1$
} }
} }
@ -155,21 +159,13 @@ public class WMLProposalProvider extends AbstractWMLProposalProvider
if (key.getName().equals("next_scenario") || //$NON-NLS-1$ if (key.getName().equals("next_scenario") || //$NON-NLS-1$
key.getName().equals("first_scenario")) //$NON-NLS-1$ key.getName().equals("first_scenario")) //$NON-NLS-1$
{ {
IFile file = WMLUtil.getActiveEditorFile(); for(ConfigFile config : projectCache_.getConfigs().values())
if (file == null)
{
Logger.getInstance().logError("FATAL! file is null (and it shouldn't)"); //$NON-NLS-1$
return;
}
for(ConfigFile config : ProjectUtils.
getCacheForProject(file.getProject()).getConfigs().values())
{ {
if (StringUtils.isNullOrEmpty( config.ScenarioId )) if (StringUtils.isNullOrEmpty( config.ScenarioId ))
continue; continue;
acceptor.accept(createCompletionProposal(config.ScenarioId, acceptor.accept(createCompletionProposal(config.ScenarioId,
config.ScenarioId, WMLLabelProvider.getImageByName("scenario.png"), //$NON-NLS-1$ config.ScenarioId, WMLLabelProvider.getImageByName("scenario.png"), //$NON-NLS-1$
context, 1700)); context, KEY_VALUE_PRIORITY));
} }
} }
else else
@ -178,7 +174,7 @@ public class WMLProposalProvider extends AbstractWMLProposalProvider
model.eContainer() instanceof WMLTag) model.eContainer() instanceof WMLTag)
{ {
WMLTag parent = (WMLTag) model.eContainer(); WMLTag parent = (WMLTag) model.eContainer();
Tag tag = SchemaParser.getInstance().getTags().get(parent.getName()); Tag tag = schemaParser_.getTags().get(parent.getName());
if (tag != null) if (tag != null)
{ {
TagKey tagKey = tag.getChildKey(key.getName()); TagKey tagKey = tag.getChildKey(key.getName());
@ -213,11 +209,11 @@ public class WMLProposalProvider extends AbstractWMLProposalProvider
if (tag != null) if (tag != null)
{ {
if (SchemaParser.getInstance(). getTags().get(tag.getName()) != null) Tag schemaTag = schemaParser_.getTags().get(tag.getName());
if ( schemaTag != null)
{ {
boolean found = false; boolean found = false;
for(TagKey key : SchemaParser.getInstance(). for(TagKey key : schemaTag.getKeyChildren())
getTags().get(tag.getName()).getKeyChildren())
{ {
// skip forbidden keys // skip forbidden keys
if (key.isForbidden()) if (key.isForbidden())
@ -237,7 +233,7 @@ public class WMLProposalProvider extends AbstractWMLProposalProvider
acceptor.accept(createCompletionProposal(key.getName() + "=", //$NON-NLS-1$ acceptor.accept(createCompletionProposal(key.getName() + "=", //$NON-NLS-1$
key.getName(), key.getName(),
getImage(WmlFactoryImpl.eINSTANCE.getWmlPackage().getWMLKey()), getImage(WmlFactoryImpl.eINSTANCE.getWmlPackage().getWMLKey()),
context, 1500)); context, KEY_NAME_PRIORITY));
} }
} }
} }
@ -274,7 +270,7 @@ public class WMLProposalProvider extends AbstractWMLProposalProvider
// remove ugly new lines that break indentation // 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$ parentIndent = parentIndent.replace("\r", "").replace("\n", ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
Tag tagChildren = SchemaParser.getInstance().getTags().get(parentTag.getName()); Tag tagChildren = schemaParser_.getTags().get(parentTag.getName());
if (tagChildren != null) if (tagChildren != null)
{ {
boolean found = false; boolean found = false;
@ -307,7 +303,7 @@ public class WMLProposalProvider extends AbstractWMLProposalProvider
} }
else // we are at the root else // we are at the root
{ {
Tag rootTag = SchemaParser.getInstance().getTags().get("root"); //$NON-NLS-1$ Tag rootTag = schemaParser_.getTags().get("root"); //$NON-NLS-1$
dbg("root node. adding tags: "+ rootTag.getTagChildren().size()); //$NON-NLS-1$ dbg("root node. adding tags: "+ rootTag.getTagChildren().size()); //$NON-NLS-1$
for(Tag tag : rootTag.getTagChildren()) for(Tag tag : rootTag.getTagChildren())
{ {
@ -327,7 +323,6 @@ public class WMLProposalProvider extends AbstractWMLProposalProvider
private ICompletionProposal tagProposal(Tag tag, String indent, boolean ruleProposal, private ICompletionProposal tagProposal(Tag tag, String indent, boolean ruleProposal,
ContentAssistContext context) ContentAssistContext context)
{ {
// dbg("indent:[" + indent +"]");
StringBuilder proposal = new StringBuilder(); StringBuilder proposal = new StringBuilder();
if (ruleProposal) if (ruleProposal)
proposal.append("["); //$NON-NLS-1$ proposal.append("["); //$NON-NLS-1$
@ -342,7 +337,7 @@ public class WMLProposalProvider extends AbstractWMLProposalProvider
proposal.append(String.format("%s[/%s]",indent, tag.getName())); //$NON-NLS-1$ proposal.append(String.format("%s[/%s]",indent, tag.getName())); //$NON-NLS-1$
return createCompletionProposal(proposal.toString(), tag.getName(), return createCompletionProposal(proposal.toString(), tag.getName(),
getImage(WmlFactoryImpl.eINSTANCE.getWmlPackage().getWMLTag()), getImage(WmlFactoryImpl.eINSTANCE.getWmlPackage().getWMLTag()),
context, 100); context, TAG_PRIORITY);
} }
private ICompletionProposal createCompletionProposal(String proposal, private ICompletionProposal createCompletionProposal(String proposal,

View File

@ -22,13 +22,13 @@ import org.eclipse.xtext.ui.editor.XtextEditor;
import org.eclipse.xtext.ui.editor.utils.EditorUtils; import org.eclipse.xtext.ui.editor.utils.EditorUtils;
import org.eclipse.xtext.util.concurrent.IUnitOfWork; import org.eclipse.xtext.util.concurrent.IUnitOfWork;
import org.wesnoth.Logger; import org.wesnoth.Logger;
import org.wesnoth.installs.WesnothInstallsUtils;
import org.wesnoth.preprocessor.Define; import org.wesnoth.preprocessor.Define;
import org.wesnoth.projects.ProjectUtils; import org.wesnoth.projects.ProjectUtils;
import org.wesnoth.ui.WMLUtil; import org.wesnoth.ui.WMLUtil;
import org.wesnoth.wml.WMLMacroCall; import org.wesnoth.wml.WMLMacroCall;
import org.wesnoth.wml.WMLTag; import org.wesnoth.wml.WMLTag;
/** /**
* A handler that handles pressing F2 on a resource in the editor * A handler that handles pressing F2 on a resource in the editor
*/ */
@ -39,6 +39,9 @@ public class WMLDocHandler extends AbstractHandler
try try
{ {
final XtextEditor editor = EditorUtils.getActiveXtextEditor(event); final XtextEditor editor = EditorUtils.getActiveXtextEditor(event);
final String installName =
WesnothInstallsUtils.getInstallNameForResource( WMLUtil.getActiveEditorFile( ) );
editor.getDocument().readOnly(new IUnitOfWork.Void<XtextResource>() editor.getDocument().readOnly(new IUnitOfWork.Void<XtextResource>()
{ {
private WMLDocInformationPresenter presenter_; private WMLDocInformationPresenter presenter_;
@ -81,7 +84,7 @@ public class WMLDocHandler extends AbstractHandler
{ {
presenter_ = new WMLDocInformationPresenter( presenter_ = new WMLDocInformationPresenter(
editor.getSite().getShell(), editor.getSite().getShell(),
new WMLDocTag(((WMLTag)container.getElement()).getName()), new WMLDocTag( installName, ((WMLTag)container.getElement()).getName()),
positionAbsolute); positionAbsolute);
presenter_.create(); presenter_.create();
} }

View File

@ -18,7 +18,6 @@ import org.wesnoth.schema.SchemaParser;
import org.wesnoth.schema.Tag; import org.wesnoth.schema.Tag;
import org.wesnoth.ui.Messages; import org.wesnoth.ui.Messages;
/** /**
* Displays wml doc for a tag * Displays wml doc for a tag
* [tag] or [/tag] * [tag] or [/tag]
@ -30,10 +29,11 @@ public class WMLDocTag implements IWMLDocProvider
private String contents_; private String contents_;
private List<StyleRange> styleRanges_; private List<StyleRange> styleRanges_;
public WMLDocTag(String name) public WMLDocTag( String installName, String name )
{ {
tag_ = SchemaParser.getInstance().getTags().get(name); tag_ = SchemaParser.getInstance( installName ).getTags().get(name);
} }
/** /**
* A method used for lazly generating the documentation * A method used for lazly generating the documentation
*/ */

View File

@ -18,7 +18,8 @@ public class WMLStandaloneSetup extends WMLStandaloneSetupGenerated
{ {
public static void doSetup() { public static void doSetup() {
new WMLStandaloneSetup().createInjectorAndDoEMFRegistration(); new WMLStandaloneSetup().createInjectorAndDoEMFRegistration();
SchemaParser.getInstance().parseSchema(false);
SchemaParser.reloadSchemas( false );
} }
} }

View File

@ -21,7 +21,6 @@ import org.wesnoth.wml.WMLRoot;
import org.wesnoth.wml.WMLTag; import org.wesnoth.wml.WMLTag;
import org.wesnoth.wml.WmlPackage; import org.wesnoth.wml.WmlPackage;
/** /**
* This represents the validator for config files * This represents the validator for config files
* *
@ -56,10 +55,13 @@ public class WMLJavaValidator extends AbstractWMLJavaValidator
{ {
searchName = "root"; //$NON-NLS-1$ searchName = "root"; //$NON-NLS-1$
} }
if (SchemaParser.getInstance().getTags().get(searchName) != null)
//TODO: get the editor based on this validator??
Tag schemaTag = SchemaParser.getInstance( null ).getTags().get(searchName);
if ( schemaTag != null )
{ {
for(Tag childTag : SchemaParser.getInstance().getTags().get(searchName). for(Tag childTag : schemaTag.getTagChildren())
getTagChildren())
{ {
if (childTag.getName().equals(tag.getName())) if (childTag.getName().equals(tag.getName()))
{ {

View File

@ -20,13 +20,12 @@ import org.wesnoth.schema.SchemaParser;
import org.wesnoth.templates.TemplateProvider; import org.wesnoth.templates.TemplateProvider;
import org.wesnoth.utils.GUIUtils; import org.wesnoth.utils.GUIUtils;
public class ReloadFilesHandler extends AbstractHandler public class ReloadFilesHandler extends AbstractHandler
{ {
@Override @Override
public Object execute(ExecutionEvent event) public Object execute(ExecutionEvent event)
{ {
SchemaParser.getInstance().parseSchema(true); SchemaParser.reloadSchemas( true );
TemplateProvider.getInstance().loadTemplates(); TemplateProvider.getInstance().loadTemplates();

View File

@ -139,6 +139,10 @@ public class Preferences extends AbstractPreferenceInitializer
*/ */
public static Paths getPaths( String installName ) public static Paths getPaths( String installName )
{ {
// no null allowed -> fallback to ""
if ( installName == null )
installName = "";
Paths paths = paths_.get( installName ); Paths paths = paths_.get( installName );
if ( paths == null ) { if ( paths == null ) {
paths = new Paths( getInstallPrefix( installName ) ); paths = new Paths( getInstallPrefix( installName ) );

View File

@ -11,34 +11,70 @@ package org.wesnoth.schema;
import java.io.File; import java.io.File;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Stack; import java.util.Stack;
import org.wesnoth.Logger; import org.wesnoth.Logger;
import org.wesnoth.Messages; import org.wesnoth.Messages;
import org.wesnoth.installs.WesnothInstall;
import org.wesnoth.installs.WesnothInstallsUtils;
import org.wesnoth.preferences.Preferences; import org.wesnoth.preferences.Preferences;
import org.wesnoth.utils.ResourceUtils; import org.wesnoth.utils.ResourceUtils;
import org.wesnoth.utils.StringUtils; import org.wesnoth.utils.StringUtils;
/** /**
* This is a 'schema.cfg' parser. * This is a 'schema.cfg' parser.
*/ */
public class SchemaParser public class SchemaParser
{ {
//TODO: add a faster search method for keys/tags by name protected static Map< String, SchemaParser > parsers_ =
private static SchemaParser instance_; new HashMap<String, SchemaParser>();
public static SchemaParser getInstance() /**
* Returns a SchemaParser instance based on the specified install
* @param installName The name of the install
* @return A SchemaParser singleton instance
*/
public static SchemaParser getInstance( String installName )
{ {
if (instance_ == null) // null not allowed
instance_ = new SchemaParser(); if ( installName == null )
return instance_; installName = "";
SchemaParser parser = parsers_.get( installName );
if (parser == null) {
parser = new SchemaParser( installName );
parsers_.put( installName, parser );
} }
private Map<String, String> primitives_ = new HashMap<String, String>(); return parser;
private Map<String, Tag> tags_ = new HashMap<String, Tag>(); }
private boolean parsingDone_ = false;
/**
* Reloads all currently stored schemas
* @param force True to force reloading schemas
*/
public static void reloadSchemas( boolean force )
{
List< WesnothInstall > installs = WesnothInstallsUtils.getInstalls( );
for ( WesnothInstall install : installs ) {
getInstance( install.getName( ) ).parseSchema( force );
}
}
private Map<String, String> primitives_;
private Map<String, Tag> tags_;
private boolean parsingDone_;
private String installName_;
private SchemaParser( String installName )
{
installName_ = installName;
primitives_ = new HashMap<String, String>();
tags_ = new HashMap<String, Tag>();
parsingDone_ = false;
}
/** /**
* Parses the schema * Parses the schema
@ -50,9 +86,7 @@ public class SchemaParser
*/ */
public void parseSchema( boolean force ) public void parseSchema( boolean force )
{ {
//TODO should parse schema for each install type parseSchemaFile( force, Preferences.getPaths( installName_ ).getSchemaPath( ) );
// for now, use the default install
parseSchemaFile( force, Preferences.getPaths( null ).getSchemaPath( ) );
} }
/** /**
@ -254,27 +288,6 @@ public class SchemaParser
Logger.getInstance().log(Messages.SchemaParser_36); Logger.getInstance().log(Messages.SchemaParser_36);
parsingDone_ = true; parsingDone_ = true;
// try
// {
// BufferedWriter bw = new BufferedWriter(new PrintWriter(new File("E:/work/gw/data/schema-out.cfg")));
// // print primitives
// for (Entry<String, String> primitive : primitives_.entrySet())
// {
// bw.write(primitive.getKey() + ": " + primitive.getValue() + "\n");
// }
// // print tags
// Tag root = tags_.get("root");
// for (Tag tag : root.getTagChildren())
// {
// bw.write(getOutput(tag, 0));
// }
// bw.close();
// } catch (Exception e)
// {
// Logger.getInstance().logException(e);
// }
// System.out.println("End writing result");
} }
/** /**

View File

@ -22,9 +22,11 @@ public class WizardGenerator extends NewWizardTemplate
private byte indent_; private byte indent_;
public WizardGenerator(String title, String tagName, byte indent) { public WizardGenerator(String title, String tagName, byte indent) {
SchemaParser.getInstance().parseSchema(false);
// TODO: wizards should ask the install
SchemaParser.getInstance( null ).parseSchema(false);
setWindowTitle(title); setWindowTitle(title);
Tag tagContent = SchemaParser.getInstance().getTags().get(tagName); Tag tagContent = SchemaParser.getInstance( null ).getTags().get(tagName);
tagName_ = tagName; tagName_ = tagName;
indent_ = indent; indent_ = indent;