From: jsurfer Date: Tue, 5 Oct 2004 20:55:35 +0000 (+0000) Subject: improved codetemplate wizards; new html tag wizards X-Git-Url: http://git.phpeclipse.com?hp=dabda7992b51b27a4064308aef119dc1fbe8a173 improved codetemplate wizards; new html tag wizards --- diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/WebBrowser.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/WebBrowser.java index 829d813..d0b396f 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/WebBrowser.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/WebBrowser.java @@ -1,17 +1,11 @@ /** - * Copyright (c) 2003 IBM Corporation and others. - * All rights reserved.   This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM - Initial API and implementation + * Copyright (c) 2003 IBM Corporation and others. All rights reserved.   This program and the accompanying materials are made + * available under the terms of the Common Public License v1.0 which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html  * Contributors: IBM - Initial API and implementation */ //TODO 1. Handle the sizing of a popup running in shelled out secondary window. //TODO 2. Support printing: waiting on eclipse bug 47937/44823. - package net.sourceforge.phpeclipse.webbrowser.internal; import java.util.*; @@ -31,551 +25,589 @@ import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.swt.browser.*; public class WebBrowser extends Composite { - protected Composite toolbarComp; - protected Composite statusComp; - protected Combo combo; - protected Clipboard clipboard; - protected boolean showToolbar; - protected ToolItem back; - protected ToolItem forward; - protected ToolItem stop; - protected ToolItem favorites; - protected ToolItem refresh; - protected BusyIndicator busy; - protected boolean showStatusbar; - protected ProgressBar progress; - protected Label status; - private static int MAX_HISTORY = 50; - protected static java.util.List history; - protected Browser browser; - protected Shell shell; - protected WebBrowserEditor editor; - protected String title; - - public WebBrowser(Composite parent, final boolean showToolbar, final boolean showStatusbar) { - super(parent, SWT.NONE); - - this.showToolbar = showToolbar; - this.showStatusbar = showStatusbar; - - GridLayout layout = new GridLayout(); - layout.marginHeight = 3; - layout.marginWidth = 3; - layout.horizontalSpacing = 3; - layout.verticalSpacing = 3; - layout.numColumns = 1; - setLayout(layout); - setLayoutData(new GridData(GridData.FILL_BOTH)); - clipboard = new Clipboard(parent.getDisplay()); - WorkbenchHelp.setHelp(this, ContextIds.WEB_BROWSER); - - if (showToolbar) { - toolbarComp = new Composite(this, SWT.NONE); - GridLayout outerLayout = new GridLayout(); - outerLayout.numColumns = 2; - outerLayout.marginWidth = 0; - outerLayout.marginHeight = 0; - toolbarComp.setLayout(outerLayout); - toolbarComp.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL)); - - // create the top line, with a combo box for history and a "go" button - Composite top = new Composite(toolbarComp, SWT.NONE); - GridLayout topLayout = new GridLayout(); - topLayout.numColumns = 2; - topLayout.marginWidth = 0; - topLayout.marginHeight = 0; - top.setLayout(topLayout); - top.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_CENTER | GridData.FILL_HORIZONTAL)); - - combo = new Combo(top, SWT.DROP_DOWN); - - updateHistory(); - - combo.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent we) { - try { - if (combo.getSelectionIndex() != -1) - setURL(combo.getItem(combo.getSelectionIndex())); - } catch (Exception e) { } - } - }); - combo.addListener(SWT.DefaultSelection, new Listener() { - public void handleEvent(Event e) { - setURL(combo.getText()); - } - }); - combo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - WorkbenchHelp.setHelp(combo, ContextIds.WEB_BROWSER_URL); - - ToolBar toolbar = new ToolBar(top, SWT.FLAT); - fillToolBar(toolbar); - - new ToolItem(toolbar, SWT.SEPARATOR); - - busy = new BusyIndicator(toolbarComp, SWT.NONE); - busy.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); - } - - // create a new SWT Web browser widget, checking once again to make sure we can use it in this environment - if (WebBrowserUtil.canUseInternalWebBrowser() & WebBrowserUtil.isInternalBrowserOperational()) - this.browser = new Browser(this, SWT.NONE); - else { - WebBrowserUtil.openError(WebBrowserUIPlugin.getResource("%errorCouldNotLaunchInternalWebBrowser")); - return; - } - - if (showToolbar) { - back.setEnabled(browser.isBackEnabled()); - forward.setEnabled(browser.isForwardEnabled()); - } - - WorkbenchHelp.setHelp(browser, ContextIds.WEB_BROWSER_WEB); - GridData data = new GridData(); - data.horizontalAlignment = GridData.FILL; - data.verticalAlignment = GridData.FILL; - data.horizontalSpan = 3; - data.grabExcessHorizontalSpace = true; - data.grabExcessVerticalSpace = true; - browser.setLayoutData(data); - - if (showStatusbar) - createStatusArea(this); - - addBrowserListeners(); - } - /** - * - */ - protected void addBrowserListeners() { - if (showStatusbar) { - // respond to Browser StatusTextEvents events by updating the status Text label - browser.addStatusTextListener(new StatusTextListener() { - public void changed(StatusTextEvent event) { - status.setText(event.text); - } - }); - } - - /** Add listener for new window creation so that we can instead of opening a separate - * new window in which the session is lost, we can instead open a new window in a new - * shell within the browser area thereby maintaining the session. - */ - browser.addOpenWindowListener(new OpenWindowListener() { - public void open(WindowEvent event) { - Shell shell2 = new Shell(getDisplay()); - shell2.setLayout(new FillLayout()); - shell2.setText(WebBrowserUIPlugin.getResource("%viewWebBrowserTitle")); - shell2.setImage(getShell().getImage()); - WebBrowser browser2 = new WebBrowser(shell2, showToolbar, showStatusbar); - browser2.shell = shell2; - event.browser = browser2.browser; - shell2.open(); - } - }); - - browser.addCloseWindowListener(new CloseWindowListener(){ - public void close(WindowEvent event) { - // if shell is not null, it must be a secondary popup window, else its an editor window - if (shell != null) - shell.dispose(); - else - editor.closeEditor(); - } - }); - - browser.addProgressListener(new ProgressListener() { - public void changed(ProgressEvent event) { - if (event.total == 0) - return; - - boolean done = (event.current == event.total); - - int percentProgress = event.current * 100 / event.total; - if (showStatusbar) { - if (done) - progress.setSelection(0); - else - progress.setSelection(percentProgress); - } - - if (showToolbar) { - if (!busy.isBusy() && (percentProgress > 0 && percentProgress < 100)) { - busy.setBusy(true); - } - // Once the progress hits 100 percent, done, set busy to false - else if (busy.isBusy() && done) { - busy.setBusy(false); - } - } - } - - public void completed(ProgressEvent event) { - if (showStatusbar) - progress.setSelection(0); - if (showToolbar) { - busy.setBusy(false); - back.setEnabled(browser.isBackEnabled()); - forward.setEnabled(browser.isForwardEnabled()); - } - } - }); - - if (showToolbar) { - browser.addLocationListener(new LocationListener() { - public void changed(LocationEvent event) { - if (!event.top) - return; - if (!isHome()) { - combo.setText(event.location); - addToHistory(event.location); - updateHistory(); - } else - combo.setText(""); - } - - public void changing(LocationEvent event) { } - }); - } - - browser.addTitleListener(new TitleListener() { - public void changed(TitleEvent event) { - title = event.title; - } - }); - } - - /** - * Return the underlying browser control. - * - * @return org.eclipse.swt.browser.Browser - */ - public Browser getBrowser() { - return browser; - } - - /** - * - */ - protected void forward() { - browser.forward(); - } - - /** - * - */ - protected void back() { - browser.back(); - } - - /** - * - */ - protected void stop() { - browser.stop(); - } - - /** - * - */ - protected void navigate(String url) { - Trace.trace(Trace.FINER, "Navigate: " + url); - if (url != null && url.equals(getURL())) { - refresh(); - return; - } - browser.setUrl(url); - } - - /** - * Refresh the currently viewed page. - */ - public void refresh() { - browser.refresh(); - } - - protected void setURL(String url, boolean browse) { - Trace.trace(Trace.FINEST, "setURL: " + url + " " + browse); - if (url == null) { - home(); - return; - } - - if (url.endsWith(WebBrowserPreference.getHomePageURL().substring(9))) - return; - - // check URL maps - Iterator iterator = WebBrowserUtil.getURLMaps().iterator(); - String newURL = null; - while (iterator.hasNext() && newURL == null) { - try { - IURLMap map = (IURLMap) iterator.next(); - newURL = map.getMappedURL(url); - } catch (Exception e) { } - } - if (newURL != null) - url = newURL; - - if (browse) - navigate(url); - - addToHistory(url); - updateHistory(); - } - - protected void addToHistory(String url) { - if (history == null) - history = WebBrowserPreference.getInternalWebBrowserHistory(); - int found = -1; - int size = history.size(); - for (int i = 0; i < size; i++){ - String s = (String) history.get(i); - if (s.equals(url)) { - found = i; - break; - } - } - - if (found == -1) { - if (size >= MAX_HISTORY) - history.remove(size - 1); - history.add(0, url); - WebBrowserPreference.setInternalWebBrowserHistory(history); - } else if (found != 0) { - history.remove(found); - history.add(0, url); - WebBrowserPreference.setInternalWebBrowserHistory(history); - } - } - - public void setURL(String url) { - setURL(url, true); - } - - /** - * Creates the Web browser status area. - */ - private void createStatusArea(Composite parent) { - Composite composite = new Composite(parent, SWT.NONE); - GridLayout layout = new GridLayout(); - layout.numColumns = 2; - layout.marginHeight = 0; - layout.marginWidth = 0; - layout.horizontalSpacing = 4; - layout.verticalSpacing = 0; - composite.setLayout(layout); - composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - - // Add a label for displaying status messages as they are received from the control - status = new Label(composite, SWT.SINGLE | SWT.READ_ONLY); - GridData gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL); - gridData.horizontalIndent = 2; - status.setLayoutData(gridData); - - // Add a progress bar to display downloading progress information - progress = new ProgressBar(composite, SWT.BORDER); - gridData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING | GridData.VERTICAL_ALIGN_FILL); - gridData.widthHint = 100; - gridData.heightHint = 10; - progress.setLayoutData(gridData); - } - - /** - * - */ - public void dispose() { - super.dispose(); - - showStatusbar = false; - showToolbar = false; - - if (busy != null) - busy.dispose(); - busy = null; - - browser = null; - } - - /** - * Populate the toolbar. - * @param toolbar org.eclipse.swt.widgets.ToolBar - */ - private void fillToolBar(final ToolBar toolbar) { - ToolItem go = new ToolItem(toolbar, SWT.NONE); - go.setImage(ImageResource.getImage(ImageResource.IMG_ELCL_NAV_GO)); - go.setHotImage(ImageResource.getImage(ImageResource.IMG_CLCL_NAV_GO)); - go.setDisabledImage(ImageResource.getImage(ImageResource.IMG_DLCL_NAV_GO)); - go.setToolTipText(WebBrowserUIPlugin.getResource("%actionWebBrowserGo")); - go.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent event) { - setURL(combo.getText()); - } - }); - - new ToolItem(toolbar, SWT.SEPARATOR); - - favorites = new ToolItem(toolbar, SWT.DROP_DOWN); - favorites.setImage(ImageResource.getImage(ImageResource.IMG_ELCL_NAV_FAVORITES)); - favorites.setHotImage(ImageResource.getImage(ImageResource.IMG_CLCL_NAV_FAVORITES)); - favorites.setDisabledImage(ImageResource.getImage(ImageResource.IMG_DLCL_NAV_FAVORITES)); - favorites.setToolTipText(WebBrowserUIPlugin.getResource("%actionWebBrowserFavorites")); - - favorites.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent event) { - if (event.detail == SWT.ARROW) { - Rectangle r = favorites.getBounds(); - showFavorites(toolbar, toolbar.toDisplay(r.x, r.y + r.height)); - } else - addFavorite(); - } - }); - - // create back and forward actions - back = new ToolItem(toolbar, SWT.NONE); - back.setImage(ImageResource.getImage(ImageResource.IMG_ELCL_NAV_BACKWARD)); - back.setHotImage(ImageResource.getImage(ImageResource.IMG_CLCL_NAV_BACKWARD)); - back.setDisabledImage(ImageResource.getImage(ImageResource.IMG_DLCL_NAV_BACKWARD)); - back.setToolTipText(WebBrowserUIPlugin.getResource("%actionWebBrowserBack")); - back.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent event) { - back(); - } - }); - - forward = new ToolItem(toolbar, SWT.NONE); - forward.setImage(ImageResource.getImage(ImageResource.IMG_ELCL_NAV_FORWARD)); - forward.setHotImage(ImageResource.getImage(ImageResource.IMG_CLCL_NAV_FORWARD)); - forward.setDisabledImage(ImageResource.getImage(ImageResource.IMG_DLCL_NAV_FORWARD)); - forward.setToolTipText(WebBrowserUIPlugin.getResource("%actionWebBrowserForward")); - forward.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent event) { - forward(); - } - }); - - // create refresh, stop, and print actions - stop = new ToolItem(toolbar, SWT.NONE); - stop.setImage(ImageResource.getImage(ImageResource.IMG_ELCL_NAV_STOP)); - stop.setHotImage(ImageResource.getImage(ImageResource.IMG_CLCL_NAV_STOP)); - stop.setDisabledImage(ImageResource.getImage(ImageResource.IMG_DLCL_NAV_STOP)); - stop.setToolTipText(WebBrowserUIPlugin.getResource("%actionWebBrowserStop")); - stop.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent event) { - stop(); - } - }); - - refresh = new ToolItem(toolbar, SWT.NONE); - refresh.setImage(ImageResource.getImage(ImageResource.IMG_ELCL_NAV_REFRESH)); - refresh.setHotImage(ImageResource.getImage(ImageResource.IMG_CLCL_NAV_REFRESH)); - refresh.setDisabledImage(ImageResource.getImage(ImageResource.IMG_DLCL_NAV_REFRESH)); - refresh.setToolTipText(WebBrowserUIPlugin.getResource("%actionWebBrowserRefresh")); - refresh.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent event) { - refresh(); - } - }); - } - - protected void addFavorite() { - java.util.List list = WebBrowserPreference.getInternalWebBrowserFavorites(); - Favorite f = new Favorite(title, browser.getUrl()); - if (!list.contains(f)) { - list.add(f); - WebBrowserPreference.setInternalWebBrowserFavorites(list); - } - } - - protected void showFavorites(Control parent, Point p) { - Menu perspectiveBarMenu = null; - if (perspectiveBarMenu == null) { - Menu menu = new Menu(parent); - - // locked favorites - Iterator iterator = WebBrowserUtil.getLockedFavorites().iterator(); - if (iterator.hasNext()) { - while (iterator.hasNext()) { - final Favorite f = (Favorite) iterator.next(); - MenuItem item = new MenuItem(menu, SWT.NONE); - item.setText(f.getName()); - item.setImage(ImageResource.getImage(ImageResource.IMG_FAVORITE)); - item.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent event) { - setURL(f.getURL()); - } - }); - } - - new MenuItem(menu, SWT.SEPARATOR); - } - - iterator = WebBrowserPreference.getInternalWebBrowserFavorites().iterator(); - if (!iterator.hasNext()) { - MenuItem item = new MenuItem(menu, SWT.NONE); - item.setText(WebBrowserUIPlugin.getResource("%actionWebBrowserNoFavorites")); - } - while (iterator.hasNext()) { - final Favorite f = (Favorite) iterator.next(); - MenuItem item = new MenuItem(menu, SWT.NONE); - item.setText(f.getName()); - item.setImage(ImageResource.getImage(ImageResource.IMG_FAVORITE)); - item.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent event) { - setURL(f.getURL()); - } - }); - } - - new MenuItem(menu, SWT.SEPARATOR); - - MenuItem item = new MenuItem(menu, SWT.NONE); - item.setText(WebBrowserUIPlugin.getResource("%actionWebBrowserOrganizeFavorites")); - item.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent event) { - OrganizeFavoritesDialog dialog = new OrganizeFavoritesDialog(shell); - dialog.open(); - } - }); - - perspectiveBarMenu = menu; - } - - if (perspectiveBarMenu != null) { - perspectiveBarMenu.setLocation(p.x, p.y); - perspectiveBarMenu.setVisible(true); - } - } - - public void home() { - navigate(WebBrowserPreference.getHomePageURL()); - } - - /** - * Returns true if the homepage is currently being displayed. - * @return boolean - */ - protected boolean isHome() { - return getURL() != null && getURL().endsWith(WebBrowserPreference.getHomePageURL().substring(9)); - } - - protected String getURL() { - return browser.getUrl(); - } - - /** - * Update the history list to the global copy. - */ - protected void updateHistory() { - if (combo == null) - return; - - String temp = combo.getText(); - if (history == null) - history = WebBrowserPreference.getInternalWebBrowserHistory(); - - String[] historyList = new String[history.size()]; - history.toArray(historyList); - combo.setItems(historyList); - - combo.setText(temp); - } + protected Composite toolbarComp; + + protected Composite statusComp; + + protected Combo combo; + + protected Clipboard clipboard; + + protected boolean showToolbar; + + protected ToolItem back; + + protected ToolItem forward; + + protected ToolItem stop; + + protected ToolItem favorites; + + protected ToolItem refresh; + + protected BusyIndicator busy; + + protected boolean showStatusbar; + + protected ProgressBar progress; + + protected Label status; + + private static int MAX_HISTORY = 50; + + protected static java.util.List history; + + protected Browser browser; + + protected Shell shell; + + protected WebBrowserEditor editor; + + protected String title; + + public WebBrowser(Composite parent, final boolean showToolbar, final boolean showStatusbar) { + super(parent, SWT.NONE); + + this.showToolbar = showToolbar; + this.showStatusbar = showStatusbar; + + GridLayout layout = new GridLayout(); + layout.marginHeight = 3; + layout.marginWidth = 3; + layout.horizontalSpacing = 3; + layout.verticalSpacing = 3; + layout.numColumns = 1; + setLayout(layout); + setLayoutData(new GridData(GridData.FILL_BOTH)); + clipboard = new Clipboard(parent.getDisplay()); + WorkbenchHelp.setHelp(this, ContextIds.WEB_BROWSER); + + if (showToolbar) { + toolbarComp = new Composite(this, SWT.NONE); + GridLayout outerLayout = new GridLayout(); + outerLayout.numColumns = 2; + outerLayout.marginWidth = 0; + outerLayout.marginHeight = 0; + toolbarComp.setLayout(outerLayout); + toolbarComp.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL)); + + // create the top line, with a combo box for history and a "go" button + Composite top = new Composite(toolbarComp, SWT.NONE); + GridLayout topLayout = new GridLayout(); + topLayout.numColumns = 2; + topLayout.marginWidth = 0; + topLayout.marginHeight = 0; + top.setLayout(topLayout); + top.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_CENTER | GridData.FILL_HORIZONTAL)); + + combo = new Combo(top, SWT.DROP_DOWN); + + updateHistory(); + + combo.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent we) { + try { + if (combo.getSelectionIndex() != -1) + setURL(combo.getItem(combo.getSelectionIndex())); + } catch (Exception e) { + } + } + }); + combo.addListener(SWT.DefaultSelection, new Listener() { + public void handleEvent(Event e) { + setURL(combo.getText()); + } + }); + combo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + WorkbenchHelp.setHelp(combo, ContextIds.WEB_BROWSER_URL); + + ToolBar toolbar = new ToolBar(top, SWT.FLAT); + fillToolBar(toolbar); + + new ToolItem(toolbar, SWT.SEPARATOR); + + busy = new BusyIndicator(toolbarComp, SWT.NONE); + busy.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); + } + + // create a new SWT Web browser widget, checking once again to make sure we can use it in this environment + if (WebBrowserUtil.canUseInternalWebBrowser() & WebBrowserUtil.isInternalBrowserOperational()) + this.browser = new Browser(this, SWT.NONE); + else { + WebBrowserUtil.openError(WebBrowserUIPlugin.getResource("%errorCouldNotLaunchInternalWebBrowser")); + return; + } + + if (showToolbar) { + back.setEnabled(browser.isBackEnabled()); + forward.setEnabled(browser.isForwardEnabled()); + } + + WorkbenchHelp.setHelp(browser, ContextIds.WEB_BROWSER_WEB); + GridData data = new GridData(); + data.horizontalAlignment = GridData.FILL; + data.verticalAlignment = GridData.FILL; + data.horizontalSpan = 3; + data.grabExcessHorizontalSpace = true; + data.grabExcessVerticalSpace = true; + browser.setLayoutData(data); + + if (showStatusbar) + createStatusArea(this); + + addBrowserListeners(); + } + + /** + * + */ + protected void addBrowserListeners() { + if (showStatusbar) { + // respond to Browser StatusTextEvents events by updating the status Text label + browser.addStatusTextListener(new StatusTextListener() { + public void changed(StatusTextEvent event) { + status.setText(event.text); + } + }); + } + + /** + * Add listener for new window creation so that we can instead of opening a separate new window in which the session is lost, we + * can instead open a new window in a new shell within the browser area thereby maintaining the session. + */ + browser.addOpenWindowListener(new OpenWindowListener() { + public void open(WindowEvent event) { + Shell shell2 = new Shell(getDisplay()); + shell2.setLayout(new FillLayout()); + shell2.setText(WebBrowserUIPlugin.getResource("%viewWebBrowserTitle")); + shell2.setImage(getShell().getImage()); + WebBrowser browser2 = new WebBrowser(shell2, showToolbar, showStatusbar); + browser2.shell = shell2; + event.browser = browser2.browser; + shell2.open(); + } + }); + + browser.addCloseWindowListener(new CloseWindowListener() { + public void close(WindowEvent event) { + // if shell is not null, it must be a secondary popup window, else its an editor window + if (shell != null) + shell.dispose(); + else + editor.closeEditor(); + } + }); + + browser.addProgressListener(new ProgressListener() { + public void changed(ProgressEvent event) { + if (event.total == 0) + return; + + boolean done = (event.current == event.total); + + int percentProgress = event.current * 100 / event.total; + if (showStatusbar) { + if (done) + progress.setSelection(0); + else + progress.setSelection(percentProgress); + } + + if (showToolbar) { + if (!busy.isBusy() && (percentProgress > 0 && percentProgress < 100)) { + busy.setBusy(true); + } + // Once the progress hits 100 percent, done, set busy to false + else if (busy.isBusy() && done) { + busy.setBusy(false); + } + } + } + + public void completed(ProgressEvent event) { + if (showStatusbar) + progress.setSelection(0); + if (showToolbar) { + busy.setBusy(false); + back.setEnabled(browser.isBackEnabled()); + forward.setEnabled(browser.isForwardEnabled()); + } + } + }); + + if (showToolbar) { + browser.addLocationListener(new LocationListener() { + public void changed(LocationEvent event) { + if (!event.top) + return; + if (!isHome()) { + combo.setText(event.location); + addToHistory(event.location); + updateHistory(); + } else + combo.setText(""); + } + + public void changing(LocationEvent event) { + } + }); + } + + browser.addTitleListener(new TitleListener() { + public void changed(TitleEvent event) { + title = event.title; + } + }); + } + + /** + * Return the underlying browser control. + * + * @return org.eclipse.swt.browser.Browser + */ + public Browser getBrowser() { + return browser; + } + + /** + * + */ + protected void forward() { + browser.forward(); + } + + /** + * + */ + protected void back() { + browser.back(); + } + + /** + * + */ + protected void stop() { + browser.stop(); + } + + /** + * + */ + protected void navigate(String url) { + Trace.trace(Trace.FINER, "Navigate: " + url); + if (url != null && url.equals(getURL())) { + refresh(); + return; + } + browser.setUrl(url); + } + + /** + * Refresh the currently viewed page. + */ + public void refresh() { + browser.refresh(); + } + + protected void setURL(String url, boolean browse) { + Trace.trace(Trace.FINEST, "setURL: " + url + " " + browse); + if (url == null) { + home(); + return; + } + + if (url.endsWith(WebBrowserPreference.getHomePageURL().substring(9))) + return; + + // check URL maps + Iterator iterator = WebBrowserUtil.getURLMaps().iterator(); + String newURL = null; + while (iterator.hasNext() && newURL == null) { + try { + IURLMap map = (IURLMap) iterator.next(); + newURL = map.getMappedURL(url); + } catch (Exception e) { + } + } + if (newURL != null) + url = newURL; + + if (browse) + navigate(url); + + addToHistory(url); + updateHistory(); + } + + protected void addToHistory(String url) { + if (history == null) + history = WebBrowserPreference.getInternalWebBrowserHistory(); + int found = -1; + int size = history.size(); + for (int i = 0; i < size; i++) { + String s = (String) history.get(i); + if (s.equals(url)) { + found = i; + break; + } + } + + if (found == -1) { + if (size >= MAX_HISTORY) + history.remove(size - 1); + history.add(0, url); + WebBrowserPreference.setInternalWebBrowserHistory(history); + } else if (found != 0) { + history.remove(found); + history.add(0, url); + WebBrowserPreference.setInternalWebBrowserHistory(history); + } + } + + public void setURL(String url) { + setURL(url, true); + } + + /** + * Creates the Web browser status area. + */ + private void createStatusArea(Composite parent) { + Composite composite = new Composite(parent, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.numColumns = 2; + layout.marginHeight = 0; + layout.marginWidth = 0; + layout.horizontalSpacing = 4; + layout.verticalSpacing = 0; + composite.setLayout(layout); + composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + + // Add a label for displaying status messages as they are received from the control + status = new Label(composite, SWT.SINGLE | SWT.READ_ONLY); + GridData gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL); + gridData.horizontalIndent = 2; + status.setLayoutData(gridData); + + // Add a progress bar to display downloading progress information + progress = new ProgressBar(composite, SWT.BORDER); + gridData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING | GridData.VERTICAL_ALIGN_FILL); + gridData.widthHint = 100; + gridData.heightHint = 10; + progress.setLayoutData(gridData); + } + + /** + * + */ + public void dispose() { + super.dispose(); + + showStatusbar = false; + showToolbar = false; + + if (busy != null) + busy.dispose(); + busy = null; + + browser = null; + } + + /** + * Populate the toolbar. + * + * @param toolbar + * org.eclipse.swt.widgets.ToolBar + */ + private void fillToolBar(final ToolBar toolbar) { + ToolItem go = new ToolItem(toolbar, SWT.NONE); + go.setImage(ImageResource.getImage(ImageResource.IMG_ELCL_NAV_GO)); + go.setHotImage(ImageResource.getImage(ImageResource.IMG_CLCL_NAV_GO)); + go.setDisabledImage(ImageResource.getImage(ImageResource.IMG_DLCL_NAV_GO)); + go.setToolTipText(WebBrowserUIPlugin.getResource("%actionWebBrowserGo")); + go.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent event) { + setURL(combo.getText()); + } + }); + + new ToolItem(toolbar, SWT.SEPARATOR); + + favorites = new ToolItem(toolbar, SWT.DROP_DOWN); + favorites.setImage(ImageResource.getImage(ImageResource.IMG_ELCL_NAV_FAVORITES)); + favorites.setHotImage(ImageResource.getImage(ImageResource.IMG_CLCL_NAV_FAVORITES)); + favorites.setDisabledImage(ImageResource.getImage(ImageResource.IMG_DLCL_NAV_FAVORITES)); + favorites.setToolTipText(WebBrowserUIPlugin.getResource("%actionWebBrowserFavorites")); + + favorites.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent event) { + if (event.detail == SWT.ARROW) { + Rectangle r = favorites.getBounds(); + showFavorites(toolbar, toolbar.toDisplay(r.x, r.y + r.height)); + } else + addFavorite(); + } + }); + + // create back and forward actions + back = new ToolItem(toolbar, SWT.NONE); + back.setImage(ImageResource.getImage(ImageResource.IMG_ELCL_NAV_BACKWARD)); + back.setHotImage(ImageResource.getImage(ImageResource.IMG_CLCL_NAV_BACKWARD)); + back.setDisabledImage(ImageResource.getImage(ImageResource.IMG_DLCL_NAV_BACKWARD)); + back.setToolTipText(WebBrowserUIPlugin.getResource("%actionWebBrowserBack")); + back.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent event) { + back(); + } + }); + + forward = new ToolItem(toolbar, SWT.NONE); + forward.setImage(ImageResource.getImage(ImageResource.IMG_ELCL_NAV_FORWARD)); + forward.setHotImage(ImageResource.getImage(ImageResource.IMG_CLCL_NAV_FORWARD)); + forward.setDisabledImage(ImageResource.getImage(ImageResource.IMG_DLCL_NAV_FORWARD)); + forward.setToolTipText(WebBrowserUIPlugin.getResource("%actionWebBrowserForward")); + forward.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent event) { + forward(); + } + }); + + // create refresh, stop, and print actions + stop = new ToolItem(toolbar, SWT.NONE); + stop.setImage(ImageResource.getImage(ImageResource.IMG_ELCL_NAV_STOP)); + stop.setHotImage(ImageResource.getImage(ImageResource.IMG_CLCL_NAV_STOP)); + stop.setDisabledImage(ImageResource.getImage(ImageResource.IMG_DLCL_NAV_STOP)); + stop.setToolTipText(WebBrowserUIPlugin.getResource("%actionWebBrowserStop")); + stop.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent event) { + stop(); + } + }); + + refresh = new ToolItem(toolbar, SWT.NONE); + refresh.setImage(ImageResource.getImage(ImageResource.IMG_ELCL_NAV_REFRESH)); + refresh.setHotImage(ImageResource.getImage(ImageResource.IMG_CLCL_NAV_REFRESH)); + refresh.setDisabledImage(ImageResource.getImage(ImageResource.IMG_DLCL_NAV_REFRESH)); + refresh.setToolTipText(WebBrowserUIPlugin.getResource("%actionWebBrowserRefresh")); + refresh.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent event) { + refresh(); + } + }); + } + + protected void addFavorite() { + java.util.List list = WebBrowserPreference.getInternalWebBrowserFavorites(); + Favorite f = new Favorite(title, browser.getUrl()); + if (!list.contains(f)) { + list.add(f); + WebBrowserPreference.setInternalWebBrowserFavorites(list); + } + } + + protected void showFavorites(Control parent, Point p) { + Menu perspectiveBarMenu = null; + if (perspectiveBarMenu == null) { + Menu menu = new Menu(parent); + + // locked favorites + Iterator iterator = WebBrowserUtil.getLockedFavorites().iterator(); + if (iterator.hasNext()) { + while (iterator.hasNext()) { + final Favorite f = (Favorite) iterator.next(); + MenuItem item = new MenuItem(menu, SWT.NONE); + item.setText(f.getName()); + item.setImage(ImageResource.getImage(ImageResource.IMG_FAVORITE)); + item.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent event) { + setURL(f.getURL()); + } + }); + } + + new MenuItem(menu, SWT.SEPARATOR); + } + + iterator = WebBrowserPreference.getInternalWebBrowserFavorites().iterator(); + if (!iterator.hasNext()) { + MenuItem item = new MenuItem(menu, SWT.NONE); + item.setText(WebBrowserUIPlugin.getResource("%actionWebBrowserNoFavorites")); + } + while (iterator.hasNext()) { + final Favorite f = (Favorite) iterator.next(); + MenuItem item = new MenuItem(menu, SWT.NONE); + item.setText(f.getName()); + item.setImage(ImageResource.getImage(ImageResource.IMG_FAVORITE)); + item.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent event) { + setURL(f.getURL()); + } + }); + } + + new MenuItem(menu, SWT.SEPARATOR); + + MenuItem item = new MenuItem(menu, SWT.NONE); + item.setText(WebBrowserUIPlugin.getResource("%actionWebBrowserOrganizeFavorites")); + item.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent event) { + OrganizeFavoritesDialog dialog = new OrganizeFavoritesDialog(shell); + dialog.open(); + } + }); + + perspectiveBarMenu = menu; + } + + if (perspectiveBarMenu != null) { + perspectiveBarMenu.setLocation(p.x, p.y); + perspectiveBarMenu.setVisible(true); + } + } + + public void home() { + navigate(WebBrowserPreference.getHomePageURL()); + } + + /** + * Returns true if the homepage is currently being displayed. + * + * @return boolean + */ + protected boolean isHome() { + return getURL() != null && getURL().endsWith(WebBrowserPreference.getHomePageURL().substring(9)); + } + + protected String getURL() { + return browser.getUrl(); + } + + /** + * Update the history list to the global copy. + */ + protected void updateHistory() { + if (combo == null) + return; + + String temp = combo.getText(); + if (history == null) + history = WebBrowserPreference.getInternalWebBrowserHistory(); + + String[] historyList = new String[history.size()]; + history.toArray(historyList); + combo.setItems(historyList); + + combo.setText(temp); + } + + public void addProgressListener(ProgressListener listener) { + browser.addProgressListener(listener); + } + + public void addStatusTextListener(StatusTextListener listener) { + browser.addStatusTextListener(listener); + } + + public void addTitleListener(TitleListener listener) { + browser.addTitleListener(listener); + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/views/BrowserView.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/views/BrowserView.java index 60eddb6..4636163 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/views/BrowserView.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/views/BrowserView.java @@ -20,6 +20,9 @@ import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; +import org.eclipse.swt.browser.ProgressListener; +import org.eclipse.swt.browser.StatusTextListener; +import org.eclipse.swt.browser.TitleListener; import org.eclipse.swt.widgets.Composite; import org.eclipse.ui.part.ViewPart; @@ -74,32 +77,50 @@ public class BrowserView extends ViewPart { public void setUrl(final String url) { if (instance != null) { instance.setURL(url); -// try { -// ResourcesPlugin.getWorkspace().run(new IWorkspaceRunnable() { -// public void run(IProgressMonitor monitor) throws CoreException { -// instance.setURL(url); -// } -// }, null); -// } catch (CoreException e) { -// // TODO Auto-generated catch block -// e.printStackTrace(); -// } + // try { + // ResourcesPlugin.getWorkspace().run(new IWorkspaceRunnable() { + // public void run(IProgressMonitor monitor) throws CoreException { + // instance.setURL(url); + // } + // }, null); + // } catch (CoreException e) { + // // TODO Auto-generated catch block + // e.printStackTrace(); + // } } } public void refresh() { if (instance != null) { instance.refresh(); -// try { -// ResourcesPlugin.getWorkspace().run(new IWorkspaceRunnable() { -// public void run(IProgressMonitor monitor) throws CoreException { -// instance.refresh(); -// } -// }, null); -// } catch (CoreException e) { -// // TODO Auto-generated catch block -// e.printStackTrace(); -// } + // try { + // ResourcesPlugin.getWorkspace().run(new IWorkspaceRunnable() { + // public void run(IProgressMonitor monitor) throws CoreException { + // instance.refresh(); + // } + // }, null); + // } catch (CoreException e) { + // // TODO Auto-generated catch block + // e.printStackTrace(); + // } + } + } + + public void addProgressListener(ProgressListener listener) { + if (instance != null) { + instance.addProgressListener(listener); + } + } + + public void addStatusTextListener(StatusTextListener listener) { + if (instance != null) { + instance.addStatusTextListener(listener); + } + } + + public void addTitleListener(TitleListener listener) { + if (instance != null) { + instance.addTitleListener(listener); } } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/icons/wizban/editelem_wiz.gif b/net.sourceforge.phpeclipse/icons/wizban/editelem_wiz.gif new file mode 100644 index 0000000..2ab1adb Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/wizban/editelem_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/plugin.properties b/net.sourceforge.phpeclipse/plugin.properties index b14c08f..7cddd75 100644 --- a/net.sourceforge.phpeclipse/plugin.properties +++ b/net.sourceforge.phpeclipse/plugin.properties @@ -18,6 +18,7 @@ viewPHPResources.name=PHP Resources newWizardCategory.name=PHP newWizardPHPProject.name=PHP Project newWizardPHPFile.name=PHP File +newWizardHTMLFile.name=HTML file NewPHPClass.label= Class NewPHPClass.description=Create a PHP class diff --git a/net.sourceforge.phpeclipse/plugin.xml b/net.sourceforge.phpeclipse/plugin.xml index 5e67157..5448972 100644 --- a/net.sourceforge.phpeclipse/plugin.xml +++ b/net.sourceforge.phpeclipse/plugin.xml @@ -278,6 +278,16 @@ Create a basic PHP file. + + + Create a basic HTML file. + + + + + + TokenNameKEYWORD && token != TokenNamelist && token != - // TokenNamenew) { - // char[] ident = scanner.getCurrentIdentifierSource(); - // String keyword = new String(ident); - // if (token == TokenNameAT) { - // getNextToken(); - // if (token != TokenNamerequire && token != TokenNamerequire_once - // && token != TokenNameinclude && token != TokenNameinclude_once - // && token != TokenNameIdentifier && token != TokenNameVariable - // && token != TokenNameStringInterpolated) { - // throwSyntaxError("identifier expected after '@'."); - // } - // } - // if (token == TokenNameinclude || token == TokenNameinclude_once) { - // getNextToken(); - // if (token == TokenNameLPAREN) { - // expr(); - // if (token == TokenNameSEMICOLON) { - // getNextToken(); - // } else { - // if (previousToken != TokenNameAT && token != TokenNameStopPHP) { - // throwSyntaxError("';' expected after 'include' or 'include_once'."); - // } - // // getNextToken(); - // } - // } else { - // concatenationExpression(); - // } - // return; - // } else if (token == TokenNamerequire || token == - // TokenNamerequire_once) - // { - // getNextToken(); - // //constant(); - // if (token == TokenNameLPAREN) { - // expr(); - // if (token == TokenNameSEMICOLON) { - // getNextToken(); - // } else { - // if (previousToken != TokenNameAT && token != TokenNameStopPHP) { - // throwSyntaxError("';' expected after 'require' or 'require_once'."); - // } - // // getNextToken(); - // } - // } else { - // concatenationExpression(); - // } - // return; - // } else + + private Statement statement(int previousToken) { + Statement statement = null; + Expression expression; + int sourceStart = scanner.getCurrentTokenStartPosition(); if (token == TokenNameif) { getNextToken(); if (token == TokenNameLPAREN) { @@ -633,14 +623,14 @@ public class Parser //extends PHPParserSuperclass } else { throwSyntaxError("'(' expected after 'if' keyword."); } - expr(); + expression = expr(); if (token == TokenNameRPAREN) { getNextToken(); } else { throwSyntaxError("')' expected after 'if' condition."); } ifStatement(); - return; + return new IfStatement(expression, statement, sourceStart, scanner.getCurrentTokenEndPosition()); } else if (token == TokenNameswitch) { getNextToken(); if (token == TokenNameLPAREN) { @@ -655,7 +645,7 @@ public class Parser //extends PHPParserSuperclass throwSyntaxError("')' expected after 'switch' condition."); } switchStatement(); - return; + return statement; } else if (token == TokenNamefor) { getNextToken(); if (token == TokenNameLPAREN) { @@ -694,7 +684,7 @@ public class Parser //extends PHPParserSuperclass } } forStatement(); - return; + return statement; } else if (token == TokenNamewhile) { getNextToken(); if (token == TokenNameLPAREN) { @@ -709,7 +699,7 @@ public class Parser //extends PHPParserSuperclass throwSyntaxError("')' expected after 'while' condition."); } whileStatement(); - return; + return statement; } else if (token == TokenNamedo) { getNextToken(); if (token == TokenNameLBRACE) { @@ -749,7 +739,7 @@ public class Parser //extends PHPParserSuperclass } getNextToken(); } - return; + return statement; } else if (token == TokenNameforeach) { getNextToken(); if (token == TokenNameLPAREN) { @@ -776,7 +766,7 @@ public class Parser //extends PHPParserSuperclass throwSyntaxError("')' expected after 'foreach' expression."); } foreachStatement(); - return; + return statement; } else if (token == TokenNamecontinue || token == TokenNamebreak || token == TokenNamereturn) { getNextToken(); if (token != TokenNameSEMICOLON) { @@ -790,7 +780,7 @@ public class Parser //extends PHPParserSuperclass } getNextToken(); } - return; + return statement; } else if (token == TokenNameecho) { getNextToken(); expressionList(); @@ -802,10 +792,10 @@ public class Parser //extends PHPParserSuperclass } getNextToken(); } - return; + return statement; } else if (token == TokenNameINLINE_HTML) { getNextToken(); - return; + return statement; // } else if (token == TokenNameprint) { // getNextToken(); // expression(); @@ -829,7 +819,7 @@ public class Parser //extends PHPParserSuperclass } getNextToken(); } - return; + return statement; } else if (token == TokenNamestatic) { getNextToken(); static_var_list(); @@ -841,7 +831,7 @@ public class Parser //extends PHPParserSuperclass } getNextToken(); } - return; + return statement; } else if (token == TokenNameunset) { getNextToken(); if (token == TokenNameLPAREN) { @@ -863,14 +853,14 @@ public class Parser //extends PHPParserSuperclass } getNextToken(); } - return; + return statement; } else if (token == TokenNamefunction) { MethodDeclaration methodDecl = new MethodDeclaration(this.compilationUnit.compilationResult); methodDecl.declarationSourceStart = scanner.getCurrentTokenStartPosition(); methodDecl.modifiers = AccDefault; getNextToken(); functionDefinition(methodDecl); - return; + return statement; } else if (token == TokenNametry) { getNextToken(); if (token != TokenNameLBRACE) { @@ -882,7 +872,7 @@ public class Parser //extends PHPParserSuperclass throwSyntaxError("'}' expected in 'try' statement."); } getNextToken(); - return; + return statement; } else if (token == TokenNamecatch) { getNextToken(); if (token != TokenNameLPAREN) { @@ -910,7 +900,7 @@ public class Parser //extends PHPParserSuperclass } getNextToken(); additional_catches(); - return; + return statement; } else if (token == TokenNamethrow) { getNextToken(); expr(); @@ -919,12 +909,12 @@ public class Parser //extends PHPParserSuperclass } else { throwSyntaxError("';' expected after 'throw' exxpression."); } - return; + return statement; } else if (token == TokenNamefinal || token == TokenNameabstract || token == TokenNameclass || token == TokenNameinterface) { TypeDeclaration typeDecl = new TypeDeclaration(this.compilationUnit.compilationResult); typeDecl.declarationSourceStart = scanner.getCurrentTokenStartPosition(); typeDecl.declarationSourceEnd = scanner.getCurrentTokenEndPosition(); - typeDecl.name = new char[]{' '}; + typeDecl.name = new char[] { ' ' }; // default super class typeDecl.superclass = new SingleTypeReference(TypeConstants.OBJECT, 0); compilationUnit.types.add(typeDecl); @@ -936,7 +926,7 @@ public class Parser //extends PHPParserSuperclass astPtr--; astLengthPtr--; } - return; + return statement; // } else { // throwSyntaxError("Unexpected keyword '" + keyword + "'"); } else if (token == TokenNameLBRACE) { @@ -946,7 +936,7 @@ public class Parser //extends PHPParserSuperclass } if (token == TokenNameRBRACE) { getNextToken(); - return; + return statement; } else { throwSyntaxError("'}' expected."); } @@ -956,7 +946,7 @@ public class Parser //extends PHPParserSuperclass } if (token == TokenNameSEMICOLON) { getNextToken(); - return; + return statement; } else { if (token != TokenNameINLINE_HTML && token != TokenNameEOF) { throwSyntaxError("';' expected after expression (Found token: " + scanner.toStringAction(token) + ")"); @@ -964,7 +954,10 @@ public class Parser //extends PHPParserSuperclass getNextToken(); } } + // may be null + return statement; } + private void additional_catches() { while (token == TokenNamecatch) { getNextToken(); @@ -992,6 +985,7 @@ public class Parser //extends PHPParserSuperclass getNextToken(); } } + private void foreach_variable() { // w_variable //| '&' w_variable @@ -1000,6 +994,7 @@ public class Parser //extends PHPParserSuperclass } w_variable(); } + private void foreach_optional_arg() { // /* empty */ //| T_DOUBLE_ARROW foreach_variable @@ -1008,6 +1003,7 @@ public class Parser //extends PHPParserSuperclass foreach_variable(); } } + private void global_var_list() { // global_var_list: // global_var_list ',' global_var @@ -1020,6 +1016,7 @@ public class Parser //extends PHPParserSuperclass getNextToken(); } } + private void global_var() { //global_var: // T_VARIABLE @@ -1041,6 +1038,7 @@ public class Parser //extends PHPParserSuperclass } } } + private void static_var_list() { //static_var_list: // static_var_list ',' T_VARIABLE @@ -1063,6 +1061,7 @@ public class Parser //extends PHPParserSuperclass } } } + private void unset_variables() { // unset_variables: // unset_variable @@ -1077,15 +1076,18 @@ public class Parser //extends PHPParserSuperclass getNextToken(); } } + private final void initializeModifiers() { this.modifiers = 0; this.modifiersSourceStart = -1; } + private final void checkAndSetModifiers(int flag) { this.modifiers |= flag; if (this.modifiersSourceStart < 0) this.modifiersSourceStart = this.scanner.startPosition; } + private void unticked_class_declaration_statement(TypeDeclaration typeDecl) { initializeModifiers(); if (token == TokenNameinterface) { @@ -1100,15 +1102,15 @@ public class Parser //extends PHPParserSuperclass if (token == TokenNameIdentifier || token > TokenNameKEYWORD) { typeDecl.name = scanner.getCurrentIdentifierSource(); if (token > TokenNameKEYWORD) { - problemReporter.phpKeywordWarning(new String[]{scanner.toStringAction(token)}, scanner.getCurrentTokenStartPosition(), scanner.getCurrentTokenEndPosition(), - referenceContext, compilationUnit.compilationResult); -// throwSyntaxError("Don't use a keyword for interface declaration [" + scanner.toStringAction(token) + "].", -// typeDecl.sourceStart, typeDecl.sourceEnd); + problemReporter.phpKeywordWarning(new String[] { scanner.toStringAction(token) }, scanner.getCurrentTokenStartPosition(), + scanner.getCurrentTokenEndPosition(), referenceContext, compilationUnit.compilationResult); + // throwSyntaxError("Don't use a keyword for interface declaration [" + scanner.toStringAction(token) + "].", + // typeDecl.sourceStart, typeDecl.sourceEnd); } getNextToken(); interface_extends_list(); } else { - typeDecl.name = new char[]{' '}; + typeDecl.name = new char[] { ' ' }; throwSyntaxError("Interface name expected after keyword 'interface'.", typeDecl.sourceStart, typeDecl.sourceEnd); return; } @@ -1125,10 +1127,10 @@ public class Parser //extends PHPParserSuperclass if (token == TokenNameIdentifier || token > TokenNameKEYWORD) { typeDecl.name = scanner.getCurrentIdentifierSource(); if (token > TokenNameKEYWORD) { - problemReporter.phpKeywordWarning(new String[]{scanner.toStringAction(token)}, scanner.getCurrentTokenStartPosition(), scanner.getCurrentTokenEndPosition(), - referenceContext, compilationUnit.compilationResult); -// throwSyntaxError("Don't use a keyword for class declaration [" + scanner.toStringAction(token) + "].", -// typeDecl.sourceStart, typeDecl.sourceEnd); + problemReporter.phpKeywordWarning(new String[] { scanner.toStringAction(token) }, scanner.getCurrentTokenStartPosition(), + scanner.getCurrentTokenEndPosition(), referenceContext, compilationUnit.compilationResult); + // throwSyntaxError("Don't use a keyword for class declaration [" + scanner.toStringAction(token) + "].", + // typeDecl.sourceStart, typeDecl.sourceEnd); } getNextToken(); // extends_from: @@ -1146,7 +1148,7 @@ public class Parser //extends PHPParserSuperclass } implements_list(); } else { - typeDecl.name = new char[]{' '}; + typeDecl.name = new char[] { ' ' }; throwSyntaxError("Class name expected after keyword 'class'.", typeDecl.sourceStart, typeDecl.sourceEnd); return; } @@ -1172,6 +1174,7 @@ public class Parser //extends PHPParserSuperclass throwSyntaxError("'{' expected at start of class body."); } } + private void class_entry_type() { // T_CLASS // | T_ABSTRACT T_CLASS @@ -1196,6 +1199,7 @@ public class Parser //extends PHPParserSuperclass throwSyntaxError("Keyword 'class' 'final' or 'abstract' expected"); } } + private void interface_extends_list() { // /* empty */ // | T_EXTENDS interface_list @@ -1204,6 +1208,7 @@ public class Parser //extends PHPParserSuperclass interface_list(); } } + private void implements_list() { // /* empty */ // | T_IMPLEMENTS interface_list @@ -1212,6 +1217,7 @@ public class Parser //extends PHPParserSuperclass interface_list(); } } + private void interface_list() { // interface_list: // fully_qualified_class_name @@ -1228,6 +1234,7 @@ public class Parser //extends PHPParserSuperclass getNextToken(); } while (true); } + // private void classBody(TypeDeclaration typeDecl) { // //'{' [class-element-list] '}' // if (token == TokenNameLBRACE) { @@ -1252,6 +1259,7 @@ public class Parser //extends PHPParserSuperclass || token == TokenNameabstract || token == TokenNamefinal || token == TokenNamefunction || token == TokenNamevar || token == TokenNameconst); } + private void class_statement(ArrayList list) { // class_statement: // variable_modifiers class_variable_declaration ';' @@ -1260,7 +1268,7 @@ public class Parser //extends PHPParserSuperclass // '(' parameter_list ')' method_body initializeModifiers(); int declarationSourceStart = scanner.getCurrentTokenStartPosition(); - + if (token == TokenNamevar) { checkAndSetModifiers(AccPublic); problemReporter.phpVarDeprecatedWarning(scanner.getCurrentTokenStartPosition(), scanner.getCurrentTokenEndPosition(), @@ -1268,7 +1276,7 @@ public class Parser //extends PHPParserSuperclass getNextToken(); class_variable_declaration(declarationSourceStart, list); } else if (token == TokenNameconst) { - checkAndSetModifiers(AccFinal|AccPublic); + checkAndSetModifiers(AccFinal | AccPublic); class_constant_declaration(declarationSourceStart, list); if (token != TokenNameSEMICOLON) { throwSyntaxError("';' expected after class const declaration."); @@ -1293,6 +1301,7 @@ public class Parser //extends PHPParserSuperclass } } } + private void class_constant_declaration(int declarationSourceStart, ArrayList list) { // class_constant_declaration ',' T_STRING '=' static_scalar // | T_CONST T_STRING '=' static_scalar @@ -1325,6 +1334,7 @@ public class Parser //extends PHPParserSuperclass getNextToken(); } } + // private void variable_modifiers() { // // variable_modifiers: // // non_empty_member_modifiers @@ -1394,6 +1404,7 @@ public class Parser //extends PHPParserSuperclass } return foundToken; } + private void class_variable_declaration(int declarationSourceStart, ArrayList list) { // class_variable_declaration: // class_variable_declaration ',' T_VARIABLE @@ -1404,9 +1415,9 @@ public class Parser //extends PHPParserSuperclass do { if (token == TokenNameVariable) { classVariable = scanner.getCurrentIdentifierSource(); - // indexManager.addIdentifierInformation('v', classVariable, buf, -1, -1); - FieldDeclaration fieldDeclaration = new FieldDeclaration(classVariable, scanner - .getCurrentTokenStartPosition(), scanner.getCurrentTokenEndPosition()); + // indexManager.addIdentifierInformation('v', classVariable, buf, -1, -1); + FieldDeclaration fieldDeclaration = new FieldDeclaration(classVariable, scanner.getCurrentTokenStartPosition(), scanner + .getCurrentTokenEndPosition()); fieldDeclaration.modifiers = this.modifiers; fieldDeclaration.declarationSourceStart = declarationSourceStart; fieldDeclaration.declarationSourceEnd = scanner.getCurrentTokenEndPosition(); @@ -1435,6 +1446,7 @@ public class Parser //extends PHPParserSuperclass } getNextToken(); } + private void functionDefinition(MethodDeclaration methodDecl) { boolean isAbstract = false; if (astPtr == 0) { @@ -1444,7 +1456,7 @@ public class Parser //extends PHPParserSuperclass if (node instanceof TypeDeclaration) { TypeDeclaration typeDecl = ((TypeDeclaration) node); if (typeDecl.methods == null) { - typeDecl.methods = new AbstractMethodDeclaration[]{methodDecl}; + typeDecl.methods = new AbstractMethodDeclaration[] { methodDecl }; } else { AbstractMethodDeclaration[] newMethods; System.arraycopy(typeDecl.methods, 0, newMethods = new AbstractMethodDeclaration[typeDecl.methods.length + 1], 1, @@ -1469,6 +1481,7 @@ public class Parser //extends PHPParserSuperclass } functionBody(methodDecl); } + private void functionDeclarator(MethodDeclaration methodDecl) { //identifier '(' [parameter-list] ')' if (token == TokenNameAND) { @@ -1479,10 +1492,10 @@ public class Parser //extends PHPParserSuperclass if (Scanner.isIdentifierOrKeyword(token)) { methodDecl.selector = scanner.getCurrentIdentifierSource(); if (token > TokenNameKEYWORD) { - problemReporter.phpKeywordWarning(new String[]{scanner.toStringAction(token)}, scanner.getCurrentTokenStartPosition(), scanner.getCurrentTokenEndPosition(), - referenceContext, compilationUnit.compilationResult); -// reportSyntaxWarning("Don't use keyword for function declaration [" + scanner.toStringAction(token) + "].", -// scanner.getCurrentTokenStartPosition(), scanner.getCurrentTokenEndPosition()); + problemReporter.phpKeywordWarning(new String[] { scanner.toStringAction(token) }, scanner.getCurrentTokenStartPosition(), + scanner.getCurrentTokenEndPosition(), referenceContext, compilationUnit.compilationResult); + // reportSyntaxWarning("Don't use keyword for function declaration [" + scanner.toStringAction(token) + "].", + // scanner.getCurrentTokenStartPosition(), scanner.getCurrentTokenEndPosition()); } getNextToken(); if (token == TokenNameLPAREN) { @@ -1491,7 +1504,7 @@ public class Parser //extends PHPParserSuperclass throwSyntaxError("'(' expected in function declaration."); } if (token != TokenNameRPAREN) { - parameter_list(); + parameter_list(); } if (token != TokenNameRPAREN) { throwSyntaxError("')' expected in function declaration."); @@ -1504,12 +1517,14 @@ public class Parser //extends PHPParserSuperclass throwSyntaxError("Function name expected after keyword 'function'."); } } + // private void parameter_list() { // non_empty_parameter_list // | /* empty */ non_empty_parameter_list(true); } + private void non_empty_parameter_list(boolean empty_allowed) { // optional_class_type T_VARIABLE // | optional_class_type '&' T_VARIABLE @@ -1549,10 +1564,12 @@ public class Parser //extends PHPParserSuperclass throwSyntaxError("Identifier expected in parameter list."); } } + private void optional_class_type() { // /* empty */ //| T_STRING } + private void parameterDeclaration() { //variable //variable-reference @@ -1578,6 +1595,7 @@ public class Parser //extends PHPParserSuperclass // declaration."); // } } + private void labeledStatementList() { if (token != TokenNamecase && token != TokenNamedefault) { throwSyntaxError("'case' or 'default' expected."); @@ -1619,7 +1637,7 @@ public class Parser //extends PHPParserSuperclass break; } if (token != TokenNamecase) { - statementList(); + statementList(); } } else { throwSyntaxError("':' character expected after 'default'."); @@ -1627,6 +1645,7 @@ public class Parser //extends PHPParserSuperclass } } while (token == TokenNamecase || token == TokenNamedefault); } + // public void labeledStatement() { // if (token == TokenNamecase) { // getNextToken(); @@ -1682,26 +1701,26 @@ public class Parser //extends PHPParserSuperclass if (token != TokenNameendif) { statementList(); switch (token) { - case TokenNameelse : + case TokenNameelse: + getNextToken(); + if (token == TokenNameCOLON) { getNextToken(); - if (token == TokenNameCOLON) { + if (token != TokenNameendif) { + statementList(); + } + } else { + if (token == TokenNameif) { //'else if' getNextToken(); - if (token != TokenNameendif) { - statementList(); - } + elseifStatementList(); } else { - if (token == TokenNameif) { //'else if' - getNextToken(); - elseifStatementList(); - } else { - throwSyntaxError("':' expected after 'else'."); - } + throwSyntaxError("':' expected after 'else'."); } - break; - case TokenNameelseif : - getNextToken(); - elseifStatementList(); - break; + } + break; + case TokenNameelseif: + getNextToken(); + elseifStatementList(); + break; } } if (token != TokenNameendif) { @@ -1735,34 +1754,36 @@ public class Parser //extends PHPParserSuperclass } } } + private void elseifStatementList() { do { elseifStatement(); switch (token) { - case TokenNameelse : + case TokenNameelse: + getNextToken(); + if (token == TokenNameCOLON) { getNextToken(); - if (token == TokenNameCOLON) { + if (token != TokenNameendif) { + statementList(); + } + return; + } else { + if (token == TokenNameif) { //'else if' getNextToken(); - if (token != TokenNameendif) { - statementList(); - } - return; } else { - if (token == TokenNameif) { //'else if' - getNextToken(); - } else { - throwSyntaxError("':' expected after 'else'."); - } + throwSyntaxError("':' expected after 'else'."); } - break; - case TokenNameelseif : - getNextToken(); - break; - default : - return; + } + break; + case TokenNameelseif: + getNextToken(); + break; + default: + return; } } while (true); } + private void elseifStatement() { if (token == TokenNameLPAREN) { getNextToken(); @@ -1780,6 +1801,7 @@ public class Parser //extends PHPParserSuperclass } } } + private void switchStatement() { if (token == TokenNameCOLON) { // ':' [labeled-statement-list] 'endswitch' ';' @@ -1808,6 +1830,7 @@ public class Parser //extends PHPParserSuperclass getNextToken(); } } + private void forStatement() { if (token == TokenNameCOLON) { getNextToken(); @@ -1824,6 +1847,7 @@ public class Parser //extends PHPParserSuperclass statement(TokenNameEOF); } } + private void whileStatement() { // ':' statement-list 'endwhile' ';' if (token == TokenNameCOLON) { @@ -1841,6 +1865,7 @@ public class Parser //extends PHPParserSuperclass statement(TokenNameEOF); } } + private void foreachStatement() { if (token == TokenNameCOLON) { getNextToken(); @@ -1857,6 +1882,7 @@ public class Parser //extends PHPParserSuperclass statement(TokenNameEOF); } } + // private void exitStatus() { // if (token == TokenNameLPAREN) { // getNextToken(); @@ -1882,17 +1908,23 @@ public class Parser //extends PHPParserSuperclass } } while (true); } - private void expr() { + + private Expression expr() { // r_variable // | expr_without_variable // if (token!=TokenNameEOF) { if (Scanner.TRACE) { System.out.println("TRACE: expr()"); } - expr_without_variable(true); + return expr_without_variable(true); // } } - private void expr_without_variable(boolean only_variable) { + + private Expression expr_without_variable(boolean only_variable) { + Expression expression = new Expression(); + expression.sourceStart = scanner.getCurrentTokenStartPosition(); + // default, may be overwritten + expression.sourceEnd = scanner.getCurrentTokenEndPosition(); // internal_functions_in_yacc // | T_CLONE expr // | T_PRINT expr @@ -1963,255 +1995,255 @@ public class Parser //extends PHPParserSuperclass System.out.println("TRACE: expr_without_variable() PART 1"); } switch (token) { - case TokenNameisset : - case TokenNameempty : - case TokenNameeval : - case TokenNameinclude : - case TokenNameinclude_once : - case TokenNamerequire : - case TokenNamerequire_once : - internal_functions_in_yacc(); - break; - // | '(' expr ')' - case TokenNameLPAREN : + case TokenNameisset: + case TokenNameempty: + case TokenNameeval: + case TokenNameinclude: + case TokenNameinclude_once: + case TokenNamerequire: + case TokenNamerequire_once: + internal_functions_in_yacc(); + break; + // | '(' expr ')' + case TokenNameLPAREN: + getNextToken(); + expr(); + if (token == TokenNameRPAREN) { getNextToken(); - expr(); - if (token == TokenNameRPAREN) { - getNextToken(); + } else { + throwSyntaxError("')' expected in expression."); + } + break; + // | T_CLONE expr + // | T_PRINT expr + // | '@' expr + // | '+' expr + // | '-' expr + // | '!' expr + // | '~' expr + // | T_INT_CAST expr + // | T_DOUBLE_CAST expr + // | T_STRING_CAST expr + // | T_ARRAY_CAST expr + // | T_OBJECT_CAST expr + // | T_BOOL_CAST expr + // | T_UNSET_CAST expr + case TokenNameclone: + case TokenNameprint: + case TokenNameAT: + case TokenNamePLUS: + case TokenNameMINUS: + case TokenNameNOT: + case TokenNameTWIDDLE: + case TokenNameintCAST: + case TokenNamedoubleCAST: + case TokenNamestringCAST: + case TokenNamearrayCAST: + case TokenNameobjectCAST: + case TokenNameboolCAST: + case TokenNameunsetCAST: + getNextToken(); + expr(); + break; + case TokenNameexit: + getNextToken(); + exit_expr(); + break; + // scalar: + // T_STRING + //| T_STRING_VARNAME + //| class_constant + //| T_START_HEREDOC encaps_list T_END_HEREDOC + // | '`' encaps_list '`' + // | common_scalar + // | '`' encaps_list '`' + case TokenNameEncapsedString0: + scanner.encapsedStringStack.push(new Character('`')); + getNextToken(); + try { + if (token == TokenNameEncapsedString0) { } else { - throwSyntaxError("')' expected in expression."); + encaps_list(); + if (token != TokenNameEncapsedString0) { + throwSyntaxError("\'`\' expected at end of string" + "(Found token: " + scanner.toStringAction(token) + " )"); + } } - break; - // | T_CLONE expr - // | T_PRINT expr - // | '@' expr - // | '+' expr - // | '-' expr - // | '!' expr - // | '~' expr - // | T_INT_CAST expr - // | T_DOUBLE_CAST expr - // | T_STRING_CAST expr - // | T_ARRAY_CAST expr - // | T_OBJECT_CAST expr - // | T_BOOL_CAST expr - // | T_UNSET_CAST expr - case TokenNameclone : - case TokenNameprint : - case TokenNameAT : - case TokenNamePLUS : - case TokenNameMINUS : - case TokenNameNOT : - case TokenNameTWIDDLE : - case TokenNameintCAST : - case TokenNamedoubleCAST : - case TokenNamestringCAST : - case TokenNamearrayCAST : - case TokenNameobjectCAST : - case TokenNameboolCAST : - case TokenNameunsetCAST : - getNextToken(); - expr(); - break; - case TokenNameexit : - getNextToken(); - exit_expr(); - break; - // scalar: - // T_STRING - //| T_STRING_VARNAME - //| class_constant - //| T_START_HEREDOC encaps_list T_END_HEREDOC - // | '`' encaps_list '`' - // | common_scalar - // | '`' encaps_list '`' - case TokenNameEncapsedString0 : - scanner.encapsedStringStack.push(new Character('`')); + } finally { + scanner.encapsedStringStack.pop(); getNextToken(); - try { - if (token == TokenNameEncapsedString0) { - } else { - encaps_list(); - if (token != TokenNameEncapsedString0) { - throwSyntaxError("\'`\' expected at end of string" + "(Found token: " + scanner.toStringAction(token) + " )"); - } + } + break; + // | '\'' encaps_list '\'' + case TokenNameEncapsedString1: + scanner.encapsedStringStack.push(new Character('\'')); + getNextToken(); + try { + if (token == TokenNameEncapsedString1) { + } else { + encaps_list(); + if (token != TokenNameEncapsedString1) { + throwSyntaxError("\'\'\' expected at end of string" + "(Found token: " + scanner.toStringAction(token) + " )"); } - } finally { - scanner.encapsedStringStack.pop(); - getNextToken(); } - break; - // | '\'' encaps_list '\'' - case TokenNameEncapsedString1 : - scanner.encapsedStringStack.push(new Character('\'')); + } finally { + scanner.encapsedStringStack.pop(); getNextToken(); - try { - if (token == TokenNameEncapsedString1) { - } else { - encaps_list(); - if (token != TokenNameEncapsedString1) { - throwSyntaxError("\'\'\' expected at end of string" + "(Found token: " + scanner.toStringAction(token) + " )"); - } + } + break; + //| '"' encaps_list '"' + case TokenNameEncapsedString2: + scanner.encapsedStringStack.push(new Character('"')); + getNextToken(); + try { + if (token == TokenNameEncapsedString2) { + } else { + encaps_list(); + if (token != TokenNameEncapsedString2) { + throwSyntaxError("'\"' expected at end of string" + "(Found token: " + scanner.toStringAction(token) + " )"); } - } finally { - scanner.encapsedStringStack.pop(); - getNextToken(); } - break; - //| '"' encaps_list '"' - case TokenNameEncapsedString2 : - scanner.encapsedStringStack.push(new Character('"')); + } finally { + scanner.encapsedStringStack.pop(); + getNextToken(); + } + break; + case TokenNameIntegerLiteral: + case TokenNameDoubleLiteral: + case TokenNameStringDoubleQuote: + case TokenNameStringSingleQuote: + case TokenNameStringInterpolated: + case TokenNameFILE: + case TokenNameLINE: + case TokenNameCLASS_C: + case TokenNameMETHOD_C: + case TokenNameFUNC_C: + common_scalar(); + break; + case TokenNameHEREDOC: + getNextToken(); + break; + case TokenNamearray: + // T_ARRAY '(' array_pair_list ')' + getNextToken(); + if (token == TokenNameLPAREN) { getNextToken(); - try { - if (token == TokenNameEncapsedString2) { - } else { - encaps_list(); - if (token != TokenNameEncapsedString2) { - throwSyntaxError("'\"' expected at end of string" + "(Found token: " + scanner.toStringAction(token) + " )"); - } - } - } finally { - scanner.encapsedStringStack.pop(); + if (token == TokenNameRPAREN) { getNextToken(); + break; + } + array_pair_list(); + if (token != TokenNameRPAREN) { + throwSyntaxError("')' expected after keyword 'array'" + "(Found token: " + scanner.toStringAction(token) + ")"); } - break; - case TokenNameIntegerLiteral : - case TokenNameDoubleLiteral : - case TokenNameStringDoubleQuote : - case TokenNameStringSingleQuote : - case TokenNameStringInterpolated : - case TokenNameFILE : - case TokenNameLINE : - case TokenNameCLASS_C : - case TokenNameMETHOD_C : - case TokenNameFUNC_C : - common_scalar(); - break; - case TokenNameHEREDOC : getNextToken(); - break; - case TokenNamearray : - // T_ARRAY '(' array_pair_list ')' + } else { + throwSyntaxError("'(' expected after keyword 'array'" + "(Found token: " + scanner.toStringAction(token) + ")"); + } + break; + case TokenNamelist: + // | T_LIST '(' assignment_list ')' '=' expr + getNextToken(); + if (token == TokenNameLPAREN) { getNextToken(); - if (token == TokenNameLPAREN) { - getNextToken(); - if (token == TokenNameRPAREN) { - getNextToken(); - break; - } - array_pair_list(); - if (token != TokenNameRPAREN) { - throwSyntaxError("')' expected after keyword 'array'" + "(Found token: " + scanner.toStringAction(token) + ")"); - } - getNextToken(); - } else { - throwSyntaxError("'(' expected after keyword 'array'" + "(Found token: " + scanner.toStringAction(token) + ")"); + assignment_list(); + if (token != TokenNameRPAREN) { + throwSyntaxError("')' expected after 'list' keyword."); } - break; - case TokenNamelist : - // | T_LIST '(' assignment_list ')' '=' expr getNextToken(); - if (token == TokenNameLPAREN) { + if (token != TokenNameEQUAL) { + throwSyntaxError("'=' expected after 'list' keyword."); + } getNextToken(); - assignment_list(); - if (token != TokenNameRPAREN) { - throwSyntaxError("')' expected after 'list' keyword."); - } + expr(); + } else { + throwSyntaxError("'(' expected after 'list' keyword."); + } + break; + case TokenNamenew: + // | T_NEW class_name_reference ctor_arguments + getNextToken(); + class_name_reference(); + ctor_arguments(); + break; + // | T_INC rw_variable + // | T_DEC rw_variable + case TokenNamePLUS_PLUS: + case TokenNameMINUS_MINUS: + getNextToken(); + rw_variable(); + break; + // | variable '=' expr + // | variable '=' '&' variable + // | variable '=' '&' T_NEW class_name_reference ctor_arguments + // | variable T_PLUS_EQUAL expr + // | variable T_MINUS_EQUAL expr + // | variable T_MUL_EQUAL expr + // | variable T_DIV_EQUAL expr + // | variable T_CONCAT_EQUAL expr + // | variable T_MOD_EQUAL expr + // | variable T_AND_EQUAL expr + // | variable T_OR_EQUAL expr + // | variable T_XOR_EQUAL expr + // | variable T_SL_EQUAL expr + // | variable T_SR_EQUAL expr + // | rw_variable T_INC + // | rw_variable T_DEC + case TokenNameIdentifier: + case TokenNameVariable: + case TokenNameDOLLAR: + variable(); + switch (token) { + case TokenNameEQUAL: + getNextToken(); + if (token == TokenNameAND) { getNextToken(); - if (token != TokenNameEQUAL) { - throwSyntaxError("'=' expected after 'list' keyword."); + if (token == TokenNamenew) { + // | variable '=' '&' T_NEW class_name_reference + // ctor_arguments + getNextToken(); + class_name_reference(); + ctor_arguments(); + } else { + variable(); } - getNextToken(); - expr(); } else { - throwSyntaxError("'(' expected after 'list' keyword."); + expr(); } break; - case TokenNamenew : - // | T_NEW class_name_reference ctor_arguments - getNextToken(); - class_name_reference(); - ctor_arguments(); + case TokenNamePLUS_EQUAL: + case TokenNameMINUS_EQUAL: + case TokenNameMULTIPLY_EQUAL: + case TokenNameDIVIDE_EQUAL: + case TokenNameDOT_EQUAL: + case TokenNameREMAINDER_EQUAL: + case TokenNameAND_EQUAL: + case TokenNameOR_EQUAL: + case TokenNameXOR_EQUAL: + case TokenNameRIGHT_SHIFT_EQUAL: + case TokenNameLEFT_SHIFT_EQUAL: + getNextToken(); + expr(); break; - // | T_INC rw_variable - // | T_DEC rw_variable - case TokenNamePLUS_PLUS : - case TokenNameMINUS_MINUS : + case TokenNamePLUS_PLUS: + case TokenNameMINUS_MINUS: getNextToken(); - rw_variable(); break; - // | variable '=' expr - // | variable '=' '&' variable - // | variable '=' '&' T_NEW class_name_reference ctor_arguments - // | variable T_PLUS_EQUAL expr - // | variable T_MINUS_EQUAL expr - // | variable T_MUL_EQUAL expr - // | variable T_DIV_EQUAL expr - // | variable T_CONCAT_EQUAL expr - // | variable T_MOD_EQUAL expr - // | variable T_AND_EQUAL expr - // | variable T_OR_EQUAL expr - // | variable T_XOR_EQUAL expr - // | variable T_SL_EQUAL expr - // | variable T_SR_EQUAL expr - // | rw_variable T_INC - // | rw_variable T_DEC - case TokenNameIdentifier : - case TokenNameVariable : - case TokenNameDOLLAR : - variable(); - switch (token) { - case TokenNameEQUAL : - getNextToken(); - if (token == TokenNameAND) { - getNextToken(); - if (token == TokenNamenew) { - // | variable '=' '&' T_NEW class_name_reference - // ctor_arguments - getNextToken(); - class_name_reference(); - ctor_arguments(); - } else { - variable(); - } - } else { - expr(); - } - break; - case TokenNamePLUS_EQUAL : - case TokenNameMINUS_EQUAL : - case TokenNameMULTIPLY_EQUAL : - case TokenNameDIVIDE_EQUAL : - case TokenNameDOT_EQUAL : - case TokenNameREMAINDER_EQUAL : - case TokenNameAND_EQUAL : - case TokenNameOR_EQUAL : - case TokenNameXOR_EQUAL : - case TokenNameRIGHT_SHIFT_EQUAL : - case TokenNameLEFT_SHIFT_EQUAL : - getNextToken(); - expr(); - break; - case TokenNamePLUS_PLUS : - case TokenNameMINUS_MINUS : - getNextToken(); - break; - default : - if (!only_variable) { - throwSyntaxError("Variable expression not allowed (found token '" + scanner.toStringAction(token) + "')."); - } + default: + if (!only_variable) { + throwSyntaxError("Variable expression not allowed (found token '" + scanner.toStringAction(token) + "')."); } - break; - default : - if (token != TokenNameINLINE_HTML) { - if (token > TokenNameKEYWORD) { - getNextToken(); - break; - } else { - throwSyntaxError("Error in expression (found token '" + scanner.toStringAction(token) + "')."); - } + } + break; + default: + if (token != TokenNameINLINE_HTML) { + if (token > TokenNameKEYWORD) { + getNextToken(); + break; + } else { + throwSyntaxError("Error in expression (found token '" + scanner.toStringAction(token) + "')."); } - return; + } + return expression; } if (Scanner.TRACE) { System.out.println("TRACE: expr_without_variable() PART 2"); @@ -2242,52 +2274,53 @@ public class Parser //extends PHPParserSuperclass // | expr T_IS_GREATER_OR_EQUAL expr while (true) { switch (token) { - case TokenNameOR_OR : - case TokenNameAND_AND : - case TokenNameand : - case TokenNameor : - case TokenNamexor : - case TokenNameAND : - case TokenNameOR : - case TokenNameXOR : - case TokenNameDOT : - case TokenNamePLUS : - case TokenNameMINUS : - case TokenNameMULTIPLY : - case TokenNameDIVIDE : - case TokenNameREMAINDER : - case TokenNameLEFT_SHIFT : - case TokenNameRIGHT_SHIFT : - case TokenNameEQUAL_EQUAL_EQUAL : - case TokenNameNOT_EQUAL_EQUAL : - case TokenNameEQUAL_EQUAL : - case TokenNameNOT_EQUAL : - case TokenNameLESS : - case TokenNameLESS_EQUAL : - case TokenNameGREATER : - case TokenNameGREATER_EQUAL : + case TokenNameOR_OR: + case TokenNameAND_AND: + case TokenNameand: + case TokenNameor: + case TokenNamexor: + case TokenNameAND: + case TokenNameOR: + case TokenNameXOR: + case TokenNameDOT: + case TokenNamePLUS: + case TokenNameMINUS: + case TokenNameMULTIPLY: + case TokenNameDIVIDE: + case TokenNameREMAINDER: + case TokenNameLEFT_SHIFT: + case TokenNameRIGHT_SHIFT: + case TokenNameEQUAL_EQUAL_EQUAL: + case TokenNameNOT_EQUAL_EQUAL: + case TokenNameEQUAL_EQUAL: + case TokenNameNOT_EQUAL: + case TokenNameLESS: + case TokenNameLESS_EQUAL: + case TokenNameGREATER: + case TokenNameGREATER_EQUAL: getNextToken(); expr(); - break; - // | expr T_INSTANCEOF class_name_reference - // | expr '?' expr ':' expr - case TokenNameinstanceof : + break; + // | expr T_INSTANCEOF class_name_reference + // | expr '?' expr ':' expr + case TokenNameinstanceof: + getNextToken(); + class_name_reference(); + break; + case TokenNameQUESTION: getNextToken(); - class_name_reference(); - break; - case TokenNameQUESTION : + expr(); + if (token == TokenNameCOLON) { getNextToken(); expr(); - if (token == TokenNameCOLON) { - getNextToken(); - expr(); - } - break; - default : - return; + } + break; + default: + return expression; } } } + private void class_name_reference() { // class_name_reference: // T_STRING @@ -2301,6 +2334,7 @@ public class Parser //extends PHPParserSuperclass dynamic_class_name_reference(); } } + private void dynamic_class_name_reference() { //dynamic_class_name_reference: // base_variable T_OBJECT_OPERATOR object_property @@ -2316,6 +2350,7 @@ public class Parser //extends PHPParserSuperclass dynamic_class_name_variable_properties(); } } + private void dynamic_class_name_variable_properties() { // dynamic_class_name_variable_properties: // dynamic_class_name_variable_properties @@ -2328,6 +2363,7 @@ public class Parser //extends PHPParserSuperclass dynamic_class_name_variable_property(); } } + private void dynamic_class_name_variable_property() { // dynamic_class_name_variable_property: // T_OBJECT_OPERATOR object_property @@ -2339,6 +2375,7 @@ public class Parser //extends PHPParserSuperclass object_property(); } } + private void ctor_arguments() { // ctor_arguments: // /* empty */ @@ -2356,6 +2393,7 @@ public class Parser //extends PHPParserSuperclass getNextToken(); } } + private void assignment_list() { // assignment_list: // assignment_list ',' assignment_list_element @@ -2368,6 +2406,7 @@ public class Parser //extends PHPParserSuperclass getNextToken(); } } + private void assignment_list_element() { //assignment_list_element: // variable @@ -2391,6 +2430,7 @@ public class Parser //extends PHPParserSuperclass } } } + private void array_pair_list() { // array_pair_list: // /* empty */ @@ -2400,6 +2440,7 @@ public class Parser //extends PHPParserSuperclass getNextToken(); } } + private void non_empty_array_pair_list() { //non_empty_array_pair_list: // non_empty_array_pair_list ',' expr T_DOUBLE_ARROW expr @@ -2438,6 +2479,7 @@ public class Parser //extends PHPParserSuperclass } } } + // private void variableList() { // do { // variable(); @@ -2460,6 +2502,7 @@ public class Parser //extends PHPParserSuperclass } reference_variable(); } + private void function_call() { // function_call: // T_STRING '(' function_call_parameter_list ')' @@ -2468,8 +2511,8 @@ public class Parser //extends PHPParserSuperclass //| variable_without_objects '(' function_call_parameter_list ')' char[] defineName = null; char[] ident = null; - int startPos=0; - int endPos=0; + int startPos = 0; + int endPos = 0; if (Scanner.TRACE) { System.out.println("TRACE: function_call()"); } @@ -2480,57 +2523,44 @@ public class Parser //extends PHPParserSuperclass endPos = scanner.getCurrentTokenEndPosition(); getNextToken(); switch (token) { - case TokenNamePAAMAYIM_NEKUDOTAYIM : - // static member: - defineName = null; + case TokenNamePAAMAYIM_NEKUDOTAYIM: + // static member: + defineName = null; + getNextToken(); + if (token == TokenNameIdentifier) { + // class _constant getNextToken(); - if (token == TokenNameIdentifier) { - // class _constant - getNextToken(); - } else { - // static member: - variable_without_objects(); - } - break; + } else { + // static member: + variable_without_objects(); + } + break; } } else { variable_without_objects(); } if (token != TokenNameLPAREN) { - if (defineName!=null) { + if (defineName != null) { // does this identifier contain only uppercase characters? - if (defineName.length==3) { - if (defineName[0]=='d' && - defineName[1]=='i' && - defineName[2]=='e' ) { - defineName=null; - } - } else if (defineName.length==4) { - if (defineName[0]=='t' && - defineName[1]=='r' && - defineName[2]=='u' && - defineName[3]=='e' ) { - defineName=null; - } else if (defineName[0]=='n' && - defineName[1]=='u' && - defineName[2]=='l' && - defineName[3]=='l' ) { - defineName=null; + if (defineName.length == 3) { + if (defineName[0] == 'd' && defineName[1] == 'i' && defineName[2] == 'e') { + defineName = null; + } + } else if (defineName.length == 4) { + if (defineName[0] == 't' && defineName[1] == 'r' && defineName[2] == 'u' && defineName[3] == 'e') { + defineName = null; + } else if (defineName[0] == 'n' && defineName[1] == 'u' && defineName[2] == 'l' && defineName[3] == 'l') { + defineName = null; } - } else if (defineName.length==5) { - if (defineName[0]=='f' && - defineName[1]=='a' && - defineName[2]=='l' && - defineName[3]=='s' && - defineName[4]=='e' ) { - defineName=null; + } else if (defineName.length == 5) { + if (defineName[0] == 'f' && defineName[1] == 'a' && defineName[2] == 'l' && defineName[3] == 's' && defineName[4] == 'e') { + defineName = null; } } - if (defineName!=null) { - for (int i=0; i' expected in variable_property."); } } + private void method_or_not() { // method_or_not: // '(' function_call_parameter_list ')' @@ -2885,6 +2932,7 @@ public class Parser //extends PHPParserSuperclass getNextToken(); } } + private void exit_expr() { // /* empty */ // | '(' ')' @@ -2903,6 +2951,7 @@ public class Parser //extends PHPParserSuperclass } getNextToken(); } + private void encaps_list() { // encaps_list encaps_var // | encaps_list T_STRING @@ -2918,64 +2967,65 @@ public class Parser //extends PHPParserSuperclass // | /* empty */ while (true) { switch (token) { - case TokenNameSTRING : - getNextToken(); - break; - case TokenNameLBRACE : - // scanner.encapsedStringStack.pop(); - getNextToken(); - break; - case TokenNameRBRACE : - // scanner.encapsedStringStack.pop(); - getNextToken(); - break; - case TokenNameLBRACKET : - // scanner.encapsedStringStack.pop(); - getNextToken(); - break; - case TokenNameRBRACKET : - // scanner.encapsedStringStack.pop(); - getNextToken(); - break; - case TokenNameMINUS_GREATER : - // scanner.encapsedStringStack.pop(); - getNextToken(); - break; - case TokenNameVariable : - case TokenNameDOLLAR_LBRACE : - case TokenNameLBRACE_DOLLAR : - encaps_var(); - break; - default : - char encapsedChar = ((Character) scanner.encapsedStringStack.peek()).charValue(); - if (encapsedChar == '$') { - scanner.encapsedStringStack.pop(); - encapsedChar = ((Character) scanner.encapsedStringStack.peek()).charValue(); - switch (encapsedChar) { - case '`' : - if (token == TokenNameEncapsedString0) { - return; - } - token = TokenNameSTRING; - continue; - case '\'' : - if (token == TokenNameEncapsedString1) { - return; - } - token = TokenNameSTRING; - continue; - case '"' : - if (token == TokenNameEncapsedString2) { - return; - } - token = TokenNameSTRING; - continue; + case TokenNameSTRING: + getNextToken(); + break; + case TokenNameLBRACE: + // scanner.encapsedStringStack.pop(); + getNextToken(); + break; + case TokenNameRBRACE: + // scanner.encapsedStringStack.pop(); + getNextToken(); + break; + case TokenNameLBRACKET: + // scanner.encapsedStringStack.pop(); + getNextToken(); + break; + case TokenNameRBRACKET: + // scanner.encapsedStringStack.pop(); + getNextToken(); + break; + case TokenNameMINUS_GREATER: + // scanner.encapsedStringStack.pop(); + getNextToken(); + break; + case TokenNameVariable: + case TokenNameDOLLAR_LBRACE: + case TokenNameLBRACE_DOLLAR: + encaps_var(); + break; + default: + char encapsedChar = ((Character) scanner.encapsedStringStack.peek()).charValue(); + if (encapsedChar == '$') { + scanner.encapsedStringStack.pop(); + encapsedChar = ((Character) scanner.encapsedStringStack.peek()).charValue(); + switch (encapsedChar) { + case '`': + if (token == TokenNameEncapsedString0) { + return; } + token = TokenNameSTRING; + continue; + case '\'': + if (token == TokenNameEncapsedString1) { + return; + } + token = TokenNameSTRING; + continue; + case '"': + if (token == TokenNameEncapsedString2) { + return; + } + token = TokenNameSTRING; + continue; } - return; + } + return; } } } + private void encaps_var() { // T_VARIABLE // | T_VARIABLE '[' encaps_var_offset ']' @@ -2984,71 +3034,111 @@ public class Parser //extends PHPParserSuperclass // | T_DOLLAR_OPEN_CURLY_BRACES T_STRING_VARNAME '[' expr ']' '}' // | T_CURLY_OPEN variable '}' switch (token) { - case TokenNameVariable : + case TokenNameVariable: + getNextToken(); + if (token == TokenNameLBRACKET) { + getNextToken(); + expr(); //encaps_var_offset(); + if (token != TokenNameRBRACKET) { + throwSyntaxError("']' expected after variable."); + } + // scanner.encapsedStringStack.pop(); + getNextToken(); + // } + } else if (token == TokenNameMINUS_GREATER) { + getNextToken(); + if (token != TokenNameIdentifier) { + throwSyntaxError("Identifier expected after '->'."); + } + // scanner.encapsedStringStack.pop(); + getNextToken(); + } + // else { + // // scanner.encapsedStringStack.pop(); + // int tempToken = TokenNameSTRING; + // if (!scanner.encapsedStringStack.isEmpty() + // && (token == TokenNameEncapsedString0 + // || token == TokenNameEncapsedString1 + // || token == TokenNameEncapsedString2 || token == + // TokenNameERROR)) { + // char encapsedChar = ((Character) + // scanner.encapsedStringStack.peek()) + // .charValue(); + // switch (token) { + // case TokenNameEncapsedString0 : + // if (encapsedChar == '`') { + // tempToken = TokenNameEncapsedString0; + // } + // break; + // case TokenNameEncapsedString1 : + // if (encapsedChar == '\'') { + // tempToken = TokenNameEncapsedString1; + // } + // break; + // case TokenNameEncapsedString2 : + // if (encapsedChar == '"') { + // tempToken = TokenNameEncapsedString2; + // } + // break; + // case TokenNameERROR : + // if (scanner.source[scanner.currentPosition - 1] == '\\') { + // scanner.currentPosition--; + // getNextToken(); + // } + // break; + // } + // } + // token = tempToken; + // } + break; + case TokenNameDOLLAR_LBRACE: + getNextToken(); + if (token == TokenNameDOLLAR_LBRACE) { + encaps_var(); + } else if (token == TokenNameIdentifier) { getNextToken(); if (token == TokenNameLBRACKET) { getNextToken(); - // if (token == TokenNameRBRACKET) { - // getNextToken(); - // } else { - expr(); //encaps_var_offset(); + // if (token == TokenNameRBRACKET) { + // getNextToken(); + // } else { + expr(); if (token != TokenNameRBRACKET) { - throwSyntaxError("']' expected after variable."); + throwSyntaxError("']' expected after '${'."); } - // scanner.encapsedStringStack.pop(); getNextToken(); - // } - } else if (token == TokenNameMINUS_GREATER) { + // } + } + } else { + expr(); + } + if (token != TokenNameRBRACE) { + throwSyntaxError("'}' expected."); + } + getNextToken(); + break; + case TokenNameLBRACE_DOLLAR: + getNextToken(); + if (token == TokenNameLBRACE_DOLLAR) { + encaps_var(); + } else if (token == TokenNameIdentifier || token > TokenNameKEYWORD) { + getNextToken(); + if (token == TokenNameLBRACKET) { getNextToken(); - if (token != TokenNameIdentifier) { - throwSyntaxError("Identifier expected after '->'."); + // if (token == TokenNameRBRACKET) { + // getNextToken(); + // } else { + expr(); + if (token != TokenNameRBRACKET) { + throwSyntaxError("']' expected."); } - // scanner.encapsedStringStack.pop(); getNextToken(); - } - // else { - // // scanner.encapsedStringStack.pop(); - // int tempToken = TokenNameSTRING; - // if (!scanner.encapsedStringStack.isEmpty() - // && (token == TokenNameEncapsedString0 - // || token == TokenNameEncapsedString1 - // || token == TokenNameEncapsedString2 || token == - // TokenNameERROR)) { - // char encapsedChar = ((Character) - // scanner.encapsedStringStack.peek()) - // .charValue(); - // switch (token) { - // case TokenNameEncapsedString0 : - // if (encapsedChar == '`') { - // tempToken = TokenNameEncapsedString0; - // } - // break; - // case TokenNameEncapsedString1 : - // if (encapsedChar == '\'') { - // tempToken = TokenNameEncapsedString1; - // } - // break; - // case TokenNameEncapsedString2 : - // if (encapsedChar == '"') { - // tempToken = TokenNameEncapsedString2; - // } - // break; - // case TokenNameERROR : - // if (scanner.source[scanner.currentPosition - 1] == '\\') { - // scanner.currentPosition--; - // getNextToken(); - // } - // break; - // } - // } - // token = tempToken; - // } - break; - case TokenNameDOLLAR_LBRACE : - getNextToken(); - if (token == TokenNameDOLLAR_LBRACE) { - encaps_var(); - } else if (token == TokenNameIdentifier) { + // } + } else if (token == TokenNameMINUS_GREATER) { + getNextToken(); + if (token != TokenNameIdentifier && token != TokenNameVariable) { + throwSyntaxError("String or Variable token expected."); + } getNextToken(); if (token == TokenNameLBRACKET) { getNextToken(); @@ -3062,183 +3152,142 @@ public class Parser //extends PHPParserSuperclass getNextToken(); // } } - } else { - expr(); } + // if (token != TokenNameRBRACE) { + // throwSyntaxError("'}' expected after '{$'."); + // } + // // scanner.encapsedStringStack.pop(); + // getNextToken(); + } else { + expr(); if (token != TokenNameRBRACE) { throwSyntaxError("'}' expected."); } + // scanner.encapsedStringStack.pop(); getNextToken(); - break; - case TokenNameLBRACE_DOLLAR : - getNextToken(); - if (token == TokenNameLBRACE_DOLLAR) { - encaps_var(); - } else if (token == TokenNameIdentifier || token > TokenNameKEYWORD) { - getNextToken(); - if (token == TokenNameLBRACKET) { - getNextToken(); - // if (token == TokenNameRBRACKET) { - // getNextToken(); - // } else { - expr(); - if (token != TokenNameRBRACKET) { - throwSyntaxError("']' expected."); - } - getNextToken(); - // } - } else if (token == TokenNameMINUS_GREATER) { - getNextToken(); - if (token != TokenNameIdentifier && - token != TokenNameVariable) { - throwSyntaxError("String or Variable token expected."); - } - getNextToken(); - if (token == TokenNameLBRACKET) { - getNextToken(); - // if (token == TokenNameRBRACKET) { - // getNextToken(); - // } else { - expr(); - if (token != TokenNameRBRACKET) { - throwSyntaxError("']' expected after '${'."); - } - getNextToken(); - // } - } - } - // if (token != TokenNameRBRACE) { - // throwSyntaxError("'}' expected after '{$'."); - // } - // // scanner.encapsedStringStack.pop(); - // getNextToken(); - } else { - expr(); - if (token != TokenNameRBRACE) { - throwSyntaxError("'}' expected."); - } - // scanner.encapsedStringStack.pop(); - getNextToken(); - } - break; + } + break; } } + private void encaps_var_offset() { // T_STRING // | T_NUM_STRING // | T_VARIABLE switch (token) { - case TokenNameSTRING : - getNextToken(); - break; - case TokenNameIntegerLiteral : - getNextToken(); - break; - case TokenNameVariable : - getNextToken(); - break; - case TokenNameIdentifier : - getNextToken(); - break; - default : - throwSyntaxError("Variable or String token expected."); - break; + case TokenNameSTRING: + getNextToken(); + break; + case TokenNameIntegerLiteral: + getNextToken(); + break; + case TokenNameVariable: + getNextToken(); + break; + case TokenNameIdentifier: + getNextToken(); + break; + default: + throwSyntaxError("Variable or String token expected."); + break; } } + private void internal_functions_in_yacc() { int start = 0; ImportReference impt = null; switch (token) { - case TokenNameisset : - // T_ISSET '(' isset_variables ')' - getNextToken(); - if (token != TokenNameLPAREN) { - throwSyntaxError("'(' expected after keyword 'isset'"); - } - getNextToken(); - isset_variables(); - if (token != TokenNameRPAREN) { - throwSyntaxError("')' expected after keyword 'isset'"); - } - getNextToken(); - break; - case TokenNameempty : - // T_EMPTY '(' variable ')' - getNextToken(); - if (token != TokenNameLPAREN) { - throwSyntaxError("'(' expected after keyword 'empty'"); - } - getNextToken(); - variable(); - if (token != TokenNameRPAREN) { - throwSyntaxError("')' expected after keyword 'empty'"); - } - getNextToken(); - break; - case TokenNameinclude : - //T_INCLUDE expr - start = scanner.getCurrentTokenStartPosition(); - getNextToken(); - expr(); + case TokenNameisset: + // T_ISSET '(' isset_variables ')' + getNextToken(); + if (token != TokenNameLPAREN) { + throwSyntaxError("'(' expected after keyword 'isset'"); + } + getNextToken(); + isset_variables(); + if (token != TokenNameRPAREN) { + throwSyntaxError("')' expected after keyword 'isset'"); + } + getNextToken(); + break; + case TokenNameempty: + // T_EMPTY '(' variable ')' + getNextToken(); + if (token != TokenNameLPAREN) { + throwSyntaxError("'(' expected after keyword 'empty'"); + } + getNextToken(); + variable(); + if (token != TokenNameRPAREN) { + throwSyntaxError("')' expected after keyword 'empty'"); + } + getNextToken(); + break; + case TokenNameinclude: + //T_INCLUDE expr + start = scanner.getCurrentTokenStartPosition(); + getNextToken(); + expr(); - impt = new ImportReference(scanner.getCurrentTokenSource(start), start, scanner.getCurrentTokenEndPosition(), false); - impt.declarationSourceEnd = impt.sourceEnd; - impt.declarationEnd = impt.declarationSourceEnd; - //endPosition is just before the ; - impt.declarationSourceStart = start; - includesList.add(impt); - break; - case TokenNameinclude_once : - // T_INCLUDE_ONCE expr - start = scanner.getCurrentTokenStartPosition(); - getNextToken(); - expr(); - impt = new ImportReference(scanner.getCurrentTokenSource(start), start, scanner.getCurrentTokenEndPosition(), false); - impt.declarationSourceEnd = impt.sourceEnd; - impt.declarationEnd = impt.declarationSourceEnd; - //endPosition is just before the ; - impt.declarationSourceStart = start; - includesList.add(impt); - break; - case TokenNameeval : - // T_EVAL '(' expr ')' - getNextToken(); - if (token != TokenNameLPAREN) { - throwSyntaxError("'(' expected after keyword 'eval'"); - } - getNextToken(); - expr(); - if (token != TokenNameRPAREN) { - throwSyntaxError("')' expected after keyword 'eval'"); - } - getNextToken(); - break; - case TokenNamerequire : - //T_REQUIRE expr - start = scanner.getCurrentTokenStartPosition(); - getNextToken(); - expr(); - impt = new ImportReference(scanner.getCurrentTokenSource(start), start, scanner.getCurrentTokenEndPosition(), false); - impt.declarationSourceEnd = impt.sourceEnd; - impt.declarationEnd = impt.declarationSourceEnd; - //endPosition is just before the ; - impt.declarationSourceStart = start; - includesList.add(impt); - break; - case TokenNamerequire_once : - // T_REQUIRE_ONCE expr - start = scanner.getCurrentTokenStartPosition(); - getNextToken(); - expr(); - impt = new ImportReference(scanner.getCurrentTokenSource(start), start, scanner.getCurrentTokenEndPosition(), false); - impt.declarationSourceEnd = impt.sourceEnd; - impt.declarationEnd = impt.declarationSourceEnd; - //endPosition is just before the ; - impt.declarationSourceStart = start; - includesList.add(impt); - break; + impt = new ImportReference(scanner.getCurrentTokenSource(start), start, scanner.getCurrentTokenEndPosition(), false); + impt.declarationSourceEnd = impt.sourceEnd; + impt.declarationEnd = impt.declarationSourceEnd; + //endPosition is just before the ; + impt.declarationSourceStart = start; + includesList.add(impt); + break; + case TokenNameinclude_once: + // T_INCLUDE_ONCE expr + start = scanner.getCurrentTokenStartPosition(); + getNextToken(); + expr(); + impt = new ImportReference(scanner.getCurrentTokenSource(start), start, scanner.getCurrentTokenEndPosition(), false); + impt.declarationSourceEnd = impt.sourceEnd; + impt.declarationEnd = impt.declarationSourceEnd; + //endPosition is just before the ; + impt.declarationSourceStart = start; + includesList.add(impt); + break; + case TokenNameeval: + // T_EVAL '(' expr ')' + getNextToken(); + if (token != TokenNameLPAREN) { + throwSyntaxError("'(' expected after keyword 'eval'"); + } + getNextToken(); + expr(); + if (token != TokenNameRPAREN) { + throwSyntaxError("')' expected after keyword 'eval'"); + } + getNextToken(); + break; + case TokenNamerequire: + //T_REQUIRE expr + start = scanner.getCurrentTokenStartPosition(); + getNextToken(); + expr(); + impt = new ImportReference(scanner.getCurrentTokenSource(start), start, scanner.getCurrentTokenEndPosition(), false); + impt.declarationSourceEnd = impt.sourceEnd; + impt.declarationEnd = impt.declarationSourceEnd; + //endPosition is just before the ; + impt.declarationSourceStart = start; + includesList.add(impt); + break; + case TokenNamerequire_once: + // T_REQUIRE_ONCE expr + start = scanner.getCurrentTokenStartPosition(); + getNextToken(); + expr(); + impt = new ImportReference(scanner.getCurrentTokenSource(start), start, scanner.getCurrentTokenEndPosition(), false); + impt.declarationSourceEnd = impt.sourceEnd; + impt.declarationEnd = impt.declarationSourceEnd; + //endPosition is just before the ; + impt.declarationSourceStart = start; + includesList.add(impt); + break; } } + private void isset_variables() { // variable // | isset_variables ',' @@ -3254,6 +3303,7 @@ public class Parser //extends PHPParserSuperclass } } } + private boolean common_scalar() { // common_scalar: // T_LNUMBER @@ -3265,39 +3315,40 @@ public class Parser //extends PHPParserSuperclass // | T_METHOD_C // | T_FUNC_C switch (token) { - case TokenNameIntegerLiteral : - getNextToken(); - return true; - case TokenNameDoubleLiteral : - getNextToken(); - return true; - case TokenNameStringDoubleQuote : - getNextToken(); - return true; - case TokenNameStringSingleQuote : - getNextToken(); - return true; - case TokenNameStringInterpolated : - getNextToken(); - return true; - case TokenNameFILE : - getNextToken(); - return true; - case TokenNameLINE : - getNextToken(); - return true; - case TokenNameCLASS_C : - getNextToken(); - return true; - case TokenNameMETHOD_C : - getNextToken(); - return true; - case TokenNameFUNC_C : - getNextToken(); - return true; + case TokenNameIntegerLiteral: + getNextToken(); + return true; + case TokenNameDoubleLiteral: + getNextToken(); + return true; + case TokenNameStringDoubleQuote: + getNextToken(); + return true; + case TokenNameStringSingleQuote: + getNextToken(); + return true; + case TokenNameStringInterpolated: + getNextToken(); + return true; + case TokenNameFILE: + getNextToken(); + return true; + case TokenNameLINE: + getNextToken(); + return true; + case TokenNameCLASS_C: + getNextToken(); + return true; + case TokenNameMETHOD_C: + getNextToken(); + return true; + case TokenNameFUNC_C: + getNextToken(); + return true; } return false; } + private void scalar() { // scalar: // T_STRING @@ -3309,6 +3360,7 @@ public class Parser //extends PHPParserSuperclass //| T_START_HEREDOC encaps_list T_END_HEREDOC throwSyntaxError("Not yet implemented (scalar)."); } + private void static_scalar() { // static_scalar: /* compile-time evaluated scalars */ // common_scalar @@ -3321,98 +3373,99 @@ public class Parser //extends PHPParserSuperclass return; } switch (token) { - case TokenNameIdentifier : + case TokenNameIdentifier: + getNextToken(); + // static_class_constant: + // T_STRING T_PAAMAYIM_NEKUDOTAYIM T_STRING + if (token == TokenNamePAAMAYIM_NEKUDOTAYIM) { getNextToken(); - // static_class_constant: - // T_STRING T_PAAMAYIM_NEKUDOTAYIM T_STRING - if (token == TokenNamePAAMAYIM_NEKUDOTAYIM) { + if (token == TokenNameIdentifier) { getNextToken(); - if (token == TokenNameIdentifier) { - getNextToken(); - } else { - throwSyntaxError("Identifier expected after '::' operator."); - } + } else { + throwSyntaxError("Identifier expected after '::' operator."); } - break; - case TokenNameEncapsedString0 : - try { - scanner.currentCharacter = scanner.source[scanner.currentPosition++]; - while (scanner.currentCharacter != '`') { - if (scanner.currentCharacter == '\\') { - scanner.currentPosition++; - } - scanner.currentCharacter = scanner.source[scanner.currentPosition++]; + } + break; + case TokenNameEncapsedString0: + try { + scanner.currentCharacter = scanner.source[scanner.currentPosition++]; + while (scanner.currentCharacter != '`') { + if (scanner.currentCharacter == '\\') { + scanner.currentPosition++; } - getNextToken(); - } catch (IndexOutOfBoundsException e) { - throwSyntaxError("'`' expected at end of static string."); - } - break; - case TokenNameEncapsedString1 : - try { scanner.currentCharacter = scanner.source[scanner.currentPosition++]; - while (scanner.currentCharacter != '\'') { - if (scanner.currentCharacter == '\\') { - scanner.currentPosition++; - } - scanner.currentCharacter = scanner.source[scanner.currentPosition++]; - } - getNextToken(); - } catch (IndexOutOfBoundsException e) { - throwSyntaxError("'\'' expected at end of static string."); } - break; - case TokenNameEncapsedString2 : - try { - scanner.currentCharacter = scanner.source[scanner.currentPosition++]; - while (scanner.currentCharacter != '"') { - if (scanner.currentCharacter == '\\') { - scanner.currentPosition++; - } - scanner.currentCharacter = scanner.source[scanner.currentPosition++]; + getNextToken(); + } catch (IndexOutOfBoundsException e) { + throwSyntaxError("'`' expected at end of static string."); + } + break; + case TokenNameEncapsedString1: + try { + scanner.currentCharacter = scanner.source[scanner.currentPosition++]; + while (scanner.currentCharacter != '\'') { + if (scanner.currentCharacter == '\\') { + scanner.currentPosition++; } - getNextToken(); - } catch (IndexOutOfBoundsException e) { - throwSyntaxError("'\"' expected at end of static string."); + scanner.currentCharacter = scanner.source[scanner.currentPosition++]; } - break; - case TokenNamePLUS : - getNextToken(); - static_scalar(); - break; - case TokenNameMINUS : - getNextToken(); - static_scalar(); - break; - case TokenNamearray : getNextToken(); - if (token != TokenNameLPAREN) { - throwSyntaxError("'(' expected after keyword 'array'"); + } catch (IndexOutOfBoundsException e) { + throwSyntaxError("'\'' expected at end of static string."); + } + break; + case TokenNameEncapsedString2: + try { + scanner.currentCharacter = scanner.source[scanner.currentPosition++]; + while (scanner.currentCharacter != '"') { + if (scanner.currentCharacter == '\\') { + scanner.currentPosition++; + } + scanner.currentCharacter = scanner.source[scanner.currentPosition++]; } getNextToken(); - if (token == TokenNameRPAREN) { - getNextToken(); - break; - } - non_empty_static_array_pair_list(); - if (token != TokenNameRPAREN) { - throwSyntaxError("')' expected after keyword 'array'"); - } + } catch (IndexOutOfBoundsException e) { + throwSyntaxError("'\"' expected at end of static string."); + } + break; + case TokenNamePLUS: + getNextToken(); + static_scalar(); + break; + case TokenNameMINUS: + getNextToken(); + static_scalar(); + break; + case TokenNamearray: + getNextToken(); + if (token != TokenNameLPAREN) { + throwSyntaxError("'(' expected after keyword 'array'"); + } + getNextToken(); + if (token == TokenNameRPAREN) { getNextToken(); break; - // case TokenNamenull : - // getNextToken(); - // break; - // case TokenNamefalse : - // getNextToken(); - // break; - // case TokenNametrue : - // getNextToken(); - // break; - default : - throwSyntaxError("Static scalar/constant expected."); + } + non_empty_static_array_pair_list(); + if (token != TokenNameRPAREN) { + throwSyntaxError("')' expected after keyword 'array'"); + } + getNextToken(); + break; + // case TokenNamenull : + // getNextToken(); + // break; + // case TokenNamefalse : + // getNextToken(); + // break; + // case TokenNametrue : + // getNextToken(); + // break; + default: + throwSyntaxError("Static scalar/constant expected."); } } + private void non_empty_static_array_pair_list() { // non_empty_static_array_pair_list: // non_empty_static_array_pair_list ',' static_scalar T_DOUBLE_ARROW @@ -3435,6 +3488,7 @@ public class Parser //extends PHPParserSuperclass } } } + public void reportSyntaxError() { //int act, int currentKind, int // stateStackTop) { /* remember current scanner position */ @@ -3524,7 +3578,7 @@ public class Parser //extends PHPParserSuperclass try { tokenSource = this.scanner.getCurrentTokenSource(); } catch (Exception e) { - tokenSource = new char[]{}; + tokenSource = new char[] {}; } // problemReporter().parseError( // this.scanner.startPosition, @@ -3539,31 +3593,48 @@ public class Parser //extends PHPParserSuperclass scanner.startPosition = startPos; scanner.currentPosition = currentPos; } + public static final int RoundBracket = 0; + public static final int SquareBracket = 1; + public static final int CurlyBracket = 2; + public static final int BracketKinds = 3; + protected int[] nestedMethod; //the ptr is nestedType + protected int nestedType, dimensions; + //ast stack final static int AstStackIncrement = 100; + protected int astPtr; + protected ASTNode[] astStack = new ASTNode[AstStackIncrement]; + protected int astLengthPtr; + protected int[] astLengthStack; + ASTNode[] noAstNodes = new ASTNode[AstStackIncrement]; + public CompilationUnitDeclaration compilationUnit; /* * the result from parse() */ + protected ReferenceContext referenceContext; + protected ProblemReporter problemReporter; + protected CompilerOptions options; + private ArrayList includesList; + // protected CompilationResult compilationResult; /** - * Returns this parser's problem reporter initialized with its reference - * context. Also it is assumed that a problem is going to be reported, so - * initializes the compilation result's line positions. + * Returns this parser's problem reporter initialized with its reference context. Also it is assumed that a problem is going to be + * reported, so initializes the compilation result's line positions. */ public ProblemReporter problemReporter() { if (scanner.recordLineSeparator) { @@ -3572,6 +3643,7 @@ public class Parser //extends PHPParserSuperclass problemReporter.referenceContext = referenceContext; return problemReporter; } + /* * Reconsider the entire source looking for inconsistencies in {} () [] */ @@ -3580,13 +3652,13 @@ public class Parser //extends PHPParserSuperclass boolean anomaliesDetected = false; try { char[] source = scanner.source; - int[] leftCount = {0, 0, 0}; - int[] rightCount = {0, 0, 0}; - int[] depths = {0, 0, 0}; - int[][] leftPositions = new int[][]{new int[10], new int[10], new int[10]}; - int[][] leftDepths = new int[][]{new int[10], new int[10], new int[10]}; - int[][] rightPositions = new int[][]{new int[10], new int[10], new int[10]}; - int[][] rightDepths = new int[][]{new int[10], new int[10], new int[10]}; + int[] leftCount = { 0, 0, 0 }; + int[] rightCount = { 0, 0, 0 }; + int[] depths = { 0, 0, 0 }; + int[][] leftPositions = new int[][] { new int[10], new int[10], new int[10] }; + int[][] leftDepths = new int[][] { new int[10], new int[10], new int[10] }; + int[][] rightPositions = new int[][] { new int[10], new int[10], new int[10] }; + int[][] rightDepths = new int[][] { new int[10], new int[10], new int[10] }; scanner.currentPosition = scanner.initialPosition; //starting // point // (first-zero-based @@ -3618,131 +3690,156 @@ public class Parser //extends PHPParserSuperclass } while (isWhiteSpace && (scanner.currentPosition < scanner.eofPosition)); // -------consume token until } is found--------- switch (scanner.currentCharacter) { - case '{' : { - int index = leftCount[CurlyBracket]++; - if (index == leftPositions[CurlyBracket].length) { - System.arraycopy(leftPositions[CurlyBracket], 0, (leftPositions[CurlyBracket] = new int[index * 2]), 0, index); - System.arraycopy(leftDepths[CurlyBracket], 0, (leftDepths[CurlyBracket] = new int[index * 2]), 0, index); - } - leftPositions[CurlyBracket][index] = scanner.startPosition; - leftDepths[CurlyBracket][index] = depths[CurlyBracket]++; + case '{': { + int index = leftCount[CurlyBracket]++; + if (index == leftPositions[CurlyBracket].length) { + System.arraycopy(leftPositions[CurlyBracket], 0, (leftPositions[CurlyBracket] = new int[index * 2]), 0, index); + System.arraycopy(leftDepths[CurlyBracket], 0, (leftDepths[CurlyBracket] = new int[index * 2]), 0, index); } - break; - case '}' : { - int index = rightCount[CurlyBracket]++; - if (index == rightPositions[CurlyBracket].length) { - System.arraycopy(rightPositions[CurlyBracket], 0, (rightPositions[CurlyBracket] = new int[index * 2]), 0, index); - System.arraycopy(rightDepths[CurlyBracket], 0, (rightDepths[CurlyBracket] = new int[index * 2]), 0, index); - } - rightPositions[CurlyBracket][index] = scanner.startPosition; - rightDepths[CurlyBracket][index] = --depths[CurlyBracket]; + leftPositions[CurlyBracket][index] = scanner.startPosition; + leftDepths[CurlyBracket][index] = depths[CurlyBracket]++; + } + break; + case '}': { + int index = rightCount[CurlyBracket]++; + if (index == rightPositions[CurlyBracket].length) { + System.arraycopy(rightPositions[CurlyBracket], 0, (rightPositions[CurlyBracket] = new int[index * 2]), 0, index); + System.arraycopy(rightDepths[CurlyBracket], 0, (rightDepths[CurlyBracket] = new int[index * 2]), 0, index); } - break; - case '(' : { - int index = leftCount[RoundBracket]++; - if (index == leftPositions[RoundBracket].length) { - System.arraycopy(leftPositions[RoundBracket], 0, (leftPositions[RoundBracket] = new int[index * 2]), 0, index); - System.arraycopy(leftDepths[RoundBracket], 0, (leftDepths[RoundBracket] = new int[index * 2]), 0, index); - } - leftPositions[RoundBracket][index] = scanner.startPosition; - leftDepths[RoundBracket][index] = depths[RoundBracket]++; + rightPositions[CurlyBracket][index] = scanner.startPosition; + rightDepths[CurlyBracket][index] = --depths[CurlyBracket]; + } + break; + case '(': { + int index = leftCount[RoundBracket]++; + if (index == leftPositions[RoundBracket].length) { + System.arraycopy(leftPositions[RoundBracket], 0, (leftPositions[RoundBracket] = new int[index * 2]), 0, index); + System.arraycopy(leftDepths[RoundBracket], 0, (leftDepths[RoundBracket] = new int[index * 2]), 0, index); } - break; - case ')' : { - int index = rightCount[RoundBracket]++; - if (index == rightPositions[RoundBracket].length) { - System.arraycopy(rightPositions[RoundBracket], 0, (rightPositions[RoundBracket] = new int[index * 2]), 0, index); - System.arraycopy(rightDepths[RoundBracket], 0, (rightDepths[RoundBracket] = new int[index * 2]), 0, index); - } - rightPositions[RoundBracket][index] = scanner.startPosition; - rightDepths[RoundBracket][index] = --depths[RoundBracket]; + leftPositions[RoundBracket][index] = scanner.startPosition; + leftDepths[RoundBracket][index] = depths[RoundBracket]++; + } + break; + case ')': { + int index = rightCount[RoundBracket]++; + if (index == rightPositions[RoundBracket].length) { + System.arraycopy(rightPositions[RoundBracket], 0, (rightPositions[RoundBracket] = new int[index * 2]), 0, index); + System.arraycopy(rightDepths[RoundBracket], 0, (rightDepths[RoundBracket] = new int[index * 2]), 0, index); } - break; - case '[' : { - int index = leftCount[SquareBracket]++; - if (index == leftPositions[SquareBracket].length) { - System.arraycopy(leftPositions[SquareBracket], 0, (leftPositions[SquareBracket] = new int[index * 2]), 0, index); - System.arraycopy(leftDepths[SquareBracket], 0, (leftDepths[SquareBracket] = new int[index * 2]), 0, index); - } - leftPositions[SquareBracket][index] = scanner.startPosition; - leftDepths[SquareBracket][index] = depths[SquareBracket]++; + rightPositions[RoundBracket][index] = scanner.startPosition; + rightDepths[RoundBracket][index] = --depths[RoundBracket]; + } + break; + case '[': { + int index = leftCount[SquareBracket]++; + if (index == leftPositions[SquareBracket].length) { + System.arraycopy(leftPositions[SquareBracket], 0, (leftPositions[SquareBracket] = new int[index * 2]), 0, index); + System.arraycopy(leftDepths[SquareBracket], 0, (leftDepths[SquareBracket] = new int[index * 2]), 0, index); } - break; - case ']' : { - int index = rightCount[SquareBracket]++; - if (index == rightPositions[SquareBracket].length) { - System.arraycopy(rightPositions[SquareBracket], 0, (rightPositions[SquareBracket] = new int[index * 2]), 0, index); - System.arraycopy(rightDepths[SquareBracket], 0, (rightDepths[SquareBracket] = new int[index * 2]), 0, index); + leftPositions[SquareBracket][index] = scanner.startPosition; + leftDepths[SquareBracket][index] = depths[SquareBracket]++; + } + break; + case ']': { + int index = rightCount[SquareBracket]++; + if (index == rightPositions[SquareBracket].length) { + System.arraycopy(rightPositions[SquareBracket], 0, (rightPositions[SquareBracket] = new int[index * 2]), 0, index); + System.arraycopy(rightDepths[SquareBracket], 0, (rightDepths[SquareBracket] = new int[index * 2]), 0, index); + } + rightPositions[SquareBracket][index] = scanner.startPosition; + rightDepths[SquareBracket][index] = --depths[SquareBracket]; + } + break; + case '\'': { + if (scanner.getNextChar('\\')) { + scanner.scanEscapeCharacter(); + } else { // consume next character + scanner.unicodeAsBackSlash = false; + // if (((scanner.currentCharacter = + // source[scanner.currentPosition++]) == + // '\\') && + // (source[scanner.currentPosition] == + // 'u')) { + // scanner.getNextUnicodeChar(); + // } else { + if (scanner.withoutUnicodePtr != 0) { + scanner.withoutUnicodeBuffer[++scanner.withoutUnicodePtr] = scanner.currentCharacter; } - rightPositions[SquareBracket][index] = scanner.startPosition; - rightDepths[SquareBracket][index] = --depths[SquareBracket]; + // } } - break; - case '\'' : { - if (scanner.getNextChar('\\')) { + scanner.getNextChar('\''); + break; + } + case '"': + // consume next character + scanner.unicodeAsBackSlash = false; + // if (((scanner.currentCharacter = + // source[scanner.currentPosition++]) == '\\') && + // (source[scanner.currentPosition] == 'u')) { + // scanner.getNextUnicodeChar(); + // } else { + if (scanner.withoutUnicodePtr != 0) { + scanner.withoutUnicodeBuffer[++scanner.withoutUnicodePtr] = scanner.currentCharacter; + } + // } + while (scanner.currentCharacter != '"') { + if (scanner.currentCharacter == '\r') { + if (source[scanner.currentPosition] == '\n') + scanner.currentPosition++; + break; // the string cannot go further that + // the line + } + if (scanner.currentCharacter == '\n') { + break; // the string cannot go further that + // the line + } + if (scanner.currentCharacter == '\\') { scanner.scanEscapeCharacter(); - } else { // consume next character - scanner.unicodeAsBackSlash = false; - // if (((scanner.currentCharacter = - // source[scanner.currentPosition++]) == - // '\\') && - // (source[scanner.currentPosition] == - // 'u')) { - // scanner.getNextUnicodeChar(); - // } else { - if (scanner.withoutUnicodePtr != 0) { - scanner.withoutUnicodeBuffer[++scanner.withoutUnicodePtr] = scanner.currentCharacter; - } - // } } - scanner.getNextChar('\''); - break; - } - case '"' : // consume next character scanner.unicodeAsBackSlash = false; - // if (((scanner.currentCharacter = - // source[scanner.currentPosition++]) == '\\') && - // (source[scanner.currentPosition] == 'u')) { - // scanner.getNextUnicodeChar(); - // } else { + // if (((scanner.currentCharacter = + // source[scanner.currentPosition++]) == '\\') + // && (source[scanner.currentPosition] == 'u')) + // { + // scanner.getNextUnicodeChar(); + // } else { if (scanner.withoutUnicodePtr != 0) { scanner.withoutUnicodeBuffer[++scanner.withoutUnicodePtr] = scanner.currentCharacter; } - // } - while (scanner.currentCharacter != '"') { - if (scanner.currentCharacter == '\r') { - if (source[scanner.currentPosition] == '\n') - scanner.currentPosition++; - break; // the string cannot go further that - // the line - } - if (scanner.currentCharacter == '\n') { - break; // the string cannot go further that - // the line - } - if (scanner.currentCharacter == '\\') { - scanner.scanEscapeCharacter(); + // } + } + break; + case '/': { + int test; + if ((test = scanner.getNextChar('/', '*')) == 0) { //line + // comment + //get the next char + if (((scanner.currentCharacter = source[scanner.currentPosition++]) == '\\') + && (source[scanner.currentPosition] == 'u')) { + //-------------unicode traitement + // ------------ + int c1 = 0, c2 = 0, c3 = 0, c4 = 0; + scanner.currentPosition++; + while (source[scanner.currentPosition] == 'u') { + scanner.currentPosition++; } - // consume next character - scanner.unicodeAsBackSlash = false; - // if (((scanner.currentCharacter = - // source[scanner.currentPosition++]) == '\\') - // && (source[scanner.currentPosition] == 'u')) - // { - // scanner.getNextUnicodeChar(); - // } else { - if (scanner.withoutUnicodePtr != 0) { - scanner.withoutUnicodeBuffer[++scanner.withoutUnicodePtr] = scanner.currentCharacter; + if ((c1 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 || c1 < 0 + || (c2 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 || c2 < 0 + || (c3 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 || c3 < 0 + || (c4 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 || c4 < 0) { //error + // don't + // care of the + // value + scanner.currentCharacter = 'A'; + } //something different from \n and \r + else { + scanner.currentCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); } - // } } - break; - case '/' : { - int test; - if ((test = scanner.getNextChar('/', '*')) == 0) { //line - // comment + while (scanner.currentCharacter != '\r' && scanner.currentCharacter != '\n') { //get the next char + scanner.startPosition = scanner.currentPosition; if (((scanner.currentCharacter = source[scanner.currentPosition++]) == '\\') && (source[scanner.currentPosition] == 'u')) { //-------------unicode traitement @@ -3756,75 +3853,76 @@ public class Parser //extends PHPParserSuperclass || (c2 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 || c2 < 0 || (c3 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 || c3 < 0 || (c4 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 || c4 < 0) { //error - // don't + // don't // care of the // value scanner.currentCharacter = 'A'; - } //something different from \n and \r + } //something different from \n + // and \r else { scanner.currentCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); } } - while (scanner.currentCharacter != '\r' && scanner.currentCharacter != '\n') { - //get the next char - scanner.startPosition = scanner.currentPosition; - if (((scanner.currentCharacter = source[scanner.currentPosition++]) == '\\') - && (source[scanner.currentPosition] == 'u')) { - //-------------unicode traitement - // ------------ - int c1 = 0, c2 = 0, c3 = 0, c4 = 0; - scanner.currentPosition++; - while (source[scanner.currentPosition] == 'u') { - scanner.currentPosition++; - } - if ((c1 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 || c1 < 0 - || (c2 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 || c2 < 0 - || (c3 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 || c3 < 0 - || (c4 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 || c4 < 0) { //error - // don't - // care of the - // value - scanner.currentCharacter = 'A'; - } //something different from \n - // and \r - else { - scanner.currentCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); - } - } - } - if (scanner.recordLineSeparator && ((scanner.currentCharacter == '\r') || (scanner.currentCharacter == '\n'))) { - if (scanner.lineEnds[scanner.linePtr] < scanner.startPosition) { - // only record line positions we - // have not recorded yet - scanner.pushLineSeparator(); - if (this.scanner.taskTags != null) { - this.scanner.checkTaskTag(this.scanner.getCurrentTokenStartPosition(), this.scanner - .getCurrentTokenEndPosition()); - } + } + if (scanner.recordLineSeparator && ((scanner.currentCharacter == '\r') || (scanner.currentCharacter == '\n'))) { + if (scanner.lineEnds[scanner.linePtr] < scanner.startPosition) { + // only record line positions we + // have not recorded yet + scanner.pushLineSeparator(); + if (this.scanner.taskTags != null) { + this.scanner.checkTaskTag(this.scanner.getCurrentTokenStartPosition(), this.scanner + .getCurrentTokenEndPosition()); } } - break; } - if (test > 0) { //traditional and annotation - // comment - boolean star = false; - // consume next character - scanner.unicodeAsBackSlash = false; - // if (((scanner.currentCharacter = - // source[scanner.currentPosition++]) == - // '\\') && - // (source[scanner.currentPosition] == - // 'u')) { - // scanner.getNextUnicodeChar(); - // } else { - if (scanner.withoutUnicodePtr != 0) { - scanner.withoutUnicodeBuffer[++scanner.withoutUnicodePtr] = scanner.currentCharacter; + break; + } + if (test > 0) { //traditional and annotation + // comment + boolean star = false; + // consume next character + scanner.unicodeAsBackSlash = false; + // if (((scanner.currentCharacter = + // source[scanner.currentPosition++]) == + // '\\') && + // (source[scanner.currentPosition] == + // 'u')) { + // scanner.getNextUnicodeChar(); + // } else { + if (scanner.withoutUnicodePtr != 0) { + scanner.withoutUnicodeBuffer[++scanner.withoutUnicodePtr] = scanner.currentCharacter; + } + // } + if (scanner.currentCharacter == '*') { + star = true; + } + //get the next char + if (((scanner.currentCharacter = source[scanner.currentPosition++]) == '\\') + && (source[scanner.currentPosition] == 'u')) { + //-------------unicode traitement + // ------------ + int c1 = 0, c2 = 0, c3 = 0, c4 = 0; + scanner.currentPosition++; + while (source[scanner.currentPosition] == 'u') { + scanner.currentPosition++; } - // } - if (scanner.currentCharacter == '*') { - star = true; + if ((c1 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 || c1 < 0 + || (c2 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 || c2 < 0 + || (c3 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 || c3 < 0 + || (c4 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 || c4 < 0) { //error + // don't + // care of the + // value + scanner.currentCharacter = 'A'; + } //something different from * and / + else { + scanner.currentCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); } - //get the next char + } + //loop until end of comment */ + while ((scanner.currentCharacter != '/') || (!star)) { + star = scanner.currentCharacter == '*'; + //get next char if (((scanner.currentCharacter = source[scanner.currentPosition++]) == '\\') && (source[scanner.currentPosition] == 'u')) { //-------------unicode traitement @@ -3838,59 +3936,33 @@ public class Parser //extends PHPParserSuperclass || (c2 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 || c2 < 0 || (c3 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 || c3 < 0 || (c4 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 || c4 < 0) { //error - // don't + // don't // care of the // value scanner.currentCharacter = 'A'; - } //something different from * and / + } //something different from * and + // / else { scanner.currentCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); } } - //loop until end of comment */ - while ((scanner.currentCharacter != '/') || (!star)) { - star = scanner.currentCharacter == '*'; - //get next char - if (((scanner.currentCharacter = source[scanner.currentPosition++]) == '\\') - && (source[scanner.currentPosition] == 'u')) { - //-------------unicode traitement - // ------------ - int c1 = 0, c2 = 0, c3 = 0, c4 = 0; - scanner.currentPosition++; - while (source[scanner.currentPosition] == 'u') { - scanner.currentPosition++; - } - if ((c1 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 || c1 < 0 - || (c2 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 || c2 < 0 - || (c3 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 || c3 < 0 - || (c4 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 || c4 < 0) { //error - // don't - // care of the - // value - scanner.currentCharacter = 'A'; - } //something different from * and - // / - else { - scanner.currentCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); - } - } - } - if (this.scanner.taskTags != null) { - this.scanner.checkTaskTag(this.scanner.getCurrentTokenStartPosition(), this.scanner.getCurrentTokenEndPosition()); - } - break; + } + if (this.scanner.taskTags != null) { + this.scanner.checkTaskTag(this.scanner.getCurrentTokenStartPosition(), this.scanner.getCurrentTokenEndPosition()); } break; } - default : - if (Scanner.isPHPIdentifierStart(scanner.currentCharacter)) { - scanner.scanIdentifierOrKeyword(false); - break; - } - if (Character.isDigit(scanner.currentCharacter)) { - scanner.scanNumber(false); - break; - } + break; + } + default: + if (Scanner.isPHPIdentifierStart(scanner.currentCharacter)) { + scanner.scanIdentifierOrKeyword(false); + break; + } + if (Character.isDigit(scanner.currentCharacter)) { + scanner.scanNumber(false); + break; + } } //-----------------end switch while // try-------------------- @@ -3967,6 +4039,7 @@ public class Parser //extends PHPParserSuperclass return anomaliesDetected; } } + protected void pushOnAstLengthStack(int pos) { try { astLengthStack[++astLengthPtr] = pos; @@ -3978,6 +4051,7 @@ public class Parser //extends PHPParserSuperclass astLengthStack[astLengthPtr] = pos; } } + protected void pushOnAstStack(ASTNode node) { /* * add a new obj on top of the ast stack diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/SyntaxError.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/SyntaxError.java index b3b03d7..90ca397 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/SyntaxError.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/SyntaxError.java @@ -1,25 +1,7 @@ -/* - * SyntaxError.java - * Copyright (C) 2000 Klaus Hartlage - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - */ package net.sourceforge.phpdt.internal.compiler.parser; /** - * Exception for a syntax error detected by the HartMath parser. + * Exception for a syntax error detected by the parser. */ public class SyntaxError extends Error { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CodeTemplateContext.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CodeTemplateContext.java index 01908fe..e9e4621 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CodeTemplateContext.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CodeTemplateContext.java @@ -106,4 +106,7 @@ public class CodeTemplateContext extends TemplateContext { setVariable(CodeTemplateContextType.PROJECTNAME, cu.getJavaProject().getElementName()); } + public void setFileNameVariable(String filename) { + setVariable(CodeTemplateContextType.FILENAME, filename); + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CodeTemplateContextType.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CodeTemplateContextType.java index 1452f68..6c8ee5e 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CodeTemplateContextType.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CodeTemplateContextType.java @@ -38,6 +38,7 @@ public class CodeTemplateContextType extends TemplateContextType { public static final String GETTERBODY_CONTEXTTYPE= "php_getterbody_context"; //$NON-NLS-1$ public static final String SETTERBODY_CONTEXTTYPE= "php_setterbody_context"; //$NON-NLS-1$ public static final String NEWTYPE_CONTEXTTYPE= "php_newtype_context"; //$NON-NLS-1$ + public static final String NEWHTML_CONTEXTTYPE= "php_newhtml_context"; //$NON-NLS-1$ public static final String TYPECOMMENT_CONTEXTTYPE= "php_typecomment_context"; //$NON-NLS-1$ public static final String FIELDCOMMENT_CONTEXTTYPE= "php_fieldcomment_context"; //$NON-NLS-1$ public static final String METHODCOMMENT_CONTEXTTYPE= "php_methodcomment_context"; //$NON-NLS-1$ @@ -51,6 +52,7 @@ public class CodeTemplateContextType extends TemplateContextType { public static final String CATCHBLOCK= "catchblock"; //$NON-NLS-1$ public static final String METHODSTUB= "methodbody"; //$NON-NLS-1$ public static final String NEWTYPE= "newtype"; //$NON-NLS-1$ + public static final String NEWHTML= "newhtml"; //$NON-NLS-1$ public static final String CONSTRUCTORSTUB= "constructorbody"; //$NON-NLS-1$ public static final String GETTERSTUB= "getterbody"; //$NON-NLS-1$ public static final String SETTERSTUB= "setterbody"; //$NON-NLS-1$ @@ -172,7 +174,13 @@ public class CodeTemplateContextType extends TemplateContextType { addResolver(new CodeTemplateVariableResolver(TYPE_DECLARATION, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.typedeclaration"))); //$NON-NLS-1$ addResolver(new CodeTemplateVariableResolver(TYPE_COMMENT, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.typecomment"))); //$NON-NLS-1$ addCompilationUnitVariables(); - } else if (TYPECOMMENT_CONTEXTTYPE.equals(contextName)) { + } else if (NEWHTML_CONTEXTTYPE.equals(contextName)) { + addResolver(new CodeTemplateVariableResolver(TYPENAME, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.typename"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver(PACKAGE_DECLARATION, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.packdeclaration"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver(TYPE_DECLARATION, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.typedeclaration"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver(TYPE_COMMENT, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.typecomment"))); //$NON-NLS-1$ + addCompilationUnitVariables(); + }else if (TYPECOMMENT_CONTEXTTYPE.equals(contextName)) { addResolver(new CodeTemplateVariableResolver(TYPENAME, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.typename"))); //$NON-NLS-1$ addResolver(new CodeTemplateVariableResolver(ENCLOSING_TYPE, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.enclosingtype"))); //$NON-NLS-1$ addResolver(new TagsVariableResolver()); @@ -268,6 +276,7 @@ public class CodeTemplateContextType extends TemplateContextType { registry.addContextType(new CodeTemplateContextType(CodeTemplateContextType.GETTERBODY_CONTEXTTYPE)); registry.addContextType(new CodeTemplateContextType(CodeTemplateContextType.SETTERBODY_CONTEXTTYPE)); registry.addContextType(new CodeTemplateContextType(CodeTemplateContextType.NEWTYPE_CONTEXTTYPE)); + registry.addContextType(new CodeTemplateContextType(CodeTemplateContextType.NEWHTML_CONTEXTTYPE)); registry.addContextType(new CodeTemplateContextType(CodeTemplateContextType.TYPECOMMENT_CONTEXTTYPE)); registry.addContextType(new CodeTemplateContextType(CodeTemplateContextType.FIELDCOMMENT_CONTEXTTYPE)); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/internal/compiler/ast/Expression.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/internal/compiler/ast/Expression.java index cdeb2ae..9794ce1 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/internal/compiler/ast/Expression.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/internal/compiler/ast/Expression.java @@ -10,17 +10,14 @@ *******************************************************************************/ package net.sourceforge.phpeclipse.internal.compiler.ast; -import net.sourceforge.phpdt.internal.compiler.codegen.Label; import net.sourceforge.phpdt.internal.compiler.flow.FlowContext; import net.sourceforge.phpdt.internal.compiler.flow.FlowInfo; import net.sourceforge.phpdt.internal.compiler.impl.Constant; import net.sourceforge.phpdt.internal.compiler.lookup.BaseTypeBinding; import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; -import net.sourceforge.phpdt.internal.compiler.problem.ShouldNotImplement; -import net.sourceforge.phpdt.internal.compiler.util.Util; -public abstract class Expression extends Statement { +public class Expression extends Statement { //some expression may not be used - from a java semantic point //of view only - as statements. Other may. In order to avoid the creation diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/IMiscProjectPreferences.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/IMiscProjectPreferences.java deleted file mode 100644 index a60a5f0..0000000 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/IMiscProjectPreferences.java +++ /dev/null @@ -1,33 +0,0 @@ -package net.sourceforge.phpeclipse.preferences; - -import org.eclipse.core.runtime.QualifiedName; - -/** - * constnats for project preferences - */ -public interface IMiscProjectPreferences { - - /** - * namespace URI for the properties - */ -// public static final String PROPERTY_NAMESPACE = "http://phpeclipse.org"; - - // public static final String PREF_ID = "net.sourceforge.phpeclipse.preferences.PHPMiscProjectPreferences"; -// /** -// * property local name for the publish directory -// */ -// public static final String PUBLISH_PROPERTY = "publish"; -// -// /** -// * property qualified name for the publish directory -// */ -// public static final QualifiedName PUBLISH_PROPERTY_NAME = -// new QualifiedName(PROPERTY_NAMESPACE,PUBLISH_PROPERTY); -// -// /** -// * default value for the publish directory name -// */ -// public static final String DEFAULT_PUBLISH_DIR = "c:\\temp"; - - -} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/HTMLFileWizard.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/HTMLFileWizard.java new file mode 100644 index 0000000..fac8bb8 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/HTMLFileWizard.java @@ -0,0 +1,182 @@ +package net.sourceforge.phpeclipse.wizards; + +/********************************************************************** + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + + Contributors: + IBM Corporation - Initial implementation + Klaus Hartlage - www.eclipseproject.de + **********************************************************************/ + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.InvocationTargetException; + +import net.sourceforge.phpdt.internal.corext.codemanipulation.StubUtility; +import net.sourceforge.phpdt.internal.corext.template.php.CodeTemplateContext; +import net.sourceforge.phpdt.internal.corext.template.php.CodeTemplateContextType; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.core.resources.IContainer; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IResource; +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.IStatus; +import org.eclipse.core.runtime.Path; +import org.eclipse.core.runtime.Status; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.operation.IRunnableWithProgress; +import org.eclipse.jface.text.templates.Template; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.wizard.Wizard; +import org.eclipse.ui.INewWizard; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.IWorkbenchWizard; +import org.eclipse.ui.PartInitException; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.ide.IDE; + +/** + * This wizard creates one file with the extension "html". + */ +public class HTMLFileWizard extends Wizard implements INewWizard { + + private HTMLFileWizardPage page; + + private ISelection selection; + + // the name of the file to create + private String fFileName; + + public HTMLFileWizard() { + super(); + setNeedsProgressMonitor(true); + } + + /** + * Adding the page to the wizard. + */ + public void addPages() { + page = new HTMLFileWizardPage(selection); + addPage(page); + } + + /** + * This method is called when 'Finish' button is pressed in the wizard. We will create an operation and run it using wizard as + * execution context. + */ + public boolean performFinish() { + final String containerName = page.getContainerName(); + final String fileName = page.getFileName(); + IRunnableWithProgress op = new IRunnableWithProgress() { + public void run(IProgressMonitor monitor) throws InvocationTargetException { + try { + doFinish(containerName, fileName, monitor); + } catch (CoreException e) { + throw new InvocationTargetException(e); + } finally { + monitor.done(); + } + } + }; + try { + getContainer().run(true, false, op); + } catch (InterruptedException e) { + return false; + } catch (InvocationTargetException e) { + Throwable realException = e.getTargetException(); + MessageDialog.openError(getShell(), PHPWizardMessages.getString("Wizard.error"), realException.getMessage()); + return false; + } + return true; + } + + /** + * The worker method. It will find the container, create the file if missing or just replace its contents, and open the editor on + * the newly created file. + */ + private void doFinish(String containerName, String fileName, IProgressMonitor monitor) throws CoreException { + // create a sample file + monitor.beginTask(PHPWizardMessages.getString("Wizard.Monitor.creating") + " " + fileName, 2); + IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); + IResource resource = root.findMember(new Path(containerName)); + if (!resource.exists() || !(resource instanceof IContainer)) { + throwCoreException(PHPWizardMessages.getString("Wizard.Monitor.containerDoesNotExistException")); + } + IContainer container = (IContainer) resource; + final IFile file = container.getFile(new Path(fileName)); + try { + InputStream stream; + stream = openContentStream(fileName); + if (file.exists()) { + file.setContents(stream, true, true, monitor); + } else { + file.create(stream, true, monitor); + } + stream.close(); + } catch (IOException e) { + } + monitor.worked(1); + monitor.setTaskName(PHPWizardMessages.getString("Wizard.Monitor.openingFile")); + getShell().getDisplay().asyncExec(new Runnable() { + public void run() { + IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); + try { + IDE.openEditor(page, file, true); + } catch (PartInitException e) { + } + } + }); + monitor.worked(1); + } + + /** + * We will initialize file contents with a sample text. + */ + private InputStream openContentStream(String fileName) { + try { + Template template = PHPeclipsePlugin.getDefault().getCodeTemplateStore().findTemplate(CodeTemplateContextType.NEWHTML); + if (template == null) { + return null; + } + String lineDelimiter = System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ + CodeTemplateContext context = new CodeTemplateContext(template.getContextTypeId(), null, lineDelimiter); + context.setFileNameVariable(fileName); + return new ByteArrayInputStream(StubUtility.evaluateTemplate(context, template).getBytes()); + } catch (CoreException e) { + e.printStackTrace(); + return null; + } + } + + private void throwCoreException(String message) throws CoreException { + IStatus status = new Status(IStatus.ERROR, "net.sourceforge.phpeclipse.wizards", IStatus.OK, message, null); + throw new CoreException(status); + } + + /** + * We will accept the selection in the workbench to see if we can initialize from it. + * + * @see IWorkbenchWizard#init(IWorkbench, IStructuredSelection) + */ + public void init(IWorkbench workbench, IStructuredSelection selection) { + this.selection = selection; + } + + /** + * Sets the name of the file to create (used to set the class name in the new file) + */ + public void setFileName(String name) { + fFileName = name; + } +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/HTMLFileWizardPage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/HTMLFileWizardPage.java new file mode 100644 index 0000000..554b6b4 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/HTMLFileWizardPage.java @@ -0,0 +1,235 @@ +package net.sourceforge.phpeclipse.wizards; + +/********************************************************************** + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + + Contributors: + IBM Corporation - Initial implementation + Klaus Hartlage - www.eclipseproject.de + **********************************************************************/ + +import net.sourceforge.phpdt.internal.ui.util.PHPFileUtil; + +import org.eclipse.core.resources.IContainer; +import org.eclipse.core.resources.IFolder; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.Path; +import org.eclipse.jface.dialogs.IDialogPage; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.wizard.WizardPage; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.ModifyEvent; +import org.eclipse.swt.events.ModifyListener; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Text; +import org.eclipse.ui.dialogs.ContainerSelectionDialog; + +/** + * The "New" wizard page allows setting the container for the new file as well + * as the file name. The page will only accept file name without the extension + * OR with the extension that matches the expected one (cs). + */ + +public class HTMLFileWizardPage extends WizardPage { + private Text containerText; + + private Text fileText; + + private ISelection selection; + + /** + * Constructor for SampleNewWizardPage. + * + * @param pageName + */ + public HTMLFileWizardPage(ISelection selection) { + super("wizardPage"); + setTitle(PHPWizardMessages.getString("WizardPage.html.title")); + setDescription(PHPWizardMessages.getString("WizardPage.html.description")); + this.selection = selection; + } + + /** + * @see IDialogPage#createControl(Composite) + */ + public void createControl(Composite parent) { + Composite container = new Composite(parent, SWT.NULL); + GridLayout layout = new GridLayout(); + container.setLayout(layout); + layout.numColumns = 3; + layout.verticalSpacing = 9; + Label label = new Label(container, SWT.NULL); + label.setText(PHPWizardMessages.getString("WizardPage.containerLabel")); + + containerText = new Text(container, SWT.BORDER | SWT.SINGLE); + GridData gd = new GridData(GridData.FILL_HORIZONTAL); + containerText.setLayoutData(gd); + containerText.addModifyListener(new ModifyListener() { + public void modifyText(ModifyEvent e) { + dialogChanged(); + } + }); + + Button button = new Button(container, SWT.PUSH); + button.setText(PHPWizardMessages.getString("WizardPage.browseButtonText")); + button.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent e) { + handleBrowse(); + } + }); + label = new Label(container, SWT.NULL); + label.setText(PHPWizardMessages.getString("WizardPage.fileLabel")); + + fileText = new Text(container, SWT.BORDER | SWT.SINGLE); + gd = new GridData(GridData.FILL_HORIZONTAL); + fileText.setLayoutData(gd); + fileText.addModifyListener(new ModifyListener() { + public void modifyText(ModifyEvent e) { + dialogChanged(); + } + }); + initialize(); + dialogChanged(); + setControl(container); + } + + /** + * Tests if the current workbench selection is a suitable container to use. + */ + + private void initialize() { + if (selection != null && selection.isEmpty() == false + && selection instanceof IStructuredSelection) { + IStructuredSelection ssel = (IStructuredSelection) selection; + if (ssel.size() > 1) + return; + Object obj = ssel.getFirstElement(); + if (obj instanceof IResource) { + IContainer container; + if (obj instanceof IContainer) + container = (IContainer) obj; + else + container = ((IResource) obj).getParent(); + containerText.setText(container.getFullPath().toString()); + } + } + fileText.setText("*.html"); + } + + /** + * Uses the standard container selection dialog to choose the new value for + * the container field. + */ + + private void handleBrowse() { + ContainerSelectionDialog dialog = new ContainerSelectionDialog(getShell(), + ResourcesPlugin.getWorkspace().getRoot(), false, PHPWizardMessages + .getString("WizardPage.selectNewFileContainer")); + if (dialog.open() == ContainerSelectionDialog.OK) { + Object[] result = dialog.getResult(); + if (result.length == 1) { + IContainer container = (IContainer) result[0]; + containerText.setText(container.getFullPath().toString()); + } + } + } + + /** + * Ensures that both text fields are set. + */ + private void dialogChanged() { + String container = getContainerName(); + String fileName = getFileName(); + + if (container.length() == 0) { + updateStatus(PHPWizardMessages + .getString("WizardPage.containerMustBeSpecified")); + return; + } + if (fileName.length() == 0) { + updateStatus("WizardPage.nameMustBeSpecified"); + return; + } + +// if (!PHPFileUtil.isPHPFileName(fileName)) { +// updateStatus(PHPWizardMessages.getString("WizardPage.mustBePHP")); +// return; +// } + updateStatus(null); + } + + private void updateStatus(String message) { + setErrorMessage(message); + setPageComplete(message == null); + } + + public String getContainerName() { + return containerText.getText(); + } + + public String getFileName() { + return fileText.getText(); + } + + /** + * @see WizardPage#isPageComplete() + */ + public boolean isPageComplete() { + return !checkFolderForExistingFile() && super.isPageComplete(); + } + + /** + * Finds the current directory where the file should be created + */ + protected boolean checkFolderForExistingFile() { + boolean result = false; + + if (containerText.getText() != null) { + IPath containerPath = new Path(containerText.getText().trim()); + if (containerPath.segmentCount() > 1) { + IFolder container = ResourcesPlugin.getWorkspace().getRoot().getFolder( + containerPath); + if (container != null && container.exists()) { + IResource file = container.getFile(fileText.getText().trim()); + if (file != null && file.exists()) { + this.setErrorMessage(PHPWizardMessages + .getString("WizardPage.fileAlreadyExists")); + result = true; + } + } + } else { + // this is a project + IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject( + containerText.getText().trim()); + if (project != null && project.exists()) { + IResource file = project.getFile(fileText.getText().trim()); + if (file != null && file.exists()) { + this.setErrorMessage(PHPWizardMessages + .getString("WizardPage.fileAlreadyExists")); + result = true; + } + } + } + } + + if (!result) + ((HTMLFileWizard) this.getWizard()).setFileName(fileText.getText().trim()); + + return result; + } + +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/PHPFileWizard.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/PHPFileWizard.java index 9f4a0e6..6e6b2da 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/PHPFileWizard.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/PHPFileWizard.java @@ -1,16 +1,16 @@ package net.sourceforge.phpeclipse.wizards; /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html -Contributors: - IBM Corporation - Initial implementation - Klaus Hartlage - www.eclipseproject.de -**********************************************************************/ + Contributors: + IBM Corporation - Initial implementation + Klaus Hartlage - www.eclipseproject.de + **********************************************************************/ import java.io.ByteArrayInputStream; import java.io.IOException; @@ -47,18 +47,17 @@ import org.eclipse.ui.PlatformUI; import org.eclipse.ui.ide.IDE; /** - * This wizard creates one file with the extension - * "php". + * This wizard creates one file with the extension "php". */ public class PHPFileWizard extends Wizard implements INewWizard { private PHPFileWizardPage page; + private ISelection selection; // the name of the file to create - private String fileName; + private String fFileName; - public PHPFileWizard() { super(); setNeedsProgressMonitor(true); @@ -73,10 +72,8 @@ public class PHPFileWizard extends Wizard implements INewWizard { } /** - * This method is called when 'Finish' button is pressed in - * the wizard. - * We will create an operation and run it - * using wizard as execution context. + * This method is called when 'Finish' button is pressed in the wizard. We will create an operation and run it using wizard as + * execution context. */ public boolean performFinish() { final String containerName = page.getContainerName(); @@ -105,9 +102,8 @@ public class PHPFileWizard extends Wizard implements INewWizard { } /** - * The worker method. It will find the container, create the - * file if missing or just replace its contents, and open - * the editor on the newly created file. + * The worker method. It will find the container, create the file if missing or just replace its contents, and open the editor on + * the newly created file. */ private void doFinish(String containerName, String fileName, IProgressMonitor monitor) throws CoreException { // create a sample file @@ -124,7 +120,7 @@ public class PHPFileWizard extends Wizard implements INewWizard { try { InputStream stream; if (className == null) { - stream = openContentStream(); + stream = openContentStream(fileName); } else { stream = openContentStreamClass(className); } @@ -142,7 +138,7 @@ public class PHPFileWizard extends Wizard implements INewWizard { public void run() { IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); try { - IDE.openEditor(page,file,true); + IDE.openEditor(page, file, true); } catch (PartInitException e) { } } @@ -152,21 +148,28 @@ public class PHPFileWizard extends Wizard implements INewWizard { /** * Check if the filename is like this anyname.class.php - * @param fileName the filename + * + * @param fFileName + * the filename * @return the anyname or null */ private static final String getClassName(final String fileName) { final int lastDot = fileName.lastIndexOf('.'); - if (lastDot == -1) return null; - final int precLastDot = fileName.lastIndexOf('.',lastDot-1); - if (precLastDot == -1) return null; - if (!fileName.substring(precLastDot+1,lastDot).toUpperCase().equals("CLASS")) return null; - return fileName.substring(0,precLastDot); + if (lastDot == -1) + return null; + final int precLastDot = fileName.lastIndexOf('.', lastDot - 1); + if (precLastDot == -1) + return null; + if (!fileName.substring(precLastDot + 1, lastDot).toUpperCase().equals("CLASS")) + return null; + return fileName.substring(0, precLastDot); } /** * We will initialize file contents for a class - * @param className the classname + * + * @param className + * the classname */ private InputStream openContentStreamClass(final String className) { StringBuffer contents = new StringBuffer(""); -// return new ByteArrayInputStream(contents.toString().getBytes()); + private InputStream openContentStream(String fileName) { + try { + Template template = PHPeclipsePlugin.getDefault().getCodeTemplateStore().findTemplate(CodeTemplateContextType.NEWTYPE); + if (template == null) { + return null; + } + String lineDelimiter = System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ + CodeTemplateContext context = new CodeTemplateContext(template.getContextTypeId(), null, lineDelimiter); + context.setFileNameVariable(fileName); + return new ByteArrayInputStream(StubUtility.evaluateTemplate(context, template).getBytes()); + } catch (CoreException e) { + e.printStackTrace(); + return null; + } + } private void throwCoreException(String message) throws CoreException { @@ -220,8 +209,8 @@ public class PHPFileWizard extends Wizard implements INewWizard { } /** - * We will accept the selection in the workbench to see if - * we can initialize from it. + * We will accept the selection in the workbench to see if we can initialize from it. + * * @see IWorkbenchWizard#init(IWorkbench, IStructuredSelection) */ public void init(IWorkbench workbench, IStructuredSelection selection) { @@ -229,10 +218,9 @@ public class PHPFileWizard extends Wizard implements INewWizard { } /** - * Sets the name of the file to create - * (used to set the class name in the new file) + * Sets the name of the file to create (used to set the class name in the new file) */ public void setFileName(String name) { - fileName = name; + fFileName = name; } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/PHPFileWizardPage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/PHPFileWizardPage.java index eb48f26..c84715c 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/PHPFileWizardPage.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/PHPFileWizardPage.java @@ -127,7 +127,7 @@ public class PHPFileWizardPage extends WizardPage { containerText.setText(container.getFullPath().toString()); } } - fileText.setText("index.php"); + fileText.setText("*.php"); } /** @@ -165,10 +165,10 @@ public class PHPFileWizardPage extends WizardPage { return; } - if (!PHPFileUtil.isPHPFileName(fileName)) { - updateStatus(PHPWizardMessages.getString("WizardPage.mustBePHP")); - return; - } +// if (!PHPFileUtil.isPHPFileName(fileName)) { +// updateStatus(PHPWizardMessages.getString("WizardPage.mustBePHP")); +// return; +// } updateStatus(null); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/PHPWizardMessages.properties b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/PHPWizardMessages.properties index 33e0dda..0f24a03 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/PHPWizardMessages.properties +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/PHPWizardMessages.properties @@ -5,7 +5,9 @@ ################################### WizardPage.title=PHP New File -WizardPage.description=This wizard creates a new file with *.php extension that can be opened by the PHP editor. +WizardPage.description=This wizard creates a new PHP file. +WizardPage.html.title=HTML New File +WizardPage.html.description=This wizard creates a new HTML file. WizardPage.containerLabel=&Container: WizardPage.fileLabel=&File name: WizardPage.browseButtonText=Browse... @@ -15,6 +17,8 @@ WizardPage.nameMustBeSpecified=File name must be specified. WizardPage.containerMustBeSpecified=File container must be specified. WizardPage.selectNewFileContainer=Select new file container. + + Wizard.error=An error occured Wizard.Monitor.creating=Creating Wizard.Monitor.openingFile=Opening file for editing... diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/TempnewPHPProject.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/TempnewPHPProject.java index caff19b..d0ac04f 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/TempnewPHPProject.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/TempnewPHPProject.java @@ -19,75 +19,76 @@ import org.eclipse.ui.dialogs.WizardNewProjectCreationPage; import org.eclipse.ui.wizards.newresource.BasicNewProjectResourceWizard; import org.eclipse.ui.wizards.newresource.BasicNewResourceWizard; - public class TempnewPHPProject extends BasicNewResourceWizard implements INewWizard { -/*This class has been added to cvs to provide a project page that - * works correctly and doesn't freezde while i investigate the - * errors completely - */ - private WizardNewProjectCreationPage phpProjPage; - private IConfigurationElement fConfigElement; + /* + * This class has been added to cvs to provide a project page that works correctly and doesn't freezde while i investigate the + * errors completely + */ + private WizardNewProjectCreationPage phpProjPage; - public TempnewPHPProject() { - setNeedsProgressMonitor(true); - setWindowTitle("New Project creation"); //$NON-NLS-1$ + private IConfigurationElement fConfigElement; - } + public TempnewPHPProject() { + setNeedsProgressMonitor(true); + setWindowTitle("New Project creation"); //$NON-NLS-1$ - public void addPages() { - super.addPages(); - phpProjPage= new WizardNewProjectCreationPage("NewProjectCreationWizard"); //$NON-NLS-1$ - phpProjPage.setTitle(PHPWizardMessages.getString("WizardNewProjectCreationPage.pageTitle")); //$NON-NLS-1$ - phpProjPage.setDescription(PHPWizardMessages.getString("WizardNewProjectCreationPage.pageDescription")); //$NON-NLS-1$ - addPage(phpProjPage); - } + } - public void setInitializationData(IConfigurationElement cfig, String propertyName, Object data) { - fConfigElement= cfig; - } + public void addPages() { + super.addPages(); + phpProjPage = new WizardNewProjectCreationPage("NewProjectCreationWizard"); //$NON-NLS-1$ + phpProjPage.setTitle(PHPWizardMessages.getString("WizardNewProjectCreationPage.pageTitle")); //$NON-NLS-1$ + phpProjPage.setDescription(PHPWizardMessages.getString("WizardNewProjectCreationPage.pageDescription")); //$NON-NLS-1$ + addPage(phpProjPage); + } - protected void initializeDefaultPageImageDescriptor() { - // not used yet - } + public void setInitializationData(IConfigurationElement cfig, String propertyName, Object data) { + fConfigElement = cfig; + } - protected void finishPage() throws InterruptedException, CoreException { - createProject(phpProjPage.getProjectHandle(), phpProjPage.getLocationPath(), new NullProgressMonitor()); - BasicNewProjectResourceWizard.updatePerspective(fConfigElement); - selectAndReveal(phpProjPage.getProjectHandle()); - } - protected void handleFinishException(Shell shell, InvocationTargetException e) { - ExceptionHandler.handle(e, getShell(), "Error title", "Error message"); - } + protected void initializeDefaultPageImageDescriptor() { + // not used yet + } - public boolean performFinish() { - try { - finishPage(); - } catch (InterruptedException e) { - } catch (CoreException e) { - } - return true; - } + protected void finishPage() throws InterruptedException, CoreException { + createProject(phpProjPage.getProjectHandle(), phpProjPage.getLocationPath(), new NullProgressMonitor()); + BasicNewProjectResourceWizard.updatePerspective(fConfigElement); + selectAndReveal(phpProjPage.getProjectHandle()); + } - public void createProject(IProject project, IPath locationPath, IProgressMonitor monitor) throws CoreException { - try { - if (!project.exists()) { - IProjectDescription desc= project.getWorkspace().newProjectDescription(project.getName()); - if (Platform.getLocation().equals(locationPath)) { - locationPath= null; - } - desc.setLocation(locationPath); - project.create(desc, monitor); - monitor= null; - } - if (!project.isOpen()) { - project.open(monitor); - monitor= null; - } - JavaCore.addPHPNature(project, new NullProgressMonitor()); - } finally { - if (monitor != null) { - monitor.done(); - } - } - } -} + protected void handleFinishException(Shell shell, InvocationTargetException e) { + ExceptionHandler.handle(e, getShell(), "Error title", "Error message"); + } + + public boolean performFinish() { + try { + finishPage(); + } catch (InterruptedException e) { + } catch (CoreException e) { + } + return true; + } + + public void createProject(IProject project, IPath locationPath, IProgressMonitor monitor) throws CoreException { + try { + if (!project.exists()) { + IProjectDescription desc = project.getWorkspace().newProjectDescription(project.getName()); + if (Platform.getLocation().equals(locationPath)) { + locationPath = null; + } + desc.setLocation(locationPath); + project.create(desc, monitor); + monitor = null; + } + if (!project.isOpen()) { + project.open(monitor); + monitor = null; + } + JavaCore.addPHPNature(project, new NullProgressMonitor()); + } finally { + if (monitor != null) { + monitor.done(); + } + } + } +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/EditElementWizard.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/EditElementWizard.java new file mode 100644 index 0000000..3535053 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/EditElementWizard.java @@ -0,0 +1,116 @@ +/* + * $Id: EditElementWizard.java,v 1.1 2004-10-05 20:51:57 jsurfer Exp $ + * Copyright Narushima Hironori. All rights reserved. + */ +package net.sourceforge.phpeclipse.wizards.html; + +import net.sourceforge.phpdt.internal.ui.PHPUiImages; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.core.resources.IFile; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.ITextSelection; +import org.eclipse.jface.wizard.IWizardPage; +import org.eclipse.jface.wizard.Wizard; +import org.eclipse.ui.IEditorInput; +import org.eclipse.ui.IFileEditorInput; +import org.eclipse.ui.texteditor.ITextEditor; + +/** + * EditElementWizard. TODO: privides extension point element editor. pluggable element edit page. + */ +public class EditElementWizard extends Wizard { + + static Object[] elementEditPages = new Object[] { + // "a", AElementWizardPage.class, + // "img", ImgElementWizardPage.class, + "dl", ListElementWizardPage.class, + "ul", ListElementWizardPage.class, + "ol", ListElementWizardPage.class, + "table", TableElementWizardPage.class }; + + String targetElemName; + + ITextEditor htEditor; + + EditElementWizardPage rootPage; + + /** + * Second argument specify element name, If specify null, call new element edit wizard page. + */ + public EditElementWizard(ITextEditor editor, String targetElemName) { + htEditor = editor; + this.targetElemName = targetElemName; + + setWindowTitle("Edit HTML Element"); + setDefaultPageImageDescriptor(PHPUiImages.getImageRegistry().getDescriptor("wizban/editelem_wiz.gif")); + + setForcePreviousAndNextButtons(true); + } + + public void addPages() { + if (targetElemName == null) { + rootPage = new NewElementWizardPage(); + } else { + IDocument doc = getDocument(); + rootPage = createElementEditPage(targetElemName); + rootPage.setEditType(EditElementWizardPage.MODIFY); + } + addPage(rootPage); + } + + public boolean performFinish() { + IWizardPage page = rootPage; + for (IWizardPage p; (p = page.getNextPage()) != null;) { + page = p; + } + if (page instanceof EditElementWizardPage) { + ((EditElementWizardPage) page).performFinish(); + } + return true; + } + + public IDocument getDocument() { + return htEditor.getDocumentProvider().getDocument(htEditor.getEditorInput()); + } + + public ITextSelection getSelection() { + return (ITextSelection) htEditor.getSelectionProvider().getSelection(); + } + + public void setSelection(ITextSelection sel) { + htEditor.getSelectionProvider().setSelection(sel); + } + + public IFile getCurrentEditFile() { + IEditorInput input = htEditor.getEditorInput(); + return (input instanceof IFileEditorInput) ? ((IFileEditorInput) input).getFile() : null; + } + + /** + * If not edit target returns UnknownElementWizardPage. + */ + public EditElementWizardPage createElementEditPage(String elementName) { + EditElementWizardPage page = null; + try { + for (int i = 0; i < elementEditPages.length; i += 2) { + if (((String) elementEditPages[i]).equalsIgnoreCase(elementName)) { + Class klass = (Class) elementEditPages[i + 1]; + page = (EditElementWizardPage) klass.newInstance(); + } + } + } catch (InstantiationException e) { + PHPeclipsePlugin.log(e); + } catch (IllegalAccessException e) { + PHPeclipsePlugin.log(e); + } + if (page == null) { + page = new UnknownElementWizardPage(); + } + page.setElementName(elementName); + page.setWizard(this); + + return page; + } + +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/EditElementWizardPage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/EditElementWizardPage.java new file mode 100644 index 0000000..144e166 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/EditElementWizardPage.java @@ -0,0 +1,186 @@ +/* + * $Id: EditElementWizardPage.java,v 1.1 2004-10-05 20:51:57 jsurfer Exp $ + * Copyright Narushima Hironori. All rights reserved. + */ +package net.sourceforge.phpeclipse.wizards.html; + +import java.io.IOException; +import java.io.StringReader; + +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.ITextSelection; +import org.eclipse.jface.text.TextSelection; +import org.eclipse.jface.wizard.IWizard; +import org.eclipse.jface.wizard.WizardPage; +import org.eclipse.swt.SWT; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Text; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + +/** + * + * + */ +public abstract class EditElementWizardPage extends WizardPage implements IPreviewer { + + final public static int NEW = 0, MODIFY = 1; + + private static DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); + + Composite extendComp; + + Text preview; + + private String elementName = null; + + int editType = NEW; + + protected EditElementWizardPage(String pageName) { + super(pageName); + } + + public void createControl(Composite parent) { + Composite base = new Composite(parent, SWT.NONE); + setControl(base); + base.setLayout(new GridLayout(1, false)); + + // create child control. + Composite childControlBase = new Composite(base, SWT.NONE); + childControlBase.setLayoutData(new GridData(GridData.FILL_BOTH)); + try { + createChildControl(childControlBase); + } catch (CoreException e) { + PHPeclipsePlugin.log(e); + return; + } + + // preview components. + Composite previewBase = new Composite(base, SWT.NONE); + + GridData gd = new GridData(GridData.FILL_HORIZONTAL); + previewBase.setLayoutData(gd); + previewBase.setLayout(new GridLayout(1, false)); + + Label labe = new Label(previewBase, SWT.NONE); + labe.setText("Preview:"); + gd = new GridData(GridData.FILL_HORIZONTAL); + labe.setLayoutData(gd); + + preview = new Text(previewBase, SWT.BORDER | SWT.MULTI | SWT.READ_ONLY | SWT.WRAP | SWT.V_SCROLL | SWT.H_SCROLL); + gd = new GridData(GridData.FILL_HORIZONTAL); + gd.widthHint = 0; + gd.heightHint = preview.getLineHeight() * 4; + preview.setLayoutData(gd); + + refreshPreview(); + } + + abstract protected void createChildControl(Composite parent) throws CoreException; + + public abstract String getPreviewText(); + + public void refreshPreview() { + if (preview != null) { + String text = getPreviewText(); + preview.setText(text == null ? "" : text); + } + } + + public String getElementName() { + return elementName; + } + + public void setElementName(String string) { + elementName = string; + } + + protected IFile getEditFile() { + IFile file = null; + IWizard wiz = getWizard(); + if (wiz instanceof EditElementWizard) { + file = ((EditElementWizard) wiz).getCurrentEditFile(); + } + return file; + } + + protected void performFinish() { + EditElementWizard wiz = (EditElementWizard) getWizard(); + ITextSelection sel = wiz.getSelection(); + IDocument doc = wiz.getDocument(); + int offset = sel.getOffset(); + try { + doc.replace(offset, sel.getLength(), getPreviewText()); + } catch (BadLocationException e) { + PHPeclipsePlugin.log(e); + } + int index = doc.get().indexOf('>', offset); + if (index != -1) { + wiz.setSelection(new TextSelection(index + 1, 0)); + } + } + + /** + * Returns edit type. + */ + public int getEditType() { + return editType; + } + + /** + * Sets edit type that types are EditElementWizardPage.NEW, EditElementWizardPage.MODIFY. Default value is NEW. + */ + public void setEditType(int i) { + editType = i; + } + + protected String getSelectionText() { + return ((EditElementWizard) getWizard()).getSelection().getText(); + } + + protected Element getParsedSelectionText() { + String selText = getSelectionText(); + try { + InputSource source = new InputSource(new StringReader(selText)); + Document doc = docBuilderFactory.newDocumentBuilder().parse(source); + return doc.getDocumentElement(); + } catch (SAXException e) { + } catch (IOException e) { + } catch (ParserConfigurationException e) { + } + return null; + + } + + protected static String chooseContent(String text) { + int b = -1, e = -1, len = text.length(); + for (int i = 0; i < len; i++) { + if (text.charAt(i) == '>') { + b = i + 1; + break; + } + } + for (int i = len - 1; i >= 0; i--) { + if (text.charAt(i) == '<') { + e = i; + break; + } + } + return (b != -1 && e != -1 && b < len && e < len) ? text.substring(b, e) : ""; + + } + +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/ElementWriter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/ElementWriter.java new file mode 100644 index 0000000..8163410 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/ElementWriter.java @@ -0,0 +1,133 @@ +/* + * $Id: ElementWriter.java,v 1.1 2004-10-05 20:51:57 jsurfer Exp $ + * Copyright Narushima Hironori. All rights reserved. + */ +package net.sourceforge.phpeclipse.wizards.html; + +import java.io.*; +import java.util.HashMap; + +import org.w3c.dom.*; + +/** + * ElementWriter provides destribute xml code. + */ +public class ElementWriter { + + final public static int + BEGIN_CHANGELINE = 1, + END_CHANGELINE = 2; + + boolean trim = true; + HashMap expandOptions = new HashMap(); + int defaultExpandOption; + String indent; + + public ElementWriter() { + this(0, " "); + } + + public ElementWriter(int defaultExpandOption, String indent) { + this.defaultExpandOption = defaultExpandOption; + this.indent = indent; + } + + public void setExpandOption(String elementName, int value){ + expandOptions.put(elementName, new Integer(value)); + } + + public int getExpandOption(String elementName){ + if( expandOptions.containsKey(elementName)){ + return ((Integer)expandOptions.get(elementName)).intValue(); + } + return defaultExpandOption; + } + + boolean isBeginChangeLine(String elementName){ + return (getExpandOption(elementName) & BEGIN_CHANGELINE) != 0; + } + + boolean isEndChangeLine(String elementName){ + return (getExpandOption(elementName) & END_CHANGELINE) != 0; + } + + public String expandTag(Element element){ + StringBuffer buff = new StringBuffer(); + expandTag(element, 0, buff); + return buff.toString(); + } + + public void writeTag(Element element, OutputStream out) throws IOException { + OutputStreamWriter writer = new OutputStreamWriter(out); + try{ + writer.write("\n\n"); + writer.write(new ElementWriter().expandTag(element)); + }finally{ + if(writer != null){ + writer.close(); + } + } + } + + void expandTag(Element element, int level, StringBuffer buff){ + expandIndent(level, buff); + + String elementName = element.getNodeName(); + buff.append('<' + elementName ); + NamedNodeMap attrs = element.getAttributes(); + for(int i=0; i'); + if(!emptyElem ){ + NodeList childElements = element.getChildNodes(); + if(isBeginChangeLine(elementName)){ + buff.append('\n'); + } + for(int i=0; i'); + } + // already inserted change line. + if( isEndChangeLine(elementName) ){ + buff.append('\n'); + } + } + + void expandIndent(int level, StringBuffer buff){ + if(indent != null){ + for(int i=0; i\n"); + buff.append( getSelectionText() ); + buff.append("\n\n"); + + return buff.toString(); + } + +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/HTMLUtilities.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/HTMLUtilities.java new file mode 100644 index 0000000..945bbcf --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/HTMLUtilities.java @@ -0,0 +1,37 @@ +/* + * $Id: HTMLUtilities.java,v 1.1 2004-10-05 20:51:57 jsurfer Exp $ + * Copyright Narushima Hironori. All rights reserved. + */ +package net.sourceforge.phpeclipse.wizards.html; + + +/** + * + */ +public class HTMLUtilities { + + final static String[] specialMarks = { + "&", "&", + "<", "<", + ">", ">", + "\"", """, + }; + + public static String escape(String text){ + for (int i = 0; i < specialMarks.length; i+=2) { + text = text.replaceAll(specialMarks[i], specialMarks[i+1]); + } + return text; + } + + public static String unescape(String text){ + for (int i = specialMarks.length-1; i>=0 ; i-=2) { + text = text.replaceAll(specialMarks[i], specialMarks[i-1]); + } + return text; + } + + + + +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/IPreviewer.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/IPreviewer.java new file mode 100644 index 0000000..bd2f1e5 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/IPreviewer.java @@ -0,0 +1,14 @@ +/* + * $Id: IPreviewer.java,v 1.1 2004-10-05 20:51:57 jsurfer Exp $ + * Copyright Narushima Hironori. All rights reserved. + */ +package net.sourceforge.phpeclipse.wizards.html; + +/** + * + */ +public interface IPreviewer { + + String getPreviewText(); + +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/InsertHTMLElementAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/InsertHTMLElementAction.java new file mode 100644 index 0000000..ac5303d --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/InsertHTMLElementAction.java @@ -0,0 +1,51 @@ +/* + * $Id: InsertHTMLElementAction.java,v 1.1 2004-10-05 20:51:57 jsurfer Exp $ + * Copyright Narushima Hironori. All rights reserved. + */ +package net.sourceforge.phpeclipse.wizards.html; + +import net.sourceforge.phpeclipse.wizards.html.EditElementWizard; + +import org.eclipse.jface.action.IAction; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.wizard.WizardDialog; +import org.eclipse.swt.SWT; +import org.eclipse.ui.*; +import org.eclipse.ui.texteditor.ITextEditor; + + +/** + * InsertTagAction + */ +public class InsertHTMLElementAction implements IEditorActionDelegate { + + ITextEditor targetEditor = null; + + public InsertHTMLElementAction() { + } + + public void setActiveEditor(IAction action, IEditorPart targetEditor) { + if(targetEditor instanceof ITextEditor){ + this.targetEditor = (ITextEditor)targetEditor; + } + } + + public void run(IAction action) { + + WizardDialog wizDialog = + new WizardDialog( + targetEditor.getSite().getShell(), + new EditElementWizard(targetEditor, null) ){ + + protected int getShellStyle() { + return super.getShellStyle() | SWT.RESIZE; + } + }; + + wizDialog.open(); + } + + public void selectionChanged(IAction action, ISelection selection) { + } + +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/ListElementWizardPage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/ListElementWizardPage.java new file mode 100644 index 0000000..e67d461 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/ListElementWizardPage.java @@ -0,0 +1,80 @@ +/* + * $Id: ListElementWizardPage.java,v 1.1 2004-10-05 20:51:57 jsurfer Exp $ + * Copyright Narushima Hironori. All rights reserved. + */ +package net.sourceforge.phpeclipse.wizards.html; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.*; +import org.eclipse.swt.layout.*; +import org.eclipse.swt.widgets.*; + +/** + * + */ +public class ListElementWizardPage extends EditElementWizardPage { + + final static String[] LIST_TYPES = {"ul", "ol", "dl"}; + + Combo types; + + public ListElementWizardPage() { + super("ListElementWizardPage"); + setTitle("List"); + setDescription("Editing list element."); + } + + protected void createChildControl(Composite parent) { + parent.setLayout(new GridLayout(2, false)); + Label labe = new Label(parent, SWT.NONE); + labe.setText("List &Type:"); + + types = new Combo(parent, SWT.DROP_DOWN | SWT.READ_ONLY); + + for (int i = 0; i < LIST_TYPES.length; i++) { + String type = LIST_TYPES[i]; + types.add(type); + if( getElementName().equals(type) ){ + types.select(i); + } + } + + types.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + types.addSelectionListener(new SelectionListener() { + public void widgetSelected(SelectionEvent e) { + setElementName( types.getText() ); + refreshPreview(); + } + public void widgetDefaultSelected(SelectionEvent e) {} + }); + } + + public String getPreviewText() { + String content = ((EditElementWizard) getWizard() ).getSelection().getText().trim(); + + String elemName = getElementName(); + switch (getEditType()) { + case MODIFY: + content = chooseContent(content).trim(); + break; + + case NEW: + String[] lines = content.split("\n+"); + StringBuffer result = new StringBuffer(); + for (int i = 0; i < lines.length; i++) { + String itemElemName; + if(elemName.equals("dl")){ + itemElemName = (i % 2 == 0) ? "dt" : "dd"; + }else{ + itemElemName = "li"; + } + result.append( "<" + itemElemName + ">" + lines[i].trim() + "\n"); + } + content = result.toString(); + break; + } + + return "<" + elemName + ">\n" + content + "\n"; + } + +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/NewElementWizardPage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/NewElementWizardPage.java new file mode 100644 index 0000000..4b39fa9 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/NewElementWizardPage.java @@ -0,0 +1,78 @@ +/* + * $Id: NewElementWizardPage.java,v 1.1 2004-10-05 20:51:57 jsurfer Exp $ + * Copyright Narushima Hironori. All rights reserved. + */ +package net.sourceforge.phpeclipse.wizards.html; + +import org.eclipse.jface.wizard.IWizardPage; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.*; +import org.eclipse.swt.layout.*; +import org.eclipse.swt.widgets.*; + + +/** + * + */ +public class NewElementWizardPage extends EditElementWizardPage { + + Text elementName; + EditElementWizardPage nextPage = null; + + public NewElementWizardPage() { + super("NewElementPage"); + setTitle("Create HTML Element"); + setDescription("Specify new HTML tag (dl,ul,ol or table) and configure that tag."); + } + + protected void createChildControl(Composite base) { + // create foundation component + base.setLayout(new GridLayout(1, false)); + + // element input components + new Label(base, SWT.NONE).setText("&Element Name:"); + + elementName = new Text(base, SWT.BORDER | SWT.SINGLE); + elementName.setLayoutData( new GridData(GridData.FILL_HORIZONTAL)); + elementName.addModifyListener( new ModifyListener() { + public void modifyText(ModifyEvent e) { + String eName = elementName.getText(); + if( eName.indexOf(' ') != -1 ){ + setErrorMessage("Don't contain blink in speicfied element name."); + } else if (eName.length() == 0){ + setErrorMessage("Need to specify element name."); + } else { + setErrorMessage(null); + nextPage = ((EditElementWizard)getWizard()).createElementEditPage(eName); + nextPage.setElementName(eName); + if( nextPage instanceof UnknownElementWizardPage){ + setMessage("This editor does not known element name.", WARNING); + }else{ + setMessage(null, NONE); + } + } + refreshPreview(); + getWizard().getContainer().updateButtons(); + } + }); + } + + public String getPreviewText(){ + if(nextPage instanceof EditElementWizardPage){ + return ((EditElementWizardPage)nextPage).getPreviewText(); + } + return null; + } + + public void setErrorMessage(String newMessage) { + super.setErrorMessage(newMessage); + if( newMessage != null){ + nextPage = null; + } + } + + public IWizardPage getNextPage() { + return nextPage; + } + +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/NumVerifyListener.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/NumVerifyListener.java new file mode 100644 index 0000000..4773702 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/NumVerifyListener.java @@ -0,0 +1,19 @@ +/* + * $Id: NumVerifyListener.java,v 1.1 2004-10-05 20:51:57 jsurfer Exp $ + * Copyright Narushima Hironori. All rights reserved. + */ +package net.sourceforge.phpeclipse.wizards.html; + +import java.util.regex.Pattern; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.*; + +public class NumVerifyListener implements VerifyListener { + + Pattern numPattern = Pattern.compile("^\\d+$"); + + public void verifyText(VerifyEvent ev) { + ev.doit = numPattern.matcher( ev.text ).matches() || ev.keyCode == SWT.DEL || ev.character == SWT.BS; + } +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/SomeItemInputDialog.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/SomeItemInputDialog.java new file mode 100644 index 0000000..19a7d32 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/SomeItemInputDialog.java @@ -0,0 +1,116 @@ +/* + * $Id: SomeItemInputDialog.java,v 1.1 2004-10-05 20:51:57 jsurfer Exp $ + * Copyright Narushima Hironori. All rights reserved. + */ +package net.sourceforge.phpeclipse.wizards.html; + +import org.eclipse.jface.dialogs.*; +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.*; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.layout.*; +import org.eclipse.swt.widgets.*; + +/** + * + */ +public class SomeItemInputDialog extends Dialog { + + String dialogTitle; + String[] inputMessages; + + IInputValidator[] validators; + Text[] texts; + Text error; + + String[] errorMsgs; + String[] resultValues; + + public SomeItemInputDialog(Shell parentShell, String dialogTitle, String[] inputMessages, IInputValidator[] validators) { + super(parentShell); + if(inputMessages.length != validators.length){ + throw new IllegalArgumentException("Specify validator counts and input message count is not same."); + } + + this.dialogTitle = dialogTitle; + this.inputMessages = (String[])inputMessages.clone(); + this.validators = (IInputValidator[])validators.clone(); + this.errorMsgs = new String[validators.length]; + + setShellStyle(SWT.RESIZE | getShellStyle()); + } + + protected void configureShell(Shell newShell) { + super.configureShell(newShell); + newShell.setText(dialogTitle); + } + + protected Control createDialogArea(Composite parent) { + Composite base = (Composite)super.createDialogArea(parent); + GridLayout gl = new GridLayout(2, false); + gl.marginWidth = 4; + gl.marginHeight = 6; + base.setLayout(gl); + + texts = new Text[inputMessages.length]; + for(int i=0; i"); + + String[] splitRegexpCandidates = { + "\t", + ",", + "\\s", + "\\s+", + }; + + public StringDivider() { + } + + public String[][] divide(String content){ + return divide(content, getDivideSuitedRegexp(content)); + } + + public String[][] divide(String content, String regexp){ + String[] lines = content.split("\n"); + int len = lines.length; + String[][] dist = new String[len][]; + + int max = Integer.MIN_VALUE; + for (int i = 0; i < len; i++) { + String line = lines[i]; + String[] cells = line.split(regexp); + dist[i] = cells; + if(max < cells.length){ + max = cells.length; + } + } + for (int i = 0; i < len; i++) { + String[] newArray = new String[max]; + Arrays.fill(newArray, ""); + System.arraycopy(dist[i], 0, newArray, 0, dist[i].length); + dist[i] = newArray; + } + return dist; + } + + public String getDivideSuitedRegexp(String content){ + String[] lines = content.split("\n"); + + String resultRegexp = null; + int score = Integer.MAX_VALUE, cellCount = Integer.MIN_VALUE; + + for (int i = 0; i < splitRegexpCandidates.length; i++) { + String regexp = splitRegexpCandidates[i]; + int max = Integer.MIN_VALUE, min = Integer.MAX_VALUE; + for (int j = 0; j < lines.length; j++) { + String[] vals = lines[j].split(regexp); + if(max < vals.length){ + max = vals.length; + } + if(min > vals.length){ + min = vals.length; + } + } + int s = max - min; + if( score > s || (score == s && max > cellCount)){ + cellCount = max; + score = s; + resultRegexp = regexp; + } + } + return resultRegexp; + } + +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/TableElementCellModifier.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/TableElementCellModifier.java new file mode 100644 index 0000000..b6b06bb --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/TableElementCellModifier.java @@ -0,0 +1,75 @@ +/* + * $Id: TableElementCellModifier.java,v 1.1 2004-10-05 20:51:57 jsurfer Exp $ + * Copyright Narushima Hironori. All rights reserved. + */ +package net.sourceforge.phpeclipse.wizards.html; + +import javax.xml.parsers.DocumentBuilderFactory; + +import org.eclipse.jface.util.*; +import org.eclipse.jface.viewers.ICellModifier; +import org.eclipse.swt.widgets.Item; +import org.w3c.dom.*; + +/** + * + */ +public class TableElementCellModifier implements ICellModifier { + + DocumentBuilderFactory builderFactory; + IPropertyChangeListener listener; + + public TableElementCellModifier(IPropertyChangeListener listener) { + builderFactory = DocumentBuilderFactory.newInstance(); + this.listener = listener; + } + + public boolean canModify(Object element, String property) { + return getValue(element, property) != null; + } + + public Object getValue(Object trElem, String property) { + if(trElem instanceof Element){ + Element e = (Element)trElem; + if( e.getNodeName().equals("tr") ){ + int v = TableElementModel.toNumeric(property); + Element[] cells = TableElementModel.chooseCellElements(e); + if(v >= 0 && v < cells.length){ + NodeList nodes = cells[v].getChildNodes(); + if(nodes.getLength() == 1){ + Node n = nodes.item(0); + if(n instanceof Text){ + return n.getNodeValue(); + } + } + } + } + } + return null; + } + + public void modify(Object element, String property, Object value) { + if (element instanceof Item) { + element = ((Item) element).getData(); + } + Element trElem = (Element)element; + int index = TableElementModel.toNumeric(property); + Element cellElem = TableElementModel.chooseCellElements(trElem)[index]; + + NodeList nodes = cellElem.getChildNodes(); + for(int i=0; i 0){ + for (int i = 0; i < cells.length; i++) { + String[] rows = cells[i]; + Element tr = document.createElement("tr"); + for (int j = 0; j < rows.length; j++) { + Element e = document.createElement("td"); + e.appendChild(document.createTextNode(rows[j])); + tr.appendChild(e); + } + tableElement.appendChild(tr); + } + + setColumnCount(cells[0].length); + }else{ + Element tr = document.createElement("tr"); + Element td = document.createElement("td"); + td.appendChild(document.createTextNode("")); + tr.appendChild(td); + tableElement.appendChild(tr); + + setColumnCount(1); + } + } + + String[] createColumnProperties(){ + int len = getColumnCount(); + String[] props = new String[len]; + for(int i=0; i rows.length){ + for(int i=rows.length; i colLen ){ + for(int j=0, len = newLength - colLen; j 0){ + Element tr = (Element)trs.item(0); + return chooseCellElements(tr).length; + }else{ + return 0; + } + } + + public static Element[] chooseCellElements(Element tr){ + NodeList nodeList = tr.getChildNodes(); + + ArrayList result = new ArrayList(); + for(int i=0; i 0){ + buff.append(CHAR_TABLE[u-1]); + } + buff.append( CHAR_TABLE[i % CHAR_TABLE.length] ); + return buff.toString(); + } + + /** + * Return index of char map. If can not parse values return -1. + */ + public static int toNumeric(String code){ + int result = -1; + for(int i=0; i= 0){ + if(result == -1){ + result = 0; + } + int v = match; + int u = code.length()-1-i; + if(u>0){ + v = CHAR_TABLE.length * u * (v+1); + } + result += v; + } + } + return result; + } + + public void move(Element tr, int moveCount){ + Element[] rows = getRows(); + int index = -1; + for(int i=0;i 0){ + // move down; + for(int i=index; i=moveCount+index+1 && i >= 1; i--){ + tableElement.insertBefore(rows[index], rows[i-1]); + } + }else{ + return; + } + } + + public void insertNewRowBefore(Element tr){ + Element newRow = createRowElement(); + if( tr == null){ + tableElement.appendChild(newRow); + }else{ + tableElement.insertBefore(newRow, tr); + } + } + + public void removeRow(Element tr){ + tableElement.removeChild(tr); + } + + public String[] getColumnProperties() { + return (String[])columnProperties.clone(); + } + +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/TableElementWizardPage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/TableElementWizardPage.java new file mode 100644 index 0000000..cce7813 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/TableElementWizardPage.java @@ -0,0 +1,285 @@ +/* + * $Id: TableElementWizardPage.java,v 1.1 2004-10-05 20:51:57 jsurfer Exp $ + * Copyright Narushima Hironori. All rights reserved. + */ +package net.sourceforge.phpeclipse.wizards.html; + +import java.io.IOException; + +import javax.xml.parsers.ParserConfigurationException; + +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.jface.util.IPropertyChangeListener; +import org.eclipse.jface.util.PropertyChangeEvent; +import org.eclipse.jface.viewers.CellEditor; +import org.eclipse.jface.viewers.ISelectionChangedListener; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.viewers.SelectionChangedEvent; +import org.eclipse.jface.viewers.TableViewer; +import org.eclipse.jface.viewers.TextCellEditor; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.ModifyEvent; +import org.eclipse.swt.events.ModifyListener; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Combo; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Table; +import org.eclipse.swt.widgets.TableColumn; +import org.eclipse.swt.widgets.Text; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +/** + * TableElementWizardPage. + */ +public class TableElementWizardPage extends EditElementWizardPage { + + final public static int COLUMNS_MAX = 32, ROWS_MAX = 256; + + final static String[] expandStyleLabels = { "Flat", "Table", "Enumerate", }; + + TableElementModel model; + + TableViewer viewer; + + CellEditor[] editors; + + Combo expandStyleCombo = null; + + Text colsText, rowsText; + + Button addButton, removeButton, upButton, downButton; + + SelectionListener buttonListener = new SelectionListener() { + public void widgetSelected(SelectionEvent ev) { + Element e = getCurrentSelection(); + if (ev.widget == addButton) { + model.insertNewRowBefore(e); + } else if (ev.widget == removeButton) { + model.removeRow(e); + } else if (ev.widget == upButton) { + model.move(e, -1); + } else if (ev.widget == downButton) { + model.move(e, 1); + } + refreshAll(); + } + + public void widgetDefaultSelected(SelectionEvent e) { + } + }; + + ModifyListener cellCountChangeListener = new ModifyListener() { + public void modifyText(ModifyEvent e) { + try { + if (e.widget == colsText) { + int cols = Integer.parseInt(colsText.getText()); + if (cols < 1) + cols = 1; + if (cols > COLUMNS_MAX) + cols = COLUMNS_MAX; + model.setColumnCount(cols); + } else if (e.widget == rowsText) { + int rows = Integer.parseInt(rowsText.getText()); + if (rows < 1) + rows = 1; + if (rows > ROWS_MAX) + rows = ROWS_MAX; + model.setRowCount(rows); + } + refreshAll(); + } catch (NumberFormatException x) { + } + } + }; + + public TableElementWizardPage() { + super("TableElementWizardPage"); + setTitle("Table"); + setDescription("Edit table element and cells modifier."); + } + + public String getPreviewText() { + if (model == null) { + initModel(); + } + return (model != null) ? model.expandCodes() : null; + } + + void initModel() { + String content = ((EditElementWizard) getWizard()).getSelection().getText().trim(); + try { + model = new TableElementModel(content, getEditType() == NEW); + } catch (ParserConfigurationException e) { + PHPeclipsePlugin.log(e); + } catch (SAXException e) { + PHPeclipsePlugin.log(e); + } catch (IOException e) { + PHPeclipsePlugin.log(e); + } + } + + protected void createChildControl(Composite parent) { + parent.setLayout(new GridLayout(2, false)); + + // table settings + viewer = new TableViewer(parent, SWT.SINGLE | SWT.FULL_SELECTION | SWT.BORDER); + refreshTableHeaderColumns(); + + viewer.setContentProvider(new TableElementContentProvider()); + viewer.setLabelProvider(new TableElementLabelProvider()); + viewer.setCellModifier(new TableElementCellModifier(new IPropertyChangeListener() { + public void propertyChange(PropertyChangeEvent event) { + refreshAll(); + } + })); + + viewer.setInput(model); + viewer.addSelectionChangedListener(new ISelectionChangedListener() { + public void selectionChanged(SelectionChangedEvent event) { + refreshButtonState(); + refreshPreview(); + } + }); + + Table table = viewer.getTable(); + table.setLinesVisible(true); + table.setHeaderVisible(true); + + GridData gd = new GridData(GridData.FILL_BOTH); + gd.verticalSpan = 2; + table.setLayoutData(gd); + + // text input area setting + Composite textInputArea = new Composite(parent, SWT.NONE); + textInputArea.setLayout(new GridLayout(1, false)); + textInputArea.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_BEGINNING)); + rowsText = createNumInputText(textInputArea, "&Rows:"); + colsText = createNumInputText(textInputArea, "&Columns:"); + + // button area. + Composite buttonArea = new Composite(parent, SWT.NONE); + buttonArea.setLayout(new GridLayout(1, false)); + buttonArea.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_END)); + addButton = createButton(buttonArea, "&Add"); + removeButton = createButton(buttonArea, "&Remove"); + upButton = createButton(buttonArea, "&Up"); + downButton = createButton(buttonArea, "&Down"); + + // init state + TableColumn[] cols = table.getColumns(); + for (int i = 0; i < cols.length; i++) { + cols[i].pack(); + } + refreshTableLengthText(); + refreshButtonState(); + } + + Button createButton(Composite parent, String text) { + Button button = new Button(parent, SWT.NONE); + button.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); + button.setText(text); + button.addSelectionListener(buttonListener); + return button; + } + + Text createNumInputText(Composite parent, String label) { + Label labe = new Label(parent, SWT.NONE); + labe.setText(label); + + Text text = new Text(parent, SWT.BORDER); + text.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); + text.setTextLimit(2); + text.addVerifyListener(new NumVerifyListener()); + text.addModifyListener(cellCountChangeListener); + return text; + } + + void refreshAll() { + refreshTableHeaderColumns(); + refreshTableLengthText(); + refreshButtonState(); + refreshPreview(); + viewer.refresh(); + } + + void refreshTableHeaderColumns() { + if (model == null) { + initModel(); + } + + Table table = viewer.getTable(); + TableColumn[] cols = table.getColumns(); + CellEditor[] editors = viewer.getCellEditors(); + + String[] props = model.getColumnProperties(); + viewer.setColumnProperties(props); + // modify cell length + if (props.length > cols.length) { + CellEditor[] newEditors = new CellEditor[props.length]; + if (editors != null) { + System.arraycopy(editors, 0, newEditors, 0, editors.length); + } + for (int i = cols.length; i < props.length; i++) { + TableColumn col = new TableColumn(table, SWT.LEFT); + col.setText(TableElementModel.toColumnName(i)); + newEditors[i] = new TextCellEditor(table); + } + viewer.setCellEditors(newEditors); + } else if (props.length < cols.length) { + for (int i = props.length; i < cols.length; i++) { + cols[i].dispose(); + editors[i].dispose(); + } + CellEditor[] newEditors = new CellEditor[props.length]; + System.arraycopy(editors, 0, newEditors, 0, props.length); + viewer.setCellEditors(newEditors); + } + + // adjust table fields. + viewer.refresh(); + cols = table.getColumns(); + for (int i = 0; i < cols.length; i++) { + cols[i].pack(); + } + } + + void refreshTableLengthText() { + String cols = String.valueOf(model.getColumnCount()); + if (!cols.equals(colsText.getText())) { + colsText.setText(cols); + } + String rows = String.valueOf(model.getRowCount()); + if (!rows.equals(rowsText.getText())) { + rowsText.setText(rows); + } + } + + void refreshButtonState() { + Element e = getCurrentSelection(); + boolean enable = (e != null); + + removeButton.setEnabled(enable); + int currentIndex = -1; + Element[] rows = model.getRows(); + for (int i = 0; i < rows.length; i++) { + if (rows[i].equals(e)) { + currentIndex = i; + } + } + upButton.setEnabled(enable && currentIndex > 0); + downButton.setEnabled(enable && currentIndex < rows.length - 1); + } + + Element getCurrentSelection() { + IStructuredSelection sel = (IStructuredSelection) viewer.getSelection(); + return (sel != null) ? (Element) sel.getFirstElement() : null; + } + +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/UnknownElementWizardPage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/UnknownElementWizardPage.java new file mode 100644 index 0000000..d6ad3a5 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/UnknownElementWizardPage.java @@ -0,0 +1,326 @@ +/* + * $Id: UnknownElementWizardPage.java,v 1.1 2004-10-05 20:51:57 jsurfer Exp $ + * Copyright Narushima Hironori. All rights reserved. + */ +package net.sourceforge.phpeclipse.wizards.html; + +import java.util.ArrayList; + +import org.eclipse.jface.dialogs.IInputValidator; +import org.eclipse.jface.viewers.ArrayContentProvider; +import org.eclipse.jface.viewers.CellEditor; +import org.eclipse.jface.viewers.ICellModifier; +import org.eclipse.jface.viewers.ILabelProviderListener; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.viewers.ITableLabelProvider; +import org.eclipse.jface.viewers.TableViewer; +import org.eclipse.jface.viewers.TextCellEditor; +import org.eclipse.jface.window.Window; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Item; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Table; +import org.eclipse.swt.widgets.TableColumn; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; + + +/** + * + * + */ +public class UnknownElementWizardPage extends EditElementWizardPage { + + // key of TableCell for attribute editor. + final static String + NAME = "ColumnProperty-name", + VALUE = "ColumnProperty-value"; + + Button emptyElementCheck, addButton, removeButton, upButton, downButton; + + TableViewer unknownElementAttrs; + ArrayList + attrs = new ArrayList(), + listeners = new ArrayList(); + + SelectionListener elemTypeChangeListener = new SelectionListener() { + public void widgetSelected(SelectionEvent e) { + refreshPreview(); + } + + public void widgetDefaultSelected(SelectionEvent e) { + } + }; + + public UnknownElementWizardPage(){ + super("UnknownElementEditPage"); + setTitle("Unknown"); + setDescription("Editor for any HTML element."); + } + + static IInputValidator attrValidator = new IInputValidator() { + public String isValid(String newText) { + if( newText.length() == 0){ + return "Need to specify name"; + } + if( newText.indexOf(' ') != -1 || newText.indexOf('\n') != -1 || newText.indexOf('\t') != -1 ){ + return "Not contain blank"; + } + return null; + } + }; + + protected void createChildControl(Composite parent) { + // empty eleemnt + parent.setLayout( new GridLayout(2, false) ); + + //// attribute editor + Label labe = new Label(parent, SWT.NONE); + labe.setText("Element &Attribute:"); + GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); + labe.setLayoutData(gd); + new Label(parent, SWT.NONE); + + // attribute display table setting + unknownElementAttrs = new TableViewer(parent, SWT.BORDER | SWT.SINGLE | SWT.FULL_SELECTION); + gd = new GridData(GridData.FILL_BOTH); + gd.horizontalSpan = 1; + gd.verticalSpan = 4; + unknownElementAttrs.getControl().setLayoutData(gd); + + final Table table = unknownElementAttrs.getTable(); + new TableColumn(table, SWT.LEFT).setText("Name"); + new TableColumn(table, SWT.LEFT).setText("Value"); + + table.setLinesVisible(true); + table.setHeaderVisible(true); + // modifier setting + unknownElementAttrs.setColumnProperties(new String[]{ NAME, VALUE }); + unknownElementAttrs.setContentProvider(new ArrayContentProvider()); + + unknownElementAttrs.setCellEditors( new CellEditor[]{ + new TextCellEditor(table), + new TextCellEditor(table) + }); + unknownElementAttrs.setCellModifier(new ICellModifier() { + public boolean canModify(Object element, String property) { + return true; + } + + public Object getValue(Object element, String property) { + return ((String[])element)[property.equals(NAME) ? 0 : 1]; + } + + public void modify(Object element, String property, Object value) { + if (element instanceof Item) { + ((String[])((Item) element).getData())[property.equals(NAME) ? 0 : 1] = HTMLUtilities.unescape( (String)value ); + refreshPreview(); + } + } + }); + + unknownElementAttrs.setLabelProvider( new ITableLabelProvider() { + public Image getColumnImage(Object element, int columnIndex) { + return null; + } + + public String getColumnText(Object element, int columnIndex) { + return ((String[])element)[columnIndex]; + } + + public void addListener(ILabelProviderListener listener) {} + + public void removeListener(ILabelProviderListener listener) {} + + public void dispose() {} + + public boolean isLabelProperty(Object element, String property) { + return property.equals(NAME) || property.equals(VALUE); + } + }); + + resetAttributes(); + unknownElementAttrs.setInput(attrs); + + TableColumn[] columns = table.getColumns(); + for (int i = 0; i < columns.length; i++) { + columns[i].pack(); + } + + // buttonss + upButton = createButton(parent, "&Up"); + upButton.addSelectionListener(new SelectionListener() { + + public void widgetSelected(SelectionEvent e) { + int index = getSelectionIndex(); + if( index > 0){ + attrs.add(index-1, attrs.remove(index)); + refreshPreview(); + } + } + public void widgetDefaultSelected(SelectionEvent e) {} + }); + + downButton = createButton(parent, "&Down"); + downButton.addSelectionListener(new SelectionListener() { + public void widgetSelected(SelectionEvent e) { + int index = getSelectionIndex(); + if( index < attrs.size()-1 ){ + attrs.add(index+1, attrs.remove(index)); + refreshPreview(); + } + } + public void widgetDefaultSelected(SelectionEvent e) {} + }); + + addButton = createButton(parent, "&Add"); + addButton.addSelectionListener(new SelectionListener() { + public void widgetSelected(SelectionEvent e) { + int insertIndex = getSelectionIndex(); + String[] newData = inputValue(); + if(newData != null){ + attrs.add(newData); + refreshPreview(); + } + } + + String[] inputValue(){ + SomeItemInputDialog dialog = new SomeItemInputDialog( + getShell(), + "Input new attribute", + new String[]{"Attribute name", "Attribute value"}, + new IInputValidator[] {attrValidator, null}); + + + if( dialog.open() == Window.OK){ + return dialog.getValues(); + } + return null; + } + public void widgetDefaultSelected(SelectionEvent e) {} + }); + + removeButton = createButton(parent, "&Remove"); + removeButton.addSelectionListener(new SelectionListener() { + public void widgetSelected(SelectionEvent e) { + int index = getSelectionIndex(); + if( index != -1){ + attrs.remove(index); + refreshPreview(); + } + } + public void widgetDefaultSelected(SelectionEvent e) {} + }); + + emptyElementCheck = new Button(parent, SWT.CHECK); + gd = new GridData(GridData.FILL_HORIZONTAL); + emptyElementCheck.setLayoutData(gd); + emptyElementCheck.setText("&Empty Element"); + emptyElementCheck.addSelectionListener(elemTypeChangeListener); + emptyElementCheck.setSelection(isEmptyAsText()); + + new Label(parent, SWT.NONE); + } + + static Button createButton(Composite parent, String text){ + Button button = new Button(parent, SWT.PUSH); + GridData gd = new GridData( + GridData.VERTICAL_ALIGN_BEGINNING | GridData.HORIZONTAL_ALIGN_END); + gd.widthHint = 60; + button.setLayoutData( gd); + button.setText(text); + return button; + } + + public String getPreviewText(){ + String elemName = getElementName(); + if(elemName == null){ + return null; + } + + // sets values + + boolean empty = false; + if( emptyElementCheck == null ){ + // ui uninitialized + empty = isEmptyAsText(); + }else{ + // ui initialized + empty = emptyElementCheck.getSelection(); + } + + String content = getSelectionText(); + if( !empty && getEditType() == MODIFY){ + content = chooseContent( content ); + } + + String previewText = "<" + elemName + attrsCode(); + if(empty){ + previewText += " />"; + }else{ + previewText += ">" + content + ""; + } + return previewText; + } + + boolean isEmptyAsText(){ + String selText = getSelectionText(); + if(getEditType() == MODIFY){ + int len = selText.length(); + return selText.substring(len-2, len).equals("/>"); + } + return false; + } + + void resetAttributes(){ + attrs.clear(); + + Element elem = getParsedSelectionText(); + if( elem != null){ + NamedNodeMap as = elem.getAttributes(); + for (int i = 0; i < as.getLength(); i++) { + Node n = as.item(i); + attrs.add( new String[]{ n.getNodeName(), n.getNodeValue()}); + } + } + } + + String attrsCode(){ + StringBuffer buff = new StringBuffer(); + Object[] as = attrs.toArray(); + for (int i = 0; i < as.length; i++) { + String[] a = (String[])as[i]; + buff.append(" " + a[0] + "=\"" + HTMLUtilities.escape(a[1]) + "\""); + } + return buff.toString(); + } + + int getSelectionIndex(){ + Object sel = unknownElementAttrs.getSelection(); + if( sel instanceof IStructuredSelection){ + Object item = ((IStructuredSelection)sel).getFirstElement(); + return attrs.indexOf(item); + }else{ + return -1; + } + } + + public void refreshPreview() { + unknownElementAttrs.refresh(); + super.refreshPreview(); + } + + public void setElementName(String elemName) { + super.setElementName(elemName); + setTitle("\"" + elemName + "\" Element"); + } + +} \ No newline at end of file