From 1c4dc681cb2c2c8b022457113b0967637fb183f2 Mon Sep 17 00:00:00 2001 From: azerr Date: Fri, 27 Nov 2026 11:29:26 +0100 Subject: [PATCH] Implement catalog binding support with async entry selection - Add CatalogEntrySelectionDialog: quick-open style dialog for selecting bindable catalog entries, populated asynchronously via CompletableFuture - Add CatalogEntryLabelProvider: styled display of entries with entry type, identifier, and gray-colored catalog filename (disambiguated by path segments when needed) - Implement AssociateGrammarDialog with Catalog mode: radio button to switch between Local/Remote and Catalog modes, Browse button that fetches entries asynchronously with progress indicator - Modify AssociateGrammarHandler: fetch catalog entries only when user opens dialog, no blocking server calls in handler, fresh fetch each dialog open to reflect catalog changes - Add webURL support in XMLCatalogs: for WTP catalog contributions with webURL attributes on public entries, generate additional system entries pointing to web URLs Signed-off-by: azerr --- org.eclipse.wildwebdeveloper.xml/plugin.xml | 2 +- .../commands/AssociateGrammarHandler.java | 109 ----- .../AssociateGrammarDialog.java | 432 ++++++++++-------- .../associate/AssociateGrammarHandler.java | 146 ++++++ .../associate/BindableCatalogEntry.java | 37 ++ .../associate/CatalogEntryLabelProvider.java | 129 ++++++ .../CatalogEntrySelectionDialog.java | 369 +++++++++++++++ .../associate/GrammarFileSelectionDialog.java | 46 ++ .../xml/internal/ui/Messages.java | 6 + .../xml/internal/ui/messages.properties | 6 + .../internal/ui/preferences/XMLCatalogs.java | 6 + .../preferences/XMLPreferenceInitializer.java | 2 +- 12 files changed, 1001 insertions(+), 289 deletions(-) delete mode 100644 org.eclipse.wildwebdeveloper.xml/src/org/eclipse/wildwebdeveloper/xml/internal/commands/AssociateGrammarHandler.java rename org.eclipse.wildwebdeveloper.xml/src/org/eclipse/wildwebdeveloper/xml/internal/commands/{ => associate}/AssociateGrammarDialog.java (56%) create mode 100644 org.eclipse.wildwebdeveloper.xml/src/org/eclipse/wildwebdeveloper/xml/internal/commands/associate/AssociateGrammarHandler.java create mode 100644 org.eclipse.wildwebdeveloper.xml/src/org/eclipse/wildwebdeveloper/xml/internal/commands/associate/BindableCatalogEntry.java create mode 100644 org.eclipse.wildwebdeveloper.xml/src/org/eclipse/wildwebdeveloper/xml/internal/commands/associate/CatalogEntryLabelProvider.java create mode 100644 org.eclipse.wildwebdeveloper.xml/src/org/eclipse/wildwebdeveloper/xml/internal/commands/associate/CatalogEntrySelectionDialog.java create mode 100644 org.eclipse.wildwebdeveloper.xml/src/org/eclipse/wildwebdeveloper/xml/internal/commands/associate/GrammarFileSelectionDialog.java diff --git a/org.eclipse.wildwebdeveloper.xml/plugin.xml b/org.eclipse.wildwebdeveloper.xml/plugin.xml index ef31e674ee..2fcca3f964 100644 --- a/org.eclipse.wildwebdeveloper.xml/plugin.xml +++ b/org.eclipse.wildwebdeveloper.xml/plugin.xml @@ -231,7 +231,7 @@ - *
  • open a dialog to select the grammar file to associate and the binding - * type (xsi, DOCTYPE, xml-model, ...)
  • - *
  • insert in the XML the proper syntax to associate the selected grammar - * file / binding type by consuming the "xml.associate.grammar.insert" XML - * language server command.
  • - * - * - * @author Angelo ZERR - * - */ -public class AssociateGrammarHandler extends LSPCommandHandler { - - private static final String ASSOCIATE_GRAMMAR_INSERT = "xml.associate.grammar.insert"; - - @Override - public Object execute(ExecutionEvent event, Command command, IPath path) throws ExecutionException { - String uri = ArgumentsUtils.getArgAt(command, 0, String.class); - // Open the association grammar dialog. - AssociateGrammarDialog dialog = new AssociateGrammarDialog(HandlerUtil.getActiveShell(event), path); - if (dialog.open() == IDialogConstants.OK_ID) { - String grammarURI = dialog.getGrammarURI(); - String bindingType = dialog.getBindingType().getCode(); - TextDocumentIdentifier identifier = new TextDocumentIdentifier(uri); - try { - executeServerCommand(ASSOCIATE_GRAMMAR_INSERT, identifier, grammarURI, bindingType) // - .thenAccept(result -> { - // Insert the proper syntax for binding - Gson gson = new Gson(); - JsonObject jsonObject = gson.toJsonTree(result).getAsJsonObject(); - TextDocumentEdit edit = gson.fromJson(jsonObject, TextDocumentEdit.class); - WorkspaceEdit workEdits = new WorkspaceEdit(); - workEdits.setDocumentChanges(new ArrayList<>()); - workEdits.getDocumentChanges().add(Either.forLeft(edit)); - LSPEclipseUtils.applyWorkspaceEdit(workEdits, ASSOCIATE_GRAMMAR_INSERT); - }); - } catch (Exception e) { - ILog.get().error("Error while insert grammar association", e); - } - } - return null; - } - - private static CompletableFuture executeServerCommand(String commandId, Object... params) throws Exception { - List commandHandlers = new ArrayList<>(); - LanguageServers.forProject(null).withCapability(serverCapabilities -> { - ExecuteCommandOptions executeCommandProvider = serverCapabilities.getExecuteCommandProvider(); - return Either.forLeft( - executeCommandProvider != null ? executeCommandProvider.getCommands().contains(commandId) : false); - }).excludeInactive().collectAll((w, ls) -> CompletableFuture.completedFuture(ls)) - .thenAccept(commandHandlers::addAll).get(100, TimeUnit.MILLISECONDS); - - if (commandHandlers.size() == 1) { - LanguageServer handler = commandHandlers.get(0); - return handler.getWorkspaceService() - .executeCommand(new ExecuteCommandParams(commandId, Arrays.asList(params))); - } else if (commandHandlers.size() > 1) { - throw new IllegalStateException( - "Multiple language servers have registered to handle command '" + commandId + "'"); - } - - throw new UnsupportedOperationException( - "No language server has registered to handle command '" + commandId + "'"); - } -} diff --git a/org.eclipse.wildwebdeveloper.xml/src/org/eclipse/wildwebdeveloper/xml/internal/commands/AssociateGrammarDialog.java b/org.eclipse.wildwebdeveloper.xml/src/org/eclipse/wildwebdeveloper/xml/internal/commands/associate/AssociateGrammarDialog.java similarity index 56% rename from org.eclipse.wildwebdeveloper.xml/src/org/eclipse/wildwebdeveloper/xml/internal/commands/AssociateGrammarDialog.java rename to org.eclipse.wildwebdeveloper.xml/src/org/eclipse/wildwebdeveloper/xml/internal/commands/associate/AssociateGrammarDialog.java index 81538cad80..646c4285ca 100644 --- a/org.eclipse.wildwebdeveloper.xml/src/org/eclipse/wildwebdeveloper/xml/internal/commands/AssociateGrammarDialog.java +++ b/org.eclipse.wildwebdeveloper.xml/src/org/eclipse/wildwebdeveloper/xml/internal/commands/associate/AssociateGrammarDialog.java @@ -9,19 +9,20 @@ * Contributors: * Angelo ZERR (Red Hat Inc.) - initial implementation *******************************************************************************/ -package org.eclipse.wildwebdeveloper.xml.internal.commands; +package org.eclipse.wildwebdeveloper.xml.internal.commands.associate; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.util.Arrays; +import java.util.Collections; import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.function.Supplier; import java.util.stream.Collectors; -import java.util.stream.Stream; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IStatus; @@ -31,9 +32,6 @@ import org.eclipse.jface.dialogs.IMessageProvider; import org.eclipse.jface.dialogs.MessageDialogWithToggle; import org.eclipse.jface.dialogs.TitleAreaDialog; -import org.eclipse.jface.viewers.Viewer; -import org.eclipse.jface.viewers.ViewerFilter; -import org.eclipse.lsp4e.LSPEclipseUtils; import org.eclipse.swt.SWT; import org.eclipse.swt.events.FocusAdapter; import org.eclipse.swt.events.FocusEvent; @@ -47,14 +45,14 @@ import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; -import org.eclipse.ui.dialogs.FilteredResourcesSelectionDialog; import org.eclipse.wildwebdeveloper.xml.internal.Activator; import org.eclipse.wildwebdeveloper.xml.internal.ui.Messages; import org.eclipse.wildwebdeveloper.xml.internal.ui.preferences.XMLPreferenceServerConstants; /** * Dialog to select a grammar file (XSD, DTD, RelaxNG) and a binding type - * (standard, xml-model). Supports both local workspace files and remote URLs. + * (standard, xml-model). Supports local workspace files, remote URLs, and + * catalog-based binding. * * @author Angelo ZERR */ @@ -63,16 +61,14 @@ public class AssociateGrammarDialog extends TitleAreaDialog { /** Preference key for the "Don't ask again" toggle on the download prompt. */ public static final String PREF_ENABLE_DOWNLOAD_PROMPT = Activator.PLUGIN_ID + ".associateGrammar.enableDownloadPrompt"; //$NON-NLS-1$ - private final static List W3C_GRAMMAR_FILE_EXTENSION = Arrays.asList("xsd", "dtd"); + static final List W3C_EXTENSIONS = Arrays.asList("xsd", "dtd"); //$NON-NLS-1$ //$NON-NLS-2$ + static final List RELAXNG_EXTENSIONS = Arrays.asList("rng", "rnc"); //$NON-NLS-1$ //$NON-NLS-2$ + static final List ALL_GRAMMAR_EXTENSIONS = Arrays.asList("xsd", "dtd", "rng", "rnc"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ - private final static List RELAXNG_GRAMMAR_FILE_EXTENSION = Arrays.asList("rng", "rnc"); + public enum BindingType { - private final static List ALL_GRAMMAR_FILE_EXTENSION = Stream - .concat(W3C_GRAMMAR_FILE_EXTENSION.stream(), RELAXNG_GRAMMAR_FILE_EXTENSION.stream()).toList(); - - public static enum BindingType { - - standard("standard", "Standard (xsi, DOCTYPE)"), xmlmodel("xml-model", "XML Model association"); + standard("standard", "Standard (xsi, DOCTYPE)"), //$NON-NLS-1$ + xmlmodel("xml-model", "XML Model association"); //$NON-NLS-1$ private final String code; private final String label; @@ -91,33 +87,47 @@ public String getLabel() { } } - public static enum GrammarLocationType { - local, remote; + public enum GrammarLocationType { + local, remote, catalog } private final IPath xmlFilePath; private final IContainer xmlResourceContainer; + private final Supplier>> catalogEntriesSupplier; + /** Cached future — set on first Browse click, reused on subsequent clicks within this dialog. */ + private CompletableFuture> catalogEntriesFuture; + private List catalogEntries = Collections.emptyList(); + // Grammar section widgets private Button localRadio; private Button remoteRadio; + private Button catalogRadio; private Text localGrammarURIText; - private Button browseButton; + private Button browseLocalButton; private Text remoteGrammarURIText; + private Text selectedCatalogText; + private Button browseCatalogButton; + // Binding section widgets + private Group bindingTypeGroup; private Button standardRadio; private Button xmlModelRadio; - // Output values + // Output values — saved in saveInput() while widgets are still alive + private boolean catalogMode; private String grammarURI; private BindingType bindingType; + private BindableCatalogEntry selectedCatalogEntry; - public AssociateGrammarDialog(Shell parentShell, IPath xmlFilePath) { + public AssociateGrammarDialog(Shell parentShell, IPath xmlFilePath, + Supplier>> catalogEntriesSupplier) { super(parentShell); this.xmlFilePath = xmlFilePath; - this.xmlResourceContainer = getResourceContainer(xmlFilePath); + this.xmlResourceContainer = resolveResourceContainer(xmlFilePath); + this.catalogEntriesSupplier = catalogEntriesSupplier; } - private IContainer getResourceContainer(IPath xmlFilePath) { + private static IContainer resolveResourceContainer(IPath xmlFilePath) { IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(xmlFilePath); if (file != null && file.exists()) { return file.getProject(); @@ -153,10 +163,15 @@ private void createGrammarSection(Composite parent) { Group group = new Group(parent, SWT.NONE); group.setText(Messages.AssociateGrammarDialog_grammar_section); group.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); - group.setLayout(new GridLayout(3, false)); // radio | text | browse + group.setLayout(new GridLayout(3, false)); // col: radio | text | browse + + createLocalRow(group); + createRemoteRow(group); + createCatalogRow(group); + } - // Local row - localRadio = new Button(group, SWT.RADIO); + private void createLocalRow(Composite parent) { + localRadio = new Button(parent, SWT.RADIO); localRadio.setText(Messages.AssociateGrammarDialog_type_local); localRadio.addSelectionListener(new SelectionAdapter() { @Override @@ -168,31 +183,33 @@ public void widgetSelected(SelectionEvent e) { } }); - localGrammarURIText = new Text(group, SWT.BORDER); + localGrammarURIText = new Text(parent, SWT.BORDER); + localGrammarURIText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); localGrammarURIText.addModifyListener(e -> { updateBindingTypeRadios(getFileExtension(localGrammarURIText.getText())); validate(); }); - localGrammarURIText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); - browseButton = new Button(group, SWT.NONE); - browseButton.setText(Messages.Browse_button); - browseButton.addSelectionListener(new SelectionAdapter() { + browseLocalButton = new Button(parent, SWT.NONE); + browseLocalButton.setText(Messages.Browse_button); + browseLocalButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { GrammarFileSelectionDialog dialog = new GrammarFileSelectionDialog(getParentShell(), - xmlResourceContainer); + xmlResourceContainer, ALL_GRAMMAR_EXTENSIONS); if (dialog.open() == OK) { IFile selectedFile = (IFile) dialog.getFirstResult(); - IPath absolutePath = selectedFile.getFullPath().makeRelativeTo(xmlFilePath.removeLastSegments(1)); - localGrammarURIText.setText(absolutePath.toString()); + IPath relativePath = selectedFile.getFullPath() + .makeRelativeTo(xmlFilePath.removeLastSegments(1)); + localGrammarURIText.setText(relativePath.toString()); localGrammarURIText.getDisplay().asyncExec(localGrammarURIText::setFocus); } } }); + } - // Remote row - remoteRadio = new Button(group, SWT.RADIO); + private void createRemoteRow(Composite parent) { + remoteRadio = new Button(parent, SWT.RADIO); remoteRadio.setText(Messages.AssociateGrammarDialog_type_remote); remoteRadio.addSelectionListener(new SelectionAdapter() { @Override @@ -204,7 +221,7 @@ public void widgetSelected(SelectionEvent e) { } }); - remoteGrammarURIText = new Text(group, SWT.BORDER); + remoteGrammarURIText = new Text(parent, SWT.BORDER); remoteGrammarURIText.setMessage("https://www.example.com/schema.xsd"); //$NON-NLS-1$ remoteGrammarURIText.addFocusListener(new FocusAdapter() { @Override @@ -217,17 +234,62 @@ public void focusGained(FocusEvent e) { validate(); }); GridData remoteGd = new GridData(SWT.FILL, SWT.CENTER, true, false); - remoteGd.horizontalSpan = 2; // span browse column + remoteGd.horizontalSpan = 2; remoteGrammarURIText.setLayoutData(remoteGd); } + private void createCatalogRow(Composite parent) { + catalogRadio = new Button(parent, SWT.RADIO); + catalogRadio.setText(Messages.AssociateGrammarDialog_type_catalog); + catalogRadio.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false)); + catalogRadio.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + if (catalogRadio.getSelection()) { + updateFieldStates(); + validate(); + } + } + }); + + selectedCatalogText = new Text(parent, SWT.BORDER | SWT.READ_ONLY); + selectedCatalogText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); + selectedCatalogText.setMessage(Messages.AssociateGrammarDialog_catalog_no_selection); + + browseCatalogButton = new Button(parent, SWT.NONE); + browseCatalogButton.setText(Messages.Browse_button); + browseCatalogButton.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); + browseCatalogButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + if (catalogEntriesFuture == null) { + catalogEntriesFuture = catalogEntriesSupplier.get(); + } + CatalogEntrySelectionDialog dialog = new CatalogEntrySelectionDialog(getShell(), catalogEntriesFuture); + if (dialog.open() == OK) { + selectedCatalogEntry = dialog.getSelectedEntry(); + if (selectedCatalogEntry != null) { + catalogEntriesFuture.thenAccept(entries -> { + getShell().getDisplay().asyncExec(() -> { + if (!getShell().isDisposed()) { + selectedCatalogText.setText(new CatalogEntryLabelProvider(entries).getText(selectedCatalogEntry)); + validate(); + } + }); + }); + } + } + } + }); + } + private void createBindingTypeSection(Composite parent) { - Group group = new Group(parent, SWT.NONE); - group.setText(Messages.AssociateGrammarDialog_association_section); - group.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); - group.setLayout(new GridLayout(1, false)); + bindingTypeGroup = new Group(parent, SWT.NONE); + bindingTypeGroup.setText(Messages.AssociateGrammarDialog_association_section); + bindingTypeGroup.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); + bindingTypeGroup.setLayout(new GridLayout(1, false)); - standardRadio = new Button(group, SWT.RADIO); + standardRadio = new Button(bindingTypeGroup, SWT.RADIO); standardRadio.setText(BindingType.standard.getLabel()); standardRadio.setSelection(true); standardRadio.addSelectionListener(new SelectionAdapter() { @@ -237,7 +299,7 @@ public void widgetSelected(SelectionEvent e) { } }); - xmlModelRadio = new Button(group, SWT.RADIO); + xmlModelRadio = new Button(bindingTypeGroup, SWT.RADIO); xmlModelRadio.setText(BindingType.xmlmodel.getLabel()); xmlModelRadio.addSelectionListener(new SelectionAdapter() { @Override @@ -248,17 +310,68 @@ public void widgetSelected(SelectionEvent e) { } private void updateFieldStates() { - boolean isLocal = localRadio.getSelection(); + GrammarLocationType type = getSelectedGrammarLocationType(); + boolean isLocal = type == GrammarLocationType.local; + boolean isRemote = type == GrammarLocationType.remote; + boolean isCatalog = type == GrammarLocationType.catalog; + localGrammarURIText.setEnabled(isLocal); - browseButton.setEnabled(isLocal); - remoteGrammarURIText.setEnabled(!isLocal); - Text activeText = isLocal ? localGrammarURIText : remoteGrammarURIText; - updateBindingTypeRadios(getFileExtension(activeText.getText())); - activeText.getDisplay().asyncExec(activeText::setFocus); + browseLocalButton.setEnabled(isLocal); + remoteGrammarURIText.setEnabled(isRemote); + selectedCatalogText.setEnabled(isCatalog); + browseCatalogButton.setEnabled(isCatalog); + + // Hide binding type section in catalog mode (binding is implicit in entry type) + setGridVisible(bindingTypeGroup, !isCatalog); + bindingTypeGroup.getParent().layout(true, true); + + if (!isCatalog) { + Text activeText = isLocal ? localGrammarURIText : remoteGrammarURIText; + updateBindingTypeRadios(getFileExtension(activeText.getText())); + activeText.getDisplay().asyncExec(activeText::setFocus); + } else { + browseCatalogButton.getDisplay().asyncExec(browseCatalogButton::setFocus); + } + } + + /** Toggles visibility and excludes the control from grid layout when hidden. */ + private static void setGridVisible(Control control, boolean visible) { + if (control.getLayoutData() instanceof GridData gd) { + gd.exclude = !visible; + } + control.setVisible(visible); } private GrammarLocationType getSelectedGrammarLocationType() { - return remoteRadio.getSelection() ? GrammarLocationType.remote : GrammarLocationType.local; + if (catalogRadio != null && catalogRadio.getSelection()) { + return GrammarLocationType.catalog; + } + return remoteRadio != null && remoteRadio.getSelection() + ? GrammarLocationType.remote + : GrammarLocationType.local; + } + + /** + * Returns true if the user chose to bind via a catalog entry. + * Safe to call after the dialog is closed. + */ + public boolean isCatalogMode() { + return catalogMode; + } + + /** Returns the selected catalog entry, or null if not in catalog mode. */ + public BindableCatalogEntry getSelectedCatalogEntry() { + return selectedCatalogEntry; + } + + /** Returns the grammar URI (local path or remote URL), or null in catalog mode. */ + public String getGrammarURI() { + return grammarURI; + } + + /** Returns the binding type, or null in catalog mode. */ + public BindingType getBindingType() { + return bindingType; } @Override @@ -266,11 +379,17 @@ protected boolean isResizable() { return true; } + /** Saves all output fields while widgets are still alive (before super.okPressed disposes them). */ private void saveInput() { + this.catalogMode = getSelectedGrammarLocationType() == GrammarLocationType.catalog; + if (catalogMode) { + // selectedCatalogEntry is already set when the user picked from the browse dialog + return; + } if (getSelectedGrammarLocationType() == GrammarLocationType.local) { IFile grammarFile = findLocalGrammarFile(localGrammarURIText.getText()); - if (grammarFile != null && grammarFile.exists() && grammarFile.getLocation() != null) { - grammarURI = LSPEclipseUtils.toUri(grammarFile.getLocation()).toASCIIString(); + if (grammarFile != null && grammarFile.exists() && grammarFile.getLocationURI() != null) { + grammarURI = grammarFile.getLocationURI().toString(); } else { grammarURI = localGrammarURIText.getText(); } @@ -286,26 +405,24 @@ private void validate() { if (okButton != null) { okButton.setEnabled(status.getSeverity() != IStatus.ERROR); } - switch (status.getSeverity()) { - case IStatus.ERROR: + if (status.getSeverity() == IStatus.ERROR) { setErrorMessage(status.getMessage()); - break; - default: + } else { setErrorMessage(null); if (status.isOK()) { setMessage(Messages.bind(Messages.AssociateGrammarDialog_description, xmlFilePath.lastSegment())); } else { - setMessage(status.getMessage(), getMessageType(status.getSeverity())); + setMessage(status.getMessage(), toMessageType(status.getSeverity())); } - break; } } private IStatus performValidation() { - if (getSelectedGrammarLocationType() == GrammarLocationType.local) { - return validateLocal(); - } - return validateRemote(); + return switch (getSelectedGrammarLocationType()) { + case local -> validateLocal(); + case remote -> validateRemote(); + case catalog -> validateCatalog(); + }; } private IStatus validateLocal() { @@ -318,69 +435,17 @@ private IStatus validateLocal() { return Status.warning( Messages.bind(Messages.AssociateGrammarDialog_validation_grammar_file_notExists, uri)); } - if (isRelaxNGGrammarFile(file.getFileExtension())) { + if (RELAXNG_EXTENSIONS.contains(file.getFileExtension())) { return Status.OK_STATUS; } - if (!isStandardGramarFile(file.getFileExtension())) { + if (!W3C_EXTENSIONS.contains(file.getFileExtension())) { + String allowed = ALL_GRAMMAR_EXTENSIONS.stream().collect(Collectors.joining(", ")); //$NON-NLS-1$ return Status.warning(Messages.bind( - Messages.AssociateGrammarDialog_validation_grammar_file_invalid_fileExtension, - uri, ALL_GRAMMAR_FILE_EXTENSION.stream().collect(Collectors.joining(", ")))); + Messages.AssociateGrammarDialog_validation_grammar_file_invalid_fileExtension, uri, allowed)); } return Status.OK_STATUS; } - /** - * Resolves a workspace-relative or project-relative grammar path against the - * XML file's parent folder. Handles {@code ../} segments via - * {@link java.nio.file.Paths#normalize()}. - */ - private IFile findLocalGrammarFile(String relativeUri) { - IFile xmlFile = ResourcesPlugin.getWorkspace().getRoot().getFile(xmlFilePath); - if (xmlFile == null || !xmlFile.exists() || xmlFile.getLocation() == null) { - return xmlResourceContainer.getFile(new Path(relativeUri)); - } - java.nio.file.Path grammarFsPath = xmlFile.getLocation().toFile().getParentFile().toPath() - .resolve(relativeUri).normalize(); - IFile[] files = ResourcesPlugin.getWorkspace().getRoot() - .findFilesForLocationURI(grammarFsPath.toUri()); - return files.length > 0 ? files[0] : null; - } - - /** - * Update binding type radios based on the detected grammar file extension. - * For RelaxNG files, Standard is disabled and deselected; xml-model is selected. - */ - private void updateBindingTypeRadios(String fileExtension) { - if (standardRadio == null) { - return; - } - if (isRelaxNGGrammarFile(fileExtension)) { - standardRadio.setEnabled(false); - standardRadio.setSelection(false); - xmlModelRadio.setSelection(true); - } else { - standardRadio.setEnabled(true); - if (!standardRadio.getSelection() && !xmlModelRadio.getSelection()) { - standardRadio.setSelection(true); - } - } - } - - /** - * Returns the file extension from a path or URL string, or null if none. - */ - private static String getFileExtension(String pathOrUrl) { - if (pathOrUrl == null || pathOrUrl.isBlank()) { - return null; - } - int dot = pathOrUrl.lastIndexOf('.'); - int slash = Math.max(pathOrUrl.lastIndexOf('/'), pathOrUrl.lastIndexOf('\\')); - if (dot > slash && dot < pathOrUrl.length() - 1) { - return pathOrUrl.substring(dot + 1); - } - return null; - } - private IStatus validateRemote() { String url = remoteGrammarURIText.getText(); if (url.isBlank()) { @@ -403,43 +468,11 @@ private IStatus validateRemote() { return Status.OK_STATUS; } - private static boolean isDownloadExternalResourcesEnabled() { - return Activator.getDefault().getPreferenceStore().getBoolean( - XMLPreferenceServerConstants.XML_PREFERENCES_DOWNLOAD_EXTERNAL_RESOURCES.preferenceId); - } - - private static int getMessageType(int severity) { - switch (severity) { - case IStatus.INFO: - return IMessageProvider.INFORMATION; - case IStatus.WARNING: - return IMessageProvider.WARNING; - case IStatus.ERROR: - return IMessageProvider.ERROR; + private IStatus validateCatalog() { + if (selectedCatalogEntry == null) { + return Status.error(Messages.AssociateGrammarDialog_validation_catalog_entry_required); } - return IMessageProvider.NONE; - } - - private static boolean isStandardGramarFile(String fileExtension) { - return W3C_GRAMMAR_FILE_EXTENSION.contains(fileExtension); - } - - private static boolean isRelaxNGGrammarFile(String fileExtension) { - return RELAXNG_GRAMMAR_FILE_EXTENSION.contains(fileExtension); - } - - /** - * Returns the grammar URI to associate (workspace-relative path or remote URL). - */ - public String getGrammarURI() { - return grammarURI; - } - - /** - * Returns the binding type to use for association. - */ - public BindingType getBindingType() { - return bindingType; + return Status.OK_STATUS; } @Override @@ -448,8 +481,7 @@ protected void okPressed() { && !isDownloadExternalResourcesEnabled()) { String dontAsk = Activator.getDefault().getPreferenceStore().getString(PREF_ENABLE_DOWNLOAD_PROMPT); if (MessageDialogWithToggle.ALWAYS.equals(dontAsk)) { - Activator.getDefault().getPreferenceStore().setValue( - XMLPreferenceServerConstants.XML_PREFERENCES_DOWNLOAD_EXTERNAL_RESOURCES.preferenceId, true); + enableDownloadExternalResources(); } else if (!MessageDialogWithToggle.NEVER.equals(dontAsk)) { MessageDialogWithToggle dialog = MessageDialogWithToggle.openYesNoCancelQuestion( getShell(), @@ -464,37 +496,81 @@ protected void okPressed() { return; } if (code == IDialogConstants.YES_ID) { - Activator.getDefault().getPreferenceStore().setValue( - XMLPreferenceServerConstants.XML_PREFERENCES_DOWNLOAD_EXTERNAL_RESOURCES.preferenceId, - true); + enableDownloadExternalResources(); } } // NEVER → proceed without enabling download } - saveInput(); + saveInput(); // must be called before super.okPressed() disposes widgets super.okPressed(); } + // ---- Helpers ------------------------------------------------------------- + /** - * File selection dialog restricted to grammar extensions (xsd, dtd, rng, rnc). - * Subclasses {@link FilteredResourcesSelectionDialog} to call the protected - * {@code addListFilter} from within the class hierarchy. + * Resolves a workspace-relative grammar path against the XML file's parent + * folder. Handles {@code ../} segments via {@link java.nio.file.Path#normalize()}. */ - private static final class GrammarFileSelectionDialog extends FilteredResourcesSelectionDialog { - - GrammarFileSelectionDialog(Shell shell, IContainer container) { - super(shell, false, container, IResource.FILE); - setInitialPattern("*."); //$NON-NLS-1$ - addListFilter(new ViewerFilter() { - @Override - public boolean select(Viewer viewer, Object parentElement, Object element) { - if (element instanceof IFile file) { - return ALL_GRAMMAR_FILE_EXTENSION.contains(file.getFileExtension()); - } - return true; - } - }); + private IFile findLocalGrammarFile(String relativeUri) { + IFile xmlFile = ResourcesPlugin.getWorkspace().getRoot().getFile(xmlFilePath); + if (xmlFile == null || !xmlFile.exists() || xmlFile.getLocation() == null) { + return xmlResourceContainer.getFile(new Path(relativeUri)); + } + java.nio.file.Path grammarFsPath = xmlFile.getLocation().toFile().getParentFile().toPath() + .resolve(relativeUri).normalize(); + IFile[] files = ResourcesPlugin.getWorkspace().getRoot() + .findFilesForLocationURI(grammarFsPath.toUri()); + return files.length > 0 ? files[0] : null; + } + + /** + * Updates binding type radio buttons based on the detected grammar extension. + * RelaxNG files force xml-model; standard is disabled for them. + */ + private void updateBindingTypeRadios(String fileExtension) { + if (standardRadio == null) { + return; + } + if (RELAXNG_EXTENSIONS.contains(fileExtension)) { + standardRadio.setEnabled(false); + standardRadio.setSelection(false); + xmlModelRadio.setSelection(true); + } else { + standardRadio.setEnabled(true); + if (!standardRadio.getSelection() && !xmlModelRadio.getSelection()) { + standardRadio.setSelection(true); + } } } + private static String getFileExtension(String pathOrUrl) { + if (pathOrUrl == null || pathOrUrl.isBlank()) { + return null; + } + int dot = pathOrUrl.lastIndexOf('.'); + int slash = Math.max(pathOrUrl.lastIndexOf('/'), pathOrUrl.lastIndexOf('\\')); + if (dot > slash && dot < pathOrUrl.length() - 1) { + return pathOrUrl.substring(dot + 1); + } + return null; + } + + private static boolean isDownloadExternalResourcesEnabled() { + return Activator.getDefault().getPreferenceStore().getBoolean( + XMLPreferenceServerConstants.XML_PREFERENCES_DOWNLOAD_EXTERNAL_RESOURCES.preferenceId); + } + + private static void enableDownloadExternalResources() { + Activator.getDefault().getPreferenceStore().setValue( + XMLPreferenceServerConstants.XML_PREFERENCES_DOWNLOAD_EXTERNAL_RESOURCES.preferenceId, true); + } + + private static int toMessageType(int severity) { + return switch (severity) { + case IStatus.INFO -> IMessageProvider.INFORMATION; + case IStatus.WARNING -> IMessageProvider.WARNING; + case IStatus.ERROR -> IMessageProvider.ERROR; + default -> IMessageProvider.NONE; + }; + } } diff --git a/org.eclipse.wildwebdeveloper.xml/src/org/eclipse/wildwebdeveloper/xml/internal/commands/associate/AssociateGrammarHandler.java b/org.eclipse.wildwebdeveloper.xml/src/org/eclipse/wildwebdeveloper/xml/internal/commands/associate/AssociateGrammarHandler.java new file mode 100644 index 0000000000..cdac36c176 --- /dev/null +++ b/org.eclipse.wildwebdeveloper.xml/src/org/eclipse/wildwebdeveloper/xml/internal/commands/associate/AssociateGrammarHandler.java @@ -0,0 +1,146 @@ +/******************************************************************************* + * Copyright (c) 2022 2023 Red Hat Inc. and others. + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Angelo ZERR (Red Hat Inc.) - initial implementation + *******************************************************************************/ +package org.eclipse.wildwebdeveloper.xml.internal.commands.associate; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.CompletableFuture; + +import org.eclipse.core.commands.ExecutionEvent; +import org.eclipse.core.commands.ExecutionException; +import org.eclipse.core.runtime.ILog; +import org.eclipse.core.runtime.IPath; +import org.eclipse.jface.dialogs.IDialogConstants; +import org.eclipse.lsp4e.LSPEclipseUtils; +import org.eclipse.lsp4e.LanguageServers; +import org.eclipse.lsp4e.command.LSPCommandHandler; +import org.eclipse.lsp4j.Command; +import org.eclipse.lsp4j.ExecuteCommandOptions; +import org.eclipse.lsp4j.ExecuteCommandParams; +import org.eclipse.lsp4j.TextDocumentEdit; +import org.eclipse.lsp4j.TextDocumentIdentifier; +import org.eclipse.lsp4j.WorkspaceEdit; +import org.eclipse.lsp4j.jsonrpc.messages.Either; +import org.eclipse.ui.handlers.HandlerUtil; + +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; + +/** + * LSP command handler called by "Bind to grammar/schema..." code lens from an + * XML file which is not associated with a grammar. This handler: + * + *
      + *
    • Opens a dialog immediately (no blocking server call).
    • + *
    • The dialog fetches bindable catalog entries asynchronously when it opens, + * using the supplier provided by this handler. Each dialog open triggers a fresh + * fetch so catalog changes are always reflected.
    • + *
    • Inserts the proper syntax into the XML document by calling + * {@code xml.associate.grammar.insert}.
    • + *
    + * + * @author Angelo ZERR + */ +public class AssociateGrammarHandler extends LSPCommandHandler { + + private static final String ASSOCIATE_GRAMMAR_INSERT = "xml.associate.grammar.insert"; //$NON-NLS-1$ + private static final String LIST_BINDABLE_CATALOG_ENTRIES = "xml.catalog.entries.bindable"; //$NON-NLS-1$ + + @Override + public Object execute(ExecutionEvent event, Command command, IPath path) throws ExecutionException { + String uri = (String) command.getArguments().get(0); + TextDocumentIdentifier identifier = new TextDocumentIdentifier(uri); + + // Open the dialog immediately; it will call the supplier to start the fetch. + // Each dialog instance fetches fresh entries so stale cache is never an issue. + AssociateGrammarDialog dialog = new AssociateGrammarDialog( + HandlerUtil.getActiveShell(event), path, this::catalogEntriesFuture); + if (dialog.open() != IDialogConstants.OK_ID) { + return null; + } + + CompletableFuture future; + if (dialog.isCatalogMode()) { + BindableCatalogEntry entry = dialog.getSelectedCatalogEntry(); + future = executeServerCommand(ASSOCIATE_GRAMMAR_INSERT, + identifier, + entry.entryType, + "catalog", //$NON-NLS-1$ + entry.identifier, + entry.targetURI, + entry.uriValue); + } else { + future = executeServerCommand(ASSOCIATE_GRAMMAR_INSERT, + identifier, dialog.getGrammarURI(), dialog.getBindingType().getCode()); + } + future.thenAccept(AssociateGrammarHandler::applyEdit) + .exceptionally(e -> { + ILog.get().error("Error while inserting grammar association", e); //$NON-NLS-1$ + return null; + }); + return null; + } + + /** Fetches bindable catalog entries from the server. No caching here — each dialog open gets fresh data. */ + private CompletableFuture> catalogEntriesFuture() { + return executeServerCommand(LIST_BINDABLE_CATALOG_ENTRIES) + .thenApply(result -> { + if (result == null) { + return Collections.emptyList(); + } + Gson gson = new Gson(); + JsonArray array = gson.toJsonTree(result).getAsJsonArray(); + List entries = new ArrayList<>(array.size()); + for (int i = 0; i < array.size(); i++) { + entries.add(gson.fromJson(array.get(i), BindableCatalogEntry.class)); + } + return entries; + }); + } + + private static void applyEdit(Object result) { + Gson gson = new Gson(); + JsonObject jsonObject = gson.toJsonTree(result).getAsJsonObject(); + TextDocumentEdit edit = gson.fromJson(jsonObject, TextDocumentEdit.class); + WorkspaceEdit workEdits = new WorkspaceEdit(); + workEdits.setDocumentChanges(new ArrayList<>()); + workEdits.getDocumentChanges().add(Either.forLeft(edit)); + LSPEclipseUtils.applyWorkspaceEdit(workEdits, ASSOCIATE_GRAMMAR_INSERT); + } + + private static CompletableFuture executeServerCommand(String commandId, Object... params) { + return LanguageServers.forProject(null) + .withCapability(serverCapabilities -> { + ExecuteCommandOptions executeCommandProvider = serverCapabilities.getExecuteCommandProvider(); + return Either.forLeft(executeCommandProvider != null + ? executeCommandProvider.getCommands().contains(commandId) + : false); + }) + .excludeInactive() + .collectAll((w, ls) -> CompletableFuture.completedFuture(ls)) + .thenCompose(commandHandlers -> { + if (commandHandlers.size() == 1) { + return commandHandlers.get(0).getWorkspaceService() + .executeCommand(new ExecuteCommandParams(commandId, Arrays.asList(params))); + } + if (commandHandlers.size() > 1) { + return CompletableFuture.failedFuture(new IllegalStateException( + "Multiple language servers registered for command '" + commandId + "'")); //$NON-NLS-1$ //$NON-NLS-2$ + } + return CompletableFuture.failedFuture(new UnsupportedOperationException( + "No language server registered for command '" + commandId + "'")); //$NON-NLS-1$ //$NON-NLS-2$ + }); + } +} diff --git a/org.eclipse.wildwebdeveloper.xml/src/org/eclipse/wildwebdeveloper/xml/internal/commands/associate/BindableCatalogEntry.java b/org.eclipse.wildwebdeveloper.xml/src/org/eclipse/wildwebdeveloper/xml/internal/commands/associate/BindableCatalogEntry.java new file mode 100644 index 0000000000..a7eb2834a9 --- /dev/null +++ b/org.eclipse.wildwebdeveloper.xml/src/org/eclipse/wildwebdeveloper/xml/internal/commands/associate/BindableCatalogEntry.java @@ -0,0 +1,37 @@ +/******************************************************************************* + * Copyright (c) 2026 Red Hat Inc. and others. + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Angelo ZERR (Red Hat Inc.) - initial implementation + *******************************************************************************/ +package org.eclipse.wildwebdeveloper.xml.internal.commands.associate; + +/** + * A catalog entry that can be bound to an XML document, as returned by the + * {@code xml.catalog.entries.bindable} LemMinX command. + */ +public class BindableCatalogEntry { + + /** URI of the catalog file that declares this entry. */ + public String catalogURI; + + /** Entry type: {@code "public"}, {@code "system"}, or {@code "uri"}. */ + public String entryType; + + /** The identifier: publicId, systemId, or uri-name attribute value. */ + public String identifier; + + /** The resolved grammar URI (file:/// or http(s)://). */ + public String targetURI; + + /** The raw {@code uri} attribute value from the catalog entry. */ + public String uriValue; + + /** Grammar type: {@code "xsd"}, {@code "dtd"}, {@code "rng"}, {@code "rnc"}. */ + public String grammarType; +} diff --git a/org.eclipse.wildwebdeveloper.xml/src/org/eclipse/wildwebdeveloper/xml/internal/commands/associate/CatalogEntryLabelProvider.java b/org.eclipse.wildwebdeveloper.xml/src/org/eclipse/wildwebdeveloper/xml/internal/commands/associate/CatalogEntryLabelProvider.java new file mode 100644 index 0000000000..2788924d5e --- /dev/null +++ b/org.eclipse.wildwebdeveloper.xml/src/org/eclipse/wildwebdeveloper/xml/internal/commands/associate/CatalogEntryLabelProvider.java @@ -0,0 +1,129 @@ +/******************************************************************************* + * Copyright (c) 2026 Red Hat Inc. and others. + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Angelo ZERR (Red Hat Inc.) - initial implementation + *******************************************************************************/ +package org.eclipse.wildwebdeveloper.xml.internal.commands.associate; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.eclipse.jface.viewers.DelegatingStyledCellLabelProvider.IStyledLabelProvider; +import org.eclipse.jface.viewers.LabelProvider; +import org.eclipse.jface.viewers.StyledString; + +/** + * Label provider for {@link BindableCatalogEntry} items with styled text. + * Displays {@code "TYPE identifier [GRAMMARTYPE] — catalog.xml"}. + * Catalog filename is shown in a lighter gray color. + * When several catalog files share the same filename, the minimum number of + * parent directory segments is prepended to disambiguate: + * {@code "— project/catalog.xml"} or {@code "— org/project/catalog.xml"}. + */ +public class CatalogEntryLabelProvider extends LabelProvider implements IStyledLabelProvider { + + /** Maps each catalog URI to its shortest disambiguating path label. */ + private final Map catalogLabels; + + public CatalogEntryLabelProvider(List entries) { + catalogLabels = buildCatalogLabels(entries); + } + + @Override + public StyledString getStyledText(Object element) { + if (element instanceof BindableCatalogEntry entry) { + String type = entry.entryType != null ? entry.entryType.toUpperCase() : "?"; //$NON-NLS-1$ + String catalog = catalogLabels.getOrDefault(entry.catalogURI, ""); //$NON-NLS-1$ + + StyledString result = new StyledString(); + result.append(type + " " + entry.identifier); //$NON-NLS-1$ + if (!catalog.isEmpty()) { + result.append(" — " + catalog, StyledString.QUALIFIER_STYLER); //$NON-NLS-1$ + } + return result; + } + return new StyledString(); + } + + @Override + public String getText(Object element) { + return getStyledText(element).getString(); + } + + /** + * Builds the shortest path label for every catalog URI in the entry list. + * URIs that share a filename are disambiguated by adding parent segments + * one at a time until all labels in the conflicting group are unique. + */ + private static Map buildCatalogLabels(List entries) { + // Collect distinct catalog URIs per filename + Map> filenameToUris = new HashMap<>(); + for (BindableCatalogEntry entry : entries) { + String filename = CatalogEntrySelectionDialog.catalogFileName(entry.catalogURI); + if (!filename.isEmpty()) { + filenameToUris.computeIfAbsent(filename, k -> new HashSet<>()).add(entry.catalogURI); + } + } + + Map result = new HashMap<>(); + for (Map.Entry> e : filenameToUris.entrySet()) { + Set uris = e.getValue(); + if (uris.size() == 1) { + // Unique filename: just the filename + String uri = uris.iterator().next(); + result.put(uri, e.getKey()); + } else { + // Ambiguous: find the minimum depth that makes all labels distinct + result.putAll(disambiguate(uris)); + } + } + return result; + } + + /** + * Returns a map from URI to the shortest path suffix that uniquely identifies + * each URI within the given set. Increases depth (number of trailing path + * segments) until all labels are distinct or depth exceeds 20. + */ + static Map disambiguate(Set uris) { + Map labels = new HashMap<>(); + for (int depth = 1; depth <= 20; depth++) { + Map> labelToUris = new HashMap<>(); + for (String uri : uris) { + String label = lastSegments(uri, depth); + labelToUris.computeIfAbsent(label, k -> new ArrayList<>()).add(uri); + } + // Assign labels for URIs that are now unique at this depth + for (Map.Entry> le : labelToUris.entrySet()) { + if (le.getValue().size() == 1) { + labels.putIfAbsent(le.getValue().get(0), le.getKey()); + } + } + if (labels.size() == uris.size()) { + break; + } + } + return labels; + } + + /** Returns the last {@code n} slash-separated segments of {@code uri}. */ + static String lastSegments(String uri, int n) { + if (uri == null || uri.isEmpty()) { + return ""; //$NON-NLS-1$ + } + String[] parts = uri.split("[/\\\\]"); //$NON-NLS-1$ + int start = Math.max(0, parts.length - n); + return String.join("/", Arrays.copyOfRange(parts, start, parts.length)); //$NON-NLS-1$ + } +} diff --git a/org.eclipse.wildwebdeveloper.xml/src/org/eclipse/wildwebdeveloper/xml/internal/commands/associate/CatalogEntrySelectionDialog.java b/org.eclipse.wildwebdeveloper.xml/src/org/eclipse/wildwebdeveloper/xml/internal/commands/associate/CatalogEntrySelectionDialog.java new file mode 100644 index 0000000000..90b7aa48cf --- /dev/null +++ b/org.eclipse.wildwebdeveloper.xml/src/org/eclipse/wildwebdeveloper/xml/internal/commands/associate/CatalogEntrySelectionDialog.java @@ -0,0 +1,369 @@ +/******************************************************************************* + * Copyright (c) 2026 Red Hat Inc. and others. + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Angelo ZERR (Red Hat Inc.) - initial implementation + *******************************************************************************/ +package org.eclipse.wildwebdeveloper.xml.internal.commands.associate; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.function.Supplier; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; +import org.eclipse.jface.dialogs.IDialogSettings; +import org.eclipse.jface.resource.JFaceResources; +import org.eclipse.jface.viewers.DelegatingStyledCellLabelProvider.IStyledLabelProvider; +import org.eclipse.jface.viewers.ILabelProvider; +import org.eclipse.jface.viewers.LabelProvider; +import org.eclipse.jface.viewers.StyledString; +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.StyleRange; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.TextStyle; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.ProgressBar; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.dialogs.FilteredItemsSelectionDialog; +import org.eclipse.ui.dialogs.IStyledStringHighlighter; +import org.eclipse.ui.statushandlers.StatusManager; +import org.eclipse.wildwebdeveloper.xml.internal.Activator; +import org.eclipse.wildwebdeveloper.xml.internal.ui.Messages; + +/** + * Quick-open style dialog for selecting a bindable catalog entry. + * If loading the entries fails, the dialog is closed and the error is shown with + * the standard workbench error dialog (with expandable stack trace) and logged. + *

    + */ +public class CatalogEntrySelectionDialog extends FilteredItemsSelectionDialog { + + private static final String DIALOG_SETTINGS_ID = "CatalogEntrySelectionDialog"; //$NON-NLS-1$ + + private final CompletableFuture> entriesFuture; + private List entries = Collections.emptyList(); + private ProgressBar progressBar; + private volatile ItemsFilter currentFilter; + + public CatalogEntrySelectionDialog(Shell shell, CompletableFuture> entriesFuture) { + super(shell); + this.entriesFuture = entriesFuture; + setTitle(Messages.CatalogEntrySelectionDialog_title); + setListLabelProvider(createListLabelProvider()); + setDetailsLabelProvider(new DetailLabelProvider()); + setInitialPattern("**", FULL_SELECTION); //$NON-NLS-1$ + } + + @Override + public int open() { + // Future already failed: don't even open the dialog, just report the error. + if (entriesFuture.isCompletedExceptionally()) { + try { + entriesFuture.get(); + } catch (Exception ex) { + reportError(ex); + } + return CANCEL; + } + return super.open(); + } + + @Override + protected Control createExtendedContentArea(Composite parent) { + boolean done = entriesFuture.isDone(); + progressBar = new ProgressBar(parent, SWT.INDETERMINATE); + GridData data = new GridData(SWT.FILL, SWT.CENTER, true, false); + data.exclude = done; + progressBar.setLayoutData(data); + progressBar.setVisible(!done); + return progressBar; + } + + @Override + public void create() { + super.create(); + // Handle completion (waiting or already done) + if (!entriesFuture.isDone()) { + entriesFuture.whenComplete((loadedEntries, ex) -> { + getShell().getDisplay().asyncExec(() -> handleCompletion(loadedEntries, ex)); + }); + } else { + try { + handleCompletion(entriesFuture.get(), null); + } catch (Exception ex) { + handleCompletion(null, ex); + } + } + } + + /** Handles future completion: displays entries, or closes the dialog and reports the error. */ + private void handleCompletion(List loadedEntries, Throwable ex) { + Shell shell = getShell(); + if (shell == null || shell.isDisposed()) { + return; + } + if (ex != null) { + Display display = shell.getDisplay(); + close(); // closes the selection dialog (Cancel) + display.asyncExec(() -> reportError(ex)); + return; + } + progressBar.setVisible(false); + ((GridData) progressBar.getLayoutData()).exclude = true; + progressBar.getParent().layout(true, true); + entries = loadedEntries; + setListLabelProvider(createListLabelProvider()); + scheduleRefresh(); + } + + /** Shows the standard workbench error dialog (stack trace in "Details") and logs the error. */ + private static void reportError(Throwable ex) { + IStatus status = Status.error(Messages.CatalogEntrySelectionDialog_loadError, unwrap(ex)); + StatusManager.getManager().handle(status, StatusManager.SHOW | StatusManager.LOG); + } + + /** Unwraps CompletionException / ExecutionException to get the real error. */ + private static Throwable unwrap(Throwable ex) { + while ((ex instanceof CompletionException || ex instanceof ExecutionException) && ex.getCause() != null) { + ex = ex.getCause(); + } + return ex; + } + + @Override + protected IDialogSettings getDialogSettings() { + IDialogSettings settings = Activator.getDefault().getDialogSettings(); + IDialogSettings section = settings.getSection(DIALOG_SETTINGS_ID); + if (section == null) { + section = settings.addNewSection(DIALOG_SETTINGS_ID); + } + return section; + } + + @Override + protected IStatus validateItem(Object item) { + return Status.OK_STATUS; + } + + @Override + protected ItemsFilter createFilter() { + ItemsFilter filter = new ItemsFilter() { + @Override + public boolean matchItem(Object item) { + if (item instanceof BindableCatalogEntry entry) { + return matchesAll() + || matches(entry.identifier) + || matches(catalogFileName(entry.catalogURI)); + } + return false; + } + + /** The initial pattern ("**") or an empty pattern must list everything. */ + private boolean matchesAll() { + String pattern = getPattern(); + return pattern == null || pattern.isBlank() || pattern.chars().allMatch(c -> c == '*'); + } + + @Override + public boolean isConsistentItem(Object item) { + return item instanceof BindableCatalogEntry; + } + }; + currentFilter = filter; + return filter; + } + + @Override + @SuppressWarnings("rawtypes") + protected Comparator getItemsComparator() { + return Comparator.comparing((BindableCatalogEntry e) -> e.identifier, String.CASE_INSENSITIVE_ORDER); + } + + @Override + protected void fillContentProvider(AbstractContentProvider contentProvider, ItemsFilter itemsFilter, + IProgressMonitor progressMonitor) throws CoreException { + // This runs in a background job: wait for the entries instead of reading + // a field that may still be empty when the first refresh happens. + List loaded = awaitEntries(progressMonitor); + progressMonitor.beginTask(null, loaded.size()); + for (BindableCatalogEntry entry : loaded) { + contentProvider.add(entry, itemsFilter); + progressMonitor.worked(1); + } + progressMonitor.done(); + } + + /** + * Waits for the entries, polling so that the job stays cancellable. On failure + * or cancellation returns an empty list (the error itself is reported by + * {@link #handleCompletion}). + */ + private List awaitEntries(IProgressMonitor monitor) { + while (!monitor.isCanceled()) { + try { + return entriesFuture.get(100, TimeUnit.MILLISECONDS); + } catch (TimeoutException e) { + // not ready yet, keep waiting + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + break; + } catch (Exception e) { // ExecutionException, CancellationException + break; + } + } + return Collections.emptyList(); + } + + @Override + public String getElementName(Object item) { + if (item instanceof BindableCatalogEntry entry) { + return entry.identifier; + } + return ""; //$NON-NLS-1$ + } + + /** Returns the entry the user selected, or {@code null} if cancelled. */ + public BindableCatalogEntry getSelectedEntry() { + Object[] result = getResult(); + if (result != null && result.length > 0 && result[0] instanceof BindableCatalogEntry entry) { + return entry; + } + return null; + } + + static String catalogFileName(String uri) { + if (uri == null || uri.isEmpty()) { + return ""; //$NON-NLS-1$ + } + int slash = Math.max(uri.lastIndexOf('/'), uri.lastIndexOf('\\')); + return slash >= 0 ? uri.substring(slash + 1) : uri; + } + + /** Wraps the catalog label provider so that the text matching the pattern is bold. */ + private ILabelProvider createListLabelProvider() { + return new MatchHighlightLabelProvider(new CatalogEntryLabelProvider(entries), () -> { + ItemsFilter filter = currentFilter; + return filter != null ? filter.getPattern() : null; + }, this::getStyledStringHighlighter); + } + + /** Decorates a label provider: the parts of the label matching the filter pattern are shown in bold. */ + private static final class MatchHighlightLabelProvider extends LabelProvider implements IStyledLabelProvider { + + private final ILabelProvider delegate; + private final Supplier patternSupplier; + private final Supplier highlighterSupplier; + private final StyledString.Styler boldStyler = new StyledString.Styler() { + @Override + public void applyStyles(TextStyle textStyle) { + textStyle.font = JFaceResources.getFontRegistry().getBold(JFaceResources.DEFAULT_FONT); + } + }; + + MatchHighlightLabelProvider(ILabelProvider delegate, Supplier patternSupplier, + Supplier highlighterSupplier) { + this.delegate = delegate; + this.patternSupplier = patternSupplier; + this.highlighterSupplier = highlighterSupplier; + } + + @Override + public Image getImage(Object element) { + return delegate.getImage(element); + } + + @Override + public String getText(Object element) { + return delegate.getText(element); + } + + @Override + public StyledString getStyledText(Object element) { + StyledString result; + if (delegate instanceof IStyledLabelProvider styled && styled.getStyledText(element) != null) { + result = styled.getStyledText(element); + } else { + String text = delegate.getText(element); + result = new StyledString(text != null ? text : ""); //$NON-NLS-1$ + } + String pattern = patternSupplier.get(); + IStyledStringHighlighter highlighter = highlighterSupplier.get(); + if (highlighter != null && pattern != null) { + // Same highlighter as the Open Resource dialog (handles wildcards, camelCase...) + StyledString highlighted = highlighter.highlight(result.getString(), pattern, boldStyler); + if (highlighted != null) { + for (StyleRange range : highlighted.getStyleRanges()) { + result.setStyle(range.start, range.length, boldStyler); + } + } + } else { + for (int[] region : matchingRegions(result.getString(), pattern)) { + result.setStyle(region[0], region[1], boldStyler); + } + } + return result; + } + + /** + * Returns {offset, length} regions of {@code text} matching the literal parts + * of {@code pattern} (wildcards '*' and '?' and spaces separate the parts). + */ + private static List matchingRegions(String text, String pattern) { + List regions = new ArrayList<>(); + if (text == null || pattern == null) { + return regions; + } + String lowerText = text.toLowerCase(); + int from = 0; + for (String token : pattern.toLowerCase().split("[*?\\s]+")) { //$NON-NLS-1$ + if (token.isEmpty()) { + continue; + } + int index = lowerText.indexOf(token, from); + if (index < 0) { + continue; + } + regions.add(new int[] { index, token.length() }); + from = index + token.length(); + } + return regions; + } + + @Override + public void dispose() { + delegate.dispose(); + super.dispose(); + } + } + + /** Shows the catalog filename and resolved target URI in the details pane. */ + private static final class DetailLabelProvider extends LabelProvider { + @Override + public String getText(Object element) { + if (element instanceof BindableCatalogEntry entry) { + String catalog = catalogFileName(entry.catalogURI); + String target = entry.targetURI != null ? entry.targetURI : ""; //$NON-NLS-1$ + return catalog.isEmpty() ? target : catalog + " — " + target; //$NON-NLS-1$ + } + return ""; //$NON-NLS-1$ + } + } +} \ No newline at end of file diff --git a/org.eclipse.wildwebdeveloper.xml/src/org/eclipse/wildwebdeveloper/xml/internal/commands/associate/GrammarFileSelectionDialog.java b/org.eclipse.wildwebdeveloper.xml/src/org/eclipse/wildwebdeveloper/xml/internal/commands/associate/GrammarFileSelectionDialog.java new file mode 100644 index 0000000000..6d01e4682a --- /dev/null +++ b/org.eclipse.wildwebdeveloper.xml/src/org/eclipse/wildwebdeveloper/xml/internal/commands/associate/GrammarFileSelectionDialog.java @@ -0,0 +1,46 @@ +/******************************************************************************* + * Copyright (c) 2026 Red Hat Inc. and others. + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Angelo ZERR (Red Hat Inc.) - initial implementation + *******************************************************************************/ +package org.eclipse.wildwebdeveloper.xml.internal.commands.associate; + +import java.util.List; + +import org.eclipse.core.resources.IContainer; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IResource; +import org.eclipse.jface.viewers.Viewer; +import org.eclipse.jface.viewers.ViewerFilter; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.dialogs.FilteredResourcesSelectionDialog; + +/** + * Workspace file-picker dialog restricted to grammar extensions + * (xsd, dtd, rng, rnc). + */ +public class GrammarFileSelectionDialog extends FilteredResourcesSelectionDialog { + + private final List grammarExtensions; + + public GrammarFileSelectionDialog(Shell shell, IContainer container, List grammarExtensions) { + super(shell, false, container, IResource.FILE); + this.grammarExtensions = grammarExtensions; + setInitialPattern("*."); //$NON-NLS-1$ + addListFilter(new ViewerFilter() { + @Override + public boolean select(Viewer viewer, Object parentElement, Object element) { + if (element instanceof IFile file) { + return grammarExtensions.contains(file.getFileExtension()); + } + return true; + } + }); + } +} diff --git a/org.eclipse.wildwebdeveloper.xml/src/org/eclipse/wildwebdeveloper/xml/internal/ui/Messages.java b/org.eclipse.wildwebdeveloper.xml/src/org/eclipse/wildwebdeveloper/xml/internal/ui/Messages.java index f557e86cb5..8986733c65 100644 --- a/org.eclipse.wildwebdeveloper.xml/src/org/eclipse/wildwebdeveloper/xml/internal/ui/Messages.java +++ b/org.eclipse.wildwebdeveloper.xml/src/org/eclipse/wildwebdeveloper/xml/internal/ui/Messages.java @@ -81,13 +81,19 @@ public class Messages extends NLS { public static String AssociateGrammarDialog_association_section; public static String AssociateGrammarDialog_type_local; public static String AssociateGrammarDialog_type_remote; + public static String AssociateGrammarDialog_type_catalog; public static String AssociateGrammarDialog_validation_grammar_file_required; public static String AssociateGrammarDialog_validation_grammar_file_notExists; public static String AssociateGrammarDialog_validation_grammar_file_invalid_fileExtension; public static String AssociateGrammarDialog_validation_grammar_url_required; public static String AssociateGrammarDialog_validation_grammar_url_invalid; public static String AssociateGrammarDialog_validation_download_external_disabled; + public static String AssociateGrammarDialog_catalog_no_selection; + public static String AssociateGrammarDialog_validation_no_catalog_entries; + public static String AssociateGrammarDialog_validation_catalog_entry_required; public static String AssociateGrammarDialog_download_prompt_title; + public static String CatalogEntrySelectionDialog_title; + public static String CatalogEntrySelectionDialog_loadError; public static String AssociateGrammarDialog_download_prompt_message; public static String AssociateGrammarDialog_download_prompt_toggle; diff --git a/org.eclipse.wildwebdeveloper.xml/src/org/eclipse/wildwebdeveloper/xml/internal/ui/messages.properties b/org.eclipse.wildwebdeveloper.xml/src/org/eclipse/wildwebdeveloper/xml/internal/ui/messages.properties index 1f35c8eb64..37ea993a9a 100644 --- a/org.eclipse.wildwebdeveloper.xml/src/org/eclipse/wildwebdeveloper/xml/internal/ui/messages.properties +++ b/org.eclipse.wildwebdeveloper.xml/src/org/eclipse/wildwebdeveloper/xml/internal/ui/messages.properties @@ -76,12 +76,18 @@ AssociateGrammarDialog_grammar_section=Schema / Grammar AssociateGrammarDialog_association_section=Association AssociateGrammarDialog_type_local=Local AssociateGrammarDialog_type_remote=Remote +AssociateGrammarDialog_type_catalog=Catalog AssociateGrammarDialog_validation_grammar_file_required=The grammar file is required. AssociateGrammarDialog_validation_grammar_file_notExists=The grammar file ''{0}'' doesn''t exist. AssociateGrammarDialog_validation_grammar_file_invalid_fileExtension=The grammar file ''{0}'' should have one of the following extensions: {1}. AssociateGrammarDialog_validation_grammar_url_required=The grammar URL is required. AssociateGrammarDialog_validation_grammar_url_invalid=The grammar URL ''{0}'' is not a valid URL. AssociateGrammarDialog_validation_download_external_disabled="Download external resources" is disabled. LemMinX will not fetch the remote grammar, so grammar-driven features will be unavailable. +AssociateGrammarDialog_catalog_no_selection=(no catalog entry selected) +AssociateGrammarDialog_validation_no_catalog_entries=No catalog entries are available. Configure XML catalogs in Preferences > XML > Catalogs. +AssociateGrammarDialog_validation_catalog_entry_required=Select a catalog entry to associate with this XML file. +CatalogEntrySelectionDialog_title=Select Catalog Entry +CatalogEntrySelectionDialog_loadError=Failed to load catalog entries: AssociateGrammarDialog_download_prompt_title=Enable download of external resources? AssociateGrammarDialog_download_prompt_message=The preference "Download external resources like referenced DTD, XSD" is currently disabled.\n\nWithout it, LemMinX will not fetch the remote grammar and grammar-driven features (completion, validation, hover, code actions…) will be unavailable.\n\nDo you want to enable it now? AssociateGrammarDialog_download_prompt_toggle=Don''t ask again diff --git a/org.eclipse.wildwebdeveloper.xml/src/org/eclipse/wildwebdeveloper/xml/internal/ui/preferences/XMLCatalogs.java b/org.eclipse.wildwebdeveloper.xml/src/org/eclipse/wildwebdeveloper/xml/internal/ui/preferences/XMLCatalogs.java index b6aa3ce10c..4a69544fde 100644 --- a/org.eclipse.wildwebdeveloper.xml/src/org/eclipse/wildwebdeveloper/xml/internal/ui/preferences/XMLCatalogs.java +++ b/org.eclipse.wildwebdeveloper.xml/src/org/eclipse/wildwebdeveloper/xml/internal/ui/preferences/XMLCatalogs.java @@ -81,6 +81,12 @@ private static File getWTPExtensionCatalog() { if (publicId != null && uri != null) { catalogFile.append("\n"); + // If public entry has webURL, also create a system entry for it + String webURL = element.getAttribute("webURL"); + if (webURL != null && !webURL.isEmpty()) { + catalogFile.append("\n"); + } } break; } diff --git a/org.eclipse.wildwebdeveloper.xml/src/org/eclipse/wildwebdeveloper/xml/internal/ui/preferences/XMLPreferenceInitializer.java b/org.eclipse.wildwebdeveloper.xml/src/org/eclipse/wildwebdeveloper/xml/internal/ui/preferences/XMLPreferenceInitializer.java index 3261e43633..5bfd29a247 100644 --- a/org.eclipse.wildwebdeveloper.xml/src/org/eclipse/wildwebdeveloper/xml/internal/ui/preferences/XMLPreferenceInitializer.java +++ b/org.eclipse.wildwebdeveloper.xml/src/org/eclipse/wildwebdeveloper/xml/internal/ui/preferences/XMLPreferenceInitializer.java @@ -50,7 +50,7 @@ import org.eclipse.jface.dialogs.MessageDialogWithToggle; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.wildwebdeveloper.xml.internal.Activator; -import org.eclipse.wildwebdeveloper.xml.internal.commands.AssociateGrammarDialog; +import org.eclipse.wildwebdeveloper.xml.internal.commands.associate.AssociateGrammarDialog; /** * XML preference initializer.