/******************************************************************************* * Copyright (c) 2007, 2010 Association for Decentralized Information Management * in Industry THTH ry. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * VTT Technical Research Centre of Finland - initial API and implementation *******************************************************************************/ package org.simantics.document.ui.dialogs; import java.util.HashMap; import java.util.Map; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.IInputValidator; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; /** * Base class for validated text input dialogs. * * @author Marko Luukkainen * */ public abstract class TextInputDialog extends Dialog{ // cache for all used validators private Map validators = new HashMap(); protected TextInputDialog(Shell parentShell) { super(parentShell); } protected boolean validate(Text text, IInputValidator validator) { String err = null; if (validator != null) err = validator.isValid(text.getText()); // add validator to the cache validators.put(validator, err); Control button = getButton(IDialogConstants.OK_ID); // disable ok button if any of the validators are reporting errors. if (button != null) { boolean valid = true; for (String s : validators.values()) if (s != null) valid = false; button.setEnabled(valid); } if (err != null) { text.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_RED)); text.setToolTipText(err); return false; } else { text.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_WIDGET_FOREGROUND)); text.setToolTipText(null); return true; } } protected String updateName(String url, String name) { if (url.length() > 0 ) { if (name == null) { return new String(url); } else if (Math.abs(url.length() - name.length()) <= 1) { int common = Math.min(name.length(), url.length()); if (name.regionMatches(0, url, 0, common)) { return new String(url); } } } return null; } }