/**
- * 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.*;
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
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;
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
newWizardCategory.name=PHP
newWizardPHPProject.name=PHP Project
newWizardPHPFile.name=PHP File
+newWizardHTMLFile.name=HTML file
NewPHPClass.label= Class
NewPHPClass.description=Create a PHP class
Create a basic PHP file.
</description>
</wizard>
+ <wizard
+ name="%newWizardHTMLFile.name"
+ icon="icons/obj16/htmledit.gif"
+ category="net.sourceforge.phpeclipse.wizards.NewWizardCategoryPHP"
+ class="net.sourceforge.phpeclipse.wizards.HTMLFileWizard"
+ id="net.sourceforge.phpeclipse.wizards.HTMLFileWizard">
+ <description>
+ Create a basic HTML file.
+ </description>
+ </wizard>
</extension>
<extension point="org.eclipse.ui.exportWizards">
<wizard name="%ExportWizards.Obfuscator"
id="net.sourceforge.phpeclipse.actions.opensqltable">
</action>
</viewerContribution>
+ <viewerContribution
+ targetID="#PHPEditorContext"
+ id="net.sourceforge.phpeclipse.actions.popupHTMLWizard">
+ <action
+ label="Insert HTML (dl,ul,ol,table)"
+ class="net.sourceforge.phpeclipse.wizards.html.InsertHTMLElementAction"
+ menubarPath="additions"
+ id="net.sourceforge.phpdt.phphelp.actions.contexthelp">
+ </action>
+ </viewerContribution>
<viewerContribution
targetID="#PHPRulerContext"
-/*******************************************************************************
- * Copyright (c) 2002 Klaus Hartlage - www.eclipseproject.de All rights
- * reserved. This program and the accompanying material 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) 2002 Klaus Hartlage - www.eclipseproject.de All rights reserved. This program and the accompanying material 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: Klaus Hartlage - www.eclipseproject.de
- ******************************************************************************/
+ **********************************************************************************************************************************/
package net.sourceforge.phpdt.internal.compiler.parser;
+
import java.util.ArrayList;
import net.sourceforge.phpdt.core.compiler.CharOperation;
import net.sourceforge.phpdt.internal.compiler.problem.ProblemSeverities;
import net.sourceforge.phpdt.internal.compiler.util.Util;
import net.sourceforge.phpeclipse.builder.IdentifierIndexManager;
-import net.sourceforge.phpeclipse.internal.compiler.ast.AbstractMethodDeclaration;
import net.sourceforge.phpeclipse.internal.compiler.ast.ASTNode;
+import net.sourceforge.phpeclipse.internal.compiler.ast.AbstractMethodDeclaration;
import net.sourceforge.phpeclipse.internal.compiler.ast.CompilationUnitDeclaration;
+import net.sourceforge.phpeclipse.internal.compiler.ast.Expression;
import net.sourceforge.phpeclipse.internal.compiler.ast.FieldDeclaration;
+import net.sourceforge.phpeclipse.internal.compiler.ast.IfStatement;
import net.sourceforge.phpeclipse.internal.compiler.ast.ImportReference;
import net.sourceforge.phpeclipse.internal.compiler.ast.MethodDeclaration;
import net.sourceforge.phpeclipse.internal.compiler.ast.SingleTypeReference;
+import net.sourceforge.phpeclipse.internal.compiler.ast.Statement;
import net.sourceforge.phpeclipse.internal.compiler.ast.TypeDeclaration;
import org.eclipse.core.resources.IFile;
+
public class Parser //extends PHPParserSuperclass
implements ITerminalSymbols, CompilerModifiers, ParserBasicInformation {
//internal data for the automat
protected final static int StackIncrement = 255;
+
protected int stateStackTop;
+
protected int[] stack = new int[StackIncrement];
+
public int firstToken; // handle for multiple parsing goals
+
public int lastAct; //handle for multiple parsing goals
+
protected RecoveredElement currentElement;
+
public static boolean VERBOSE_RECOVERY = false;
+
protected boolean diet = false; //tells the scanner to jump over some
+
// parts of the code/expressions like
// method bodies
//scanner token
public Scanner scanner;
+
private ArrayList phpList;
+
private int currentPHPString;
+
private boolean phpEnd;
+
// private static HashMap keywordMap = null;
private String str;
+
// current character
// char ch;
// current token
int token;
+
// row counter for syntax errors:
//int rowCount;
// column counter for syntax errors:
// // current identifier
// String identifier;
Long longNumber;
+
Double doubleNumber;
+
private String stringValue;
+
/** Contains the current expression. */
// private StringBuffer expression;
//private boolean phpMode;
protected int modifiers;
+
protected int modifiersSourceStart;
-// protected IdentifierIndexManager indexManager;
-
+
+ // protected IdentifierIndexManager indexManager;
+
protected Parser(ProblemReporter problemReporter) {
this.problemReporter = problemReporter;
this.options = problemReporter.options;
this.currentPHPString = 0;
// PHPParserSuperclass.fileToParse = fileToParse;
this.phpList = null;
-// this.indexManager = null;
+ // this.indexManager = null;
this.str = "";
this.token = TokenNameEOF;
// this.chIndx = 0;
// getNextToken();
this.initializeScanner();
}
+
public void setFileToParse(IFile fileToParse) {
this.currentPHPString = 0;
// PHPParserSuperclass.fileToParse = fileToParse;
this.phpList = null;
-// this.indexManager = null;
+ // this.indexManager = null;
this.str = "";
this.token = TokenNameEOF;
this.phpEnd = false;
this.initializeScanner();
}
+
/**
* ClassDeclaration Constructor.
*
// getNextToken();
this.initializeScanner();
}
+
public void initializeScanner() {
this.scanner = new Scanner(false /* comment */, false /* whitespace */, this.options
.getSeverity(CompilerOptions.NonExternalizedString) != ProblemSeverities.Ignore /* nls */, false, false,
this.options.taskTags/* taskTags */, this.options.taskPriorites/* taskPriorities */);
}
+
/**
* Create marker for the parse error
*/
// setMarker(fileToParse, message, charStart, charEnd, errorLevel);
// }
/**
- * This method will throw the SyntaxError. It will add the good lines and
- * columns to the Error
+ * This method will throw the SyntaxError. It will add the good lines and columns to the Error
*
* @param error
* the error message
int problemEndPosition = scanner.getCurrentTokenEndPosition();
throwSyntaxError(error, problemStartPosition, problemEndPosition + 1);
}
+
/**
- * This method will throw the SyntaxError. It will add the good lines and
- * columns to the Error
+ * This method will throw the SyntaxError. It will add the good lines and columns to the Error
*
* @param error
* the error message
// throw new SyntaxError(startRow, 0, " ", error);
// }
private void throwSyntaxError(String error, int problemStartPosition, int problemEndPosition) {
- problemReporter.phpParsingError(new String[]{error}, problemStartPosition, problemEndPosition, referenceContext,
+ problemReporter.phpParsingError(new String[] { error }, problemStartPosition, problemEndPosition, referenceContext,
compilationUnit.compilationResult);
throw new SyntaxError(1, 0, " ", error);
}
+
private void reportSyntaxError(String error, int problemStartPosition, int problemEndPosition) {
- problemReporter.phpParsingError(new String[]{error}, problemStartPosition, problemEndPosition, referenceContext,
+ problemReporter.phpParsingError(new String[] { error }, problemStartPosition, problemEndPosition, referenceContext,
compilationUnit.compilationResult);
}
+
private void reportSyntaxWarning(String error, int problemStartPosition, int problemEndPosition) {
- problemReporter.phpParsingWarning(new String[]{error}, problemStartPosition, problemEndPosition, referenceContext,
+ problemReporter.phpParsingWarning(new String[] { error }, problemStartPosition, problemEndPosition, referenceContext,
compilationUnit.compilationResult);
}
+
/**
* Method Declaration.
*
} catch (InvalidInputException e) {
token = TokenNameERROR;
String detailedMessage = e.getMessage();
-
- if (detailedMessage==Scanner.UNTERMINATED_STRING) {
+
+ if (detailedMessage == Scanner.UNTERMINATED_STRING) {
throwSyntaxError("Unterminated string.");
- } else if (detailedMessage==Scanner.UNTERMINATED_COMMENT) {
+ } else if (detailedMessage == Scanner.UNTERMINATED_COMMENT) {
throwSyntaxError("Unterminated commment.");
}
}
return;
}
+
public void init(String s) {
this.str = s;
this.token = TokenNameEOF;
scanner.setSource(s.toCharArray());
scanner.setPHPMode(false);
}
+
protected void initialize(boolean phpMode) {
initialize(phpMode, null);
}
+
protected void initialize(boolean phpMode, IdentifierIndexManager indexManager) {
compilationUnit = null;
referenceContext = null;
includesList = new ArrayList();
-// this.indexManager = indexManager;
+ // this.indexManager = indexManager;
this.str = "";
this.token = TokenNameEOF;
// this.chIndx = 0;
// this.phpMode = phpMode;
scanner.setPHPMode(phpMode);
}
+
/**
- * Parses a string with php tags i.e. '<body> <?php phpinfo() ?>
- * </body>'
+ * Parses a string with php tags i.e. '<body> <?php phpinfo() ?> </body>'
*/
public void parse(String s) {
init(s);
parse();
}
+
/**
- * Parses a string with php tags i.e. '<body> <?php phpinfo() ?>
- * </body>'
+ * Parses a string with php tags i.e. '<body> <?php phpinfo() ?> </body>'
*/
protected void parse() {
getNextToken();
}
return compilationUnit;
}
+
// public PHPOutlineInfo parseInfo(Object parent, String s) {
// PHPOutlineInfo outlineInfo = new PHPOutlineInfo(parent);
// // Stack stack = new Stack();
private boolean isVariable() {
return token == TokenNameVariable; // || token == TokenNamethis;
}
+
// private void parseDeclarations(PHPOutlineInfo outlineInfo,
// OutlineableWithChildren current, boolean goBack) {
// char[] ident;
}
} while (true);
}
+
private void functionBody(MethodDeclaration methodDecl) {
// '{' [statement-list] '}'
if (token == TokenNameLBRACE) {
throwSyntaxError("'}' expected in compound-statement.");
}
}
- private void statement(int previousToken) {
- // if (token > 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) {
} 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) {
throwSyntaxError("')' expected after 'switch' condition.");
}
switchStatement();
- return;
+ return statement;
} else if (token == TokenNamefor) {
getNextToken();
if (token == TokenNameLPAREN) {
}
}
forStatement();
- return;
+ return statement;
} else if (token == TokenNamewhile) {
getNextToken();
if (token == TokenNameLPAREN) {
throwSyntaxError("')' expected after 'while' condition.");
}
whileStatement();
- return;
+ return statement;
} else if (token == TokenNamedo) {
getNextToken();
if (token == TokenNameLBRACE) {
}
getNextToken();
}
- return;
+ return statement;
} else if (token == TokenNameforeach) {
getNextToken();
if (token == TokenNameLPAREN) {
throwSyntaxError("')' expected after 'foreach' expression.");
}
foreachStatement();
- return;
+ return statement;
} else if (token == TokenNamecontinue || token == TokenNamebreak || token == TokenNamereturn) {
getNextToken();
if (token != TokenNameSEMICOLON) {
}
getNextToken();
}
- return;
+ return statement;
} else if (token == TokenNameecho) {
getNextToken();
expressionList();
}
getNextToken();
}
- return;
+ return statement;
} else if (token == TokenNameINLINE_HTML) {
getNextToken();
- return;
+ return statement;
// } else if (token == TokenNameprint) {
// getNextToken();
// expression();
}
getNextToken();
}
- return;
+ return statement;
} else if (token == TokenNamestatic) {
getNextToken();
static_var_list();
}
getNextToken();
}
- return;
+ return statement;
} else if (token == TokenNameunset) {
getNextToken();
if (token == TokenNameLPAREN) {
}
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) {
throwSyntaxError("'}' expected in 'try' statement.");
}
getNextToken();
- return;
+ return statement;
} else if (token == TokenNamecatch) {
getNextToken();
if (token != TokenNameLPAREN) {
}
getNextToken();
additional_catches();
- return;
+ return statement;
} else if (token == TokenNamethrow) {
getNextToken();
expr();
} 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);
astPtr--;
astLengthPtr--;
}
- return;
+ return statement;
// } else {
// throwSyntaxError("Unexpected keyword '" + keyword + "'");
} else if (token == TokenNameLBRACE) {
}
if (token == TokenNameRBRACE) {
getNextToken();
- return;
+ return statement;
} else {
throwSyntaxError("'}' expected.");
}
}
if (token == TokenNameSEMICOLON) {
getNextToken();
- return;
+ return statement;
} else {
if (token != TokenNameINLINE_HTML && token != TokenNameEOF) {
throwSyntaxError("';' expected after expression (Found token: " + scanner.toStringAction(token) + ")");
getNextToken();
}
}
+ // may be null
+ return statement;
}
+
private void additional_catches() {
while (token == TokenNamecatch) {
getNextToken();
getNextToken();
}
}
+
private void foreach_variable() {
// w_variable
//| '&' w_variable
}
w_variable();
}
+
private void foreach_optional_arg() {
// /* empty */
//| T_DOUBLE_ARROW foreach_variable
foreach_variable();
}
}
+
private void global_var_list() {
// global_var_list:
// global_var_list ',' global_var
getNextToken();
}
}
+
private void global_var() {
//global_var:
// T_VARIABLE
}
}
}
+
private void static_var_list() {
//static_var_list:
// static_var_list ',' T_VARIABLE
}
}
}
+
private void unset_variables() {
// unset_variables:
// unset_variable
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) {
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;
}
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:
}
implements_list();
} else {
- typeDecl.name = new char[]{' '};
+ typeDecl.name = new char[] { ' ' };
throwSyntaxError("Class name expected after keyword 'class'.", typeDecl.sourceStart, typeDecl.sourceEnd);
return;
}
throwSyntaxError("'{' expected at start of class body.");
}
}
+
private void class_entry_type() {
// T_CLASS
// | T_ABSTRACT T_CLASS
throwSyntaxError("Keyword 'class' 'final' or 'abstract' expected");
}
}
+
private void interface_extends_list() {
// /* empty */
// | T_EXTENDS interface_list
interface_list();
}
}
+
private void implements_list() {
// /* empty */
// | T_IMPLEMENTS interface_list
interface_list();
}
}
+
private void interface_list() {
// interface_list:
// fully_qualified_class_name
getNextToken();
} while (true);
}
+
// private void classBody(TypeDeclaration typeDecl) {
// //'{' [class-element-list] '}'
// if (token == TokenNameLBRACE) {
|| token == TokenNameabstract || token == TokenNamefinal || token == TokenNamefunction || token == TokenNamevar
|| token == TokenNameconst);
}
+
private void class_statement(ArrayList list) {
// class_statement:
// variable_modifiers class_variable_declaration ';'
// '(' parameter_list ')' method_body
initializeModifiers();
int declarationSourceStart = scanner.getCurrentTokenStartPosition();
-
+
if (token == TokenNamevar) {
checkAndSetModifiers(AccPublic);
problemReporter.phpVarDeprecatedWarning(scanner.getCurrentTokenStartPosition(), scanner.getCurrentTokenEndPosition(),
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.");
}
}
}
+
private void class_constant_declaration(int declarationSourceStart, ArrayList list) {
// class_constant_declaration ',' T_STRING '=' static_scalar
// | T_CONST T_STRING '=' static_scalar
getNextToken();
}
}
+
// private void variable_modifiers() {
// // variable_modifiers:
// // non_empty_member_modifiers
}
return foundToken;
}
+
private void class_variable_declaration(int declarationSourceStart, ArrayList list) {
// class_variable_declaration:
// class_variable_declaration ',' T_VARIABLE
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();
}
getNextToken();
}
+
private void functionDefinition(MethodDeclaration methodDecl) {
boolean isAbstract = false;
if (astPtr == 0) {
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,
}
functionBody(methodDecl);
}
+
private void functionDeclarator(MethodDeclaration methodDecl) {
//identifier '(' [parameter-list] ')'
if (token == TokenNameAND) {
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) {
throwSyntaxError("'(' expected in function declaration.");
}
if (token != TokenNameRPAREN) {
- parameter_list();
+ parameter_list();
}
if (token != TokenNameRPAREN) {
throwSyntaxError("')' expected in function declaration.");
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
throwSyntaxError("Identifier expected in parameter list.");
}
}
+
private void optional_class_type() {
// /* empty */
//| T_STRING
}
+
private void parameterDeclaration() {
//variable
//variable-reference
// declaration.");
// }
}
+
private void labeledStatementList() {
if (token != TokenNamecase && token != TokenNamedefault) {
throwSyntaxError("'case' or 'default' expected.");
break;
}
if (token != TokenNamecase) {
- statementList();
+ statementList();
}
} else {
throwSyntaxError("':' character expected after 'default'.");
}
} while (token == TokenNamecase || token == TokenNamedefault);
}
+
// public void labeledStatement() {
// if (token == TokenNamecase) {
// getNextToken();
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) {
}
}
}
+
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();
}
}
}
+
private void switchStatement() {
if (token == TokenNameCOLON) {
// ':' [labeled-statement-list] 'endswitch' ';'
getNextToken();
}
}
+
private void forStatement() {
if (token == TokenNameCOLON) {
getNextToken();
statement(TokenNameEOF);
}
}
+
private void whileStatement() {
// ':' statement-list 'endwhile' ';'
if (token == TokenNameCOLON) {
statement(TokenNameEOF);
}
}
+
private void foreachStatement() {
if (token == TokenNameCOLON) {
getNextToken();
statement(TokenNameEOF);
}
}
+
// private void exitStatus() {
// if (token == TokenNameLPAREN) {
// getNextToken();
}
} 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
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");
// | 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
dynamic_class_name_reference();
}
}
+
private void dynamic_class_name_reference() {
//dynamic_class_name_reference:
// base_variable T_OBJECT_OPERATOR object_property
dynamic_class_name_variable_properties();
}
}
+
private void dynamic_class_name_variable_properties() {
// dynamic_class_name_variable_properties:
// dynamic_class_name_variable_properties
dynamic_class_name_variable_property();
}
}
+
private void dynamic_class_name_variable_property() {
// dynamic_class_name_variable_property:
// T_OBJECT_OPERATOR object_property
object_property();
}
}
+
private void ctor_arguments() {
// ctor_arguments:
// /* empty */
getNextToken();
}
}
+
private void assignment_list() {
// assignment_list:
// assignment_list ',' assignment_list_element
getNextToken();
}
}
+
private void assignment_list_element() {
//assignment_list_element:
// variable
}
}
}
+
private void array_pair_list() {
// array_pair_list:
// /* empty */
getNextToken();
}
}
+
private void non_empty_array_pair_list() {
//non_empty_array_pair_list:
// non_empty_array_pair_list ',' expr T_DOUBLE_ARROW expr
}
}
}
+
// private void variableList() {
// do {
// variable();
}
reference_variable();
}
+
private void function_call() {
// function_call:
// T_STRING '(' function_call_parameter_list ')'
//| 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()");
}
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<defineName.length;i++) {
- if (Character.isLowerCase(defineName[i])) {
- problemReporter.phpUppercaseIdentifierWarning(startPos, endPos,
- referenceContext, compilationUnit.compilationResult);
+ if (defineName != null) {
+ for (int i = 0; i < defineName.length; i++) {
+ if (Character.isLowerCase(defineName[i])) {
+ problemReporter.phpUppercaseIdentifierWarning(startPos, endPos, referenceContext, compilationUnit.compilationResult);
break;
}
}
non_empty_function_call_parameter_list();
if (token != TokenNameRPAREN) {
String functionName;
- if (ident==null) {
+ if (ident == null) {
functionName = new String(" ");
} else {
functionName = new String(ident);
}
- throwSyntaxError("')' expected in function call ("+functionName+").");
+ throwSyntaxError("')' expected in function call (" + functionName + ").");
}
getNextToken();
}
+
// private void function_call_parameter_list() {
// function_call_parameter_list:
// non_empty_function_call_parameter_list { $$ = $1; }
getNextToken();
}
}
+
private void fully_qualified_class_name() {
if (token == TokenNameIdentifier) {
getNextToken();
throwSyntaxError("Class name expected.");
}
}
+
private void static_member() {
// static_member:
// fully_qualified_class_name T_PAAMAYIM_NEKUDOTAYIM
getNextToken();
variable_without_objects();
}
+
private void base_variable_with_function_calls() {
// base_variable_with_function_calls:
// base_variable
// base_variable();
// }
}
+
private void base_variable() {
// base_variable:
// reference_variable
reference_variable();
}
}
+
// private void simple_indirect_reference() {
// // simple_indirect_reference:
// // '$'
}
}
}
+
private void compound_variable() {
// compound_variable:
// T_VARIABLE
getNextToken();
}
}
+
// private void dim_offset() {
// // dim_offset:
// // /* empty */
object_dim_list();
}
}
+
private void object_dim_list() {
//object_dim_list:
// object_dim_list '[' dim_offset ']'
}
}
}
+
private void variable_name() {
//variable_name:
// T_STRING
getNextToken();
}
}
+
private void r_variable() {
variable();
}
+
private void w_variable() {
variable();
}
+
private void rw_variable() {
variable();
}
+
private void variable() {
// variable:
// base_variable_with_function_calls T_OBJECT_OPERATOR
// }
// }
}
+
private void variable_properties() {
// variable_properties:
// variable_properties variable_property
variable_property();
}
}
+
private void variable_property() {
// variable_property:
// T_OBJECT_OPERATOR object_property method_or_not
throwSyntaxError("'->' expected in variable_property.");
}
}
+
private void method_or_not() {
// method_or_not:
// '(' function_call_parameter_list ')'
getNextToken();
}
}
+
private void exit_expr() {
// /* empty */
// | '(' ')'
}
getNextToken();
}
+
private void encaps_list() {
// encaps_list encaps_var
// | encaps_list T_STRING
// | /* 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 ']'
// | 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();
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 ','
}
}
}
+
private boolean common_scalar() {
// common_scalar:
// T_LNUMBER
// | 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
//| 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
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
}
}
}
+
public void reportSyntaxError() { //int act, int currentKind, int
// stateStackTop) {
/* remember current scanner position */
try {
tokenSource = this.scanner.getCurrentTokenSource();
} catch (Exception e) {
- tokenSource = new char[]{};
+ tokenSource = new char[] {};
}
// problemReporter().parseError(
// this.scanner.startPosition,
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) {
problemReporter.referenceContext = referenceContext;
return problemReporter;
}
+
/*
* Reconsider the entire source looking for inconsistencies in {} () []
*/
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
} 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
|| (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
|| (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--------------------
return anomaliesDetected;
}
}
+
protected void pushOnAstLengthStack(int pos) {
try {
astLengthStack[++astLengthPtr] = pos;
astLengthStack[astLengthPtr] = pos;
}
}
+
protected void pushOnAstStack(ASTNode node) {
/*
* add a new obj on top of the ast stack
-/*
- * 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 {
setVariable(CodeTemplateContextType.PROJECTNAME, cu.getJavaProject().getElementName());
}
+ public void setFileNameVariable(String filename) {
+ setVariable(CodeTemplateContextType.FILENAME, filename);
+ }
}
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$
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$
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());
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));
*******************************************************************************/
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
+++ /dev/null
-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
--- /dev/null
+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
--- /dev/null
+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
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;
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);
}
/**
- * 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();
}
/**
- * 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
try {
InputStream stream;
if (className == null) {
- stream = openContentStream();
+ stream = openContentStream(fileName);
} else {
stream = openContentStreamClass(className);
}
public void run() {
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
try {
- IDE.openEditor(page,file,true);
+ IDE.openEditor(page, file, true);
} catch (PartInitException e) {
}
}
/**
* 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("<?php\n\n");
/**
* We will initialize file contents with a sample text.
*/
- private InputStream openContentStream() {
- 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.setCompilationUnitVariables(cu);
- return new ByteArrayInputStream(StubUtility.evaluateTemplate(context, template).getBytes());
- } catch (CoreException e) {
- e.printStackTrace();
- return null;
- }
-
-// StringBuffer contents = new StringBuffer("<?php\n\n");
-// contents.append("function f0() {\n\n");
-// contents.append("}\n\n");
-// contents.append("function f1() {\n\n");
-// contents.append("}\n\n");
-// contents.append("switch($func) {\n");
-// contents.append(" case \"f1\":\n");
-// contents.append(" f1();\n");
-// contents.append(" break;\n\n");
-// contents.append(" default:\n");
-// contents.append(" f0();\n");
-// contents.append(" break;\n\n");
-// contents.append("}\n\n?>");
-// 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 {
}
/**
- * 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) {
}
/**
- * 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
containerText.setText(container.getFullPath().toString());
}
}
- fileText.setText("index.php");
+ fileText.setText("*.php");
}
/**
return;
}
- if (!PHPFileUtil.isPHPFileName(fileName)) {
- updateStatus(PHPWizardMessages.getString("WizardPage.mustBePHP"));
- return;
- }
+// if (!PHPFileUtil.isPHPFileName(fileName)) {
+// updateStatus(PHPWizardMessages.getString("WizardPage.mustBePHP"));
+// return;
+// }
updateStatus(null);
}
###################################
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...
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...
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
--- /dev/null
+/*
+ * $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
--- /dev/null
+/*
+ * $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
--- /dev/null
+/*
+ * $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("<?xml version=\"1.0\"?>\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<attrs.getLength(); i++){
+ Node n = attrs.item(i);
+ String v = n.getNodeValue();
+ if(v != null){
+ buff.append(' ' + n.getNodeName() + "=\"" + HTMLUtilities.escape(v) + "\"");
+ }
+ }
+
+ boolean emptyElem = element.getChildNodes().getLength() == 0;
+ if(emptyElem){
+ buff.append(" /");
+ }
+ buff.append('>');
+ if(!emptyElem ){
+ NodeList childElements = element.getChildNodes();
+ if(isBeginChangeLine(elementName)){
+ buff.append('\n');
+ }
+ for(int i=0; i<childElements.getLength(); i++){
+ Node node = childElements.item(i);
+ if( node instanceof Element){
+ expandTag( (Element)node, level+1, buff);
+ }else if (node instanceof Text){
+ String text = ((Text)node).getNodeValue();
+ if(trim && (text = text.trim()).length() == 0){
+ continue;
+ }
+ buff.append(text);
+ }
+ }
+ expandIndent(level, buff);
+ buff.append("</" + elementName + '>');
+ }
+ // already inserted change line.
+ if( isEndChangeLine(elementName) ){
+ buff.append('\n');
+ }
+ }
+
+ void expandIndent(int level, StringBuffer buff){
+ if(indent != null){
+ for(int i=0; i<level; i++){
+ buff.append(indent);
+ }
+ }
+ }
+
+ public int getDefaultExpandOption() {
+ return defaultExpandOption;
+ }
+
+ public void setDefaultExpandOption(int i) {
+ defaultExpandOption = i;
+ }
+
+}
\ No newline at end of file
--- /dev/null
+/*
+ * $Id: FormElementWizardPage.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.core.runtime.CoreException;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.widgets.*;
+
+/**
+ *
+ */
+public class FormElementWizardPage extends EditElementWizardPage {
+
+ Text actionText;
+ Button postRadio, getRadio, multipartCheck;
+ Combo charsetCombo;
+
+ public FormElementWizardPage() {
+ super("FormElementWizardPage");
+ }
+
+ protected void createChildControl(Composite parent) throws CoreException {
+ postRadio = new Button(parent, SWT.RADIO);
+
+ }
+
+ public String getPreviewText() {
+ boolean controlCreated = actionText != null;
+
+ StringBuffer buff = new StringBuffer("<form action=\"");
+ if(controlCreated){
+ buff.append(actionText.getText());
+ }
+ buff.append("\" method=\"");
+ if( controlCreated && postRadio.getSelection() ){
+ buff.append("POST\"");
+ if(multipartCheck.getSelection()){
+ buff.append(" enctype=\"multipart/form-data\"");
+ }
+
+ }else{
+ buff.append("GET\"");
+ }
+
+ if(controlCreated){
+ String charset = charsetCombo.getText();
+ if(charset != null){
+ buff.append(" accept-charset=\"" + charset + "\"");
+ }
+ }
+
+ buff.append(">\n");
+ buff.append( getSelectionText() );
+ buff.append("\n</form>\n");
+
+ return buff.toString();
+ }
+
+}
--- /dev/null
+/*
+ * $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;
+ }
+
+
+
+
+}
--- /dev/null
+/*
+ * $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();
+
+}
--- /dev/null
+/*
+ * $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) {
+ }
+
+}
--- /dev/null
+/*
+ * $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() + "</" + itemElemName + ">\n");
+ }
+ content = result.toString();
+ break;
+ }
+
+ return "<" + elemName + ">\n" + content + "</" + elemName + ">\n";
+ }
+
+}
--- /dev/null
+/*
+ * $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;
+ }
+
+}
--- /dev/null
+/*
+ * $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;
+ }
+}
--- /dev/null
+/*
+ * $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<inputMessages.length; i++){
+ new Label(base, SWT.NONE).setText(inputMessages[i] + ":");
+
+ final int index = i;
+ Text t = new Text(base, SWT.BORDER);
+ t.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ t.addModifyListener(new ModifyListener() {
+ public void modifyText(ModifyEvent e) {
+ refreshValidator(index);
+ }
+ });
+ texts[i] = t;
+ }
+
+ error = new Text(base, SWT.READ_ONLY);
+ GridData gd = new GridData(GridData.FILL_HORIZONTAL);
+ gd.horizontalSpan = 2;
+ error.setLayoutData(gd);
+
+ return base;
+ }
+
+ void refreshValidator(int index){
+ String data = texts[index].getText();
+ IInputValidator validator = validators[index];
+ if( validator != null){
+ errorMsgs[index] = validator.isValid(data);
+ }
+
+ Button okButton = getButton(IDialogConstants.OK_ID);
+ for(int i=0; i<errorMsgs.length; i++){
+ String msg = errorMsgs[i];
+ if(msg != null){
+ error.setText(msg);
+ okButton.setEnabled(false);
+ return;
+ }
+ }
+ error.setText("");
+ okButton.setEnabled(true);
+ }
+
+ public String[] getValues(){
+ return (String[]) resultValues.clone();
+ }
+
+ protected Point getInitialSize() {
+ Point p = super.getInitialSize();
+ return new Point( p.x * 2, (int)(p.y * 1.25) );
+ }
+
+ protected void okPressed() {
+ resultValues = new String[texts.length];
+ for (int i = 0; i < texts.length; i++) {
+ resultValues[i] = texts[i].getText();
+ }
+ super.okPressed();
+ }
+
+}
--- /dev/null
+/*
+ * $Id: StringDivider.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.Arrays;
+import java.util.regex.Pattern;
+
+public class StringDivider {
+
+ static Pattern tagNameChoosePattern = Pattern.compile("<[\\s/]*(\\w+)\\s*.*>");
+
+ 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;
+ }
+
+}
--- /dev/null
+/*
+ * $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<nodes.getLength(); i++){
+ cellElem.removeChild( nodes.item(i) );
+ }
+ Document doc = cellElem.getOwnerDocument();
+
+ if( value instanceof String){
+ cellElem.appendChild(doc.createTextNode((String)value));
+ }
+ // notify listener
+ if(listener != null){
+ String oldValue = nodes.item(0).getNodeValue();
+ listener.propertyChange(new PropertyChangeEvent(this, property, (String)value, oldValue));
+ }
+ }
+
+}
--- /dev/null
+/*
+ * $Id: TableElementContentProvider.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.viewers.*;
+
+/**
+ *
+ */
+public class TableElementContentProvider implements IStructuredContentProvider {
+
+ public TableElementContentProvider() {
+ super();
+ }
+
+ public Object[] getElements(Object inputElement) {
+ TableElementModel model = (TableElementModel)inputElement;
+ return model.getRows();
+ }
+
+ public void dispose() {
+ }
+
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+
+ }
+
+}
--- /dev/null
+/*
+ * $Id: TableElementLabelProvider.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.viewers.*;
+import org.eclipse.swt.graphics.Image;
+import org.w3c.dom.Element;
+
+/**
+ *
+ */
+public class TableElementLabelProvider implements ITableLabelProvider {
+
+ public Image getColumnImage(Object element, int columnIndex) {
+ return null;
+ }
+
+ public String getColumnText(Object element, int columnIndex) {
+ Element[] cells = TableElementModel.chooseCellElements((Element)element);
+ if(columnIndex < cells.length){
+ Element elem = cells[columnIndex];
+ return elem.toString();
+ }else{
+ throw new IllegalArgumentException("Invalid element:" + element);
+ }
+ }
+
+ public boolean isLabelProperty(Object element, String property) {
+ return TableElementModel.toNumeric(property) != -1;
+ }
+
+ public void addListener(ILabelProviderListener listener) {
+ }
+
+ public void removeListener(ILabelProviderListener listener) {
+ }
+
+ public void dispose() {
+ }
+
+}
--- /dev/null
+/*
+ * $Id: TableElementModel.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 java.util.ArrayList;
+import java.util.Arrays;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.FactoryConfigurationError;
+import javax.xml.parsers.ParserConfigurationException;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+
+/**
+ * TableElementModel
+ */
+public class TableElementModel {
+
+ final static char[] CHAR_TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
+
+ StringDivider stringDivider = new StringDivider();
+
+ ElementWriter writer;
+
+ DocumentBuilder docBuilder;
+ Document document;
+ Element tableElement;
+ String[] columnProperties;
+
+ public TableElementModel(String content, boolean parse) throws FactoryConfigurationError, ParserConfigurationException, SAXException, IOException{
+ docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
+ if(parse){
+ initAsParse(content);
+ }else{
+ initModel(content);
+ }
+ columnProperties = createColumnProperties();
+
+ // create elementWriter
+ writer = new ElementWriter(0, null);
+ writer.setExpandOption("caption", ElementWriter.END_CHANGELINE );
+ writer.setExpandOption("table", ElementWriter.BEGIN_CHANGELINE | ElementWriter.END_CHANGELINE);
+ writer.setExpandOption("thead", ElementWriter.BEGIN_CHANGELINE | ElementWriter.END_CHANGELINE);
+ writer.setExpandOption("tfoot", ElementWriter.BEGIN_CHANGELINE | ElementWriter.END_CHANGELINE);
+ writer.setExpandOption("tbody", ElementWriter.BEGIN_CHANGELINE | ElementWriter.END_CHANGELINE);
+ writer.setExpandOption("tr", ElementWriter.END_CHANGELINE);
+ }
+
+ void initModel(String content) throws ParserConfigurationException, SAXException, IOException {
+ StringReader strReader = new StringReader(content);
+ InputSource inputSrc = new InputSource(strReader);
+
+ document = docBuilder.parse(inputSrc);
+ tableElement = document.getDocumentElement();
+
+ Element[] rows = getRows();
+ for (int i = 0; i < rows.length; i++) {
+ Element[] cells = chooseCellElements(rows[i]);
+ for (int j = 0; j < cells.length; j++) {
+ Element cell = cells[j];
+ if( !cell.hasChildNodes() ){
+ cell.appendChild(document.createTextNode(""));
+ }
+ }
+ }
+ }
+
+ public void initAsParse(String content) throws ParserConfigurationException, FactoryConfigurationError {
+ // create new table model.
+ document = docBuilder.newDocument();
+ tableElement = document.createElement("table");
+
+ String[][] cells = stringDivider.divide(content);
+ if(cells.length > 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<len; i++){
+ props[i] = toColumnName(i);
+ }
+ return props;
+ }
+
+ public void setRowCount(int rowCount){
+ Element[] rows = getRows();
+ if(rowCount > rows.length){
+ for(int i=rows.length; i<rowCount; i++){
+ tableElement.appendChild( createRowElement());
+ }
+ }else if(rowCount < rows.length){
+ for(int i=rowCount; i<rows.length; i++){
+ tableElement.removeChild(rows[i]);
+ }
+ }
+ }
+
+ public Element[] getRows(){
+ ArrayList rows = new ArrayList();
+ NodeList nodes = tableElement.getElementsByTagName("tr");
+ for(int i=0; i<nodes.getLength(); i++){
+ rows.add( nodes.item(i) );
+ }
+ return (Element[])rows.toArray(new Element[rows.size()]);
+ }
+
+ public int getRowCount(){
+ return getRows().length;
+ }
+
+ Element createRowElement(){
+ Element tr = document.createElement("tr");
+ for(int i=0, columnCount = getColumnCount(); i<columnCount; i++){
+ Element td = document.createElement("td");
+ td.appendChild(document.createTextNode(""));
+ tr.appendChild(td);
+ }
+ return tr;
+ }
+
+ public void setColumnCount(int newLength){
+ NodeList trs = tableElement.getElementsByTagName("tr");
+ for(int i=0; i<trs.getLength(); i++){
+ Element tr = (Element)trs.item(i);
+ Element[] cells = chooseCellElements(tr);
+ int colLen = cells.length;
+
+ if( newLength > colLen ){
+ for(int j=0, len = newLength - colLen; j<len; j++){
+ Element cell = document.createElement("td");
+ cell.appendChild(document.createTextNode(""));
+ tr.appendChild(cell);
+ }
+ }else if( newLength < colLen ){
+ for(int j=newLength; j<colLen; j++){
+ tr.removeChild( cells[j]);
+ }
+ }
+ }
+ columnProperties = createColumnProperties();
+ }
+
+ public int getColumnCount(){
+ NodeList trs = tableElement.getElementsByTagName("tr");
+ if( trs.getLength() > 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<nodeList.getLength(); i++){
+ Node node = nodeList.item(i);
+ if(node instanceof Element){
+ String nodeName = node.getNodeName();
+ if(nodeName.equals("td") || nodeName.equals("th") ){
+ result.add(node);
+ }
+ }
+ }
+
+ return (Element[])result.toArray(new Element[result.size()]);
+ }
+
+ public String expandCodes(){
+ return writer.expandTag(tableElement);
+ }
+
+
+ public static String toColumnName(int i){
+ StringBuffer buff = new StringBuffer();
+ int u = i / CHAR_TABLE.length;
+ if( u > 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<code.length(); i++){
+ char c = code.charAt(i);
+ int match = Arrays.binarySearch(CHAR_TABLE, c);
+ if( match >= 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<rows.length; i++){
+ if(tr.equals(rows[i])){
+ index = i;
+ }
+ }
+ if(index == -1){
+ throw new IllegalArgumentException("Invalid row node (not countained in this table):" + tr);
+ }
+ if(moveCount > 0){
+ // move down;
+ for(int i=index; i<moveCount+index && i<rows.length-1; i++){
+ tableElement.insertBefore(rows[i+1], rows[i]);
+ }
+ }else if(moveCount < 0){
+ // move up
+ 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();
+ }
+
+}
--- /dev/null
+/*
+ * $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
--- /dev/null
+/*
+ * $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 + "</" + elemName + ">";
+ }
+ 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