diff
stringlengths
262
553k
is_single_chunk
bool
2 classes
is_single_function
bool
1 class
buggy_function
stringlengths
20
391k
fixed_function
stringlengths
0
392k
diff --git a/src/com/CC/Commands/PartiesCommands.java b/src/com/CC/Commands/PartiesCommands.java index 413e367..c3303cf 100644 --- a/src/com/CC/Commands/PartiesCommands.java +++ b/src/com/CC/Commands/PartiesCommands.java @@ -1,53 +1,53 @@ package com.CC.Commands; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import com.CC.Parties.Create; import com.CC.Parties.*; public class PartiesCommands { public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { if(sender instanceof Player) { Player player = (Player)sender; if (cmd.getName().equalsIgnoreCase("party")) { - if (args.length == 0){ + if (args.length == 1){ if (args[0].equalsIgnoreCase("help")) { Help.help(player); } else if (args[0].equalsIgnoreCase("create")){ Create.create(player); } else if (args[0].equalsIgnoreCase("join")){ Join.join(player); } else if (args[0].equalsIgnoreCase("leave")){ Leave.leave(player); } else if (args[0].equalsIgnoreCase("stats") || args[0].equalsIgnoreCase("status")) { Status.status(player); } else if (args[0].equalsIgnoreCase("start")){ - if (args.length == 1 && args[1].equalsIgnoreCase("red")){ + if (args.length == 2 && args[1].equalsIgnoreCase("red")){ StartRed.start(player); - }else if (args.length == 1 && args[1].equalsIgnoreCase("blue")){ + }else if (args.length == 2 && args[1].equalsIgnoreCase("blue")){ StartBlue.start(player); } } // instance of check because NOT all senders are players. Simply typecasting to player would break on console cmd. }else{ } } } return false; } }
false
true
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { if(sender instanceof Player) { Player player = (Player)sender; if (cmd.getName().equalsIgnoreCase("party")) { if (args.length == 0){ if (args[0].equalsIgnoreCase("help")) { Help.help(player); } else if (args[0].equalsIgnoreCase("create")){ Create.create(player); } else if (args[0].equalsIgnoreCase("join")){ Join.join(player); } else if (args[0].equalsIgnoreCase("leave")){ Leave.leave(player); } else if (args[0].equalsIgnoreCase("stats") || args[0].equalsIgnoreCase("status")) { Status.status(player); } else if (args[0].equalsIgnoreCase("start")){ if (args.length == 1 && args[1].equalsIgnoreCase("red")){ StartRed.start(player); }else if (args.length == 1 && args[1].equalsIgnoreCase("blue")){ StartBlue.start(player); } } // instance of check because NOT all senders are players. Simply typecasting to player would break on console cmd. }else{ } } } return false; }
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { if(sender instanceof Player) { Player player = (Player)sender; if (cmd.getName().equalsIgnoreCase("party")) { if (args.length == 1){ if (args[0].equalsIgnoreCase("help")) { Help.help(player); } else if (args[0].equalsIgnoreCase("create")){ Create.create(player); } else if (args[0].equalsIgnoreCase("join")){ Join.join(player); } else if (args[0].equalsIgnoreCase("leave")){ Leave.leave(player); } else if (args[0].equalsIgnoreCase("stats") || args[0].equalsIgnoreCase("status")) { Status.status(player); } else if (args[0].equalsIgnoreCase("start")){ if (args.length == 2 && args[1].equalsIgnoreCase("red")){ StartRed.start(player); }else if (args.length == 2 && args[1].equalsIgnoreCase("blue")){ StartBlue.start(player); } } // instance of check because NOT all senders are players. Simply typecasting to player would break on console cmd. }else{ } } } return false; }
diff --git a/org.caleydo.core/src/org/caleydo/core/manager/view/ViewManager.java b/org.caleydo.core/src/org/caleydo/core/manager/view/ViewManager.java index b6356e521..7890d54f0 100644 --- a/org.caleydo.core/src/org/caleydo/core/manager/view/ViewManager.java +++ b/org.caleydo.core/src/org/caleydo/core/manager/view/ViewManager.java @@ -1,518 +1,518 @@ package org.caleydo.core.manager.view; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import javax.media.opengl.GLCanvas; import org.caleydo.core.command.ECommandType; import org.caleydo.core.manager.AManager; import org.caleydo.core.manager.IEventPublisher; import org.caleydo.core.manager.IGeneralManager; import org.caleydo.core.manager.IViewManager; import org.caleydo.core.manager.event.AEvent; import org.caleydo.core.manager.event.AEventListener; import org.caleydo.core.manager.event.IListenerOwner; import org.caleydo.core.manager.event.view.CreateGUIViewEvent; import org.caleydo.core.manager.execution.DisplayLoopExecution; import org.caleydo.core.manager.general.GeneralManager; import org.caleydo.core.manager.id.EManagedObjectType; import org.caleydo.core.manager.picking.PickingManager; import org.caleydo.core.manager.view.creator.IGLViewCreator; import org.caleydo.core.serialize.ASerializedView; import org.caleydo.core.view.IView; import org.caleydo.core.view.opengl.camera.IViewFrustum; import org.caleydo.core.view.opengl.canvas.AGLView; import org.caleydo.core.view.opengl.canvas.GLCaleydoCanvas; import org.caleydo.core.view.opengl.canvas.bookmarking.GLBookmarkManager; import org.caleydo.core.view.opengl.canvas.glyph.gridview.GLGlyph; import org.caleydo.core.view.opengl.canvas.glyph.sliderview.GLGlyphSliderView; import org.caleydo.core.view.opengl.canvas.grouper.GLGrouper; import org.caleydo.core.view.opengl.canvas.histogram.GLHistogram; import org.caleydo.core.view.opengl.canvas.pathway.GLPathway; import org.caleydo.core.view.opengl.canvas.radial.GLRadialHierarchy; import org.caleydo.core.view.opengl.canvas.remote.ARemoteViewLayoutRenderStyle; import org.caleydo.core.view.opengl.canvas.remote.GLRemoteRendering; import org.caleydo.core.view.opengl.canvas.remote.dataflipper.GLDataFlipper; import org.caleydo.core.view.opengl.canvas.remote.viewbrowser.GLPathwayViewBrowser; import org.caleydo.core.view.opengl.canvas.remote.viewbrowser.GLTissueViewBrowser; import org.caleydo.core.view.opengl.canvas.storagebased.heatmap.GLDendrogram; import org.caleydo.core.view.opengl.canvas.storagebased.heatmap.GLHeatMap; import org.caleydo.core.view.opengl.canvas.storagebased.heatmap.GLHierarchicalHeatMap; import org.caleydo.core.view.opengl.canvas.storagebased.parallelcoordinates.GLParallelCoordinates; import org.caleydo.core.view.opengl.canvas.tissue.GLTissue; import org.caleydo.core.view.opengl.util.overlay.infoarea.GLInfoAreaManager; import org.caleydo.core.view.swt.browser.GenomeHTMLBrowserViewRep; import org.caleydo.core.view.swt.browser.HTMLBrowserViewRep; import org.caleydo.core.view.swt.collab.CollabViewRep; import org.caleydo.core.view.swt.glyph.GlyphMappingConfigurationViewRep; import org.caleydo.core.view.swt.jogl.SwtJoglGLCanvasViewRep; import org.caleydo.core.view.swt.tabular.TabularDataViewRep; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.swt.widgets.Composite; import com.sun.opengl.util.Animator; import com.sun.opengl.util.FPSAnimator; /** * Manage all canvas, view, ViewReps and GLCanvas objects. * * @author Michael Kalkusch * @author Marc Streit * @author Alexander Lex */ public class ViewManager extends AManager<IView> implements IViewManager, IListenerOwner { protected HashMap<Integer, GLCaleydoCanvas> hashGLCanvasID2GLCanvas; protected HashMap<GLCaleydoCanvas, ArrayList<AGLView>> hashGLCanvas2GLEventListeners; protected HashMap<Integer, AGLView> hashGLEventListenerID2GLEventListener; private Animator fpsAnimator; private PickingManager pickingManager; private ConnectedElementRepresentationManager selectionManager; private GLInfoAreaManager infoAreaManager; private Composite activeSWTView; private Set<Object> busyRequests; private CreateGUIViewListener createGUIViewListener; /** * Utility object to execute code within the display loop, e.g. used by managers to avoid access conflicts * with views. */ private DisplayLoopExecution displayLoopExecution; private ArrayList<IGLViewCreator> glViewCreators; /** * Constructor. */ public ViewManager() { pickingManager = new PickingManager(); selectionManager = new ConnectedElementRepresentationManager(); infoAreaManager = new GLInfoAreaManager(); hashGLCanvasID2GLCanvas = new HashMap<Integer, GLCaleydoCanvas>(); hashGLCanvas2GLEventListeners = new HashMap<GLCaleydoCanvas, ArrayList<AGLView>>(); hashGLEventListenerID2GLEventListener = new HashMap<Integer, AGLView>(); fpsAnimator = new FPSAnimator(null, 60); busyRequests = new HashSet<Object>(); registerEventListeners(); displayLoopExecution = DisplayLoopExecution.get(); fpsAnimator.add(displayLoopExecution.getDisplayLoopCanvas()); displayLoopExecution.executeMultiple(selectionManager); glViewCreators = new ArrayList<IGLViewCreator>(); } @Override public boolean hasItem(int iItemId) { if (hashItems.containsKey(iItemId)) return true; if (hashGLCanvasID2GLCanvas.containsKey(iItemId)) return true; if (hashGLEventListenerID2GLEventListener.containsKey(iItemId)) return true; return false; } public GLCaleydoCanvas getCanvas(int iItemID) { return hashGLCanvasID2GLCanvas.get(iItemID); } public AGLView getGLEventListener(int iItemID) { return hashGLEventListenerID2GLEventListener.get(iItemID); } @Override public IView createView(final EManagedObjectType type, final int iParentContainerID, final String sLabel) { IView view = null; switch (type) { case VIEW: break; case VIEW_SWT_TABULAR_DATA_VIEWER: view = new TabularDataViewRep(iParentContainerID, sLabel); break; case VIEW_SWT_BROWSER_GENERAL: view = new HTMLBrowserViewRep(iParentContainerID, sLabel); break; case VIEW_SWT_BROWSER_GENOME: view = new GenomeHTMLBrowserViewRep(iParentContainerID, sLabel); break; case VIEW_SWT_GLYPH_MAPPINGCONFIGURATION: view = new GlyphMappingConfigurationViewRep(iParentContainerID, sLabel); break; case VIEW_SWT_COLLAB: view = new CollabViewRep(iParentContainerID, sLabel); break; default: throw new IllegalStateException("ViewManager.createView() failed due to unhandled type [" + type.toString() + "]"); } registerItem(view); return view; } @Override public IView createGLView(final EManagedObjectType useViewType, final int iParentContainerID, final String sLabel) { IView view = null; switch (useViewType) { case VIEW_GL_CANVAS: view = new SwtJoglGLCanvasViewRep(iParentContainerID, sLabel); break; default: throw new RuntimeException("Unhandled view type [" + useViewType.toString() + "]"); } registerItem(view); return view; } @Override public AGLView createGLEventListener(ECommandType type, GLCaleydoCanvas glCanvas, final String label, final IViewFrustum viewFrustum) { GeneralManager.get().getLogger().log( new Status(IStatus.INFO, IGeneralManager.PLUGIN_ID, "Creating GL canvas view from type: [" + type + "] and label: [" + label + "]")); AGLView glView = null; for (IGLViewCreator glViewCreator : glViewCreators) { - if (type.name().equals(ECommandType.CREATE_GL_SCATTERPLOT) - && glViewCreator.getViewType().equals("org.caleydo.view.scatterplot")) { + if (//type.name().equals(ECommandType.CREATE_GL_SCATTERPLOT)&& + glViewCreator.getViewType().equals("org.caleydo.view.scatterplot")) { glView = glViewCreator.createGLEventListener(type, glCanvas, label, viewFrustum); break; } // TODO: GL_CELL } if (glView == null) { switch (type) { case CREATE_GL_HEAT_MAP_3D: glView = new GLHeatMap(glCanvas, label, viewFrustum); break; case CREATE_GL_PROPAGATION_HEAT_MAP_3D: glView = new GLBookmarkManager(glCanvas, label, viewFrustum); break; case CREATE_GL_TEXTURE_HEAT_MAP_3D: glView = new GLHierarchicalHeatMap(glCanvas, label, viewFrustum); break; case CREATE_GL_PATHWAY_3D: glView = new GLPathway(glCanvas, label, viewFrustum); break; case CREATE_GL_PARALLEL_COORDINATES: glView = new GLParallelCoordinates(glCanvas, label, viewFrustum); break; case CREATE_GL_GLYPH: glView = new GLGlyph(glCanvas, label, viewFrustum); break; case CREATE_GL_GLYPH_SLIDER: glView = new GLGlyphSliderView(glCanvas, label, viewFrustum); break; case CREATE_GL_TISSUE: glView = new GLTissue(glCanvas, label, viewFrustum); break; case CREATE_GL_BUCKET_3D: glView = new GLRemoteRendering(glCanvas, label, viewFrustum, ARemoteViewLayoutRenderStyle.LayoutMode.BUCKET); break; case CREATE_GL_JUKEBOX_3D: glView = new GLRemoteRendering(glCanvas, label, viewFrustum, ARemoteViewLayoutRenderStyle.LayoutMode.JUKEBOX); break; case CREATE_GL_DATA_FLIPPER: glView = new GLDataFlipper(glCanvas, label, viewFrustum); break; case CREATE_GL_TISSUE_VIEW_BROWSER: glView = new GLTissueViewBrowser(glCanvas, label, viewFrustum); break; case CREATE_GL_PATHWAY_VIEW_BROWSER: glView = new GLPathwayViewBrowser(glCanvas, label, viewFrustum); break; case CREATE_GL_RADIAL_HIERARCHY: glView = new GLRadialHierarchy(glCanvas, label, viewFrustum); break; case CREATE_GL_HISTOGRAM: glView = new GLHistogram(glCanvas, label, viewFrustum); break; case CREATE_GL_GROUPER: glView = new GLGrouper(glCanvas, label, viewFrustum); break; case CREATE_GL_DENDROGRAM_HORIZONTAL: glView = new GLDendrogram(glCanvas, label, viewFrustum, true); break; case CREATE_GL_DENDROGRAM_VERTICAL: glView = new GLDendrogram(glCanvas, label, viewFrustum, false); break; default: throw new RuntimeException( "ViewJoglManager.createGLCanvasUser() failed due to unhandled type [" + type.toString() + "]"); } } if (glView == null) { throw new RuntimeException("Unable to create GL view because view plugin is not available!"); } registerGLEventListenerByGLCanvas(glCanvas, glView); return glView; } @Override public boolean registerGLCanvas(final GLCaleydoCanvas glCanvas) { int iGLCanvasID = glCanvas.getID(); if (hashGLCanvasID2GLCanvas.containsKey(iGLCanvasID)) { generalManager.getLogger().log( new Status(IStatus.WARNING, IGeneralManager.PLUGIN_ID, "GL Canvas with ID " + iGLCanvasID + " is already registered! Do nothing.")); return false; } hashGLCanvasID2GLCanvas.put(iGLCanvasID, glCanvas); // fpsAnimator.add(glCanvas); return true; } @Override public boolean unregisterGLCanvas(final GLCaleydoCanvas glCanvas) { if (glCanvas == null) return false; fpsAnimator.remove(glCanvas); hashGLCanvasID2GLCanvas.remove(glCanvas.getID()); hashGLCanvas2GLEventListeners.remove(glCanvas); return true; } @Override public void registerGLEventListenerByGLCanvas(final GLCaleydoCanvas glCanvas, final AGLView gLEventListener) { hashGLEventListenerID2GLEventListener.put(gLEventListener.getID(), gLEventListener); // This is the case when a view is rendered remote if (glCanvas == null) return; if (!hashGLCanvas2GLEventListeners.containsKey(glCanvas)) { hashGLCanvas2GLEventListeners.put(glCanvas, new ArrayList<AGLView>()); } hashGLCanvas2GLEventListeners.get(glCanvas).add(gLEventListener); glCanvas.addGLEventListener(gLEventListener); } @Override public void cleanup() { hashGLCanvasID2GLCanvas.clear(); hashGLCanvas2GLEventListeners.clear(); hashGLEventListenerID2GLEventListener.clear(); hashItems.clear(); } @Override public void unregisterGLEventListener(final AGLView glEventListener) { if (glEventListener == null) return; GLCaleydoCanvas parentGLCanvas = (glEventListener).getParentGLCanvas(); if (parentGLCanvas != null) { parentGLCanvas.removeGLEventListener(glEventListener); if (hashGLCanvas2GLEventListeners.containsKey(parentGLCanvas)) { hashGLCanvas2GLEventListeners.get(parentGLCanvas).remove(glEventListener); } } hashGLEventListenerID2GLEventListener.remove(glEventListener.getID()); } @Override public Collection<GLCaleydoCanvas> getAllGLCanvasUsers() { return hashGLCanvasID2GLCanvas.values(); } @Override public Collection<AGLView> getAllGLEventListeners() { return hashGLEventListenerID2GLEventListener.values(); } public PickingManager getPickingManager() { return pickingManager; } public ConnectedElementRepresentationManager getConnectedElementRepresentationManager() { return selectionManager; } public GLInfoAreaManager getInfoAreaManager() { return infoAreaManager; } @Override public void startAnimator() { // // add all canvas objects before starting animator // // this is needed because all the views are fully filled with needed // data at that time. // for (GLCaleydoCanvas glCanvas : hashGLCanvasID2GLCanvas.values()) // { // fpsAnimator.add(glCanvas); // } fpsAnimator.start(); fpsAnimator.setIgnoreExceptions(true); fpsAnimator.setPrintExceptions(true); } @Override public void stopAnimator() { if (fpsAnimator.isAnimating()) fpsAnimator.stop(); } @Override public void registerGLCanvasToAnimator(final GLCanvas glCanvas) { fpsAnimator.add(glCanvas); } @Override public void unregisterGLCanvasFromAnimator(final GLCaleydoCanvas glCanvas) { fpsAnimator.remove(glCanvas); } public void setActiveSWTView(Composite composite) { if (composite == null) throw new IllegalStateException("Tried to set a null object as active SWT view."); activeSWTView = composite; } public Composite getActiveSWTView() { return activeSWTView; } @Override public void requestBusyMode(Object requestInstance) { if (requestInstance == null) { throw new IllegalArgumentException("requestInstance must not be null"); } synchronized (busyRequests) { if (busyRequests.isEmpty()) { for (AGLView tmpGLEventListener : getAllGLEventListeners()) { if (!tmpGLEventListener.isRenderedRemote()) { tmpGLEventListener.enableBusyMode(true); } } } if (!busyRequests.contains(requestInstance)) { busyRequests.add(requestInstance); } } } @Override public void releaseBusyMode(Object requestInstance) { if (requestInstance == null) { throw new IllegalArgumentException("requestInstance must not be null"); } synchronized (busyRequests) { if (busyRequests.contains(requestInstance)) { busyRequests.remove(requestInstance); } if (busyRequests.isEmpty()) { for (AGLView tmpGLEventListener : getAllGLEventListeners()) { if (!tmpGLEventListener.isRenderedRemote()) { tmpGLEventListener.enableBusyMode(false); } } } } } public void createSWTView(ASerializedView serializedView) { generalManager.getGUIBridge().createView(serializedView); } @Override public synchronized void queueEvent(final AEventListener<? extends IListenerOwner> listener, final AEvent event) { // PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getDisplay().asyncExec(new // Runnable() { // public void run() { listener.handleEvent(event); // } // }); } private void registerEventListeners() { IGeneralManager generalManager = GeneralManager.get(); IEventPublisher eventPublisher = generalManager.getEventPublisher(); createGUIViewListener = new CreateGUIViewListener(); createGUIViewListener.setHandler(this); eventPublisher.addListener(CreateGUIViewEvent.class, createGUIViewListener); } @SuppressWarnings("unused") private void unregisterEventListeners() { IGeneralManager generalManager = GeneralManager.get(); IEventPublisher eventPublisher = generalManager.getEventPublisher(); if (createGUIViewListener != null) { eventPublisher.removeListener(createGUIViewListener); createGUIViewListener = null; } } @Override public DisplayLoopExecution getDisplayLoopExecution() { return displayLoopExecution; } @Override public void addGLViewCreator(IGLViewCreator glViewCreator) { glViewCreators.add(glViewCreator); } }
true
true
public AGLView createGLEventListener(ECommandType type, GLCaleydoCanvas glCanvas, final String label, final IViewFrustum viewFrustum) { GeneralManager.get().getLogger().log( new Status(IStatus.INFO, IGeneralManager.PLUGIN_ID, "Creating GL canvas view from type: [" + type + "] and label: [" + label + "]")); AGLView glView = null; for (IGLViewCreator glViewCreator : glViewCreators) { if (type.name().equals(ECommandType.CREATE_GL_SCATTERPLOT) && glViewCreator.getViewType().equals("org.caleydo.view.scatterplot")) { glView = glViewCreator.createGLEventListener(type, glCanvas, label, viewFrustum); break; } // TODO: GL_CELL } if (glView == null) { switch (type) { case CREATE_GL_HEAT_MAP_3D: glView = new GLHeatMap(glCanvas, label, viewFrustum); break; case CREATE_GL_PROPAGATION_HEAT_MAP_3D: glView = new GLBookmarkManager(glCanvas, label, viewFrustum); break; case CREATE_GL_TEXTURE_HEAT_MAP_3D: glView = new GLHierarchicalHeatMap(glCanvas, label, viewFrustum); break; case CREATE_GL_PATHWAY_3D: glView = new GLPathway(glCanvas, label, viewFrustum); break; case CREATE_GL_PARALLEL_COORDINATES: glView = new GLParallelCoordinates(glCanvas, label, viewFrustum); break; case CREATE_GL_GLYPH: glView = new GLGlyph(glCanvas, label, viewFrustum); break; case CREATE_GL_GLYPH_SLIDER: glView = new GLGlyphSliderView(glCanvas, label, viewFrustum); break; case CREATE_GL_TISSUE: glView = new GLTissue(glCanvas, label, viewFrustum); break; case CREATE_GL_BUCKET_3D: glView = new GLRemoteRendering(glCanvas, label, viewFrustum, ARemoteViewLayoutRenderStyle.LayoutMode.BUCKET); break; case CREATE_GL_JUKEBOX_3D: glView = new GLRemoteRendering(glCanvas, label, viewFrustum, ARemoteViewLayoutRenderStyle.LayoutMode.JUKEBOX); break; case CREATE_GL_DATA_FLIPPER: glView = new GLDataFlipper(glCanvas, label, viewFrustum); break; case CREATE_GL_TISSUE_VIEW_BROWSER: glView = new GLTissueViewBrowser(glCanvas, label, viewFrustum); break; case CREATE_GL_PATHWAY_VIEW_BROWSER: glView = new GLPathwayViewBrowser(glCanvas, label, viewFrustum); break; case CREATE_GL_RADIAL_HIERARCHY: glView = new GLRadialHierarchy(glCanvas, label, viewFrustum); break; case CREATE_GL_HISTOGRAM: glView = new GLHistogram(glCanvas, label, viewFrustum); break; case CREATE_GL_GROUPER: glView = new GLGrouper(glCanvas, label, viewFrustum); break; case CREATE_GL_DENDROGRAM_HORIZONTAL: glView = new GLDendrogram(glCanvas, label, viewFrustum, true); break; case CREATE_GL_DENDROGRAM_VERTICAL: glView = new GLDendrogram(glCanvas, label, viewFrustum, false); break; default: throw new RuntimeException( "ViewJoglManager.createGLCanvasUser() failed due to unhandled type [" + type.toString() + "]"); } } if (glView == null) { throw new RuntimeException("Unable to create GL view because view plugin is not available!"); } registerGLEventListenerByGLCanvas(glCanvas, glView); return glView; }
public AGLView createGLEventListener(ECommandType type, GLCaleydoCanvas glCanvas, final String label, final IViewFrustum viewFrustum) { GeneralManager.get().getLogger().log( new Status(IStatus.INFO, IGeneralManager.PLUGIN_ID, "Creating GL canvas view from type: [" + type + "] and label: [" + label + "]")); AGLView glView = null; for (IGLViewCreator glViewCreator : glViewCreators) { if (//type.name().equals(ECommandType.CREATE_GL_SCATTERPLOT)&& glViewCreator.getViewType().equals("org.caleydo.view.scatterplot")) { glView = glViewCreator.createGLEventListener(type, glCanvas, label, viewFrustum); break; } // TODO: GL_CELL } if (glView == null) { switch (type) { case CREATE_GL_HEAT_MAP_3D: glView = new GLHeatMap(glCanvas, label, viewFrustum); break; case CREATE_GL_PROPAGATION_HEAT_MAP_3D: glView = new GLBookmarkManager(glCanvas, label, viewFrustum); break; case CREATE_GL_TEXTURE_HEAT_MAP_3D: glView = new GLHierarchicalHeatMap(glCanvas, label, viewFrustum); break; case CREATE_GL_PATHWAY_3D: glView = new GLPathway(glCanvas, label, viewFrustum); break; case CREATE_GL_PARALLEL_COORDINATES: glView = new GLParallelCoordinates(glCanvas, label, viewFrustum); break; case CREATE_GL_GLYPH: glView = new GLGlyph(glCanvas, label, viewFrustum); break; case CREATE_GL_GLYPH_SLIDER: glView = new GLGlyphSliderView(glCanvas, label, viewFrustum); break; case CREATE_GL_TISSUE: glView = new GLTissue(glCanvas, label, viewFrustum); break; case CREATE_GL_BUCKET_3D: glView = new GLRemoteRendering(glCanvas, label, viewFrustum, ARemoteViewLayoutRenderStyle.LayoutMode.BUCKET); break; case CREATE_GL_JUKEBOX_3D: glView = new GLRemoteRendering(glCanvas, label, viewFrustum, ARemoteViewLayoutRenderStyle.LayoutMode.JUKEBOX); break; case CREATE_GL_DATA_FLIPPER: glView = new GLDataFlipper(glCanvas, label, viewFrustum); break; case CREATE_GL_TISSUE_VIEW_BROWSER: glView = new GLTissueViewBrowser(glCanvas, label, viewFrustum); break; case CREATE_GL_PATHWAY_VIEW_BROWSER: glView = new GLPathwayViewBrowser(glCanvas, label, viewFrustum); break; case CREATE_GL_RADIAL_HIERARCHY: glView = new GLRadialHierarchy(glCanvas, label, viewFrustum); break; case CREATE_GL_HISTOGRAM: glView = new GLHistogram(glCanvas, label, viewFrustum); break; case CREATE_GL_GROUPER: glView = new GLGrouper(glCanvas, label, viewFrustum); break; case CREATE_GL_DENDROGRAM_HORIZONTAL: glView = new GLDendrogram(glCanvas, label, viewFrustum, true); break; case CREATE_GL_DENDROGRAM_VERTICAL: glView = new GLDendrogram(glCanvas, label, viewFrustum, false); break; default: throw new RuntimeException( "ViewJoglManager.createGLCanvasUser() failed due to unhandled type [" + type.toString() + "]"); } } if (glView == null) { throw new RuntimeException("Unable to create GL view because view plugin is not available!"); } registerGLEventListenerByGLCanvas(glCanvas, glView); return glView; }
diff --git a/caadapter/components/hl7Transformation/src/gov/nih/nci/caadapter/hl7/v2v3/tools/DefaultDataProcessor.java b/caadapter/components/hl7Transformation/src/gov/nih/nci/caadapter/hl7/v2v3/tools/DefaultDataProcessor.java index 5de3b645e..6db5448d5 100644 --- a/caadapter/components/hl7Transformation/src/gov/nih/nci/caadapter/hl7/v2v3/tools/DefaultDataProcessor.java +++ b/caadapter/components/hl7Transformation/src/gov/nih/nci/caadapter/hl7/v2v3/tools/DefaultDataProcessor.java @@ -1,184 +1,184 @@ package gov.nih.nci.caadapter.hl7.v2v3.tools; import gov.nih.nci.caadapter.common.ApplicationException; import java.util.StringTokenizer; /** * Created by IntelliJ IDEA. * User: umkis * Date: Apr 21, 2009 * Time: 10:49:43 AM * To change this template use File | Settings | File Templates. */ public class DefaultDataProcessor { private String TAG_SYMBOL = "%%"; private String DELIMITER = ";"; private String SEPARATOR = ":"; String[] NULL_FLAVOR_VALUES = new String[] {"NI", "OTH", "NINF", "PINF", "UNK", "ASKU", "NAV", "NASK", "TRC", "MSK", "NA", "NP"}; public DefaultDataProcessor() { } public String getDefaultTagSymbol() { return TAG_SYMBOL; } public boolean isValidNullFlavorValue(String nullFlavor) { if (nullFlavor == null) return false; for(String nullF:NULL_FLAVOR_VALUES) { if (nullF.equals(nullFlavor.trim())) return true; } return false; } public String processDefaultValueTag(String defValue) throws ApplicationException { return processDefaultValueTag(defValue, null); } public String processDefaultValueTag(String defValue, String nodeValue) throws ApplicationException { String defVal = defValue; if (defVal == null) defVal = ""; if (!defVal.trim().startsWith(TAG_SYMBOL)) { if ((nodeValue == null)||(nodeValue.trim()).equals("")) return defValue; return nodeValue; } //System.out.println("GGGG : defValue="+ defValue + " nodeValue=" + nodeValue); StringTokenizer st = new StringTokenizer(defVal, DELIMITER); String nodeVal = nodeValue; if (nodeVal == null) nodeVal = ""; nodeVal = nodeVal.trim(); String res = ""; //String message = ""; boolean wasStringTag = false; boolean wasMathTag = false; while(st.hasMoreTokens()) { String next = st.nextToken(); if (next.trim().equals("")) continue; if (!next.startsWith(TAG_SYMBOL)) next = TAG_SYMBOL + "when_null:" + next; int idx = next.indexOf(SEPARATOR); if (idx < 0) continue; String key = next.substring(2, idx).trim(); String val = next.substring(idx+1).trim(); if (key.equals("")) continue; if (val.startsWith("\"")) val = val.substring(1); if (val.endsWith("\"")) val = val.substring(0, val.length()-1); if (val.equals("")) throw new ApplicationException("Null data for fuctional default value : " + next); if ((key.equalsIgnoreCase("prefix"))&&(!nodeVal.equals(""))) { wasStringTag = true; if (res.equals("")) res = val + nodeVal; else res = val + res; } if ((key.equalsIgnoreCase("suffix"))&&(!nodeVal.equals(""))) { wasStringTag = true; if (res.equals("")) res = nodeVal + val; else res = res + val; } if ((key.equalsIgnoreCase("when_null"))&&(nodeVal.equals(""))) return val; - //if (!res.equals("")) continue; + if (!res.equals("")) continue; if (nodeVal.equals("")) continue; double defDbl = 0.0; double nodeDbl = 0.0; double resultDbl = 0.0; try { defDbl = Double.parseDouble(val); //System.out.println("GGGG default value : " + val); } catch(NumberFormatException ne) { throw new ApplicationException("Invalid number format data for fuctional default value : " + next); } try { nodeDbl = Double.parseDouble(nodeVal); //System.out.println("GGGG node value : " + nodeVal); } catch(NumberFormatException ne) { throw new ApplicationException("Invalid number format input data for fuctional default process : " + nodeVal); } boolean isMathTag = true; if (key.equalsIgnoreCase("add")) resultDbl = defDbl + nodeDbl; else if (key.equalsIgnoreCase("multiply")) resultDbl = defDbl * nodeDbl; else if ((key.equalsIgnoreCase("subtract"))||(key.equalsIgnoreCase("subtract_by"))) resultDbl = nodeDbl - defDbl; else if (key.equalsIgnoreCase("subtract_from")) resultDbl = defDbl - nodeDbl; else if ((key.equalsIgnoreCase("divide"))||(key.equalsIgnoreCase("divide_by"))) { if (defDbl == 0.0) throw new ApplicationException("Divided by zero exception by default value : " + next); else resultDbl = nodeDbl / defDbl; } else if (key.equalsIgnoreCase("divide_from")) { if (nodeDbl == 0.0) throw new ApplicationException("Divided by zero exception by mapped value ("+next+") : " + nodeVal); else resultDbl = defDbl / nodeDbl; } else if ((key.equalsIgnoreCase("remainder"))||(key.equalsIgnoreCase("remainder_by"))) { if (defDbl == 0.0) resultDbl = nodeDbl; else resultDbl = nodeDbl % defDbl; } else if (key.equalsIgnoreCase("remainder_from")) { if (nodeDbl == 0.0) resultDbl = defDbl; else resultDbl = defDbl % nodeDbl; } else { isMathTag = false; throw new ApplicationException("Invalid tag for fuctional default process : "+next); } if (isMathTag) { if (wasMathTag) throw new ApplicationException("Duplicate Math tag : " + next); wasMathTag = true; if ((wasMathTag)&&(wasStringTag)) throw new ApplicationException("Math tag and String tag are mixed in these fuctional default tags : " + defValue); } if (!isMathTag) continue; res = String.valueOf(resultDbl); int idx1 = res.indexOf("."); if (idx1 < 0) { continue; } String integerPart = res.substring(0,idx1); int realPartValue = 0; try { realPartValue = Integer.parseInt(res.substring(idx1+1)); } catch(NumberFormatException ne) { return res; } if (realPartValue == 0) res = integerPart; return res; } if (!res.equals("")) return res; return nodeVal; } }
true
true
public String processDefaultValueTag(String defValue, String nodeValue) throws ApplicationException { String defVal = defValue; if (defVal == null) defVal = ""; if (!defVal.trim().startsWith(TAG_SYMBOL)) { if ((nodeValue == null)||(nodeValue.trim()).equals("")) return defValue; return nodeValue; } //System.out.println("GGGG : defValue="+ defValue + " nodeValue=" + nodeValue); StringTokenizer st = new StringTokenizer(defVal, DELIMITER); String nodeVal = nodeValue; if (nodeVal == null) nodeVal = ""; nodeVal = nodeVal.trim(); String res = ""; //String message = ""; boolean wasStringTag = false; boolean wasMathTag = false; while(st.hasMoreTokens()) { String next = st.nextToken(); if (next.trim().equals("")) continue; if (!next.startsWith(TAG_SYMBOL)) next = TAG_SYMBOL + "when_null:" + next; int idx = next.indexOf(SEPARATOR); if (idx < 0) continue; String key = next.substring(2, idx).trim(); String val = next.substring(idx+1).trim(); if (key.equals("")) continue; if (val.startsWith("\"")) val = val.substring(1); if (val.endsWith("\"")) val = val.substring(0, val.length()-1); if (val.equals("")) throw new ApplicationException("Null data for fuctional default value : " + next); if ((key.equalsIgnoreCase("prefix"))&&(!nodeVal.equals(""))) { wasStringTag = true; if (res.equals("")) res = val + nodeVal; else res = val + res; } if ((key.equalsIgnoreCase("suffix"))&&(!nodeVal.equals(""))) { wasStringTag = true; if (res.equals("")) res = nodeVal + val; else res = res + val; } if ((key.equalsIgnoreCase("when_null"))&&(nodeVal.equals(""))) return val; //if (!res.equals("")) continue; if (nodeVal.equals("")) continue; double defDbl = 0.0; double nodeDbl = 0.0; double resultDbl = 0.0; try { defDbl = Double.parseDouble(val); //System.out.println("GGGG default value : " + val); } catch(NumberFormatException ne) { throw new ApplicationException("Invalid number format data for fuctional default value : " + next); } try { nodeDbl = Double.parseDouble(nodeVal); //System.out.println("GGGG node value : " + nodeVal); } catch(NumberFormatException ne) { throw new ApplicationException("Invalid number format input data for fuctional default process : " + nodeVal); } boolean isMathTag = true; if (key.equalsIgnoreCase("add")) resultDbl = defDbl + nodeDbl; else if (key.equalsIgnoreCase("multiply")) resultDbl = defDbl * nodeDbl; else if ((key.equalsIgnoreCase("subtract"))||(key.equalsIgnoreCase("subtract_by"))) resultDbl = nodeDbl - defDbl; else if (key.equalsIgnoreCase("subtract_from")) resultDbl = defDbl - nodeDbl; else if ((key.equalsIgnoreCase("divide"))||(key.equalsIgnoreCase("divide_by"))) { if (defDbl == 0.0) throw new ApplicationException("Divided by zero exception by default value : " + next); else resultDbl = nodeDbl / defDbl; } else if (key.equalsIgnoreCase("divide_from")) { if (nodeDbl == 0.0) throw new ApplicationException("Divided by zero exception by mapped value ("+next+") : " + nodeVal); else resultDbl = defDbl / nodeDbl; } else if ((key.equalsIgnoreCase("remainder"))||(key.equalsIgnoreCase("remainder_by"))) { if (defDbl == 0.0) resultDbl = nodeDbl; else resultDbl = nodeDbl % defDbl; } else if (key.equalsIgnoreCase("remainder_from")) { if (nodeDbl == 0.0) resultDbl = defDbl; else resultDbl = defDbl % nodeDbl; } else { isMathTag = false; throw new ApplicationException("Invalid tag for fuctional default process : "+next); } if (isMathTag) { if (wasMathTag) throw new ApplicationException("Duplicate Math tag : " + next); wasMathTag = true; if ((wasMathTag)&&(wasStringTag)) throw new ApplicationException("Math tag and String tag are mixed in these fuctional default tags : " + defValue); } if (!isMathTag) continue; res = String.valueOf(resultDbl); int idx1 = res.indexOf("."); if (idx1 < 0) { continue; } String integerPart = res.substring(0,idx1); int realPartValue = 0; try { realPartValue = Integer.parseInt(res.substring(idx1+1)); } catch(NumberFormatException ne) { return res; } if (realPartValue == 0) res = integerPart; return res; } if (!res.equals("")) return res; return nodeVal; }
public String processDefaultValueTag(String defValue, String nodeValue) throws ApplicationException { String defVal = defValue; if (defVal == null) defVal = ""; if (!defVal.trim().startsWith(TAG_SYMBOL)) { if ((nodeValue == null)||(nodeValue.trim()).equals("")) return defValue; return nodeValue; } //System.out.println("GGGG : defValue="+ defValue + " nodeValue=" + nodeValue); StringTokenizer st = new StringTokenizer(defVal, DELIMITER); String nodeVal = nodeValue; if (nodeVal == null) nodeVal = ""; nodeVal = nodeVal.trim(); String res = ""; //String message = ""; boolean wasStringTag = false; boolean wasMathTag = false; while(st.hasMoreTokens()) { String next = st.nextToken(); if (next.trim().equals("")) continue; if (!next.startsWith(TAG_SYMBOL)) next = TAG_SYMBOL + "when_null:" + next; int idx = next.indexOf(SEPARATOR); if (idx < 0) continue; String key = next.substring(2, idx).trim(); String val = next.substring(idx+1).trim(); if (key.equals("")) continue; if (val.startsWith("\"")) val = val.substring(1); if (val.endsWith("\"")) val = val.substring(0, val.length()-1); if (val.equals("")) throw new ApplicationException("Null data for fuctional default value : " + next); if ((key.equalsIgnoreCase("prefix"))&&(!nodeVal.equals(""))) { wasStringTag = true; if (res.equals("")) res = val + nodeVal; else res = val + res; } if ((key.equalsIgnoreCase("suffix"))&&(!nodeVal.equals(""))) { wasStringTag = true; if (res.equals("")) res = nodeVal + val; else res = res + val; } if ((key.equalsIgnoreCase("when_null"))&&(nodeVal.equals(""))) return val; if (!res.equals("")) continue; if (nodeVal.equals("")) continue; double defDbl = 0.0; double nodeDbl = 0.0; double resultDbl = 0.0; try { defDbl = Double.parseDouble(val); //System.out.println("GGGG default value : " + val); } catch(NumberFormatException ne) { throw new ApplicationException("Invalid number format data for fuctional default value : " + next); } try { nodeDbl = Double.parseDouble(nodeVal); //System.out.println("GGGG node value : " + nodeVal); } catch(NumberFormatException ne) { throw new ApplicationException("Invalid number format input data for fuctional default process : " + nodeVal); } boolean isMathTag = true; if (key.equalsIgnoreCase("add")) resultDbl = defDbl + nodeDbl; else if (key.equalsIgnoreCase("multiply")) resultDbl = defDbl * nodeDbl; else if ((key.equalsIgnoreCase("subtract"))||(key.equalsIgnoreCase("subtract_by"))) resultDbl = nodeDbl - defDbl; else if (key.equalsIgnoreCase("subtract_from")) resultDbl = defDbl - nodeDbl; else if ((key.equalsIgnoreCase("divide"))||(key.equalsIgnoreCase("divide_by"))) { if (defDbl == 0.0) throw new ApplicationException("Divided by zero exception by default value : " + next); else resultDbl = nodeDbl / defDbl; } else if (key.equalsIgnoreCase("divide_from")) { if (nodeDbl == 0.0) throw new ApplicationException("Divided by zero exception by mapped value ("+next+") : " + nodeVal); else resultDbl = defDbl / nodeDbl; } else if ((key.equalsIgnoreCase("remainder"))||(key.equalsIgnoreCase("remainder_by"))) { if (defDbl == 0.0) resultDbl = nodeDbl; else resultDbl = nodeDbl % defDbl; } else if (key.equalsIgnoreCase("remainder_from")) { if (nodeDbl == 0.0) resultDbl = defDbl; else resultDbl = defDbl % nodeDbl; } else { isMathTag = false; throw new ApplicationException("Invalid tag for fuctional default process : "+next); } if (isMathTag) { if (wasMathTag) throw new ApplicationException("Duplicate Math tag : " + next); wasMathTag = true; if ((wasMathTag)&&(wasStringTag)) throw new ApplicationException("Math tag and String tag are mixed in these fuctional default tags : " + defValue); } if (!isMathTag) continue; res = String.valueOf(resultDbl); int idx1 = res.indexOf("."); if (idx1 < 0) { continue; } String integerPart = res.substring(0,idx1); int realPartValue = 0; try { realPartValue = Integer.parseInt(res.substring(idx1+1)); } catch(NumberFormatException ne) { return res; } if (realPartValue == 0) res = integerPart; return res; } if (!res.equals("")) return res; return nodeVal; }
diff --git a/src/resources/directory/src/java/org/wyona/yanel/impl/resources/collection/CollectionResource.java b/src/resources/directory/src/java/org/wyona/yanel/impl/resources/collection/CollectionResource.java index 64357d7b5..35baa529b 100644 --- a/src/resources/directory/src/java/org/wyona/yanel/impl/resources/collection/CollectionResource.java +++ b/src/resources/directory/src/java/org/wyona/yanel/impl/resources/collection/CollectionResource.java @@ -1,317 +1,317 @@ /* * Copyright 2007 Wyona * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.wyona.org/licenses/APACHE-LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wyona.yanel.impl.resources.collection; import org.wyona.yanel.core.Environment; import org.wyona.yanel.core.ResourceConfiguration; import org.wyona.yanel.core.api.attributes.CreatableV2; import org.wyona.yanel.core.api.attributes.ViewableV2; import org.wyona.yanel.core.attributes.viewable.View; import org.wyona.yanel.impl.resources.BasicXMLResource; import javax.servlet.http.HttpServletRequest; import org.wyona.yarep.core.Repository; import org.wyona.yarep.core.Node; import org.wyona.yanel.core.util.DateUtil; import org.wyona.yanel.core.util.PathUtil; import org.apache.log4j.Category; import java.io.File; import java.io.InputStream; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamSource; import javax.xml.transform.stream.StreamResult; import java.util.Calendar; /** * */ public class CollectionResource extends BasicXMLResource implements ViewableV2, CreatableV2 { private static Category log = Category.getInstance(CollectionResource.class); private Environment environment; public View getView(String viewId) throws Exception { return getView(viewId, null); } /** * Generates view */ public View getView(String viewId, String revisionName) throws Exception { Repository repo = getRealm().getRepository(); String yanelPath = getResourceConfigProperty("yanel-path"); InputStream xmlInputStream = getContentXML(repo, yanelPath, revisionName); return getXMLView(viewId, xmlInputStream); } /** * */ public InputStream getContentXML(Repository repo, String yanelPath, String revisionName) { environment = getEnvironment(); StringBuffer sb = new StringBuffer("<?xml version=\"1.0\"?>"); String path = getPath(); try { if (yanelPath != null) { path = yanelPath; } - log.warn("DEBUG: Path: " + path); + log.debug("Selected path: " + path); // TODO: This doesn't seem to work ... (check on Yarep ...) if (repo.getNode(path).isResource()) { log.warn("Path is a resource instead of a collection: " + path); // p = p.getParent(); } // TODO: Implement org.wyona.yarep.core.Path.getParent() if (!repo.getNode(path).isCollection()) { log.warn("Path is not a collection: " + path); log.warn("Use parent of path: " + repo.getNode(path).getParent().getPath()); } // TODO: Add realm prefix, e.g. realm-prefix="ulysses-demo" // NOTE: The schema is according to // http://cocoon.apache.org/2.1/userdocs/directory-generator.html sb.append("<dir:directory yanel:path=\"" + getPath() + "\" dir:name=\"" + repo.getNode(path).getName() + "\" dir:path=\"" + path + "\" xmlns:dir=\"http://apache.org/cocoon/directory/2.0\" xmlns:yanel=\"http://www.wyona.org/yanel/resource/directory/1.0\">"); // TODO: Do not show the children with suffix .yanel-rti resp. make // this configurable! // NOTE: Do not hardcode the .yanel-rti, but rather use // Path.getRTIPath ... Node[] children = repo.getNode(path).getNodes(); Calendar calendar = Calendar.getInstance(); if (children != null) { for (int i = 0; i < children.length; i++) { if (children[i].isResource()) { calendar.setTimeInMillis(children[i].getLastModified()); String lastModified = DateUtil.format(calendar.getTime()); sb.append("<dir:file path=\"" + children[i].getPath() + "\" name=\"" + children[i].getName() + "\" lastModified=\"" + children[i].getLastModified() + "\" date=\"" + lastModified + "\" size=\"" + children[i].getSize() + "\"/>"); } else if (children[i].isCollection()) { sb.append("<dir:directory path=\"" + children[i].getPath() + "\" name=\"" + children[i].getName() + "\"/>"); } else { sb.append("<yanel:exception yanel:path=\"" + children[i] + "\"/>"); } } if (children.length < 1) { sb.append("<yanel:no-children/>"); } } else { sb.append("<yanel:no-children/>"); } } catch (Exception e) { log.error(e.getMessage(), e); } sb.append("</dir:directory>"); return new java.io.StringBufferInputStream(sb.toString()); } public View getXMLView(String viewId, InputStream xmlInputStream) throws Exception { if (viewId == null || !viewId.equals("source")) { TransformerFactory tfactory = TransformerFactory.newInstance(); Transformer transformerIntern = tfactory.newTransformer(getXSLTStreamSource()); transformerIntern.setParameter("yanel.path.name", org.wyona.commons.io.PathUtil.getName(getPath())); transformerIntern.setParameter("yanel.path", getPath().toString()); transformerIntern.setParameter("yanel.back2context", backToContext()+backToRoot()); transformerIntern.setParameter("yarep.back2realm", backToRoot()); transformerIntern.setParameter("yarep.parent", getParent(getPath())); transformerIntern.setParameter("yanel.htdocs", PathUtil.getGlobalHtdocsPath(this)); java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); transformerIntern.transform(new StreamSource(xmlInputStream), new StreamResult(baos)); return super.getXMLView(viewId, new java.io.ByteArrayInputStream(baos.toByteArray())); } return super.getXMLView(viewId, xmlInputStream); } /** * Gets the names of the i18n message catalogues used for the i18n transformation. * Looks for an rc config property named 'i18n-catalogue'. Defaults to 'global'. * @return i18n catalogue name */ protected String[] getI18NCatalogueNames() throws Exception { String[] array = {"global","directory"}; return array; } /** * */ public boolean exists() throws Exception { log.warn("Not implemented yet!"); return true; } /** * */ public long getSize() throws Exception { // TODO: not implemented yet log.warn("TODO: Method is not implemented yet"); return -1; } /** * */ private StreamSource getXSLTStreamSource() throws Exception { String customDefaultXSLT = getResourceConfigProperty("default-xslt"); if (customDefaultXSLT != null) { return new StreamSource(getRealm().getRepository().getNode(customDefaultXSLT).getInputStream()); } File defaultXSLTFile = org.wyona.commons.io.FileUtil.file(rtd.getConfigFile().getParentFile().getAbsolutePath(), "xslt" + File.separator + "dir2xhtml.xsl"); if (log.isDebugEnabled()) log.debug("XSLT file: " + defaultXSLTFile); return new StreamSource(defaultXSLTFile); } /** * Get mime type */ public String getMimeType(String viewId) throws Exception { String mimeType = null; ResourceConfiguration rc = getConfiguration(); if (rc != null) { mimeType = rc.getProperty("mime-type"); } else { mimeType = getRTI().getProperty("mime-type"); } if (mimeType != null) return mimeType; // NOTE: Assuming fallback re dir2xhtml.xsl ... return "application/xhtml+xml"; } /** * @return a String with as many ../ as it needs to go back to from current realm to context */ private String backToContext() { String backToContext = ""; int steps = realm.getMountPoint().split("/").length - 1; for (int i = 0; i < steps; i++) { backToContext = backToContext + "../"; } return backToContext; } /** * @return a String with as many ../ as it needs to go back to from current resource to the realm-root */ private String backToRoot() { String backToRoot = ""; int steps; // TODO: Wouldn't it make more sense to use "tokens" and use a URL rewriter at the very end (also see the portlet specificatio http://jcp.org/aboutJava/communityprocess/review/jsr168/) String resourceContainerPath = environment.getResourceContainerPath(); if (log.isDebugEnabled()) { log.debug("Resource container path: " + resourceContainerPath); log.debug("Resource path: " + getPath()); } if (resourceContainerPath != null) { if (resourceContainerPath.endsWith("/") && !resourceContainerPath.equals("/")) { steps = resourceContainerPath.split("/").length - 1; } else { steps = resourceContainerPath.split("/").length - 2; } } else { if (getPath().endsWith("/") && !getPath().equals("/")) { steps = getPath().split("/").length - 1; } else { steps = getPath().split("/").length - 2; } } for (int i = 0; i < steps; i++) { backToRoot = backToRoot + "../"; } return backToRoot; } /** * @return a String ../ if path ends with a trailing slash. Otherwise a String ./ */ private String getParent(String path) { String parentPath = "./"; if (path.endsWith("/")) { parentPath = "../"; } return parentPath; } /** * */ public void create(HttpServletRequest request) { try { Repository repo = getRealm().getRepository(); org.wyona.yanel.core.util.YarepUtil.addNodes(repo, getPath().toString(), org.wyona.yarep.core.NodeType.COLLECTION); } catch (Exception e) { log.error(e.getMessage(), e); } } /** * */ public java.util.HashMap createRTIProperties(HttpServletRequest request) { java.util.HashMap map = new java.util.HashMap(); map.put("xslt", request.getParameter("rp.xslt")); map.put("mime-type", request.getParameter("rp.mime-type")); return map; } public String getCreateName(String suggestedName) { return suggestedName; } /** * */ public String getPropertyType(String name) { log.warn("Not implemented yet!"); return null; } /** * */ public Object getProperty(String name) { log.warn("Not implemented yet!"); return null; } /** * */ public String[] getPropertyNames() { log.warn("Not implemented yet!"); return null; } /** * */ public void setProperty(String name, Object value) { log.warn("Not implemented yet!"); } }
true
true
public InputStream getContentXML(Repository repo, String yanelPath, String revisionName) { environment = getEnvironment(); StringBuffer sb = new StringBuffer("<?xml version=\"1.0\"?>"); String path = getPath(); try { if (yanelPath != null) { path = yanelPath; } log.warn("DEBUG: Path: " + path); // TODO: This doesn't seem to work ... (check on Yarep ...) if (repo.getNode(path).isResource()) { log.warn("Path is a resource instead of a collection: " + path); // p = p.getParent(); } // TODO: Implement org.wyona.yarep.core.Path.getParent() if (!repo.getNode(path).isCollection()) { log.warn("Path is not a collection: " + path); log.warn("Use parent of path: " + repo.getNode(path).getParent().getPath()); } // TODO: Add realm prefix, e.g. realm-prefix="ulysses-demo" // NOTE: The schema is according to // http://cocoon.apache.org/2.1/userdocs/directory-generator.html sb.append("<dir:directory yanel:path=\"" + getPath() + "\" dir:name=\"" + repo.getNode(path).getName() + "\" dir:path=\"" + path + "\" xmlns:dir=\"http://apache.org/cocoon/directory/2.0\" xmlns:yanel=\"http://www.wyona.org/yanel/resource/directory/1.0\">"); // TODO: Do not show the children with suffix .yanel-rti resp. make // this configurable! // NOTE: Do not hardcode the .yanel-rti, but rather use // Path.getRTIPath ... Node[] children = repo.getNode(path).getNodes(); Calendar calendar = Calendar.getInstance(); if (children != null) { for (int i = 0; i < children.length; i++) { if (children[i].isResource()) { calendar.setTimeInMillis(children[i].getLastModified()); String lastModified = DateUtil.format(calendar.getTime()); sb.append("<dir:file path=\"" + children[i].getPath() + "\" name=\"" + children[i].getName() + "\" lastModified=\"" + children[i].getLastModified() + "\" date=\"" + lastModified + "\" size=\"" + children[i].getSize() + "\"/>"); } else if (children[i].isCollection()) { sb.append("<dir:directory path=\"" + children[i].getPath() + "\" name=\"" + children[i].getName() + "\"/>"); } else { sb.append("<yanel:exception yanel:path=\"" + children[i] + "\"/>"); } } if (children.length < 1) { sb.append("<yanel:no-children/>"); } } else { sb.append("<yanel:no-children/>"); } } catch (Exception e) { log.error(e.getMessage(), e); } sb.append("</dir:directory>"); return new java.io.StringBufferInputStream(sb.toString()); }
public InputStream getContentXML(Repository repo, String yanelPath, String revisionName) { environment = getEnvironment(); StringBuffer sb = new StringBuffer("<?xml version=\"1.0\"?>"); String path = getPath(); try { if (yanelPath != null) { path = yanelPath; } log.debug("Selected path: " + path); // TODO: This doesn't seem to work ... (check on Yarep ...) if (repo.getNode(path).isResource()) { log.warn("Path is a resource instead of a collection: " + path); // p = p.getParent(); } // TODO: Implement org.wyona.yarep.core.Path.getParent() if (!repo.getNode(path).isCollection()) { log.warn("Path is not a collection: " + path); log.warn("Use parent of path: " + repo.getNode(path).getParent().getPath()); } // TODO: Add realm prefix, e.g. realm-prefix="ulysses-demo" // NOTE: The schema is according to // http://cocoon.apache.org/2.1/userdocs/directory-generator.html sb.append("<dir:directory yanel:path=\"" + getPath() + "\" dir:name=\"" + repo.getNode(path).getName() + "\" dir:path=\"" + path + "\" xmlns:dir=\"http://apache.org/cocoon/directory/2.0\" xmlns:yanel=\"http://www.wyona.org/yanel/resource/directory/1.0\">"); // TODO: Do not show the children with suffix .yanel-rti resp. make // this configurable! // NOTE: Do not hardcode the .yanel-rti, but rather use // Path.getRTIPath ... Node[] children = repo.getNode(path).getNodes(); Calendar calendar = Calendar.getInstance(); if (children != null) { for (int i = 0; i < children.length; i++) { if (children[i].isResource()) { calendar.setTimeInMillis(children[i].getLastModified()); String lastModified = DateUtil.format(calendar.getTime()); sb.append("<dir:file path=\"" + children[i].getPath() + "\" name=\"" + children[i].getName() + "\" lastModified=\"" + children[i].getLastModified() + "\" date=\"" + lastModified + "\" size=\"" + children[i].getSize() + "\"/>"); } else if (children[i].isCollection()) { sb.append("<dir:directory path=\"" + children[i].getPath() + "\" name=\"" + children[i].getName() + "\"/>"); } else { sb.append("<yanel:exception yanel:path=\"" + children[i] + "\"/>"); } } if (children.length < 1) { sb.append("<yanel:no-children/>"); } } else { sb.append("<yanel:no-children/>"); } } catch (Exception e) { log.error(e.getMessage(), e); } sb.append("</dir:directory>"); return new java.io.StringBufferInputStream(sb.toString()); }
diff --git a/src/com/dmdirc/Server.java b/src/com/dmdirc/Server.java index 3d76e26a1..f77295cad 100644 --- a/src/com/dmdirc/Server.java +++ b/src/com/dmdirc/Server.java @@ -1,1688 +1,1688 @@ /* * Copyright (c) 2006-2012 DMDirc Developers * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.dmdirc; import com.dmdirc.actions.ActionManager; import com.dmdirc.actions.CoreActionType; import com.dmdirc.actions.wrappers.AliasWrapper; import com.dmdirc.commandparser.CommandManager; import com.dmdirc.commandparser.CommandType; import com.dmdirc.commandparser.parsers.ServerCommandParser; import com.dmdirc.config.ConfigManager; import com.dmdirc.config.Identity; import com.dmdirc.config.IdentityManager; import com.dmdirc.interfaces.AwayStateListener; import com.dmdirc.interfaces.ConfigChangeListener; import com.dmdirc.interfaces.Connection; import com.dmdirc.interfaces.InviteListener; import com.dmdirc.logger.ErrorLevel; import com.dmdirc.logger.Logger; import com.dmdirc.parser.common.ChannelJoinRequest; import com.dmdirc.parser.common.DefaultStringConverter; import com.dmdirc.parser.common.IgnoreList; import com.dmdirc.parser.common.MyInfo; import com.dmdirc.parser.common.ParserError; import com.dmdirc.parser.common.ThreadedParser; import com.dmdirc.parser.interfaces.ChannelInfo; import com.dmdirc.parser.interfaces.ClientInfo; import com.dmdirc.parser.interfaces.EncodingParser; import com.dmdirc.parser.interfaces.Parser; import com.dmdirc.parser.interfaces.ProtocolDescription; import com.dmdirc.parser.interfaces.SecureParser; import com.dmdirc.parser.interfaces.StringConverter; import com.dmdirc.tls.CertificateManager; import com.dmdirc.tls.CertificateProblemListener; import com.dmdirc.ui.StatusMessage; import com.dmdirc.ui.WindowManager; import com.dmdirc.ui.core.components.StatusBarManager; import com.dmdirc.ui.core.components.WindowComponent; import com.dmdirc.ui.input.TabCompleter; import com.dmdirc.ui.input.TabCompletionType; import com.dmdirc.ui.messages.Formatter; import java.net.URI; import java.net.URISyntaxException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import javax.net.ssl.TrustManager; /** * The Server class represents the client's view of a server. It maintains * a list of all channels, queries, etc, and handles parser callbacks pertaining * to the server. */ public class Server extends WritableFrameContainer implements ConfigChangeListener, CertificateProblemListener, Connection { // <editor-fold defaultstate="collapsed" desc="Properties"> // <editor-fold defaultstate="collapsed" desc="Static"> /** The name of the general domain. */ private static final String DOMAIN_GENERAL = "general".intern(); /** The name of the profile domain. */ private static final String DOMAIN_PROFILE = "profile".intern(); /** The name of the server domain. */ private static final String DOMAIN_SERVER = "server".intern(); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Instance"> /** Open channels that currently exist on the server. */ private final Map<String, Channel> channels = new ConcurrentSkipListMap<String, Channel>(); /** Open query windows on the server. */ private final Map<String, Query> queries = new ConcurrentSkipListMap<String, Query>(); /** The Parser instance handling this server. */ private Parser parser; /** The Parser instance that used to be handling this server. */ private Parser oldParser; /** The parser-supplied protocol description object. */ private ProtocolDescription protocolDescription; /** * Object used to synchronise access to parser. This object should be * locked by anything requiring that the parser reference remains the same * for a duration of time, or by anything which is updating the parser * reference. * * If used in conjunction with myStateLock, the parserLock must always be * locked INSIDE the myStateLock to prevent deadlocks. */ private final ReadWriteLock parserLock = new ReentrantReadWriteLock(); /** The raw frame used for this server instance. */ private Raw raw; /** The address of the server we're connecting to. */ private URI address; /** The profile we're using. */ private Identity profile; /** Object used to synchronise access to myState. */ private final Object myStateLock = new Object(); /** The current state of this server. */ private final ServerStatus myState = new ServerStatus(this, myStateLock); /** The timer we're using to delay reconnects. */ private Timer reconnectTimer; /** The tabcompleter used for this server. */ private final TabCompleter tabCompleter = new TabCompleter(); /** Our reason for being away, if any. */ private String awayMessage; /** Our event handler. */ private final ServerEventHandler eventHandler = new ServerEventHandler(this); /** A list of outstanding invites. */ private final List<Invite> invites = new ArrayList<Invite>(); /** A set of channels we want to join without focusing. */ private final Set<String> backgroundChannels = new HashSet<String>(); /** Our ignore list. */ private final IgnoreList ignoreList = new IgnoreList(); /** Our string convertor. */ private StringConverter converter = new DefaultStringConverter(); /** The certificate manager in use, if any. */ private CertificateManager certificateManager; // </editor-fold> // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Constructors"> /** * Creates a new server which will connect to the specified URL with * the specified profile. * * @since 0.6.3 * @param uri The address of the server to connect to * @param profile The profile to use */ public Server(final URI uri, final Identity profile) { super("server-disconnected", getHost(uri), getHost(uri), new ConfigManager(uri.getScheme(), "", "", uri.getHost()), new ServerCommandParser(), Arrays.asList(WindowComponent.TEXTAREA.getIdentifier(), WindowComponent.INPUTFIELD.getIdentifier(), WindowComponent.CERTIFICATE_VIEWER.getIdentifier())); setConnectionDetails(uri, profile); ServerManager.getServerManager().registerServer(this); WindowManager.getWindowManager().addWindow(this); tabCompleter.addEntries(TabCompletionType.COMMAND, AliasWrapper.getAliasWrapper().getAliases()); tabCompleter.addEntries(TabCompletionType.COMMAND, CommandManager.getCommandManager().getCommandNames(CommandType.TYPE_SERVER)); tabCompleter.addEntries(TabCompletionType.COMMAND, CommandManager.getCommandManager().getCommandNames(CommandType.TYPE_GLOBAL)); updateIcon(); new Timer("Server Who Timer").schedule(new TimerTask() { @Override public void run() { for (Channel channel : channels.values()) { channel.checkWho(); } } }, 0, getConfigManager().getOptionInt(DOMAIN_GENERAL, "whotime")); if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "showrawwindow")) { addRaw(); } getConfigManager().addChangeListener("formatter", "serverName", this); getConfigManager().addChangeListener("formatter", "serverTitle", this); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Connection, disconnection & reconnection"> /** * Updates the connection details for this server. If the specified URI * does not define a port, the default port from the protocol description * will be used. * * @param uri The new URI that this server should connect to * @param profile The profile that this server should use */ private void setConnectionDetails(final URI uri, final Identity profile) { this.address = uri; this.protocolDescription = new ParserFactory().getDescription(uri); this.profile = profile; if (uri.getPort() == -1 && protocolDescription != null) { try { this.address = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), protocolDescription.getDefaultPort(), uri.getPath(), uri.getQuery(), uri.getFragment()); } catch (URISyntaxException ex) { Logger.appError(ErrorLevel.MEDIUM, "Unable to construct URI", ex); } } } /** {@inheritDoc} */ @Override public void connect() { connect(address, profile); } /** {@inheritDoc} */ @Override @Precondition({ "The current parser is null or not connected", "The specified profile is not null" }) @SuppressWarnings("fallthrough") public void connect(final URI address, final Identity profile) { assert profile != null; synchronized (myStateLock) { switch (myState.getState()) { case RECONNECT_WAIT: reconnectTimer.cancel(); break; case CLOSING: // Ignore the connection attempt return; case CONNECTED: case CONNECTING: disconnect(getConfigManager().getOption(DOMAIN_GENERAL, "quitmessage")); case DISCONNECTING: while (!myState.getState().isDisconnected()) { try { myStateLock.wait(); } catch (InterruptedException ex) { return; } } break; default: // Do nothing break; } final URI connectAddress; try { parserLock.writeLock().lock(); if (parser != null) { throw new IllegalArgumentException("Connection attempt while parser " + "is still connected.\n\nMy state:" + getState()); } getConfigManager().migrate(address.getScheme(), "", "", address.getHost()); setConnectionDetails(address, profile); updateTitle(); updateIcon(); parser = buildParser(); if (parser == null) { addLine("serverUnknownProtocol", address.getScheme()); return; } connectAddress = parser.getURI(); } finally { parserLock.writeLock().unlock(); } addLine("serverConnecting", connectAddress.getHost(), connectAddress.getPort()); myState.transition(ServerState.CONNECTING); doCallbacks(); updateAwayState(null); removeInvites(); parser.connect(); if (parser instanceof ThreadedParser) { - ((ThreadedParser)parser).getControlThread().setName("Parser - " + connectAddress.toString()); + ((ThreadedParser)parser).getControlThread().setName("Parser - " + connectAddress.getHost()); } } ActionManager.getActionManager().triggerEvent( CoreActionType.SERVER_CONNECTING, null, this); } /** {@inheritDoc} */ @Override public void reconnect(final String reason) { synchronized (myStateLock) { if (myState.getState() == ServerState.CLOSING) { return; } disconnect(reason); connect(address, profile); } } /** {@inheritDoc} */ @Override public void reconnect() { reconnect(getConfigManager().getOption(DOMAIN_GENERAL, "reconnectmessage")); } /** {@inheritDoc} */ @Override public void disconnect() { disconnect(getConfigManager().getOption(DOMAIN_GENERAL, "quitmessage")); } /** {@inheritDoc} */ @Override public void disconnect(final String reason) { synchronized (myStateLock) { switch (myState.getState()) { case CLOSING: case DISCONNECTING: case DISCONNECTED: case TRANSIENTLY_DISCONNECTED: return; case RECONNECT_WAIT: reconnectTimer.cancel(); break; default: break; } clearChannels(); backgroundChannels.clear(); try { parserLock.readLock().lock(); if (parser == null) { myState.transition(ServerState.DISCONNECTED); } else { myState.transition(ServerState.DISCONNECTING); removeInvites(); updateIcon(); parser.disconnect(reason); } } finally { parserLock.readLock().unlock(); } if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "closechannelsonquit")) { closeChannels(); } if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "closequeriesonquit")) { closeQueries(); } } } /** * Schedules a reconnect attempt to be performed after a user-defiend delay. */ @Precondition("The server state is transiently disconnected") private void doDelayedReconnect() { synchronized (myStateLock) { if (myState.getState() != ServerState.TRANSIENTLY_DISCONNECTED) { throw new IllegalStateException("doDelayedReconnect when not " + "transiently disconnected\n\nState: " + myState); } final int delay = Math.max(1000, getConfigManager().getOptionInt(DOMAIN_GENERAL, "reconnectdelay")); handleNotification("connectRetry", getAddress(), delay / 1000); reconnectTimer = new Timer("Server Reconnect Timer"); reconnectTimer.schedule(new TimerTask() { @Override public void run() { synchronized (myStateLock) { if (myState.getState() == ServerState.RECONNECT_WAIT) { myState.transition(ServerState.TRANSIENTLY_DISCONNECTED); reconnect(); } } } }, delay); myState.transition(ServerState.RECONNECT_WAIT); updateIcon(); } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Child windows"> /** {@inheritDoc} */ @Override public boolean hasChannel(final String channel) { return channels.containsKey(converter.toLowerCase(channel)); } /** {@inheritDoc} */ @Override public Channel getChannel(final String channel) { return channels.get(converter.toLowerCase(channel)); } /** {@inheritDoc} */ @Override public List<String> getChannels() { return new ArrayList<String>(channels.keySet()); } /** {@inheritDoc} */ @Override public boolean hasQuery(final String host) { return queries.containsKey(converter.toLowerCase(parseHostmask(host)[0])); } /** {@inheritDoc} */ @Override public Query getQuery(final String host) { return getQuery(host, false); } /** {@inheritDoc} */ @Override public Query getQuery(final String host, final boolean focus) { synchronized (myStateLock) { if (myState.getState() == ServerState.CLOSING) { // Can't open queries while the server is closing return null; } } final String nick = parseHostmask(host)[0]; final String lnick = converter.toLowerCase(nick); if (!queries.containsKey(lnick)) { final Query newQuery = new Query(this, host, focus); tabCompleter.addEntry(TabCompletionType.QUERY_NICK, nick); queries.put(lnick, newQuery); } return queries.get(lnick); } /** {@inheritDoc} */ @Override public void updateQuery(final Query query, final String oldNick, final String newNick) { tabCompleter.removeEntry(TabCompletionType.QUERY_NICK, oldNick); tabCompleter.addEntry(TabCompletionType.QUERY_NICK, newNick); queries.put(converter.toLowerCase(newNick), query); queries.remove(converter.toLowerCase(oldNick)); } /** {@inheritDoc} */ @Override public Collection<Query> getQueries() { return Collections.unmodifiableCollection(queries.values()); } /** {@inheritDoc} */ @Override public void delQuery(final Query query) { tabCompleter.removeEntry(TabCompletionType.QUERY_NICK, query.getNickname()); queries.remove(converter.toLowerCase(query.getNickname())); } /** {@inheritDoc} */ @Override public void addRaw() { if (raw == null) { raw = new Raw(this); try { parserLock.readLock().lock(); if (parser != null) { raw.registerCallbacks(); } } finally { parserLock.readLock().unlock(); } } } /** {@inheritDoc} */ @Override public Raw getRaw() { return raw; } /** {@inheritDoc} */ @Override public void delRaw() { raw = null; //NOPMD } /** {@inheritDoc} */ @Override public void delChannel(final String chan) { tabCompleter.removeEntry(TabCompletionType.CHANNEL, chan); channels.remove(converter.toLowerCase(chan)); } /** {@inheritDoc} */ @Override public Channel addChannel(final ChannelInfo chan) { return addChannel(chan, !backgroundChannels.contains(chan.getName()) || getConfigManager().getOptionBool(DOMAIN_GENERAL, "hidechannels")); } /** {@inheritDoc} */ @Override public Channel addChannel(final ChannelInfo chan, final boolean focus) { synchronized (myStateLock) { if (myState.getState() == ServerState.CLOSING) { // Can't join channels while the server is closing return null; } } backgroundChannels.remove(chan.getName()); if (hasChannel(chan.getName())) { getChannel(chan.getName()).setChannelInfo(chan); getChannel(chan.getName()).selfJoin(); } else { final Channel newChan = new Channel(this, chan, focus); tabCompleter.addEntry(TabCompletionType.CHANNEL, chan.getName()); channels.put(converter.toLowerCase(chan.getName()), newChan); } return getChannel(chan.getName()); } /** * Closes all open channel windows associated with this server. */ private void closeChannels() { for (Channel channel : new ArrayList<Channel>(channels.values())) { channel.close(); } } /** * Clears the nicklist of all open channels. */ private void clearChannels() { for (Channel channel : channels.values()) { channel.resetWindow(); } } /** * Closes all open query windows associated with this server. */ private void closeQueries() { for (Query query : new ArrayList<Query>(queries.values())) { query.close(); } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Miscellaneous methods"> /** * Retrieves the host component of the specified URI, or throws a relevant * exception if this is not possible. * * @param uri The URI to be processed * @return The URI's host component, as returned by {@link URI#getHost()}. * @throws NullPointerException If <code>uri</code> is null * @throws IllegalArgumentException If the specified URI has no host * @since 0.6.4 */ private static String getHost(final URI uri) { if (uri.getHost() == null) { throw new IllegalArgumentException("URIs must have hosts"); } return uri.getHost(); } /** * Builds an appropriately configured {@link Parser} for this server. * * @return A configured parser. */ private Parser buildParser() { final MyInfo myInfo = buildMyInfo(); final Parser myParser = new ParserFactory().getParser(myInfo, address); if (myParser instanceof SecureParser) { certificateManager = new CertificateManager(address.getHost(), getConfigManager()); final SecureParser secureParser = (SecureParser) myParser; secureParser.setTrustManagers(new TrustManager[]{certificateManager}); secureParser.setKeyManagers(certificateManager.getKeyManager()); certificateManager.addCertificateProblemListener(this); } if (myParser instanceof EncodingParser) { final EncodingParser encodingParser = (EncodingParser) myParser; encodingParser.setEncoder(new MessageEncoder(this, myParser)); } if (myParser != null) { myParser.setIgnoreList(ignoreList); myParser.setPingTimerInterval(getConfigManager().getOptionInt(DOMAIN_SERVER, "pingtimer")); myParser.setPingTimerFraction((int) (getConfigManager().getOptionInt(DOMAIN_SERVER, "pingfrequency") / myParser.getPingTimerInterval())); if (getConfigManager().hasOptionString(DOMAIN_GENERAL, "bindip")) { myParser.setBindIP(getConfigManager().getOption(DOMAIN_GENERAL, "bindip")); } myParser.setProxy(buildProxyURI()); } return myParser; } /** * Constructs a URI for the configured proxy for this server, if any. * * @return An appropriate URI or null if no proxy is configured */ private URI buildProxyURI() { if (getConfigManager().hasOptionString(DOMAIN_SERVER, "proxy.address")) { final String type; if (getConfigManager().hasOptionString(DOMAIN_SERVER, "proxy.type")) { type = getConfigManager().getOption(DOMAIN_SERVER, "proxy.type"); } else { type = "socks"; } final int port; if (getConfigManager().hasOptionInt(DOMAIN_SERVER, "proxy.port")) { port = getConfigManager().getOptionInt(DOMAIN_SERVER, "proxy.port"); } else { port = 8080; } final String host = getConfigManager().getOptionString(DOMAIN_SERVER, "proxy.address"); final String userInfo; if (getConfigManager().hasOptionString(DOMAIN_SERVER, "proxy.username") && getConfigManager().hasOptionString(DOMAIN_SERVER, "proxy.password")) { userInfo = getConfigManager().getOption(DOMAIN_SERVER, "proxy.username") + getConfigManager().getOption(DOMAIN_SERVER, "proxy.password"); } else { userInfo = ""; } try { return new URI(type, userInfo, host, port, "", "", ""); } catch (URISyntaxException ex) { Logger.appError(ErrorLevel.MEDIUM, "Unable to create proxy URI", ex); } } return null; } /** {@inheritDoc} */ @Override public boolean compareURI(final URI uri) { if (parser != null) { return parser.compareURI(uri); } if (oldParser != null) { return oldParser.compareURI(uri); } return false; } /** {@inheritDoc} */ @Override public String[] parseHostmask(final String hostmask) { return protocolDescription.parseHostmask(hostmask); } /** * Retrieves the MyInfo object used for the Parser. * * @return The MyInfo object for our profile */ @Precondition({ "The current profile is not null", "The current profile specifies at least one nickname" }) private MyInfo buildMyInfo() { Logger.assertTrue(profile != null); Logger.assertTrue(!profile.getOptionList(DOMAIN_PROFILE, "nicknames").isEmpty()); final MyInfo myInfo = new MyInfo(); myInfo.setNickname(profile.getOptionList(DOMAIN_PROFILE, "nicknames").get(0)); myInfo.setRealname(profile.getOption(DOMAIN_PROFILE, "realname")); if (profile.hasOptionString(DOMAIN_PROFILE, "ident")) { myInfo.setUsername(profile.getOption(DOMAIN_PROFILE, "ident")); } return myInfo; } /** * Updates this server's icon. */ private void updateIcon() { final String icon = myState.getState() == ServerState.CONNECTED ? protocolDescription.isSecure(address) ? "secure-server" : "server" : "server-disconnected"; setIcon(icon); } /** * Registers callbacks. */ private void doCallbacks() { if (raw != null) { raw.registerCallbacks(); } eventHandler.registerCallbacks(); for (Query query : queries.values()) { query.reregister(); } } /** {@inheritDoc} */ @Override public void join(final ChannelJoinRequest ... requests) { join(true, requests); } /** {@inheritDoc} */ @Override public void join(final boolean focus, final ChannelJoinRequest ... requests) { synchronized (myStateLock) { if (myState.getState() == ServerState.CONNECTED) { final List<ChannelJoinRequest> pending = new ArrayList<ChannelJoinRequest>(); for (ChannelJoinRequest request : requests) { removeInvites(request.getName()); final String name; if (parser.isValidChannelName(request.getName())) { name = request.getName(); } else { name = parser.getChannelPrefixes().substring(0, 1) + request.getName(); } if (!hasChannel(name) || !getChannel(name).isOnChannel()) { if (!focus) { backgroundChannels.add(name); } pending.add(request); } } parser.joinChannels(pending.toArray(new ChannelJoinRequest[pending.size()])); } // TODO: otherwise: address.getChannels().add(channel); } } /** {@inheritDoc} */ @Override public void sendLine(final String line) { synchronized (myStateLock) { try { parserLock.readLock().lock(); if (parser != null && !line.isEmpty() && myState.getState() == ServerState.CONNECTED) { parser.sendRawMessage(line); } } finally { parserLock.readLock().unlock(); } } } /** {@inheritDoc} */ @Override public int getMaxLineLength() { try { parserLock.readLock().lock(); return parser == null ? -1 : parser.getMaxLength(); } finally { parserLock.readLock().unlock(); } } /** {@inheritDoc} */ @Override public Parser getParser() { return parser; } /** {@inheritDoc} */ @Override public Identity getProfile() { return profile; } /** {@inheritDoc} */ @Override public String getChannelPrefixes() { try { parserLock.readLock().lock(); return parser == null ? "#&" : parser.getChannelPrefixes(); } finally { parserLock.readLock().unlock(); } } /** {@inheritDoc} */ @Override public String getAddress() { try { parserLock.readLock().lock(); return parser == null ? address.getHost() : parser.getServerName(); } finally { parserLock.readLock().unlock(); } } /** {@inheritDoc} */ @Override public String getNetwork() { try { parserLock.readLock().lock(); if (parser == null) { throw new IllegalStateException("getNetwork called when " + "parser is null (state: " + getState() + ")"); } else if (parser.getNetworkName().isEmpty()) { return getNetworkFromServerName(parser.getServerName()); } else { return parser.getNetworkName(); } } finally { parserLock.readLock().unlock(); } } /** {@inheritDoc} */ @Override public boolean isNetwork(final String target) { synchronized (myStateLock) { try { parserLock.readLock().lock(); if (parser == null) { return false; } else { return getNetwork().equalsIgnoreCase(target); } } finally { parserLock.readLock().unlock(); } } } /** * Calculates a network name from the specified server name. This method * implements parts 2-4 of the procedure documented at getNetwork(). * * @param serverName The server name to parse * @return A network name for the specified server */ protected static String getNetworkFromServerName(final String serverName) { final String[] parts = serverName.split("\\."); final String[] tlds = {"biz", "com", "info", "net", "org"}; boolean isTLD = false; for (String tld : tlds) { if (serverName.endsWith("." + tld)) { isTLD = true; break; } } if (isTLD && parts.length > 2) { return parts[parts.length - 2] + "." + parts[parts.length - 1]; } else if (parts.length > 2) { final StringBuilder network = new StringBuilder(); for (int i = 1; i < parts.length; i++) { if (network.length() > 0) { network.append('.'); } network.append(parts[i]); } return network.toString(); } else { return serverName; } } /** {@inheritDoc} */ @Override public String getIrcd() { return parser.getServerSoftwareType(); } /** {@inheritDoc} */ @Override public String getProtocol() { return address.getScheme(); } /** {@inheritDoc} */ @Override public boolean isAway() { return awayMessage != null; } /** {@inheritDoc} */ @Override public String getAwayMessage() { return awayMessage; } /** {@inheritDoc} */ @Override public TabCompleter getTabCompleter() { return tabCompleter; } /** {@inheritDoc} */ @Override public ServerState getState() { return myState.getState(); } /** {@inheritDoc} */ @Override public ServerStatus getStatus() { return myState; } /** {@inheritDoc} */ @Override public void windowClosing() { synchronized (myStateLock) { // 2: Remove any callbacks or listeners eventHandler.unregisterCallbacks(); // 3: Trigger any actions neccessary disconnect(); myState.transition(ServerState.CLOSING); } closeChannels(); closeQueries(); removeInvites(); if (raw != null) { raw.close(); } // 4: Trigger action for the window closing // 5: Inform any parents that the window is closing ServerManager.getServerManager().unregisterServer(this); } /** {@inheritDoc} */ @Override public void windowClosed() { // 7: Remove any references to the window and parents oldParser = null; //NOPMD parser = null; //NOPMD } /** {@inheritDoc} */ @Override public void addLineToAll(final String messageType, final Date date, final Object... args) { for (Channel channel : channels.values()) { channel.addLine(messageType, date, args); } for (Query query : queries.values()) { query.addLine(messageType, date, args); } addLine(messageType, date, args); } /** {@inheritDoc} */ @Override public void sendCTCPReply(final String source, final String type, final String args) { if (type.equalsIgnoreCase("VERSION")) { parser.sendCTCPReply(source, "VERSION", "DMDirc " + getConfigManager().getOption("version", "version") + " - http://www.dmdirc.com/"); } else if (type.equalsIgnoreCase("PING")) { parser.sendCTCPReply(source, "PING", args); } else if (type.equalsIgnoreCase("CLIENTINFO")) { parser.sendCTCPReply(source, "CLIENTINFO", "VERSION PING CLIENTINFO"); } } /** {@inheritDoc} */ @Override public boolean isValidChannelName(final String channelName) { try { parserLock.readLock().lock(); return hasChannel(channelName) || (parser != null && parser.isValidChannelName(channelName)); } finally { parserLock.readLock().unlock(); } } /** {@inheritDoc} */ @Override public Server getServer() { return this; } /** {@inheritDoc} */ @Override protected boolean processNotificationArg(final Object arg, final List<Object> args) { if (arg instanceof ClientInfo) { final ClientInfo clientInfo = (ClientInfo) arg; args.add(clientInfo.getNickname()); args.add(clientInfo.getUsername()); args.add(clientInfo.getHostname()); return true; } else { return super.processNotificationArg(arg, args); } } /** {@inheritDoc} */ @Override public void updateTitle() { synchronized (myStateLock) { if (myState.getState() == ServerState.CLOSING) { return; } try { parserLock.readLock().lock(); final Object[] arguments = new Object[]{ address.getHost(), parser == null ? "Unknown" : parser.getServerName(), address.getPort(), parser == null ? "Unknown" : getNetwork(), parser == null ? "Unknown" : parser.getLocalClient().getNickname(), }; setName(Formatter.formatMessage(getConfigManager(), "serverName", arguments)); setTitle(Formatter.formatMessage(getConfigManager(), "serverTitle", arguments)); } finally { parserLock.readLock().unlock(); } } } /** {@inheritDoc} */ @Override public void configChanged(final String domain, final String key) { if ("formatter".equals(domain)) { updateTitle(); } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Parser callbacks"> /** * Called when the server says that the nickname we're trying to use is * already in use. * * @param nickname The nickname that we were trying to use */ public void onNickInUse(final String nickname) { final String lastNick = parser.getLocalClient().getNickname(); // If our last nick is still valid, ignore the in use message if (!converter.equalsIgnoreCase(lastNick, nickname)) { return; } String newNick = lastNick + new Random().nextInt(10); final List<String> alts = profile.getOptionList(DOMAIN_PROFILE, "nicknames"); int offset = 0; // Loop so we can check case sensitivity for (String alt : alts) { offset++; if (converter.equalsIgnoreCase(alt, lastNick)) { break; } } if (offset < alts.size() && !alts.get(offset).isEmpty()) { newNick = alts.get(offset); } parser.getLocalClient().setNickname(newNick); } /** * Called when the server sends a numeric event. * * @param numeric The numeric code for the event * @param tokens The (tokenised) arguments of the event */ public void onNumeric(final int numeric, final String[] tokens) { String snumeric = String.valueOf(numeric); if (numeric < 10) { snumeric = "00" + snumeric; } else if (numeric < 100) { snumeric = "0" + snumeric; } final String sansIrcd = "numeric_" + snumeric; StringBuffer target = new StringBuffer(""); if (getConfigManager().hasOptionString("formatter", sansIrcd)) { target = new StringBuffer(sansIrcd); } else if (getConfigManager().hasOptionString("formatter", "numeric_unknown")) { target = new StringBuffer("numeric_unknown"); } ActionManager.getActionManager().triggerEvent( CoreActionType.SERVER_NUMERIC, target, this, Integer.valueOf(numeric), tokens); handleNotification(target.toString(), (Object[]) tokens); } /** * Called when the socket has been closed. */ public void onSocketClosed() { if (Thread.holdsLock(myStateLock)) { new Thread(new Runnable() { /** {@inheritDoc} */ @Override public void run() { onSocketClosed(); } }, "Socket closed deferred thread").start(); return; } handleNotification("socketClosed", getAddress()); ActionManager.getActionManager().triggerEvent( CoreActionType.SERVER_DISCONNECTED, null, this); eventHandler.unregisterCallbacks(); synchronized (myStateLock) { if (myState.getState() == ServerState.CLOSING || myState.getState() == ServerState.DISCONNECTED) { // This has been triggered via .disconnect() return; } if (myState.getState() == ServerState.DISCONNECTING) { myState.transition(ServerState.DISCONNECTED); } else { myState.transition(ServerState.TRANSIENTLY_DISCONNECTED); } clearChannels(); try { parserLock.writeLock().lock(); oldParser = parser; parser = null; } finally { parserLock.writeLock().unlock(); } updateIcon(); if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "closechannelsondisconnect")) { closeChannels(); } if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "closequeriesondisconnect")) { closeQueries(); } removeInvites(); updateAwayState(null); if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "reconnectondisconnect") && myState.getState() == ServerState.TRANSIENTLY_DISCONNECTED) { doDelayedReconnect(); } } } /** * Called when an error was encountered while connecting. * * @param errorInfo The parser's error information */ @Precondition("The current server state is CONNECTING") public void onConnectError(final ParserError errorInfo) { synchronized (myStateLock) { if (myState.getState() == ServerState.CLOSING || myState.getState() == ServerState.DISCONNECTING) { // Do nothing return; } else if (myState.getState() != ServerState.CONNECTING) { // Shouldn't happen throw new IllegalStateException("Connect error when not " + "connecting\n\n" + getStatus().getTransitionHistory()); } myState.transition(ServerState.TRANSIENTLY_DISCONNECTED); try { parserLock.writeLock().lock(); oldParser = parser; parser = null; } finally { parserLock.writeLock().unlock(); } updateIcon(); String description; if (errorInfo.getException() == null) { description = errorInfo.getData(); } else { final Exception exception = errorInfo.getException(); if (exception instanceof java.net.UnknownHostException) { description = "Unknown host (unable to resolve)"; } else if (exception instanceof java.net.NoRouteToHostException) { description = "No route to host"; } else if (exception instanceof java.net.SocketTimeoutException) { description = "Connection attempt timed out"; } else if (exception instanceof java.net.SocketException || exception instanceof javax.net.ssl.SSLException) { description = exception.getMessage(); } else { Logger.appError(ErrorLevel.LOW, "Unknown socket error: " + exception.getClass().getCanonicalName(), new IllegalArgumentException(exception)); description = "Unknown error: " + exception.getMessage(); } } ActionManager.getActionManager().triggerEvent( CoreActionType.SERVER_CONNECTERROR, null, this, description); handleNotification("connectError", getAddress(), description); if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "reconnectonconnectfailure")) { doDelayedReconnect(); } } } /** * Called when we fail to receive a ping reply within a set period of time. */ public void onPingFailed() { StatusBarManager.getStatusBarManager().setMessage(new StatusMessage( "No ping reply from " + getName() + " for over " + ((int) (Math.floor(parser.getPingTime() / 1000.0))) + " seconds.", getConfigManager())); ActionManager.getActionManager().triggerEvent( CoreActionType.SERVER_NOPING, null, this, Long.valueOf(parser.getPingTime())); if (parser.getPingTime() >= getConfigManager().getOptionInt(DOMAIN_SERVER, "pingtimeout")) { handleNotification("stonedServer", getAddress()); reconnect(); } } /** * Called after the parser receives the 005 headers from the server. */ @Precondition("State is CONNECTING") public void onPost005() { synchronized (myStateLock) { if (myState.getState() != ServerState.CONNECTING) { // Shouldn't happen throw new IllegalStateException("Received onPost005 while not " + "connecting\n\n" + myState.getTransitionHistory()); } if (myState.getState() != ServerState.CONNECTING) { // We've transitioned while waiting for the lock. Just abort. return; } myState.transition(ServerState.CONNECTED); getConfigManager().migrate(address.getScheme(), parser.getServerSoftwareType(), getNetwork(), parser.getServerName()); updateIcon(); updateTitle(); updateIgnoreList(); converter = parser.getStringConverter(); final List<ChannelJoinRequest> requests = new ArrayList<ChannelJoinRequest>(); if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "rejoinchannels")) { for (Channel chan : channels.values()) { requests.add(new ChannelJoinRequest(chan.getName())); } } join(requests.toArray(new ChannelJoinRequest[requests.size()])); checkModeAliases(); } ActionManager.getActionManager().triggerEvent( CoreActionType.SERVER_CONNECTED, null, this); } /** * Checks that we have the necessary mode aliases for this server. */ private void checkModeAliases() { // Check we have mode aliases final String modes = parser.getBooleanChannelModes() + parser.getListChannelModes() + parser.getParameterChannelModes() + parser.getDoubleParameterChannelModes(); final String umodes = parser.getUserModes(); final StringBuffer missingModes = new StringBuffer(); final StringBuffer missingUmodes = new StringBuffer(); for (char mode : modes.toCharArray()) { if (!getConfigManager().hasOptionString(DOMAIN_SERVER, "mode" + mode)) { missingModes.append(mode); } } for (char mode : umodes.toCharArray()) { if (!getConfigManager().hasOptionString(DOMAIN_SERVER, "umode" + mode)) { missingUmodes.append(mode); } } if (missingModes.length() + missingUmodes.length() > 0) { final StringBuffer missing = new StringBuffer("Missing mode aliases: "); if (missingModes.length() > 0) { missing.append("channel: +"); missing.append(missingModes); } if (missingUmodes.length() > 0) { if (missingModes.length() > 0) { missing.append(' '); } missing.append("user: +"); missing.append(missingUmodes); } Logger.appError(ErrorLevel.LOW, missing.toString() + " [" + parser.getServerSoftwareType() + "]", new MissingModeAliasException(getNetwork(), parser, getConfigManager().getOption("identity", "modealiasversion"), missing.toString())); } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Ignore lists"> /** {@inheritDoc} */ @Override public IgnoreList getIgnoreList() { return ignoreList; } /** {@inheritDoc} */ @Override public void updateIgnoreList() { ignoreList.clear(); ignoreList.addAll(getConfigManager().getOptionList("network", "ignorelist")); } /** {@inheritDoc} */ @Override public void saveIgnoreList() { getNetworkIdentity().setOption("network", "ignorelist", ignoreList.getRegexList()); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Identity handling"> /** {@inheritDoc} */ @Override public Identity getServerIdentity() { return IdentityManager.getIdentityManager().createServerConfig(parser.getServerName()); } /** {@inheritDoc} */ @Override public Identity getNetworkIdentity() { return IdentityManager.getIdentityManager().createNetworkConfig(getNetwork()); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Invite handling"> /** {@inheritDoc} */ @Override public void addInviteListener(final InviteListener listener) { synchronized (listeners) { listeners.add(InviteListener.class, listener); } } /** {@inheritDoc} */ @Override public void removeInviteListener(final InviteListener listener) { synchronized (listeners) { listeners.remove(InviteListener.class, listener); } } /** {@inheritDoc} */ @Override public void addInvite(final Invite invite) { synchronized (invites) { for (Invite oldInvite : new ArrayList<Invite>(invites)) { if (oldInvite.getChannel().equals(invite.getChannel())) { removeInvite(oldInvite); } } invites.add(invite); synchronized (listeners) { for (InviteListener listener : listeners.get(InviteListener.class)) { listener.inviteReceived(this, invite); } } } } /** {@inheritDoc} */ @Override public void acceptInvites(final Invite ... invites) { final ChannelJoinRequest[] requests = new ChannelJoinRequest[invites.length]; for (int i = 0; i < invites.length; i++) { requests[i] = new ChannelJoinRequest(invites[i].getChannel()); } join(requests); } /** {@inheritDoc} */ @Override public void acceptInvites() { synchronized (invites) { acceptInvites(invites.toArray(new Invite[invites.size()])); } } /** {@inheritDoc} */ @Override public void removeInvites(final String channel) { for (Invite invite : new ArrayList<Invite>(invites)) { if (invite.getChannel().equals(channel)) { removeInvite(invite); } } } /** {@inheritDoc} */ @Override public void removeInvites() { for (Invite invite : new ArrayList<Invite>(invites)) { removeInvite(invite); } } /** {@inheritDoc} */ @Override public void removeInvite(final Invite invite) { synchronized (invites) { invites.remove(invite); synchronized (listeners) { for (InviteListener listener : listeners.get(InviteListener.class)) { listener.inviteExpired(this, invite); } } } } /** {@inheritDoc} */ @Override public List<Invite> getInvites() { return invites; } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Away state handling"> /** {@inheritDoc} */ @Override public void addAwayStateListener(final AwayStateListener listener) { synchronized (listeners) { listeners.add(AwayStateListener.class, listener); } } /** {@inheritDoc} */ @Override public void removeAwayStateListener(final AwayStateListener listener) { synchronized (listeners) { listeners.remove(AwayStateListener.class, listener); } } /** {@inheritDoc} */ @Override public void updateAwayState(final String message) { if ((awayMessage != null && awayMessage.equals(message)) || (awayMessage == null && message == null)) { return; } awayMessage = message; new Thread(new Runnable() { /** {@inheritDoc} */ @Override public void run() { synchronized (listeners) { if (message == null) { for (AwayStateListener listener : listeners.get(AwayStateListener.class)) { listener.onBack(); } } else { for (AwayStateListener listener : listeners.get(AwayStateListener.class)) { listener.onAway(message); } } } } }, "Away state listener runner").start(); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="TLS listener handling"> /** {@inheritDoc} */ @Override public void addCertificateProblemListener(final CertificateProblemListener listener) { listeners.add(CertificateProblemListener.class, listener); if (certificateManager != null && !certificateManager.getProblems().isEmpty()) { listener.certificateProblemEncountered(certificateManager.getChain(), certificateManager.getProblems(), certificateManager); } } /** {@inheritDoc} */ @Override public void removeCertificateProblemListener(final CertificateProblemListener listener) { listeners.remove(CertificateProblemListener.class, listener); } /** {@inheritDoc} */ @Override public void certificateProblemEncountered(final X509Certificate[] chain, final Collection<CertificateException> problems, final CertificateManager certificateManager) { for (CertificateProblemListener listener : listeners.get(CertificateProblemListener.class)) { listener.certificateProblemEncountered(chain, problems, certificateManager); } } /** {@inheritDoc} */ @Override public void certificateProblemResolved(final CertificateManager manager) { for (CertificateProblemListener listener : listeners.get(CertificateProblemListener.class)) { listener.certificateProblemResolved(manager); } } // </editor-fold> }
true
true
public void connect(final URI address, final Identity profile) { assert profile != null; synchronized (myStateLock) { switch (myState.getState()) { case RECONNECT_WAIT: reconnectTimer.cancel(); break; case CLOSING: // Ignore the connection attempt return; case CONNECTED: case CONNECTING: disconnect(getConfigManager().getOption(DOMAIN_GENERAL, "quitmessage")); case DISCONNECTING: while (!myState.getState().isDisconnected()) { try { myStateLock.wait(); } catch (InterruptedException ex) { return; } } break; default: // Do nothing break; } final URI connectAddress; try { parserLock.writeLock().lock(); if (parser != null) { throw new IllegalArgumentException("Connection attempt while parser " + "is still connected.\n\nMy state:" + getState()); } getConfigManager().migrate(address.getScheme(), "", "", address.getHost()); setConnectionDetails(address, profile); updateTitle(); updateIcon(); parser = buildParser(); if (parser == null) { addLine("serverUnknownProtocol", address.getScheme()); return; } connectAddress = parser.getURI(); } finally { parserLock.writeLock().unlock(); } addLine("serverConnecting", connectAddress.getHost(), connectAddress.getPort()); myState.transition(ServerState.CONNECTING); doCallbacks(); updateAwayState(null); removeInvites(); parser.connect(); if (parser instanceof ThreadedParser) { ((ThreadedParser)parser).getControlThread().setName("Parser - " + connectAddress.toString()); } } ActionManager.getActionManager().triggerEvent( CoreActionType.SERVER_CONNECTING, null, this); }
public void connect(final URI address, final Identity profile) { assert profile != null; synchronized (myStateLock) { switch (myState.getState()) { case RECONNECT_WAIT: reconnectTimer.cancel(); break; case CLOSING: // Ignore the connection attempt return; case CONNECTED: case CONNECTING: disconnect(getConfigManager().getOption(DOMAIN_GENERAL, "quitmessage")); case DISCONNECTING: while (!myState.getState().isDisconnected()) { try { myStateLock.wait(); } catch (InterruptedException ex) { return; } } break; default: // Do nothing break; } final URI connectAddress; try { parserLock.writeLock().lock(); if (parser != null) { throw new IllegalArgumentException("Connection attempt while parser " + "is still connected.\n\nMy state:" + getState()); } getConfigManager().migrate(address.getScheme(), "", "", address.getHost()); setConnectionDetails(address, profile); updateTitle(); updateIcon(); parser = buildParser(); if (parser == null) { addLine("serverUnknownProtocol", address.getScheme()); return; } connectAddress = parser.getURI(); } finally { parserLock.writeLock().unlock(); } addLine("serverConnecting", connectAddress.getHost(), connectAddress.getPort()); myState.transition(ServerState.CONNECTING); doCallbacks(); updateAwayState(null); removeInvites(); parser.connect(); if (parser instanceof ThreadedParser) { ((ThreadedParser)parser).getControlThread().setName("Parser - " + connectAddress.getHost()); } } ActionManager.getActionManager().triggerEvent( CoreActionType.SERVER_CONNECTING, null, this); }
diff --git a/src/main/java/hudson/plugins/dry/util/HealthAwareMavenReporter.java b/src/main/java/hudson/plugins/dry/util/HealthAwareMavenReporter.java index bf23233..44f1918 100644 --- a/src/main/java/hudson/plugins/dry/util/HealthAwareMavenReporter.java +++ b/src/main/java/hudson/plugins/dry/util/HealthAwareMavenReporter.java @@ -1,450 +1,450 @@ package hudson.plugins.dry.util; import hudson.FilePath; import hudson.maven.MavenBuild; import hudson.maven.MavenBuildProxy; import hudson.maven.MavenReporter; import hudson.maven.MojoInfo; import hudson.maven.MavenBuildProxy.BuildCallable; import hudson.model.Action; import hudson.model.BuildListener; import hudson.model.Result; import hudson.plugins.dry.util.model.AbstractAnnotation; import hudson.plugins.dry.util.model.AnnotationContainer; import hudson.plugins.dry.util.model.DefaultAnnotationContainer; import hudson.plugins.dry.util.model.FileAnnotation; import hudson.plugins.dry.util.model.Priority; import hudson.plugins.dry.util.model.WorkspaceFile; import hudson.remoting.Channel; import hudson.tasks.BuildStep; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.charset.Charset; import java.util.Collection; import org.apache.commons.lang.StringUtils; import org.apache.maven.project.MavenProject; /** * A base class for maven reporters with the following two characteristics: * <ul> * <li>It provides a unstable threshold, that could be enabled and set in the * configuration screen. If the number of annotations in a build exceeds this * value then the build is considered as {@link Result#UNSTABLE UNSTABLE}. * </li> * <li>It provides thresholds for the build health, that could be adjusted in * the configuration screen. These values are used by the * {@link HealthReportBuilder} to compute the health and the health trend graph.</li> * </ul> * * @author Ulli Hafner */ // CHECKSTYLE:COUPLING-OFF public abstract class HealthAwareMavenReporter extends MavenReporter implements HealthDescriptor { /** Default threshold priority limit. */ private static final String DEFAULT_PRIORITY_THRESHOLD_LIMIT = "low"; /** Unique identifier of this class. */ private static final long serialVersionUID = 3003791883748835331L; /** Annotation threshold to be reached if a build should be considered as unstable. */ private final String threshold; /** Annotation threshold to be reached if a build should be considered as failure. */ private final String failureThreshold; /** Threshold for new annotations to be reached if a build should be considered as failure. */ private final String newFailureThreshold; /** Annotation threshold for new warnings to be reached if a build should be considered as unstable. */ private final String newThreshold; /** Report health as 100% when the number of warnings is less than this value. */ private final String healthy; /** Report health as 0% when the number of warnings is greater than this value. */ private final String unHealthy; /** The name of the plug-in. */ private final String pluginName; /** Determines which warning priorities should be considered when evaluating the build stability and health. */ private String thresholdLimit; /** The default encoding to be used when reading and parsing files. */ private String defaultEncoding; /** * Creates a new instance of <code>HealthReportingMavenReporter</code>. * * @param threshold * Annotations threshold to be reached if a build should be * considered as unstable. * @param newThreshold * New annotations threshold to be reached if a build should be * considered as unstable. * @param failureThreshold * Annotation threshold to be reached if a build should be considered as * failure. * @param newFailureThreshold * New annotations threshold to be reached if a build should be * considered as failure. * @param healthy * Report health as 100% when the number of warnings is less than * this value * @param unHealthy * Report health as 0% when the number of warnings is greater * than this value * @param thresholdLimit * determines which warning priorities should be considered when * evaluating the build stability and health * @param pluginName * the name of the plug-in */ // CHECKSTYLE:OFF public HealthAwareMavenReporter(final String threshold, final String newThreshold, final String failureThreshold, final String newFailureThreshold, final String healthy, final String unHealthy, final String thresholdLimit, final String pluginName) { super(); this.threshold = threshold; this.newThreshold = newThreshold; this.failureThreshold = failureThreshold; this.newFailureThreshold = newFailureThreshold; this.healthy = healthy; this.unHealthy = unHealthy; this.thresholdLimit = thresholdLimit; this.pluginName = "[" + pluginName + "] "; } // CHECKSTYLE:ON /** * Initializes new fields that are not serialized yet. * * @return the object */ @edu.umd.cs.findbugs.annotations.SuppressWarnings("Se") private Object readResolve() { if (thresholdLimit == null) { thresholdLimit = DEFAULT_PRIORITY_THRESHOLD_LIMIT; } return this; } /** {@inheritDoc} */ @SuppressWarnings({"serial", "PMD.AvoidFinalLocalVariable"}) @Override public final boolean postExecute(final MavenBuildProxy build, final MavenProject pom, final MojoInfo mojo, final BuildListener listener, final Throwable error) throws InterruptedException, IOException { if (!acceptGoal(mojo.getGoal())) { return true; } if (canContinue(getCurrentResult(build))) { PluginLogger logger = new PluginLogger(listener.getLogger(), pluginName); if (hasResultAction(build)) { - logger.log("Scipping maven reporter: there is already a result available."); + logger.log("Skipping maven reporter: there is already a result available."); return true; } try { defaultEncoding = pom.getProperties().getProperty("project.build.sourceEncoding"); final ParserResult result = perform(build, pom, mojo, logger); if (defaultEncoding == null) { logger.log(Messages.Reporter_Error_NoEncoding(Charset.defaultCharset().displayName())); result.addErrorMessage(pom.getName(), Messages.Reporter_Error_NoEncoding(Charset.defaultCharset().displayName())); } build.execute(new BuildCallable<Void, IOException>() { public Void call(final MavenBuild mavenBuild) throws IOException, InterruptedException { persistResult(result, mavenBuild); return null; } }); if (build.getRootDir().isRemote()) { copyFilesToMaster(logger, build.getProjectRootDir(), build.getRootDir(), result.getAnnotations()); } } catch (AbortException exception) { logger.log(exception); build.setResult(Result.FAILURE); return false; } } return true; } /** * Returns the current result of the build. * * @param build * the build proxy * @return the current result of the build * @throws IOException * @throws InterruptedException */ private Result getCurrentResult(final MavenBuildProxy build) throws IOException, InterruptedException { return build.execute(new BuildResultCallable()); } /** * Returns whether the reporter can continue processing. This default * implementation returns <code>true</code> if the build is not aborted or * failed. * * @param result * build result * @return <code>true</code> if the build can continue */ protected boolean canContinue(final Result result) { return result != Result.ABORTED && result != Result.FAILURE; } /** * Copies all files with annotations from the slave to the master. * * @param logger * logger to log any problems * @param slaveRoot * directory to copy the files from * @param masterRoot * directory to store the copied files in * @param annotations * annotations determining the actual files to copy * @throws IOException * if the files could not be written * @throws FileNotFoundException * if the files could not be written * @throws InterruptedException * if the user cancels the processing */ private void copyFilesToMaster(final PluginLogger logger, final FilePath slaveRoot, final FilePath masterRoot, final Collection<FileAnnotation> annotations) throws IOException, FileNotFoundException, InterruptedException { FilePath directory = new FilePath(masterRoot, AbstractAnnotation.WORKSPACE_FILES); if (!directory.exists()) { directory.mkdirs(); } AnnotationContainer container = new DefaultAnnotationContainer(annotations); for (WorkspaceFile file : container.getFiles()) { FilePath masterFile = new FilePath(directory, file.getTempName()); if (!masterFile.exists()) { try { new FilePath((Channel)null, file.getName()).copyTo(masterFile); } catch (IOException exception) { String message = "Can't copy source file: source=" + file.getName() + ", destination=" + masterFile.getName(); logger.log(message); logger.printStackTrace(exception); } } } } /** * Determines whether this plug-in will accept the specified goal. The * {@link #postExecute(MavenBuildProxy, MavenProject, MojoInfo, * BuildListener, Throwable)} will only by invoked if the plug-in returns * <code>true</code>. * * @param goal the maven goal * @return <code>true</code> if the plug-in accepts this goal */ protected abstract boolean acceptGoal(final String goal); /** * Performs the publishing of the results of this plug-in. * * @param build * the build proxy (on the slave) * @param pom * the pom of the module * @param mojo * the executed mojo * @param logger * the logger to report the progress to * @return the java project containing the found annotations * @throws InterruptedException * If the build is interrupted by the user (in an attempt to * abort the build.) Normally the {@link BuildStep} * implementations may simply forward the exception it got from * its lower-level functions. * @throws IOException * If the implementation wants to abort the processing when an * {@link IOException} happens, it can simply propagate the * exception to the caller. This will cause the build to fail, * with the default error message. Implementations are * encouraged to catch {@link IOException} on its own to provide * a better error message, if it can do so, so that users have * better understanding on why it failed. */ protected abstract ParserResult perform(MavenBuildProxy build, MavenProject pom, MojoInfo mojo, PluginLogger logger) throws InterruptedException, IOException; /** * Persists the result in the build (on the master). * * @param project * the created project * @param build * the build (on the master) * @return the created result */ protected abstract BuildResult persistResult(ParserResult project, MavenBuild build); /** * Returns the default encoding derived from the maven pom file. * * @return the default encoding */ protected String getDefaultEncoding() { return defaultEncoding; } /** * Returns whether we already have a result for this build. * * @param build * the current build. * @return <code>true</code> if we already have a task result action. * @throws IOException * in case of an IO error * @throws InterruptedException * if the call has been interrupted */ @SuppressWarnings("serial") private Boolean hasResultAction(final MavenBuildProxy build) throws IOException, InterruptedException { return build.execute(new BuildCallable<Boolean, IOException>() { public Boolean call(final MavenBuild mavenBuild) throws IOException, InterruptedException { return mavenBuild.getAction(getResultActionClass()) != null; } }); } /** * Returns the type of the result action. * * @return the type of the result action */ protected abstract Class<? extends Action> getResultActionClass(); /** * Returns the path to the target folder. * * @param pom the maven pom * @return the path to the target folder */ protected FilePath getTargetPath(final MavenProject pom) { return new FilePath(new FilePath(pom.getBasedir()), "target"); } /** * Returns the threshold of all annotations to be reached if a build should * be considered as unstable. * * @return the threshold of all annotations to be reached if a build should * be considered as unstable. */ public String getThreshold() { return threshold; } /** * Returns the threshold for new annotations to be reached if a build should * be considered as unstable. * * @return the threshold for new annotations to be reached if a build should * be considered as unstable. */ public String getNewThreshold() { return newThreshold; } /** * Returns the annotation threshold to be reached if a build should be * considered as failure. * * @return the annotation threshold to be reached if a build should be * considered as failure. */ public String getFailureThreshold() { return failureThreshold; } /** * Returns the threshold of new annotations to be reached if a build should * be considered as failure. * * @return the threshold of new annotations to be reached if a build should * be considered as failure. */ public String getNewFailureThreshold() { return newFailureThreshold; } /** * Returns the healthy threshold, i.e. when health is reported as 100%. * * @return the 100% healthiness */ public String getHealthy() { return healthy; } /** * Returns the unhealthy threshold, i.e. when health is reported as 0%. * * @return the 0% unhealthiness */ public String getUnHealthy() { return unHealthy; } /** {@inheritDoc} */ public Priority getMinimumPriority() { return Priority.valueOf(StringUtils.upperCase(getThresholdLimit())); } /** * Returns the threshold limit. * * @return the threshold limit */ public String getThresholdLimit() { return thresholdLimit; } /** * Gets the build result from the master. */ private static final class BuildResultCallable implements BuildCallable<Result, IOException> { /** Unique ID. */ private static final long serialVersionUID = -270795641776014760L; /** {@inheritDoc} */ public Result call(final MavenBuild mavenBuild) throws IOException, InterruptedException { return mavenBuild.getResult(); } } /** Backward compatibility. */ @SuppressWarnings("unused") @Deprecated private transient boolean thresholdEnabled; /** Backward compatibility. */ @SuppressWarnings("unused") @Deprecated private transient int minimumAnnotations; /** Backward compatibility. */ @SuppressWarnings("unused") @Deprecated private transient int healthyAnnotations; /** Backward compatibility. */ @SuppressWarnings("unused") @Deprecated private transient int unHealthyAnnotations; /** Backward compatibility. */ @SuppressWarnings("unused") @Deprecated private transient boolean healthyReportEnabled; /** Backward compatibility. */ @SuppressWarnings("unused") @Deprecated private transient String height; }
true
true
public final boolean postExecute(final MavenBuildProxy build, final MavenProject pom, final MojoInfo mojo, final BuildListener listener, final Throwable error) throws InterruptedException, IOException { if (!acceptGoal(mojo.getGoal())) { return true; } if (canContinue(getCurrentResult(build))) { PluginLogger logger = new PluginLogger(listener.getLogger(), pluginName); if (hasResultAction(build)) { logger.log("Scipping maven reporter: there is already a result available."); return true; } try { defaultEncoding = pom.getProperties().getProperty("project.build.sourceEncoding"); final ParserResult result = perform(build, pom, mojo, logger); if (defaultEncoding == null) { logger.log(Messages.Reporter_Error_NoEncoding(Charset.defaultCharset().displayName())); result.addErrorMessage(pom.getName(), Messages.Reporter_Error_NoEncoding(Charset.defaultCharset().displayName())); } build.execute(new BuildCallable<Void, IOException>() { public Void call(final MavenBuild mavenBuild) throws IOException, InterruptedException { persistResult(result, mavenBuild); return null; } }); if (build.getRootDir().isRemote()) { copyFilesToMaster(logger, build.getProjectRootDir(), build.getRootDir(), result.getAnnotations()); } } catch (AbortException exception) { logger.log(exception); build.setResult(Result.FAILURE); return false; } } return true; }
public final boolean postExecute(final MavenBuildProxy build, final MavenProject pom, final MojoInfo mojo, final BuildListener listener, final Throwable error) throws InterruptedException, IOException { if (!acceptGoal(mojo.getGoal())) { return true; } if (canContinue(getCurrentResult(build))) { PluginLogger logger = new PluginLogger(listener.getLogger(), pluginName); if (hasResultAction(build)) { logger.log("Skipping maven reporter: there is already a result available."); return true; } try { defaultEncoding = pom.getProperties().getProperty("project.build.sourceEncoding"); final ParserResult result = perform(build, pom, mojo, logger); if (defaultEncoding == null) { logger.log(Messages.Reporter_Error_NoEncoding(Charset.defaultCharset().displayName())); result.addErrorMessage(pom.getName(), Messages.Reporter_Error_NoEncoding(Charset.defaultCharset().displayName())); } build.execute(new BuildCallable<Void, IOException>() { public Void call(final MavenBuild mavenBuild) throws IOException, InterruptedException { persistResult(result, mavenBuild); return null; } }); if (build.getRootDir().isRemote()) { copyFilesToMaster(logger, build.getProjectRootDir(), build.getRootDir(), result.getAnnotations()); } } catch (AbortException exception) { logger.log(exception); build.setResult(Result.FAILURE); return false; } } return true; }
diff --git a/qcadoo-model/src/main/java/com/qcadoo/model/internal/DataAccessServiceImpl.java b/qcadoo-model/src/main/java/com/qcadoo/model/internal/DataAccessServiceImpl.java index ca152303b..8468c9da5 100644 --- a/qcadoo-model/src/main/java/com/qcadoo/model/internal/DataAccessServiceImpl.java +++ b/qcadoo-model/src/main/java/com/qcadoo/model/internal/DataAccessServiceImpl.java @@ -1,978 +1,979 @@ /** * *************************************************************************** * Copyright (c) 2010 Qcadoo Limited * Project: Qcadoo Framework * Version: 1.2.0 * * This file is part of Qcadoo. * * Qcadoo is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation; either version 3 of the License, * or (at your option) 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *************************************************************************** */ package com.qcadoo.model.internal; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.StringUtils; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.exception.ConstraintViolationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.NoTransactionException; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.interceptor.TransactionAspectSupport; import com.google.common.base.Predicate; import com.google.common.collect.Collections2; import com.google.common.collect.Sets; import com.qcadoo.model.api.CopyException; import com.qcadoo.model.api.DataDefinition; import com.qcadoo.model.api.DataDefinitionService; import com.qcadoo.model.api.Entity; import com.qcadoo.model.api.EntityList; import com.qcadoo.model.api.EntityMessagesHolder; import com.qcadoo.model.api.EntityOpResult; import com.qcadoo.model.api.ExpressionService; import com.qcadoo.model.api.FieldDefinition; import com.qcadoo.model.api.aop.Auditable; import com.qcadoo.model.api.aop.Monitorable; import com.qcadoo.model.api.search.SearchRestrictions; import com.qcadoo.model.api.search.SearchResult; import com.qcadoo.model.api.types.Cascadeable; import com.qcadoo.model.api.types.CollectionFieldType; import com.qcadoo.model.api.types.DataDefinitionHolder; import com.qcadoo.model.api.types.FieldType; import com.qcadoo.model.api.types.HasManyType; import com.qcadoo.model.api.types.JoinFieldHolder; import com.qcadoo.model.api.types.ManyToManyType; import com.qcadoo.model.api.types.TreeType; import com.qcadoo.model.api.utils.EntityUtils; import com.qcadoo.model.api.validators.ErrorMessage; import com.qcadoo.model.internal.api.DataAccessService; import com.qcadoo.model.internal.api.EntityService; import com.qcadoo.model.internal.api.HibernateService; import com.qcadoo.model.internal.api.InternalDataDefinition; import com.qcadoo.model.internal.api.InternalFieldDefinition; import com.qcadoo.model.internal.api.PriorityService; import com.qcadoo.model.internal.api.ValidationService; import com.qcadoo.model.internal.search.SearchCriteria; import com.qcadoo.model.internal.search.SearchQuery; import com.qcadoo.model.internal.search.SearchResultImpl; import com.qcadoo.model.internal.utils.EntitySignature; import com.qcadoo.tenant.api.Standalone; @Service @Standalone public class DataAccessServiceImpl implements DataAccessService { private static final String L_DATA_DEFINITION_BELONGS_TO_DISABLED_PLUGIN = "DataDefinition belongs to disabled plugin"; private static final String L_DATA_DEFINITION_MUST_BE_GIVEN = "DataDefinition must be given"; @Autowired private DataDefinitionService dataDefinitionService; @Autowired private EntityService entityService; @Autowired private ValidationService validationService; @Autowired private PriorityService priorityService; @Autowired private ExpressionService expressionService; @Autowired private HibernateService hibernateService; private static final Logger LOG = LoggerFactory.getLogger(DataAccessServiceImpl.class); @Auditable @Override @Transactional @Monitorable public Entity save(final InternalDataDefinition dataDefinition, final Entity genericEntity) { Set<Entity> newlySavedEntities = new HashSet<Entity>(); Entity resultEntity = performSave(dataDefinition, genericEntity, new HashSet<Entity>(), newlySavedEntities); try { if (TransactionAspectSupport.currentTransactionStatus().isRollbackOnly()) { resultEntity.setNotValid(); for (Entity e : newlySavedEntities) { e.setId(null); } } } catch (NoTransactionException e) { LOG.error(e.getMessage(), e); } return resultEntity; } @SuppressWarnings("unchecked") @Monitorable private Entity performSave(final InternalDataDefinition dataDefinition, final Entity genericEntity, final Set<Entity> alreadySavedEntities, final Set<Entity> newlySavedEntities) { checkNotNull(dataDefinition, L_DATA_DEFINITION_MUST_BE_GIVEN); checkState(dataDefinition.isEnabled(), L_DATA_DEFINITION_BELONGS_TO_DISABLED_PLUGIN); checkNotNull(genericEntity, "Entity must be given"); if (alreadySavedEntities.contains(genericEntity)) { return genericEntity; } Entity genericEntityToSave = genericEntity.copy(); Object existingDatabaseEntity = getExistingDatabaseEntity(dataDefinition, genericEntity); Entity existingGenericEntity = null; if (existingDatabaseEntity != null) { existingGenericEntity = entityService.convertToGenericEntity(dataDefinition, existingDatabaseEntity); } validationService.validateGenericEntity(dataDefinition, genericEntity, existingGenericEntity); if (!genericEntity.isValid()) { copyValidationErrors(dataDefinition, genericEntityToSave, genericEntity); if (existingGenericEntity != null) { copyMissingFields(genericEntityToSave, existingGenericEntity); } logValidationErrors(genericEntityToSave); return genericEntityToSave; } Object databaseEntity = entityService.convertToDatabaseEntity(dataDefinition, genericEntity, existingDatabaseEntity); if (genericEntity.getId() == null) { priorityService.prioritizeEntity(dataDefinition, databaseEntity); } saveDatabaseEntity(dataDefinition, databaseEntity); Entity savedEntity = entityService.convertToGenericEntity(dataDefinition, databaseEntity); for (Entry<String, FieldDefinition> fieldEntry : dataDefinition.getFields().entrySet()) { if (fieldEntry.getValue().getType() instanceof HasManyType) { List<Entity> entities = (List<Entity>) genericEntity.getField(fieldEntry.getKey()); HasManyType hasManyType = (HasManyType) fieldEntry.getValue().getType(); if (entities == null || entities instanceof EntityListImpl) { savedEntity.setField(fieldEntry.getKey(), entities); continue; } List<Entity> savedEntities = saveHasManyEntities(alreadySavedEntities, newlySavedEntities, hasManyType.getJoinFieldName(), savedEntity.getId(), entities, (InternalDataDefinition) hasManyType.getDataDefinition()); EntityList dbEntities = savedEntity.getHasManyField(fieldEntry.getKey()); EntityOpResult results = removeOrphans(hasManyType, findOrphans(savedEntities, dbEntities)); if (!results.isSuccessfull()) { + // #TODO MAKU copyValidationErrors(dataDefinition, savedEntity, results.getMessagesHolder()); savedEntity.setField(fieldEntry.getKey(), existingGenericEntity.getField(fieldEntry.getKey())); return savedEntity; } savedEntity.setField(fieldEntry.getKey(), savedEntities); } else if (fieldEntry.getValue().getType() instanceof TreeType) { List<Entity> entities = (List<Entity>) genericEntity.getField(fieldEntry.getKey()); if (entities == null || entities instanceof EntityTreeImpl) { savedEntity.setField(fieldEntry.getKey(), entities); continue; } TreeType treeType = (TreeType) fieldEntry.getValue().getType(); List<Entity> savedEntities = saveTreeEntities(alreadySavedEntities, newlySavedEntities, treeType.getJoinFieldName(), savedEntity.getId(), entities, (InternalDataDefinition) treeType.getDataDefinition(), null); savedEntity.setField(fieldEntry.getKey(), savedEntities); } } if (LOG.isInfoEnabled()) { LOG.info(savedEntity + " has been saved"); } alreadySavedEntities.add(savedEntity); if (genericEntity.getId() == null && savedEntity.getId() != null) { newlySavedEntities.add(savedEntity); } return savedEntity; } private void logDeletionErrors(final Entity entity) { logEntityErrors(entity, entity + " hasn't been deleted, bacause of onDelete hook rejection"); } private void logValidationErrors(final Entity entity) { logEntityErrors(entity, entity + " hasn't been saved, bacause of validation errors"); } private void logEntityErrors(final Entity entity, final String msg) { if (!LOG.isDebugEnabled()) { return; } StringBuilder sb = new StringBuilder(); if (StringUtils.isNotEmpty(msg)) { sb.append(msg); sb.append('\n'); } for (ErrorMessage error : entity.getGlobalErrors()) { sb.append(" --- " + error.getMessage()); sb.append('\n'); } for (Map.Entry<String, ErrorMessage> error : entity.getErrors().entrySet()) { sb.append(" --- " + error.getKey() + ": " + error.getValue().getMessage()); sb.append('\n'); } LOG.info(sb.toString()); } @Override @Transactional(readOnly = true) public Object convertToDatabaseEntity(final Entity entity) { return entityService.convertToDatabaseEntity((InternalDataDefinition) entity.getDataDefinition(), entity, null); } private List<Entity> saveHasManyEntities(final Set<Entity> alreadySavedEntities, final Set<Entity> newlySavedEntities, final String joinFieldName, final Long id, final List<Entity> entities, final InternalDataDefinition dataDefinition) { List<Entity> savedEntities = new ArrayList<Entity>(); for (Entity innerEntity : entities) { innerEntity.setField(joinFieldName, id); Entity savedInnerEntity = performSave(dataDefinition, innerEntity, alreadySavedEntities, newlySavedEntities); savedEntities.add(savedInnerEntity); if (!savedInnerEntity.isValid()) { TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } } return savedEntities; } @SuppressWarnings("unchecked") private List<Entity> saveTreeEntities(final Set<Entity> alreadySavedEntities, final Set<Entity> newlySavedEntities, final String joinFieldName, final Long id, final List<Entity> entities, final InternalDataDefinition dataDefinition, final Long parentId) { List<Entity> savedEntities = new ArrayList<Entity>(); int i = 0; for (Entity innerEntity : entities) { innerEntity.setField(joinFieldName, id); innerEntity.setField("parent", parentId); innerEntity.setField("priority", ++i); List<Entity> children = (List<Entity>) innerEntity.getField("children"); innerEntity.setField("children", null); Entity savedInnerEntity = performSave(dataDefinition, innerEntity, alreadySavedEntities, newlySavedEntities); savedEntities.add(savedInnerEntity); if (children != null) { children = saveTreeEntities(alreadySavedEntities, newlySavedEntities, joinFieldName, id, children, dataDefinition, savedInnerEntity.getId()); savedInnerEntity.setField("children", children); } if (!savedInnerEntity.isValid()) { TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } } return savedEntities; } private EntityOpResult removeOrphans(final CollectionFieldType fieldType, final Iterable<Entity> orphans) { switch (fieldType.getCascade()) { case NULLIFY: return nullifyOrphans(fieldType.getJoinFieldName(), orphans); case DELETE: return deleteOrphans((InternalDataDefinition) fieldType.getDataDefinition(), orphans); default: throw new IllegalArgumentException(String.format("Unsupported cascade value '%s'", fieldType.getCascade())); } } private EntityOpResult deleteOrphans(final InternalDataDefinition dataDefinition, final Iterable<Entity> orphans) { checkNotNull(dataDefinition, L_DATA_DEFINITION_MUST_BE_GIVEN); checkState(dataDefinition.isDeletable(), "Entity must be deletable"); checkState(dataDefinition.isEnabled(), L_DATA_DEFINITION_BELONGS_TO_DISABLED_PLUGIN); for (Entity orphan : orphans) { EntityOpResult result = deleteEntity(dataDefinition, orphan.getId()); if (!result.isSuccessfull()) { return result; } } return EntityOpResult.successfull(); } private EntityOpResult nullifyOrphans(final String fieldName, final Iterable<Entity> entities) { for (Entity entity : entities) { entity.setField(fieldName, null); Entity savedEntity = entity.getDataDefinition().save(entity); if (!savedEntity.isValid()) { return EntityOpResult.failure(savedEntity); } } return EntityOpResult.successfull(); } private Collection<Entity> findOrphans(final List<Entity> savedEntities, final List<Entity> dbEntities) { final Set<Long> savedEntityIds = Sets.newHashSet(EntityUtils.getIdsView(savedEntities)); return Collections2.filter(dbEntities, new Predicate<Entity>() { @Override public boolean apply(final Entity entity) { return !savedEntityIds.contains(entity.getId()); } }); } @Override @Transactional @Monitorable public List<Entity> activate(final InternalDataDefinition dataDefinition, final Long... entityIds) { if (!dataDefinition.isActivable()) { return Collections.emptyList(); } List<Entity> activatedEntities = new ArrayList<Entity>(); for (Long entityId : entityIds) { Entity entity = get(dataDefinition, entityId); if (entity == null) { throw new IllegalStateException("Cannot activate " + entityId); } if (!entity.isActive()) { entity.setActive(true); entity = save(dataDefinition, entity); if (!entity.isValid()) { throw new IllegalStateException("Cannot activate " + entity); } LOG.info(entity + " has been activated"); activatedEntities.add(entity); } } return activatedEntities; } @Override @Transactional @Monitorable public List<Entity> deactivate(final InternalDataDefinition dataDefinition, final Long... entityIds) { if (!dataDefinition.isActivable()) { return Collections.emptyList(); } List<Entity> deactivatedEntities = new ArrayList<Entity>(); for (Long entityId : entityIds) { Entity entity = get(dataDefinition, entityId); if (entity == null) { throw new IllegalStateException("Cannot deactivate " + entityId + " (entity not found)"); } if (entity.isActive()) { entity.setActive(false); entity = save(dataDefinition, entity); if (!entity.isValid()) { throw new IllegalStateException("Cannot deactivate " + entity + " because of validation errors"); } LOG.info(entity + " has been deactivated"); deactivatedEntities.add(entity); } } return deactivatedEntities; } @Override @Transactional @Monitorable public List<Entity> copy(final InternalDataDefinition dataDefinition, final Long... entityIds) { List<Entity> copiedEntities = new ArrayList<Entity>(); for (Long entityId : entityIds) { Entity sourceEntity = get(dataDefinition, entityId); Entity targetEntity = copy(dataDefinition, sourceEntity); if (targetEntity == null) { throw new IllegalStateException("Cannot copy " + sourceEntity); } LOG.info(sourceEntity + " has been copied to " + targetEntity); targetEntity = save(dataDefinition, targetEntity); if (!targetEntity.isValid()) { throw new CopyException(targetEntity); } copiedEntities.add(targetEntity); } return copiedEntities; } public Entity copy(final InternalDataDefinition dataDefinition, final Entity sourceEntity) { Entity targetEntity = dataDefinition.create(); for (Entry<String, FieldDefinition> fieldEntry : dataDefinition.getFields().entrySet()) { FieldDefinition fieldDefinition = fieldEntry.getValue(); String fieldName = fieldEntry.getKey(); boolean copy = fieldDefinition.getType().isCopyable(); if (copy) { targetEntity.setField(fieldName, getCopyValueOfSimpleField(sourceEntity, dataDefinition, fieldName)); } } if (!dataDefinition.callCopyHook(targetEntity)) { return null; } for (String fieldName : dataDefinition.getFields().keySet()) { copyHasManyField(sourceEntity, targetEntity, dataDefinition, fieldName); } for (String fieldName : dataDefinition.getFields().keySet()) { copyTreeField(sourceEntity, targetEntity, dataDefinition, fieldName); } for (String fieldName : dataDefinition.getFields().keySet()) { copyManyToManyField(sourceEntity, targetEntity, dataDefinition, fieldName); } return targetEntity; } private void copyTreeField(final Entity sourceEntity, final Entity targetEntity, final DataDefinition dataDefinition, final String fieldName) { FieldDefinition fieldDefinition = dataDefinition.getField(fieldName); if (!(fieldDefinition.getType() instanceof TreeType) || !((TreeType) fieldDefinition.getType()).isCopyable()) { return; } TreeType treeType = ((TreeType) fieldDefinition.getType()); List<Entity> entities = new ArrayList<Entity>(); Entity root = sourceEntity.getTreeField(fieldName).getRoot(); if (root != null) { root.setField(treeType.getJoinFieldName(), null); root = copy((InternalDataDefinition) treeType.getDataDefinition(), root); if (root != null) { entities.add(root); } } targetEntity.setField(fieldName, entities); } private void copyHasManyField(final Entity sourceEntity, final Entity targetEntity, final DataDefinition dataDefinition, final String fieldName) { FieldDefinition fieldDefinition = dataDefinition.getField(fieldName); if (!(fieldDefinition.getType() instanceof HasManyType) || !((HasManyType) fieldDefinition.getType()).isCopyable()) { return; } HasManyType hasManyType = ((HasManyType) fieldDefinition.getType()); List<Entity> entities = new ArrayList<Entity>(); for (Entity childEntity : sourceEntity.getHasManyField(fieldName)) { childEntity.setField(hasManyType.getJoinFieldName(), null); Entity savedChildEntity = copy((InternalDataDefinition) hasManyType.getDataDefinition(), childEntity); if (savedChildEntity != null) { entities.add(savedChildEntity); } } targetEntity.setField(fieldName, entities); } private void copyManyToManyField(final Entity sourceEntity, final Entity targetEntity, final DataDefinition dataDefinition, final String fieldName) { FieldDefinition fieldDefinition = dataDefinition.getField(fieldName); if (!(fieldDefinition.getType() instanceof ManyToManyType) || !((ManyToManyType) fieldDefinition.getType()).isCopyable()) { return; } targetEntity.setField(fieldName, sourceEntity.getField(fieldName)); } private Object getCopyValueOfSimpleField(final Entity sourceEntity, final DataDefinition dataDefinition, final String fieldName) { InternalFieldDefinition fieldDefinition = (InternalFieldDefinition) dataDefinition.getField(fieldName); if (fieldDefinition.isUnique()) { if (fieldDefinition.canBeBothCopyableAndUnique()) { return getCopyValueOfUniqueField(dataDefinition, fieldDefinition, sourceEntity.getStringField(fieldName)); } else { sourceEntity.addError(fieldDefinition, "qcadooView.validate.field.error.invalidUniqueType"); throw new CopyException(sourceEntity); } } else if (fieldDefinition.getType() instanceof HasManyType) { return null; } else if (fieldDefinition.getType() instanceof TreeType) { return null; } else if (fieldDefinition.getType() instanceof ManyToManyType) { return null; } else { return sourceEntity.getField(fieldName); } } private String getCopyValueOfUniqueField(final DataDefinition dataDefinition, final FieldDefinition fieldDefinition, final String value) { if (value == null) { return value; } else { Matcher matcher = Pattern.compile("(.+)\\((\\d+)\\)").matcher(value); String oldValue = value; int index = 1; if (matcher.matches()) { oldValue = matcher.group(1); index = Integer.valueOf(matcher.group(2)) + 1; } while (true) { String newValue = oldValue + "(" + (index++) + ")"; int matches = dataDefinition.find().setMaxResults(1) .add(SearchRestrictions.eq(fieldDefinition.getName(), newValue)).list().getTotalNumberOfEntities(); if (matches == 0) { return newValue; } } } } @Override @Transactional(readOnly = true) @Monitorable public Entity get(final InternalDataDefinition dataDefinition, final Long entityId) { checkNotNull(dataDefinition, L_DATA_DEFINITION_MUST_BE_GIVEN); checkState(dataDefinition.isEnabled(), L_DATA_DEFINITION_BELONGS_TO_DISABLED_PLUGIN); checkNotNull(entityId, "EntityId must be given"); Object databaseEntity = getDatabaseEntity(dataDefinition, entityId); if (databaseEntity == null) { logEntityInfo(dataDefinition, entityId, "hasn't been retrieved, because it doesn't exist"); return null; } Entity entity = entityService.convertToGenericEntity(dataDefinition, databaseEntity); if (LOG.isDebugEnabled()) { LOG.debug(entity + " has been retrieved"); } return entity; } @Override @Transactional @Monitorable public EntityOpResult delete(final InternalDataDefinition dataDefinition, final Long... entityIds) { checkNotNull(dataDefinition, L_DATA_DEFINITION_MUST_BE_GIVEN); checkState(dataDefinition.isDeletable(), "Entity must be deletable"); checkState(dataDefinition.isEnabled(), L_DATA_DEFINITION_BELONGS_TO_DISABLED_PLUGIN); checkState(entityIds.length > 0, "EntityIds must be given"); for (Long entityId : entityIds) { EntityOpResult result = deleteEntity(dataDefinition, entityId); if (!result.isSuccessfull()) { return result; } } return EntityOpResult.successfull(); } @Override public InternalDataDefinition getDataDefinition(final String pluginIdentifier, final String name) { InternalDataDefinition dataDefinition = (InternalDataDefinition) dataDefinitionService.get(pluginIdentifier, name); if (dataDefinition == null) { throw new IllegalStateException("DataDefinition " + pluginIdentifier + "_" + name + " cannot be found"); } else if (!dataDefinition.isEnabled()) { throw new IllegalStateException("DataDefinition " + dataDefinition + " belongs to disabled plugin"); } return dataDefinition; } @Override @Transactional(readOnly = true) @Monitorable public SearchResult find(final SearchQuery searchQuery) { checkArgument(searchQuery != null, "SearchCriteria must be given"); Query query = searchQuery.createQuery(hibernateService.getCurrentSession()); searchQuery.addParameters(query); int totalNumberOfEntities = -1; if (searchQuery.hasFirstAndMaxResults()) { totalNumberOfEntities = hibernateService.list(query).size(); searchQuery.addFirstAndMaxResults(query); } if (totalNumberOfEntities == 0) { if (LOG.isDebugEnabled()) { LOG.debug("There is no entity matching criteria " + searchQuery); } return getResultSet(null, totalNumberOfEntities, Collections.emptyList()); } List<?> results = hibernateService.list(query); if (totalNumberOfEntities == -1) { totalNumberOfEntities = results.size(); if (totalNumberOfEntities == 0) { if (LOG.isDebugEnabled()) { LOG.debug("There is no entity matching criteria " + searchQuery); } return getResultSet(null, totalNumberOfEntities, Collections.emptyList()); } } if (LOG.isDebugEnabled()) { LOG.debug("There are " + totalNumberOfEntities + " entities matching criteria " + searchQuery); } InternalDataDefinition searchQueryDataDefinition = (InternalDataDefinition) searchQuery.getDataDefinition(); if (searchQueryDataDefinition == null) { searchQueryDataDefinition = hibernateService.resolveDataDefinition(query); } return getResultSet(searchQueryDataDefinition, totalNumberOfEntities, results); } @Override @Transactional(readOnly = true) @Monitorable public SearchResult find(final SearchCriteria searchCriteria) { checkArgument(searchCriteria != null, "SearchCriteria must be given"); Criteria criteria = searchCriteria.createCriteria(hibernateService.getCurrentSession()); int totalNumberOfEntities = hibernateService.getTotalNumberOfEntities(criteria); if (totalNumberOfEntities == 0) { LOG.info("There is no entity matching criteria " + searchCriteria); return getResultSet(null, totalNumberOfEntities, Collections.emptyList()); } searchCriteria.addFirstAndMaxResults(criteria); searchCriteria.addOrders(criteria); searchCriteria.addCacheable(criteria); List<?> results = hibernateService.list(criteria); if (LOG.isDebugEnabled()) { LOG.debug("There are " + totalNumberOfEntities + " entities matching criteria " + searchCriteria); } InternalDataDefinition searchQueryDataDefinition = (InternalDataDefinition) searchCriteria.getDataDefinition(); if (searchQueryDataDefinition == null) { searchQueryDataDefinition = hibernateService.resolveDataDefinition(criteria); } return getResultSet(searchQueryDataDefinition, totalNumberOfEntities, results); } @Override public void moveTo(final InternalDataDefinition dataDefinition, final Long entityId, final int position) { checkState(position > 0, "Position must be greaten than 0"); move(dataDefinition, entityId, position, 0); } @Override public void move(final InternalDataDefinition dataDefinition, final Long entityId, final int offset) { checkState(offset != 0, "Offset must be different than 0"); move(dataDefinition, entityId, 0, offset); } @Transactional @Monitorable private void move(final InternalDataDefinition dataDefinition, final Long entityId, final int position, final int offset) { checkNotNull(dataDefinition, L_DATA_DEFINITION_MUST_BE_GIVEN); checkState(dataDefinition.isPrioritizable(), "Entity must be prioritizable"); checkState(dataDefinition.isEnabled(), L_DATA_DEFINITION_BELONGS_TO_DISABLED_PLUGIN); checkNotNull(entityId, "EntityId must be given"); Object databaseEntity = getDatabaseEntity(dataDefinition, entityId); if (databaseEntity == null) { logEntityInfo(dataDefinition, entityId, "hasn't been prioritized, because it doesn't exist"); return; } priorityService.move(dataDefinition, databaseEntity, position, offset); logEntityInfo(dataDefinition, entityId, "has been prioritized"); } private Object getExistingDatabaseEntity(final InternalDataDefinition dataDefinition, final Entity entity) { Object existingDatabaseEntity = null; if (entity.getId() != null) { existingDatabaseEntity = getDatabaseEntity(dataDefinition, entity.getId()); checkState(existingDatabaseEntity != null, "Entity[%s][id=%s] cannot be found", dataDefinition.getPluginIdentifier() + "." + dataDefinition.getName(), entity.getId()); } return existingDatabaseEntity; } private EntityOpResult deleteEntity(final InternalDataDefinition dataDefinition, final Long entityId) { return deleteEntity(dataDefinition, entityId, Sets.<EntitySignature> newHashSet()); } private EntityOpResult deleteEntity(final InternalDataDefinition dataDefinition, final Long entityId, final Set<EntitySignature> traversedEntities) { return deleteEntity(dataDefinition, entityId, false, traversedEntities); } private EntityOpResult deleteEntity(final InternalDataDefinition dataDefinition, final Long entityId, final boolean testOnly, final Set<EntitySignature> traversedEntities) { Object databaseEntity = getDatabaseEntity(dataDefinition, entityId); checkNotNull(databaseEntity, "Entity[%s][id=%s] cannot be found", dataDefinition.getPluginIdentifier() + "." + dataDefinition.getName(), entityId); Entity entity = get(dataDefinition, entityId); if (!dataDefinition.callDeleteHook(entity)) { logDeletionErrors(entity); entity.addGlobalError("qcadooView.message.deleteFailedMessage"); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); return EntityOpResult.failure(entity); } priorityService.deprioritizeEntity(dataDefinition, databaseEntity); Map<String, FieldDefinition> fields = dataDefinition.getFields(); for (FieldDefinition fieldDefinition : fields.values()) { if (fieldDefinition.getType() instanceof CollectionFieldType) { CollectionFieldType collectionFieldType = (CollectionFieldType) fieldDefinition.getType(); @SuppressWarnings("unchecked") Collection<Entity> children = (Collection<Entity>) entity.getField(fieldDefinition.getName()); EntityOpResult cascadeDeletionRes = performCascadeStrategy(entity, collectionFieldType, children, traversedEntities); if (!cascadeDeletionRes.isSuccessfull()) { return cascadeDeletionRes; } } } if (testOnly) { logEntityInfo(dataDefinition, entityId, "may be cascade deleted"); } else { try { databaseEntity = getDatabaseEntity(dataDefinition, entityId); if (databaseEntity != null) { hibernateService.getCurrentSession().delete(databaseEntity); hibernateService.getCurrentSession().flush(); } } catch (ConstraintViolationException e) { throw new IllegalStateException(getConstraintViolationMessage(entity), e); } logEntityInfo(dataDefinition, entityId, "has been deleted"); } return new EntityOpResult(true, entity); } private EntityOpResult performCascadeStrategy(final Entity entity, final FieldType fieldType, final Collection<Entity> children, final Set<EntitySignature> traversedEntities) { if (children == null || children.isEmpty()) { return EntityOpResult.successfull(); } boolean isManyToManyType = fieldType instanceof ManyToManyType; InternalDataDefinition childDataDefinition = (InternalDataDefinition) ((DataDefinitionHolder) fieldType) .getDataDefinition(); Cascadeable.Cascade cascade = ((Cascadeable) fieldType).getCascade(); if (Cascadeable.Cascade.NULLIFY.equals(cascade)) { if (!isManyToManyType) { return performCascadeNullification(childDataDefinition, children, entity, fieldType); } return EntityOpResult.successfull(); } else if (Cascadeable.Cascade.DELETE.equals(cascade)) { return performCascadeDelete(childDataDefinition, children, isManyToManyType, traversedEntities); } else { throw new IllegalArgumentException(String.format("Unsupported cascade value '%s'", cascade)); } } private EntityOpResult performCascadeNullification(final InternalDataDefinition childDataDefinition, final Collection<Entity> children, final Entity entity, final FieldType fieldType) { String joinFieldName = ((JoinFieldHolder) fieldType).getJoinFieldName(); for (Entity child : children) { child.setField(joinFieldName, null); child = save(childDataDefinition, child); if (!child.isValid()) { String msg = String.format("Can not nullify field '%s' in %s because of following validation errors:", joinFieldName, child); logEntityErrors(child, msg); return EntityOpResult.failure(child); } } return EntityOpResult.successfull(); } private EntityOpResult performCascadeDelete(final InternalDataDefinition childDataDefinition, final Collection<Entity> children, final boolean testOnly, final Set<EntitySignature> traversedEntities) { for (Entity child : children) { EntitySignature childSignature = EntitySignature.of(child); if (!traversedEntities.contains(childSignature)) { traversedEntities.add(childSignature); EntityOpResult result = deleteEntity(childDataDefinition, child.getId(), testOnly, traversedEntities); if (!result.isSuccessfull()) { return result; } } } return EntityOpResult.successfull(); } private String getConstraintViolationMessage(final Entity entity) { String message = null; try { message = String.format("Entity [ENTITY.%s] is in use", getIdentifierExpression(entity)); } catch (Exception e) { message = "Entity is in use"; } return message; } private String getIdentifierExpression(final Entity entity) { InternalDataDefinition dataDef = (InternalDataDefinition) entity.getDataDefinition(); return expressionService.getValue(entity, dataDef.getIdentifierExpression(), Locale.ENGLISH); } private SearchResultImpl getResultSet(final InternalDataDefinition dataDefinition, final int totalNumberOfEntities, final List<?> results) { List<Entity> genericResults = new ArrayList<Entity>(); for (Object databaseEntity : results) { genericResults.add(entityService.convertToGenericEntity(dataDefinition, databaseEntity)); } SearchResultImpl resultSet = new SearchResultImpl(); resultSet.setResults(genericResults); resultSet.setTotalNumberOfEntities(totalNumberOfEntities); return resultSet; } protected Object getDatabaseEntity(final InternalDataDefinition dataDefinition, final Long entityId) { return hibernateService.getCurrentSession().get(dataDefinition.getClassForEntity(), entityId); } protected void saveDatabaseEntity(final InternalDataDefinition dataDefinition, final Object databaseEntity) { hibernateService.getCurrentSession().save(databaseEntity); } private void copyMissingFields(final Entity genericEntityToSave, final Entity existingGenericEntity) { for (Map.Entry<String, Object> field : existingGenericEntity.getFields().entrySet()) { if (!genericEntityToSave.getFields().containsKey(field.getKey())) { genericEntityToSave.setField(field.getKey(), field.getValue()); } } } private void copyValidationErrors(final DataDefinition dataDefinition, final EntityMessagesHolder target, final EntityMessagesHolder source) { for (ErrorMessage error : source.getGlobalErrors()) { target.addGlobalError(error.getMessage(), error.getVars()); } for (Map.Entry<String, ErrorMessage> error : source.getErrors().entrySet()) { target.addError(dataDefinition.getField(error.getKey()), error.getValue().getMessage(), error.getValue().getVars()); } } private void logEntityInfo(final DataDefinition dataDefinition, final Long entityId, final String message) { if (LOG.isInfoEnabled()) { StringBuilder entityInfo = new StringBuilder("Entity["); entityInfo.append(dataDefinition.getPluginIdentifier()).append('.').append(dataDefinition.getName()); entityInfo.append("][id=").append(entityId).append("] "); entityInfo.append(message); LOG.info(entityInfo.toString()); } } protected void setEntityService(final EntityService entityService) { this.entityService = entityService; } protected void setExpressionService(final ExpressionService expressionService) { this.expressionService = expressionService; } protected void setPriorityService(final PriorityService priorityService) { this.priorityService = priorityService; } protected void setValidationService(final ValidationService validationService) { this.validationService = validationService; } protected void setHibernateService(final HibernateService hibernateService) { this.hibernateService = hibernateService; } }
true
true
private Entity performSave(final InternalDataDefinition dataDefinition, final Entity genericEntity, final Set<Entity> alreadySavedEntities, final Set<Entity> newlySavedEntities) { checkNotNull(dataDefinition, L_DATA_DEFINITION_MUST_BE_GIVEN); checkState(dataDefinition.isEnabled(), L_DATA_DEFINITION_BELONGS_TO_DISABLED_PLUGIN); checkNotNull(genericEntity, "Entity must be given"); if (alreadySavedEntities.contains(genericEntity)) { return genericEntity; } Entity genericEntityToSave = genericEntity.copy(); Object existingDatabaseEntity = getExistingDatabaseEntity(dataDefinition, genericEntity); Entity existingGenericEntity = null; if (existingDatabaseEntity != null) { existingGenericEntity = entityService.convertToGenericEntity(dataDefinition, existingDatabaseEntity); } validationService.validateGenericEntity(dataDefinition, genericEntity, existingGenericEntity); if (!genericEntity.isValid()) { copyValidationErrors(dataDefinition, genericEntityToSave, genericEntity); if (existingGenericEntity != null) { copyMissingFields(genericEntityToSave, existingGenericEntity); } logValidationErrors(genericEntityToSave); return genericEntityToSave; } Object databaseEntity = entityService.convertToDatabaseEntity(dataDefinition, genericEntity, existingDatabaseEntity); if (genericEntity.getId() == null) { priorityService.prioritizeEntity(dataDefinition, databaseEntity); } saveDatabaseEntity(dataDefinition, databaseEntity); Entity savedEntity = entityService.convertToGenericEntity(dataDefinition, databaseEntity); for (Entry<String, FieldDefinition> fieldEntry : dataDefinition.getFields().entrySet()) { if (fieldEntry.getValue().getType() instanceof HasManyType) { List<Entity> entities = (List<Entity>) genericEntity.getField(fieldEntry.getKey()); HasManyType hasManyType = (HasManyType) fieldEntry.getValue().getType(); if (entities == null || entities instanceof EntityListImpl) { savedEntity.setField(fieldEntry.getKey(), entities); continue; } List<Entity> savedEntities = saveHasManyEntities(alreadySavedEntities, newlySavedEntities, hasManyType.getJoinFieldName(), savedEntity.getId(), entities, (InternalDataDefinition) hasManyType.getDataDefinition()); EntityList dbEntities = savedEntity.getHasManyField(fieldEntry.getKey()); EntityOpResult results = removeOrphans(hasManyType, findOrphans(savedEntities, dbEntities)); if (!results.isSuccessfull()) { copyValidationErrors(dataDefinition, savedEntity, results.getMessagesHolder()); savedEntity.setField(fieldEntry.getKey(), existingGenericEntity.getField(fieldEntry.getKey())); return savedEntity; } savedEntity.setField(fieldEntry.getKey(), savedEntities); } else if (fieldEntry.getValue().getType() instanceof TreeType) { List<Entity> entities = (List<Entity>) genericEntity.getField(fieldEntry.getKey()); if (entities == null || entities instanceof EntityTreeImpl) { savedEntity.setField(fieldEntry.getKey(), entities); continue; } TreeType treeType = (TreeType) fieldEntry.getValue().getType(); List<Entity> savedEntities = saveTreeEntities(alreadySavedEntities, newlySavedEntities, treeType.getJoinFieldName(), savedEntity.getId(), entities, (InternalDataDefinition) treeType.getDataDefinition(), null); savedEntity.setField(fieldEntry.getKey(), savedEntities); } } if (LOG.isInfoEnabled()) { LOG.info(savedEntity + " has been saved"); } alreadySavedEntities.add(savedEntity); if (genericEntity.getId() == null && savedEntity.getId() != null) { newlySavedEntities.add(savedEntity); } return savedEntity; }
private Entity performSave(final InternalDataDefinition dataDefinition, final Entity genericEntity, final Set<Entity> alreadySavedEntities, final Set<Entity> newlySavedEntities) { checkNotNull(dataDefinition, L_DATA_DEFINITION_MUST_BE_GIVEN); checkState(dataDefinition.isEnabled(), L_DATA_DEFINITION_BELONGS_TO_DISABLED_PLUGIN); checkNotNull(genericEntity, "Entity must be given"); if (alreadySavedEntities.contains(genericEntity)) { return genericEntity; } Entity genericEntityToSave = genericEntity.copy(); Object existingDatabaseEntity = getExistingDatabaseEntity(dataDefinition, genericEntity); Entity existingGenericEntity = null; if (existingDatabaseEntity != null) { existingGenericEntity = entityService.convertToGenericEntity(dataDefinition, existingDatabaseEntity); } validationService.validateGenericEntity(dataDefinition, genericEntity, existingGenericEntity); if (!genericEntity.isValid()) { copyValidationErrors(dataDefinition, genericEntityToSave, genericEntity); if (existingGenericEntity != null) { copyMissingFields(genericEntityToSave, existingGenericEntity); } logValidationErrors(genericEntityToSave); return genericEntityToSave; } Object databaseEntity = entityService.convertToDatabaseEntity(dataDefinition, genericEntity, existingDatabaseEntity); if (genericEntity.getId() == null) { priorityService.prioritizeEntity(dataDefinition, databaseEntity); } saveDatabaseEntity(dataDefinition, databaseEntity); Entity savedEntity = entityService.convertToGenericEntity(dataDefinition, databaseEntity); for (Entry<String, FieldDefinition> fieldEntry : dataDefinition.getFields().entrySet()) { if (fieldEntry.getValue().getType() instanceof HasManyType) { List<Entity> entities = (List<Entity>) genericEntity.getField(fieldEntry.getKey()); HasManyType hasManyType = (HasManyType) fieldEntry.getValue().getType(); if (entities == null || entities instanceof EntityListImpl) { savedEntity.setField(fieldEntry.getKey(), entities); continue; } List<Entity> savedEntities = saveHasManyEntities(alreadySavedEntities, newlySavedEntities, hasManyType.getJoinFieldName(), savedEntity.getId(), entities, (InternalDataDefinition) hasManyType.getDataDefinition()); EntityList dbEntities = savedEntity.getHasManyField(fieldEntry.getKey()); EntityOpResult results = removeOrphans(hasManyType, findOrphans(savedEntities, dbEntities)); if (!results.isSuccessfull()) { // #TODO MAKU copyValidationErrors(dataDefinition, savedEntity, results.getMessagesHolder()); savedEntity.setField(fieldEntry.getKey(), existingGenericEntity.getField(fieldEntry.getKey())); return savedEntity; } savedEntity.setField(fieldEntry.getKey(), savedEntities); } else if (fieldEntry.getValue().getType() instanceof TreeType) { List<Entity> entities = (List<Entity>) genericEntity.getField(fieldEntry.getKey()); if (entities == null || entities instanceof EntityTreeImpl) { savedEntity.setField(fieldEntry.getKey(), entities); continue; } TreeType treeType = (TreeType) fieldEntry.getValue().getType(); List<Entity> savedEntities = saveTreeEntities(alreadySavedEntities, newlySavedEntities, treeType.getJoinFieldName(), savedEntity.getId(), entities, (InternalDataDefinition) treeType.getDataDefinition(), null); savedEntity.setField(fieldEntry.getKey(), savedEntities); } } if (LOG.isInfoEnabled()) { LOG.info(savedEntity + " has been saved"); } alreadySavedEntities.add(savedEntity); if (genericEntity.getId() == null && savedEntity.getId() != null) { newlySavedEntities.add(savedEntity); } return savedEntity; }
diff --git a/src/java/com/idega/development/presentation/Logs.java b/src/java/com/idega/development/presentation/Logs.java index b3676a8..ff84b96 100644 --- a/src/java/com/idega/development/presentation/Logs.java +++ b/src/java/com/idega/development/presentation/Logs.java @@ -1,84 +1,84 @@ package com.idega.development.presentation; import com.idega.presentation.*; import com.idega.presentation.ui.*; import com.idega.presentation.text.*; import com.idega.builder.business.BuilderLogic; import com.idega.builder.business.PageCacher; import com.idega.business.IBOLookup; import com.idega.data.IDOContainer; import com.idega.idegaweb.IWMainApplication; import com.idega.idegaweb.IWBundle; import com.idega.util.IWTimestamp; import com.idega.util.FileUtil; import java.io.File; /** * Title: idega Framework * Description: * Copyright: Copyright (c) 2002 * Company: idega * @author <a href=mailto:"[email protected]">Eirikur Hrafnsson</a> * @version 1.0 */ public class Logs extends Block{ private static final String PARAM_VIEW_OUT_LOG = "iw_dev_view_out_log"; private static final String PARAM_VIEW_ERR_LOG = "iw_dev_view_err_log"; private static final String PARAM_CLEAR_OUT_LOG = "iw_dev_clear_out_log"; private static final String PARAM_CLEAR_ERR_LOG = "iw_dev_clear_err_log"; public Logs(){} public void main(IWContext iwc) throws Exception { add(IWDeveloper.getTitleTable(this.getClass())); Form form = new Form(); form.maintainParameter(IWDeveloper.actionParameter); add(form); Table table = new Table(1,2); table.setHeight(1,1,"30"); table.setHeight(1,2,Table.HUNDRED_PERCENT); table.setAlignment(1,1,Table.HORIZONTAL_ALIGN_LEFT); table.setAlignment(1,2,Table.HORIZONTAL_ALIGN_LEFT); form.add(table); SubmitButton viewOut = new SubmitButton(PARAM_VIEW_OUT_LOG,"View Out Log"); SubmitButton clearOut = new SubmitButton(PARAM_CLEAR_OUT_LOG,"Clear Out Log"); SubmitButton viewErr = new SubmitButton(PARAM_VIEW_ERR_LOG,"View Error Log"); SubmitButton clearErr = new SubmitButton(PARAM_VIEW_ERR_LOG,"Clear Error Log"); table.add(viewOut, 1, 1); table.add(viewErr, 1, 1); table.add(clearOut, 1, 1); table.add(clearErr, 1, 1); processBusiness(iwc,table); } private void processBusiness(IWContext iwc,Table table) throws Exception{ - String tomcatLogDir = System.getProperty("user.dir")+".."+FileUtil.getFileSeparator()+"logs"+FileUtil.getFileSeparator(); + String tomcatLogDir = System.getProperty("user.dir")+FileUtil.getFileSeparator()+".."+FileUtil.getFileSeparator()+"logs"+FileUtil.getFileSeparator(); if(iwc.isParameterSet(PARAM_VIEW_OUT_LOG)){ - tomcatLogDir = tomcatLogDir+"logs.out"; + tomcatLogDir = tomcatLogDir+"out.log"; table.add("<pre>"+FileUtil.getStringFromFile(tomcatLogDir)+"</pre>",1,2); } else if( iwc.isParameterSet(PARAM_VIEW_ERR_LOG) ){ - tomcatLogDir = tomcatLogDir+"logs.err"; + tomcatLogDir = tomcatLogDir+"err.log"; table.add("<pre>"+FileUtil.getStringFromFile(tomcatLogDir)+"</pre>",1,2); } else if( iwc.isParameterSet(PARAM_CLEAR_OUT_LOG) ){ - tomcatLogDir = tomcatLogDir+"logs.out"; + tomcatLogDir = tomcatLogDir+"out.log"; FileUtil.delete(tomcatLogDir); FileUtil.createFile(tomcatLogDir); table.add("<b>Out log cleared!</b><br>",1,2); table.add("<pre>"+FileUtil.getStringFromFile(tomcatLogDir)+"</pre>",1,2); } else if( iwc.isParameterSet(PARAM_CLEAR_ERR_LOG) ){ - tomcatLogDir = tomcatLogDir+"logs.err"; + tomcatLogDir = tomcatLogDir+"err.log"; FileUtil.delete(tomcatLogDir); FileUtil.createFile(tomcatLogDir); table.add("<b>Error log cleared!</b><br>",1,2); table.add("<pre>"+FileUtil.getStringFromFile(tomcatLogDir)+"</pre>",1,2); } } }
false
true
private void processBusiness(IWContext iwc,Table table) throws Exception{ String tomcatLogDir = System.getProperty("user.dir")+".."+FileUtil.getFileSeparator()+"logs"+FileUtil.getFileSeparator(); if(iwc.isParameterSet(PARAM_VIEW_OUT_LOG)){ tomcatLogDir = tomcatLogDir+"logs.out"; table.add("<pre>"+FileUtil.getStringFromFile(tomcatLogDir)+"</pre>",1,2); } else if( iwc.isParameterSet(PARAM_VIEW_ERR_LOG) ){ tomcatLogDir = tomcatLogDir+"logs.err"; table.add("<pre>"+FileUtil.getStringFromFile(tomcatLogDir)+"</pre>",1,2); } else if( iwc.isParameterSet(PARAM_CLEAR_OUT_LOG) ){ tomcatLogDir = tomcatLogDir+"logs.out"; FileUtil.delete(tomcatLogDir); FileUtil.createFile(tomcatLogDir); table.add("<b>Out log cleared!</b><br>",1,2); table.add("<pre>"+FileUtil.getStringFromFile(tomcatLogDir)+"</pre>",1,2); } else if( iwc.isParameterSet(PARAM_CLEAR_ERR_LOG) ){ tomcatLogDir = tomcatLogDir+"logs.err"; FileUtil.delete(tomcatLogDir); FileUtil.createFile(tomcatLogDir); table.add("<b>Error log cleared!</b><br>",1,2); table.add("<pre>"+FileUtil.getStringFromFile(tomcatLogDir)+"</pre>",1,2); } }
private void processBusiness(IWContext iwc,Table table) throws Exception{ String tomcatLogDir = System.getProperty("user.dir")+FileUtil.getFileSeparator()+".."+FileUtil.getFileSeparator()+"logs"+FileUtil.getFileSeparator(); if(iwc.isParameterSet(PARAM_VIEW_OUT_LOG)){ tomcatLogDir = tomcatLogDir+"out.log"; table.add("<pre>"+FileUtil.getStringFromFile(tomcatLogDir)+"</pre>",1,2); } else if( iwc.isParameterSet(PARAM_VIEW_ERR_LOG) ){ tomcatLogDir = tomcatLogDir+"err.log"; table.add("<pre>"+FileUtil.getStringFromFile(tomcatLogDir)+"</pre>",1,2); } else if( iwc.isParameterSet(PARAM_CLEAR_OUT_LOG) ){ tomcatLogDir = tomcatLogDir+"out.log"; FileUtil.delete(tomcatLogDir); FileUtil.createFile(tomcatLogDir); table.add("<b>Out log cleared!</b><br>",1,2); table.add("<pre>"+FileUtil.getStringFromFile(tomcatLogDir)+"</pre>",1,2); } else if( iwc.isParameterSet(PARAM_CLEAR_ERR_LOG) ){ tomcatLogDir = tomcatLogDir+"err.log"; FileUtil.delete(tomcatLogDir); FileUtil.createFile(tomcatLogDir); table.add("<b>Error log cleared!</b><br>",1,2); table.add("<pre>"+FileUtil.getStringFromFile(tomcatLogDir)+"</pre>",1,2); } }
diff --git a/tool/src/java/org/sakaiproject/poll/tool/producers/AddPollProducer.java b/tool/src/java/org/sakaiproject/poll/tool/producers/AddPollProducer.java index 8f5541d..072e67f 100644 --- a/tool/src/java/org/sakaiproject/poll/tool/producers/AddPollProducer.java +++ b/tool/src/java/org/sakaiproject/poll/tool/producers/AddPollProducer.java @@ -1,371 +1,370 @@ /********************************************************************************** * $URL: $ * $Id: $ *********************************************************************************** * * Copyright (c) 2006,2007 The Sakai Foundation. * * Licensed under the Educational Community License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ package org.sakaiproject.poll.tool.producers; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.text.ParseException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.sakaiproject.poll.model.Poll; import org.sakaiproject.poll.model.Option; import org.sakaiproject.poll.model.Poll; import org.sakaiproject.poll.logic.PollListManager; import org.sakaiproject.poll.logic.PollVoteManager; import org.sakaiproject.poll.tool.params.OptionViewParameters; import org.sakaiproject.poll.tool.params.VoteBean; import uk.org.ponder.beanutil.entity.EntityID; import uk.org.ponder.messageutil.MessageLocator; import uk.org.ponder.messageutil.TargettedMessageList; import uk.org.ponder.rsf.components.UIContainer; import uk.org.ponder.rsf.components.UIOutput; import uk.org.ponder.rsf.view.ComponentChecker; import uk.org.ponder.rsf.view.ViewComponentProducer; import uk.org.ponder.rsf.viewstate.EntityCentredViewParameters; import uk.org.ponder.rsf.viewstate.ViewParameters; import uk.org.ponder.rsf.viewstate.SimpleViewParameters; import uk.org.ponder.localeutil.LocaleGetter; import uk.org.ponder.rsf.components.UIForm; import uk.org.ponder.rsf.components.UIInput; import uk.org.ponder.rsf.components.UIInternalLink; import uk.org.ponder.rsf.components.UICommand; import uk.org.ponder.rsf.flow.jsfnav.NavigationCase; import uk.org.ponder.rsf.flow.jsfnav.NavigationCaseReporter; import uk.org.ponder.rsf.components.UIELBinding; import uk.org.ponder.rsf.components.UIMessage; import uk.org.ponder.rsf.components.UISelect; import uk.org.ponder.rsf.components.UISelectChoice; import uk.org.ponder.rsf.components.UISelectLabel; import uk.org.ponder.rsf.components.UIOutputMany; import uk.org.ponder.rsf.components.UIBranchContainer; import uk.org.ponder.rsf.components.UIVerbatim; import uk.org.ponder.rsf.components.decorators.DecoratorList; import uk.org.ponder.rsf.components.decorators.UILabelTargetDecorator; import uk.org.ponder.rsf.components.decorators.UITextDimensionsDecorator; import uk.org.ponder.rsf.components.decorators.UITooltipDecorator; import uk.org.ponder.rsf.viewstate.ViewParamsReporter; import uk.org.ponder.rsf.evolvers.FormatAwareDateInputEvolver; import uk.org.ponder.rsf.evolvers.TextInputEvolver; //import uk.org.ponder.rsf.components.decorators.UITextDimensionsDecorator; //import uk.org.ponder.rsf.components.decorators.DecoratorList; import org.sakaiproject.tool.api.ToolManager; import org.sakaiproject.user.api.User; import org.sakaiproject.user.api.UserDirectoryService; import org.sakaiproject.util.FormattedText; import org.sakaiproject.entity.api.Entity; public class AddPollProducer implements ViewComponentProducer,NavigationCaseReporter,ViewParamsReporter { public static final String VIEW_ID = "voteAdd"; private UserDirectoryService userDirectoryService; private PollListManager pollListManager; private ToolManager toolManager; private MessageLocator messageLocator; private LocaleGetter localegetter; private static Log m_log = LogFactory.getLog(AddPollProducer.class); public String getViewID() { return VIEW_ID; } public void setMessageLocator(MessageLocator messageLocator) { this.messageLocator = messageLocator; } public void setUserDirectoryService(UserDirectoryService userDirectoryService) { this.userDirectoryService = userDirectoryService; } public void setPollListManager(PollListManager pollListManager) { this.pollListManager = pollListManager; } public void setToolManager(ToolManager toolManager) { this.toolManager = toolManager; } public void setLocaleGetter(LocaleGetter localegetter) { this.localegetter = localegetter; } private VoteBean voteBean; public void setVoteBean(VoteBean vb){ this.voteBean = vb; } private TextInputEvolver richTextEvolver; public void setRichTextEvolver(TextInputEvolver richTextEvolver) { this.richTextEvolver = richTextEvolver; } private TargettedMessageList tml; public void setTargettedMessageList(TargettedMessageList tml) { this.tml = tml; } private Poll poll; public void setPoll(Poll p) { poll =p; } private PollVoteManager pollVoteManager; public void setPollVoteManager(PollVoteManager pvm){ this.pollVoteManager = pvm; } /* * You can change the date input to accept time as well by uncommenting the lines like this: * dateevolver.setStyle(FormatAwareDateInputEvolver.DATE_TIME_INPUT); * and commenting out lines like this: * dateevolver.setStyle(FormatAwareDateInputEvolver.DATE_INPUT); * -AZ */ private FormatAwareDateInputEvolver dateevolver; public void setDateEvolver(FormatAwareDateInputEvolver dateevolver) { this.dateevolver = dateevolver; } public void fillComponents(UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) { //process any messages if (tml.size() > 0) { for (int i = 0; i < tml.size(); i ++ ) { UIBranchContainer errorRow = UIBranchContainer.make(tofill,"error-row:", new Integer(i).toString()); if (tml.messageAt(i).args != null ) { UIMessage.make(errorRow,"error",tml.messageAt(i).acquireMessageCode(),(String[])tml.messageAt(i).args[0]); } else { UIMessage.make(errorRow,"error",tml.messageAt(i).acquireMessageCode()); } } } User currentuser = userDirectoryService.getCurrentUser(); String currentuserid = currentuser.getId(); EntityCentredViewParameters ecvp = (EntityCentredViewParameters) viewparams; Poll poll = null; boolean isNew = true; UIForm newPoll = UIForm.make(tofill, "add-poll-form"); if (voteBean.getPoll() != null) { poll = voteBean.getPoll(); UIOutput.make(tofill,"new_poll_title",messageLocator.getMessage("new_poll_title")); isNew = false; newPoll.parameters.add(new UIELBinding("#{poll.pollId}", poll.getPollId())); } else if (ecvp.mode.equals(EntityCentredViewParameters.MODE_NEW)) { UIMessage.make(tofill,"new_poll_title","new_poll_title"); //build an empty poll m_log.debug("this is a new poll"); poll = new Poll(); } else { UIMessage.make(tofill,"new_poll_title","new_poll_title_edit"); // hack but this needs to work String strId = ecvp.getELPath().substring(ecvp.getELPath().indexOf(".") + 1); m_log.debug("got id of " + strId); poll = pollListManager.getPollById(new Long(strId)); voteBean.setPoll(poll); newPoll.parameters.add(new UIELBinding("#{poll.pollId}", poll.getPollId())); isNew = false; } //only display for exisiting polls if (!isNew) { //fill the options list UIBranchContainer actionBlock = UIBranchContainer.make(newPoll, "option-headers:"); UIMessage.make(actionBlock,"options-title","new_poll_option_title"); UIInternalLink.make(actionBlock,"option-add",UIMessage.make("new_poll_option_add"), new OptionViewParameters(PollOptionProducer.VIEW_ID, null, poll.getPollId().toString())); /* * new EntityCentredViewParameters(PollOptionProducer.VIEW_ID, new EntityID("Poll", "Poll_" + poll.getPollId().toString()),EntityCentredViewParameters.MODE_NEW) */ List votes = pollVoteManager.getAllVotesForPoll(poll); if (votes != null && votes.size() > 0 ) { m_log.debug("Poll has " + votes.size() + " votes"); UIBranchContainer errorRow = UIBranchContainer.make(tofill,"error-row:", "0"); UIMessage.make(errorRow,"error", "warn_poll_has_votes"); } List options = poll.getPollOptions(); - m_log.debug("got this many options: " + options.size()); for (int i = 0; i < options.size(); i++){ Option o = (Option)options.get(i); UIBranchContainer oRow = UIBranchContainer.make(actionBlock,"options-row:",o.getOptionId().toString()); UIVerbatim.make(oRow,"options-name",o.getOptionText()); UIInternalLink editOption = UIInternalLink.make(oRow,"option-edit",UIMessage.make("new_poll_option_edit"), new OptionViewParameters(PollOptionProducer.VIEW_ID, o.getOptionId().toString())); - editOption.decorators = new DecoratorList(new UITooltipDecorator(UIMessage.make("new_poll_option_edit") +":" + FormattedText.convertFormattedTextToPlaintext(o.getOptionText()))); + editOption.decorators = new DecoratorList(new UITooltipDecorator(messageLocator.getMessage("new_poll_option_edit") +":" + FormattedText.convertFormattedTextToPlaintext(o.getOptionText()))); UIInternalLink deleteOption = UIInternalLink.make(oRow,"option-delete",UIMessage.make("new_poll_option_delete"), new OptionViewParameters(PollOptionDeleteProducer.VIEW_ID,o.getOptionId().toString())); deleteOption.decorators = new DecoratorList(new UITooltipDecorator(messageLocator.getMessage("new_poll_option_delete") +":" + FormattedText.convertFormattedTextToPlaintext(o.getOptionText()))); } } UIMessage.make(tofill, "new-poll-descr", "new_poll_title"); UIMessage pollText = UIMessage.make(tofill, "new-poll-question-label", "new_poll_question_label"); UIMessage pollDescr = UIMessage.make(tofill, "new-poll-descr-label", "new_poll_descr_label"); UIMessage.make(tofill, "new-poll-descr-label2", "new_poll_descr_label2"); UIMessage pollOpen = UIMessage.make(tofill, "new-poll-open-label", "new_poll_open_label"); UIMessage pollClose = UIMessage.make(tofill, "new-poll-close-label", "new_poll_close_label"); UIMessage.make(tofill, "new-poll-limits", "new_poll_limits"); UIMessage pollMin = UIMessage.make(tofill, "new-poll-min-limits", "new_poll_min_limits"); UIMessage pollMax = UIMessage.make(tofill, "new-poll-max-limits", "new_poll_max_limits"); //the form fields UIInput pollTextIn = UIInput.make(newPoll, "new-poll-text", "#{poll.text}",poll.getText()); UILabelTargetDecorator.targetLabel(pollText, pollTextIn); UIInput itemDescr = UIInput.make(newPoll, "newpolldescr:", "#{poll.details}", poll.getDetails()); //$NON-NLS-1$ //$NON-NLS-2$ //itemDescr.decorators = new DecoratorList(new UITextDimensionsDecorator(4, 4)); richTextEvolver.evolveTextInput(itemDescr); UILabelTargetDecorator.targetLabel(pollDescr, itemDescr); UIInput voteOpen = UIInput.make(newPoll, "openDate:", "poll.voteOpen"); UIInput voteClose = UIInput.make(newPoll, "closeDate:", "poll.voteClose"); dateevolver.setStyle(FormatAwareDateInputEvolver.DATE_TIME_INPUT); dateevolver.evolveDateInput(voteOpen, poll.getVoteOpen()); dateevolver.evolveDateInput(voteClose, poll.getVoteClose()); UILabelTargetDecorator.targetLabel(pollOpen, voteOpen); UILabelTargetDecorator.targetLabel(pollClose, voteClose); String[] minVotes = new String[]{"0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15"}; String[] maxVotes = new String[]{"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15"}; UISelect min = UISelect.make(newPoll,"min-votes",minVotes,"#{poll.minOptions}",Integer.toString(poll.getMinOptions())); UISelect max = UISelect.make(newPoll,"max-votes",maxVotes,"#{poll.maxOptions}",Integer.toString(poll.getMaxOptions())); UILabelTargetDecorator.targetLabel(pollMin, min); UILabelTargetDecorator.targetLabel(pollMax, max); /* * open - can be viewd at any time * never - not diplayed * afterVoting - after user has voted * afterClosing * */ String[] values = new String[] { "open", "afterVoting", "afterClosing","never"}; String[] labels = new String[] { messageLocator.getMessage("new_poll_open"), messageLocator.getMessage("new_poll_aftervoting"), messageLocator.getMessage("new_poll_afterClosing"), messageLocator.getMessage("new_poll_never") }; UISelect radioselect = UISelect.make(newPoll, "release-select", values, "#{poll.displayResult}", poll.getDisplayResult()); radioselect.optionnames = UIOutputMany.make(labels); String selectID = radioselect.getFullID(); //StringList optList = new StringList(); UIMessage.make(newPoll,"add_results_label","new_poll_results_label"); for (int i = 0; i < values.length; ++i) { UIBranchContainer radiobranch = UIBranchContainer.make(newPoll, "releaserow:", Integer.toString(i)); UISelectChoice choice = UISelectChoice.make(radiobranch, "release", selectID, i); UISelectLabel lb = UISelectLabel.make(radiobranch, "releaseLabel", selectID, i); UILabelTargetDecorator.targetLabel(lb, choice); } m_log.debug("About to close the form"); newPoll.parameters.add(new UIELBinding("#{poll.owner}", currentuserid)); String siteId = toolManager.getCurrentPlacement().getContext(); newPoll.parameters.add(new UIELBinding("#{poll.siteId}",siteId)); if (ecvp.mode!= null && ecvp.mode.equals(EntityCentredViewParameters.MODE_NEW)) { UICommand.make(newPoll, "submit-new-poll", UIMessage.make("new_poll_saveoption"), "#{pollToolBean.processActionAdd}"); } else { UICommand.make(newPoll, "submit-new-poll", UIMessage.make("new_poll_submit"), "#{pollToolBean.processActionAdd}"); } UICommand cancel = UICommand.make(newPoll, "cancel",UIMessage.make("new_poll_cancel"),"#{pollToolBean.cancel}"); cancel.parameters.add(new UIELBinding("#{voteCollection.submissionStatus}", "cancel")); m_log.debug("Finished generating view"); } public List reportNavigationCases() { List togo = new ArrayList(); // Always navigate back to this view. togo.add(new NavigationCase(null, new SimpleViewParameters(VIEW_ID))); togo.add(new NavigationCase("added", new SimpleViewParameters(PollToolProducer.VIEW_ID))); togo.add(new NavigationCase("option", new OptionViewParameters(PollOptionProducer.VIEW_ID, null, null))); togo.add(new NavigationCase("cancel", new SimpleViewParameters(PollToolProducer.VIEW_ID))); return togo; } public ViewParameters getViewParameters() { return new EntityCentredViewParameters(VIEW_ID, new EntityID("Poll", null)); } }
false
true
public void fillComponents(UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) { //process any messages if (tml.size() > 0) { for (int i = 0; i < tml.size(); i ++ ) { UIBranchContainer errorRow = UIBranchContainer.make(tofill,"error-row:", new Integer(i).toString()); if (tml.messageAt(i).args != null ) { UIMessage.make(errorRow,"error",tml.messageAt(i).acquireMessageCode(),(String[])tml.messageAt(i).args[0]); } else { UIMessage.make(errorRow,"error",tml.messageAt(i).acquireMessageCode()); } } } User currentuser = userDirectoryService.getCurrentUser(); String currentuserid = currentuser.getId(); EntityCentredViewParameters ecvp = (EntityCentredViewParameters) viewparams; Poll poll = null; boolean isNew = true; UIForm newPoll = UIForm.make(tofill, "add-poll-form"); if (voteBean.getPoll() != null) { poll = voteBean.getPoll(); UIOutput.make(tofill,"new_poll_title",messageLocator.getMessage("new_poll_title")); isNew = false; newPoll.parameters.add(new UIELBinding("#{poll.pollId}", poll.getPollId())); } else if (ecvp.mode.equals(EntityCentredViewParameters.MODE_NEW)) { UIMessage.make(tofill,"new_poll_title","new_poll_title"); //build an empty poll m_log.debug("this is a new poll"); poll = new Poll(); } else { UIMessage.make(tofill,"new_poll_title","new_poll_title_edit"); // hack but this needs to work String strId = ecvp.getELPath().substring(ecvp.getELPath().indexOf(".") + 1); m_log.debug("got id of " + strId); poll = pollListManager.getPollById(new Long(strId)); voteBean.setPoll(poll); newPoll.parameters.add(new UIELBinding("#{poll.pollId}", poll.getPollId())); isNew = false; } //only display for exisiting polls if (!isNew) { //fill the options list UIBranchContainer actionBlock = UIBranchContainer.make(newPoll, "option-headers:"); UIMessage.make(actionBlock,"options-title","new_poll_option_title"); UIInternalLink.make(actionBlock,"option-add",UIMessage.make("new_poll_option_add"), new OptionViewParameters(PollOptionProducer.VIEW_ID, null, poll.getPollId().toString())); /* * new EntityCentredViewParameters(PollOptionProducer.VIEW_ID, new EntityID("Poll", "Poll_" + poll.getPollId().toString()),EntityCentredViewParameters.MODE_NEW) */ List votes = pollVoteManager.getAllVotesForPoll(poll); if (votes != null && votes.size() > 0 ) { m_log.debug("Poll has " + votes.size() + " votes"); UIBranchContainer errorRow = UIBranchContainer.make(tofill,"error-row:", "0"); UIMessage.make(errorRow,"error", "warn_poll_has_votes"); } List options = poll.getPollOptions(); m_log.debug("got this many options: " + options.size()); for (int i = 0; i < options.size(); i++){ Option o = (Option)options.get(i); UIBranchContainer oRow = UIBranchContainer.make(actionBlock,"options-row:",o.getOptionId().toString()); UIVerbatim.make(oRow,"options-name",o.getOptionText()); UIInternalLink editOption = UIInternalLink.make(oRow,"option-edit",UIMessage.make("new_poll_option_edit"), new OptionViewParameters(PollOptionProducer.VIEW_ID, o.getOptionId().toString())); editOption.decorators = new DecoratorList(new UITooltipDecorator(UIMessage.make("new_poll_option_edit") +":" + FormattedText.convertFormattedTextToPlaintext(o.getOptionText()))); UIInternalLink deleteOption = UIInternalLink.make(oRow,"option-delete",UIMessage.make("new_poll_option_delete"), new OptionViewParameters(PollOptionDeleteProducer.VIEW_ID,o.getOptionId().toString())); deleteOption.decorators = new DecoratorList(new UITooltipDecorator(messageLocator.getMessage("new_poll_option_delete") +":" + FormattedText.convertFormattedTextToPlaintext(o.getOptionText()))); } } UIMessage.make(tofill, "new-poll-descr", "new_poll_title"); UIMessage pollText = UIMessage.make(tofill, "new-poll-question-label", "new_poll_question_label"); UIMessage pollDescr = UIMessage.make(tofill, "new-poll-descr-label", "new_poll_descr_label"); UIMessage.make(tofill, "new-poll-descr-label2", "new_poll_descr_label2"); UIMessage pollOpen = UIMessage.make(tofill, "new-poll-open-label", "new_poll_open_label"); UIMessage pollClose = UIMessage.make(tofill, "new-poll-close-label", "new_poll_close_label"); UIMessage.make(tofill, "new-poll-limits", "new_poll_limits"); UIMessage pollMin = UIMessage.make(tofill, "new-poll-min-limits", "new_poll_min_limits"); UIMessage pollMax = UIMessage.make(tofill, "new-poll-max-limits", "new_poll_max_limits"); //the form fields UIInput pollTextIn = UIInput.make(newPoll, "new-poll-text", "#{poll.text}",poll.getText()); UILabelTargetDecorator.targetLabel(pollText, pollTextIn); UIInput itemDescr = UIInput.make(newPoll, "newpolldescr:", "#{poll.details}", poll.getDetails()); //$NON-NLS-1$ //$NON-NLS-2$ //itemDescr.decorators = new DecoratorList(new UITextDimensionsDecorator(4, 4)); richTextEvolver.evolveTextInput(itemDescr); UILabelTargetDecorator.targetLabel(pollDescr, itemDescr); UIInput voteOpen = UIInput.make(newPoll, "openDate:", "poll.voteOpen"); UIInput voteClose = UIInput.make(newPoll, "closeDate:", "poll.voteClose"); dateevolver.setStyle(FormatAwareDateInputEvolver.DATE_TIME_INPUT); dateevolver.evolveDateInput(voteOpen, poll.getVoteOpen()); dateevolver.evolveDateInput(voteClose, poll.getVoteClose()); UILabelTargetDecorator.targetLabel(pollOpen, voteOpen); UILabelTargetDecorator.targetLabel(pollClose, voteClose); String[] minVotes = new String[]{"0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15"}; String[] maxVotes = new String[]{"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15"}; UISelect min = UISelect.make(newPoll,"min-votes",minVotes,"#{poll.minOptions}",Integer.toString(poll.getMinOptions())); UISelect max = UISelect.make(newPoll,"max-votes",maxVotes,"#{poll.maxOptions}",Integer.toString(poll.getMaxOptions())); UILabelTargetDecorator.targetLabel(pollMin, min); UILabelTargetDecorator.targetLabel(pollMax, max); /* * open - can be viewd at any time * never - not diplayed * afterVoting - after user has voted * afterClosing * */ String[] values = new String[] { "open", "afterVoting", "afterClosing","never"}; String[] labels = new String[] { messageLocator.getMessage("new_poll_open"), messageLocator.getMessage("new_poll_aftervoting"), messageLocator.getMessage("new_poll_afterClosing"), messageLocator.getMessage("new_poll_never") }; UISelect radioselect = UISelect.make(newPoll, "release-select", values, "#{poll.displayResult}", poll.getDisplayResult()); radioselect.optionnames = UIOutputMany.make(labels); String selectID = radioselect.getFullID(); //StringList optList = new StringList(); UIMessage.make(newPoll,"add_results_label","new_poll_results_label"); for (int i = 0; i < values.length; ++i) { UIBranchContainer radiobranch = UIBranchContainer.make(newPoll, "releaserow:", Integer.toString(i)); UISelectChoice choice = UISelectChoice.make(radiobranch, "release", selectID, i); UISelectLabel lb = UISelectLabel.make(radiobranch, "releaseLabel", selectID, i); UILabelTargetDecorator.targetLabel(lb, choice); } m_log.debug("About to close the form"); newPoll.parameters.add(new UIELBinding("#{poll.owner}", currentuserid)); String siteId = toolManager.getCurrentPlacement().getContext(); newPoll.parameters.add(new UIELBinding("#{poll.siteId}",siteId)); if (ecvp.mode!= null && ecvp.mode.equals(EntityCentredViewParameters.MODE_NEW)) { UICommand.make(newPoll, "submit-new-poll", UIMessage.make("new_poll_saveoption"), "#{pollToolBean.processActionAdd}"); } else { UICommand.make(newPoll, "submit-new-poll", UIMessage.make("new_poll_submit"), "#{pollToolBean.processActionAdd}"); } UICommand cancel = UICommand.make(newPoll, "cancel",UIMessage.make("new_poll_cancel"),"#{pollToolBean.cancel}"); cancel.parameters.add(new UIELBinding("#{voteCollection.submissionStatus}", "cancel")); m_log.debug("Finished generating view"); }
public void fillComponents(UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) { //process any messages if (tml.size() > 0) { for (int i = 0; i < tml.size(); i ++ ) { UIBranchContainer errorRow = UIBranchContainer.make(tofill,"error-row:", new Integer(i).toString()); if (tml.messageAt(i).args != null ) { UIMessage.make(errorRow,"error",tml.messageAt(i).acquireMessageCode(),(String[])tml.messageAt(i).args[0]); } else { UIMessage.make(errorRow,"error",tml.messageAt(i).acquireMessageCode()); } } } User currentuser = userDirectoryService.getCurrentUser(); String currentuserid = currentuser.getId(); EntityCentredViewParameters ecvp = (EntityCentredViewParameters) viewparams; Poll poll = null; boolean isNew = true; UIForm newPoll = UIForm.make(tofill, "add-poll-form"); if (voteBean.getPoll() != null) { poll = voteBean.getPoll(); UIOutput.make(tofill,"new_poll_title",messageLocator.getMessage("new_poll_title")); isNew = false; newPoll.parameters.add(new UIELBinding("#{poll.pollId}", poll.getPollId())); } else if (ecvp.mode.equals(EntityCentredViewParameters.MODE_NEW)) { UIMessage.make(tofill,"new_poll_title","new_poll_title"); //build an empty poll m_log.debug("this is a new poll"); poll = new Poll(); } else { UIMessage.make(tofill,"new_poll_title","new_poll_title_edit"); // hack but this needs to work String strId = ecvp.getELPath().substring(ecvp.getELPath().indexOf(".") + 1); m_log.debug("got id of " + strId); poll = pollListManager.getPollById(new Long(strId)); voteBean.setPoll(poll); newPoll.parameters.add(new UIELBinding("#{poll.pollId}", poll.getPollId())); isNew = false; } //only display for exisiting polls if (!isNew) { //fill the options list UIBranchContainer actionBlock = UIBranchContainer.make(newPoll, "option-headers:"); UIMessage.make(actionBlock,"options-title","new_poll_option_title"); UIInternalLink.make(actionBlock,"option-add",UIMessage.make("new_poll_option_add"), new OptionViewParameters(PollOptionProducer.VIEW_ID, null, poll.getPollId().toString())); /* * new EntityCentredViewParameters(PollOptionProducer.VIEW_ID, new EntityID("Poll", "Poll_" + poll.getPollId().toString()),EntityCentredViewParameters.MODE_NEW) */ List votes = pollVoteManager.getAllVotesForPoll(poll); if (votes != null && votes.size() > 0 ) { m_log.debug("Poll has " + votes.size() + " votes"); UIBranchContainer errorRow = UIBranchContainer.make(tofill,"error-row:", "0"); UIMessage.make(errorRow,"error", "warn_poll_has_votes"); } List options = poll.getPollOptions(); for (int i = 0; i < options.size(); i++){ Option o = (Option)options.get(i); UIBranchContainer oRow = UIBranchContainer.make(actionBlock,"options-row:",o.getOptionId().toString()); UIVerbatim.make(oRow,"options-name",o.getOptionText()); UIInternalLink editOption = UIInternalLink.make(oRow,"option-edit",UIMessage.make("new_poll_option_edit"), new OptionViewParameters(PollOptionProducer.VIEW_ID, o.getOptionId().toString())); editOption.decorators = new DecoratorList(new UITooltipDecorator(messageLocator.getMessage("new_poll_option_edit") +":" + FormattedText.convertFormattedTextToPlaintext(o.getOptionText()))); UIInternalLink deleteOption = UIInternalLink.make(oRow,"option-delete",UIMessage.make("new_poll_option_delete"), new OptionViewParameters(PollOptionDeleteProducer.VIEW_ID,o.getOptionId().toString())); deleteOption.decorators = new DecoratorList(new UITooltipDecorator(messageLocator.getMessage("new_poll_option_delete") +":" + FormattedText.convertFormattedTextToPlaintext(o.getOptionText()))); } } UIMessage.make(tofill, "new-poll-descr", "new_poll_title"); UIMessage pollText = UIMessage.make(tofill, "new-poll-question-label", "new_poll_question_label"); UIMessage pollDescr = UIMessage.make(tofill, "new-poll-descr-label", "new_poll_descr_label"); UIMessage.make(tofill, "new-poll-descr-label2", "new_poll_descr_label2"); UIMessage pollOpen = UIMessage.make(tofill, "new-poll-open-label", "new_poll_open_label"); UIMessage pollClose = UIMessage.make(tofill, "new-poll-close-label", "new_poll_close_label"); UIMessage.make(tofill, "new-poll-limits", "new_poll_limits"); UIMessage pollMin = UIMessage.make(tofill, "new-poll-min-limits", "new_poll_min_limits"); UIMessage pollMax = UIMessage.make(tofill, "new-poll-max-limits", "new_poll_max_limits"); //the form fields UIInput pollTextIn = UIInput.make(newPoll, "new-poll-text", "#{poll.text}",poll.getText()); UILabelTargetDecorator.targetLabel(pollText, pollTextIn); UIInput itemDescr = UIInput.make(newPoll, "newpolldescr:", "#{poll.details}", poll.getDetails()); //$NON-NLS-1$ //$NON-NLS-2$ //itemDescr.decorators = new DecoratorList(new UITextDimensionsDecorator(4, 4)); richTextEvolver.evolveTextInput(itemDescr); UILabelTargetDecorator.targetLabel(pollDescr, itemDescr); UIInput voteOpen = UIInput.make(newPoll, "openDate:", "poll.voteOpen"); UIInput voteClose = UIInput.make(newPoll, "closeDate:", "poll.voteClose"); dateevolver.setStyle(FormatAwareDateInputEvolver.DATE_TIME_INPUT); dateevolver.evolveDateInput(voteOpen, poll.getVoteOpen()); dateevolver.evolveDateInput(voteClose, poll.getVoteClose()); UILabelTargetDecorator.targetLabel(pollOpen, voteOpen); UILabelTargetDecorator.targetLabel(pollClose, voteClose); String[] minVotes = new String[]{"0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15"}; String[] maxVotes = new String[]{"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15"}; UISelect min = UISelect.make(newPoll,"min-votes",minVotes,"#{poll.minOptions}",Integer.toString(poll.getMinOptions())); UISelect max = UISelect.make(newPoll,"max-votes",maxVotes,"#{poll.maxOptions}",Integer.toString(poll.getMaxOptions())); UILabelTargetDecorator.targetLabel(pollMin, min); UILabelTargetDecorator.targetLabel(pollMax, max); /* * open - can be viewd at any time * never - not diplayed * afterVoting - after user has voted * afterClosing * */ String[] values = new String[] { "open", "afterVoting", "afterClosing","never"}; String[] labels = new String[] { messageLocator.getMessage("new_poll_open"), messageLocator.getMessage("new_poll_aftervoting"), messageLocator.getMessage("new_poll_afterClosing"), messageLocator.getMessage("new_poll_never") }; UISelect radioselect = UISelect.make(newPoll, "release-select", values, "#{poll.displayResult}", poll.getDisplayResult()); radioselect.optionnames = UIOutputMany.make(labels); String selectID = radioselect.getFullID(); //StringList optList = new StringList(); UIMessage.make(newPoll,"add_results_label","new_poll_results_label"); for (int i = 0; i < values.length; ++i) { UIBranchContainer radiobranch = UIBranchContainer.make(newPoll, "releaserow:", Integer.toString(i)); UISelectChoice choice = UISelectChoice.make(radiobranch, "release", selectID, i); UISelectLabel lb = UISelectLabel.make(radiobranch, "releaseLabel", selectID, i); UILabelTargetDecorator.targetLabel(lb, choice); } m_log.debug("About to close the form"); newPoll.parameters.add(new UIELBinding("#{poll.owner}", currentuserid)); String siteId = toolManager.getCurrentPlacement().getContext(); newPoll.parameters.add(new UIELBinding("#{poll.siteId}",siteId)); if (ecvp.mode!= null && ecvp.mode.equals(EntityCentredViewParameters.MODE_NEW)) { UICommand.make(newPoll, "submit-new-poll", UIMessage.make("new_poll_saveoption"), "#{pollToolBean.processActionAdd}"); } else { UICommand.make(newPoll, "submit-new-poll", UIMessage.make("new_poll_submit"), "#{pollToolBean.processActionAdd}"); } UICommand cancel = UICommand.make(newPoll, "cancel",UIMessage.make("new_poll_cancel"),"#{pollToolBean.cancel}"); cancel.parameters.add(new UIELBinding("#{voteCollection.submissionStatus}", "cancel")); m_log.debug("Finished generating view"); }
diff --git a/AndroidAsyncTest/src/com/koushikdutta/async/test/SocketIOTests.java b/AndroidAsyncTest/src/com/koushikdutta/async/test/SocketIOTests.java index e2ae3ff..4c8ec66 100644 --- a/AndroidAsyncTest/src/com/koushikdutta/async/test/SocketIOTests.java +++ b/AndroidAsyncTest/src/com/koushikdutta/async/test/SocketIOTests.java @@ -1,231 +1,231 @@ package com.koushikdutta.async.test; import android.util.Log; import com.koushikdutta.async.AsyncServer; import com.koushikdutta.async.future.SimpleFuture; import com.koushikdutta.async.http.AsyncHttpClient; import com.koushikdutta.async.http.socketio.Acknowledge; import com.koushikdutta.async.http.socketio.ConnectCallback; import com.koushikdutta.async.http.socketio.DisconnectCallback; import com.koushikdutta.async.http.socketio.EventCallback; import com.koushikdutta.async.http.socketio.JSONCallback; import com.koushikdutta.async.http.socketio.ReconnectCallback; import com.koushikdutta.async.http.socketio.SocketIOClient; import com.koushikdutta.async.http.socketio.SocketIORequest; import com.koushikdutta.async.http.socketio.StringCallback; import junit.framework.TestCase; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.concurrent.TimeUnit; public class SocketIOTests extends TestCase { public static final long TIMEOUT = 10000L; @Override protected void tearDown() throws Exception { super.tearDown(); AsyncServer.getDefault().stop(); } class TriggerFuture extends SimpleFuture<Boolean> { public void trigger(boolean val) { setComplete(val); } } public void testAcknowledge() throws Exception { final TriggerFuture trigger = new TriggerFuture(); SocketIOClient client = SocketIOClient.connect(AsyncHttpClient.getDefaultInstance(), "http://koush.clockworkmod.com:8080/", null).get(); client.emit("hello", new Acknowledge() { @Override public void acknowledge(JSONArray arguments) { trigger.trigger("hello".equals(arguments.optString(0))); } }); assertTrue(trigger.get(TIMEOUT, TimeUnit.MILLISECONDS)); } public void testSendAcknowledge() throws Exception { final TriggerFuture trigger = new TriggerFuture(); SocketIOClient client = SocketIOClient.connect(AsyncHttpClient.getDefaultInstance(), "http://koush.clockworkmod.com:8080/", null).get(); client.setStringCallback(new StringCallback() { boolean isEcho = true; @Override public void onString(String string, Acknowledge acknowledge) { if (!isEcho) { trigger.trigger("hello".equals(string)); return; } assertNotNull(acknowledge); isEcho = false; acknowledge.acknowledge(new JSONArray().put(string)); } }); client.emit("hello"); assertTrue(trigger.get(TIMEOUT, TimeUnit.MILLISECONDS)); } public void testEndpoint() throws Exception { final TriggerFuture trigger = new TriggerFuture(); SocketIOClient.connect(AsyncHttpClient.getDefaultInstance(), new SocketIORequest("http://koush.clockworkmod.com:8080/", "/chat"), new ConnectCallback() { @Override public void onConnectCompleted(Exception ex, SocketIOClient client) { assertNull(ex); client.setStringCallback(new StringCallback() { @Override public void onString(String string, Acknowledge acknowledge) { trigger.trigger("hello".equals(string)); } }); client.emit("hello"); } }); assertTrue(trigger.get(TIMEOUT, TimeUnit.MILLISECONDS)); } public void testEchoServer() throws Exception { final TriggerFuture trigger1 = new TriggerFuture(); final TriggerFuture trigger2 = new TriggerFuture(); final TriggerFuture trigger3 = new TriggerFuture(); SocketIORequest req = new SocketIORequest("http://koush.clockworkmod.com:8080"); req.setLogging("Socket.IO", Log.VERBOSE); SocketIOClient.connect(AsyncHttpClient.getDefaultInstance(), req, new ConnectCallback() { @Override public void onConnectCompleted(Exception ex, SocketIOClient client) { assertNull(ex); client.setStringCallback(new StringCallback() { @Override public void onString(String string, Acknowledge acknowledge) { trigger1.trigger("hello".equals(string)); } }); client.on("pong", new EventCallback() { @Override public void onEvent(JSONArray arguments, Acknowledge acknowledge) { trigger2.trigger(arguments.length() == 3); } }); client.setJSONCallback(new JSONCallback() { @Override public void onJSON(JSONObject json, Acknowledge acknowledge) { trigger3.trigger("world".equals(json.optString("hello"))); } }); try { client.emit("hello"); client.emit(new JSONObject("{\"hello\":\"world\"}")); client.emit("ping", new JSONArray("[2,3,4]")); } catch (JSONException e) { } } }); assertTrue(trigger1.get(TIMEOUT, TimeUnit.MILLISECONDS)); assertTrue(trigger2.get(TIMEOUT, TimeUnit.MILLISECONDS)); assertTrue(trigger3.get(TIMEOUT, TimeUnit.MILLISECONDS)); } public void testReconnect() throws Exception { final TriggerFuture disconnectTrigger = new TriggerFuture(); final TriggerFuture reconnectTrigger = new TriggerFuture(); final TriggerFuture endpointReconnectTrigger = new TriggerFuture(); final TriggerFuture echoTrigger = new TriggerFuture(); SocketIORequest req = new SocketIORequest("http://koush.clockworkmod.com:8080"); req.setLogging("socket.io", Log.VERBOSE); SocketIOClient.connect(AsyncHttpClient.getDefaultInstance(), req, new ConnectCallback() { @Override public void onConnectCompleted(Exception ex, final SocketIOClient client) { assertNull(ex); client.of("/chat", new ConnectCallback() { @Override public void onConnectCompleted(Exception ex, final SocketIOClient client) { client.setReconnectCallback(new ReconnectCallback() { @Override public void onReconnect() { client.emit("hello"); endpointReconnectTrigger.trigger(true); } }); client.setStringCallback(new StringCallback() { @Override public void onString(String string, Acknowledge acknowledge) { echoTrigger.trigger("hello".equals(string)); } }); AsyncServer.getDefault().postDelayed(new Runnable() { @Override public void run() { // this will trigger a reconnect - client.getWebSocket().close(); + client.getTransport().disconnect(); } }, 200); } }); client.setDisconnectCallback(new DisconnectCallback() { @Override public void onDisconnect(Exception e) { disconnectTrigger.trigger(true); } }); client.setReconnectCallback(new ReconnectCallback() { @Override public void onReconnect() { reconnectTrigger.trigger(true); } }); } }); assertTrue(disconnectTrigger.get(TIMEOUT, TimeUnit.MILLISECONDS)); assertTrue(reconnectTrigger.get(TIMEOUT, TimeUnit.MILLISECONDS)); assertTrue(endpointReconnectTrigger.get(TIMEOUT, TimeUnit.MILLISECONDS)); assertTrue(echoTrigger.get(TIMEOUT, TimeUnit.MILLISECONDS)); } public void testEventAck() throws Exception { final TriggerFuture trigger = new TriggerFuture(); SocketIOClient client = SocketIOClient.connect(AsyncHttpClient.getDefaultInstance(), "http://koush.clockworkmod.com:8080/", null).get(); final JSONArray args = new JSONArray(); args.put("echo"); client.on("scoop", new EventCallback() { @Override public void onEvent(JSONArray argument, Acknowledge acknowledge) { acknowledge.acknowledge(args); } }); client.on("ack", new EventCallback() { @Override public void onEvent(JSONArray argument, Acknowledge acknowledge) { trigger.trigger(args.optString(0, null).equals("echo")); } }); client.emit("poop", args); assertTrue(trigger.get(TIMEOUT, TimeUnit.MILLISECONDS)); } }
true
true
public void testReconnect() throws Exception { final TriggerFuture disconnectTrigger = new TriggerFuture(); final TriggerFuture reconnectTrigger = new TriggerFuture(); final TriggerFuture endpointReconnectTrigger = new TriggerFuture(); final TriggerFuture echoTrigger = new TriggerFuture(); SocketIORequest req = new SocketIORequest("http://koush.clockworkmod.com:8080"); req.setLogging("socket.io", Log.VERBOSE); SocketIOClient.connect(AsyncHttpClient.getDefaultInstance(), req, new ConnectCallback() { @Override public void onConnectCompleted(Exception ex, final SocketIOClient client) { assertNull(ex); client.of("/chat", new ConnectCallback() { @Override public void onConnectCompleted(Exception ex, final SocketIOClient client) { client.setReconnectCallback(new ReconnectCallback() { @Override public void onReconnect() { client.emit("hello"); endpointReconnectTrigger.trigger(true); } }); client.setStringCallback(new StringCallback() { @Override public void onString(String string, Acknowledge acknowledge) { echoTrigger.trigger("hello".equals(string)); } }); AsyncServer.getDefault().postDelayed(new Runnable() { @Override public void run() { // this will trigger a reconnect client.getWebSocket().close(); } }, 200); } }); client.setDisconnectCallback(new DisconnectCallback() { @Override public void onDisconnect(Exception e) { disconnectTrigger.trigger(true); } }); client.setReconnectCallback(new ReconnectCallback() { @Override public void onReconnect() { reconnectTrigger.trigger(true); } }); } }); assertTrue(disconnectTrigger.get(TIMEOUT, TimeUnit.MILLISECONDS)); assertTrue(reconnectTrigger.get(TIMEOUT, TimeUnit.MILLISECONDS)); assertTrue(endpointReconnectTrigger.get(TIMEOUT, TimeUnit.MILLISECONDS)); assertTrue(echoTrigger.get(TIMEOUT, TimeUnit.MILLISECONDS)); }
public void testReconnect() throws Exception { final TriggerFuture disconnectTrigger = new TriggerFuture(); final TriggerFuture reconnectTrigger = new TriggerFuture(); final TriggerFuture endpointReconnectTrigger = new TriggerFuture(); final TriggerFuture echoTrigger = new TriggerFuture(); SocketIORequest req = new SocketIORequest("http://koush.clockworkmod.com:8080"); req.setLogging("socket.io", Log.VERBOSE); SocketIOClient.connect(AsyncHttpClient.getDefaultInstance(), req, new ConnectCallback() { @Override public void onConnectCompleted(Exception ex, final SocketIOClient client) { assertNull(ex); client.of("/chat", new ConnectCallback() { @Override public void onConnectCompleted(Exception ex, final SocketIOClient client) { client.setReconnectCallback(new ReconnectCallback() { @Override public void onReconnect() { client.emit("hello"); endpointReconnectTrigger.trigger(true); } }); client.setStringCallback(new StringCallback() { @Override public void onString(String string, Acknowledge acknowledge) { echoTrigger.trigger("hello".equals(string)); } }); AsyncServer.getDefault().postDelayed(new Runnable() { @Override public void run() { // this will trigger a reconnect client.getTransport().disconnect(); } }, 200); } }); client.setDisconnectCallback(new DisconnectCallback() { @Override public void onDisconnect(Exception e) { disconnectTrigger.trigger(true); } }); client.setReconnectCallback(new ReconnectCallback() { @Override public void onReconnect() { reconnectTrigger.trigger(true); } }); } }); assertTrue(disconnectTrigger.get(TIMEOUT, TimeUnit.MILLISECONDS)); assertTrue(reconnectTrigger.get(TIMEOUT, TimeUnit.MILLISECONDS)); assertTrue(endpointReconnectTrigger.get(TIMEOUT, TimeUnit.MILLISECONDS)); assertTrue(echoTrigger.get(TIMEOUT, TimeUnit.MILLISECONDS)); }
diff --git a/src/services/combat/CombatCommands.java b/src/services/combat/CombatCommands.java index a0740570..d6cb5b25 100644 --- a/src/services/combat/CombatCommands.java +++ b/src/services/combat/CombatCommands.java @@ -1,722 +1,721 @@ /******************************************************************************* * Copyright (c) 2013 <Project SWG> * * This File is part of NGECore2. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Using NGEngine to work with NGECore2 is making a combined work based on NGEngine. * Therefore all terms and conditions of the GNU Lesser General Public License cover the combination. ******************************************************************************/ package services.combat; import main.NGECore; public class CombatCommands { public static void registerCommands(NGECore core) { // Auto Attacks core.commandService.registerCombatCommand("rangedshotrifle"); core.commandService.registerCombatCommand("rangedshotpistol"); core.commandService.registerCombatCommand("rangedshotlightrifle"); core.commandService.registerCombatCommand("rangedshot"); core.commandService.registerCombatCommand("meleehit"); core.commandService.registerCombatCommand("saberhit"); core.commandService.registerCombatCommand("fireAcidBeam"); core.commandService.registerCombatCommand("fireAcidBeamAvatar"); core.commandService.registerCombatCommand("fireAcidBeamHeavy"); core.commandService.registerCombatCommand("fireAcidRifle"); core.commandService.registerCombatCommand("fireCr1BlastCannon"); core.commandService.registerCombatCommand("fireCrusaderHeavyRifle"); core.commandService.registerCombatCommand("fireElitePistolLauncher"); core.commandService.registerCombatCommand("fireFlameThrowerLight"); core.commandService.registerCombatCommand("fireHeavyShotgun"); core.commandService.registerCombatCommand("fireHeavyWeapon"); core.commandService.registerCombatCommand("fireIceGun"); core.commandService.registerCombatCommand("fireLavaCannon"); //core.commandService.registerCombatCommand("fireLavaCannonGeneric"); core.commandService.registerCombatCommand("fireLightningBeam"); core.commandService.registerCombatCommand("fireParticleBeam"); core.commandService.registerCombatCommand("firePistolLauncher"); //core.commandService.registerCombatCommand("firePistolLauncherGeneric"); core.commandService.registerCombatCommand("firePistolLauncherMedium"); core.commandService.registerCombatCommand("firePistolLauncherTargeting"); core.commandService.registerCombatCommand("firePlasmaFlameThrower"); core.commandService.registerCombatCommand("firePulseCannon"); core.commandService.registerCombatCommand("firePvpHeavy"); core.commandService.registerCombatCommand("fireRepublicFlameThrower"); //core.commandService.registerCombatCommand("fireRepublicFlameThrowerGeneric"); core.commandService.registerCombatCommand("fireRocketLauncher"); //core.commandService.registerCombatCommand("fireRocketLauncherGeneric"); core.commandService.registerCombatCommand("fireStunCannon"); core.commandService.registerCombatCommand("fireVoidRocketLauncher"); // Bounty Hunter core.commandService.registerCombatCommand("bh_ae_dm_1"); core.commandService.registerCombatCommand("bh_ae_dm_2"); core.commandService.registerCombatCommand("bh_armor_sprint_1"); core.commandService.registerCombatCommand("bh_cover_1"); core.commandService.registerCombatCommand("bh_dm_1"); core.commandService.registerCombatCommand("bh_dm_2"); core.commandService.registerCombatCommand("bh_dm_3"); core.commandService.registerCombatCommand("bh_dm_4"); core.commandService.registerCombatCommand("bh_dm_5"); core.commandService.registerCombatCommand("bh_dm_6"); core.commandService.registerCombatCommand("bh_dm_7"); core.commandService.registerCombatCommand("bh_dm_8"); core.commandService.registerCombatCommand("bh_dm_cc_1"); core.commandService.registerCombatCommand("bh_dm_cc_2"); core.commandService.registerCombatCommand("bh_dm_cc_3"); core.commandService.registerCombatCommand("bh_dm_crit_1"); core.commandService.registerCombatCommand("bh_dm_crit_2"); core.commandService.registerCombatCommand("bh_dm_crit_3"); core.commandService.registerCombatCommand("bh_dm_crit_4"); core.commandService.registerCombatCommand("bh_dm_crit_5"); core.commandService.registerCombatCommand("bh_dm_crit_6"); core.commandService.registerCombatCommand("bh_dm_crit_7"); core.commandService.registerCombatCommand("bh_dm_crit_8"); core.commandService.registerCombatCommand("bh_dread_strike_1"); core.commandService.registerCombatCommand("bh_dread_strike_2"); core.commandService.registerCombatCommand("bh_dread_strike_3"); core.commandService.registerCombatCommand("bh_dread_strike_4"); core.commandService.registerCombatCommand("bh_dread_strike_5"); core.commandService.registerCombatCommand("bh_flawless_strike"); core.commandService.registerCombatCommand("bh_fumble_1"); core.commandService.registerCombatCommand("bh_fumble_2"); core.commandService.registerCombatCommand("bh_fumble_3"); core.commandService.registerCombatCommand("bh_fumble_4"); core.commandService.registerCombatCommand("bh_fumble_5"); core.commandService.registerCombatCommand("bh_fumble_6"); core.commandService.registerCombatCommand("bh_intimidate_1"); core.commandService.registerCombatCommand("bh_intimidate_2"); core.commandService.registerCombatCommand("bh_intimidate_3"); core.commandService.registerCombatCommand("bh_intimidate_4"); core.commandService.registerCombatCommand("bh_intimidate_5"); core.commandService.registerCombatCommand("bh_intimidate_6"); core.commandService.registerCombatCommand("bh_sniper_1"); core.commandService.registerCombatCommand("bh_sniper_2"); core.commandService.registerCombatCommand("bh_sniper_3"); core.commandService.registerCombatCommand("bh_sniper_4"); core.commandService.registerCombatCommand("bh_sniper_5"); core.commandService.registerCombatCommand("bh_sniper_6"); core.commandService.registerCombatCommand("bh_stun_1"); core.commandService.registerCombatCommand("bh_stun_2"); core.commandService.registerCombatCommand("bh_stun_3"); core.commandService.registerCombatCommand("bh_stun_4"); core.commandService.registerCombatCommand("bh_stun_5"); core.commandService.registerCombatCommand("bh_stun_6"); core.commandService.registerCombatCommand("bh_taunt_1"); core.commandService.registerCombatCommand("bh_taunt_2"); core.commandService.registerCombatCommand("bh_taunt_3"); core.commandService.registerCombatCommand("bh_taunt_4"); core.commandService.registerCombatCommand("bh_taunt_5"); core.commandService.registerCombatCommand("bh_taunt_6"); core.commandService.registerCombatCommand("bh_return_fire_command_1"); core.commandService.registerCombatCommand("bh_sh_0"); core.commandService.registerCombatCommand("bh_sh_1"); core.commandService.registerCombatCommand("bh_sh_2"); core.commandService.registerCombatCommand("bh_sh_3"); // Jedi core.commandService.registerCombatCommand("fs_sweep_1"); core.commandService.registerCombatCommand("fs_sweep_2"); core.commandService.registerCombatCommand("fs_sweep_3"); core.commandService.registerCombatCommand("fs_sweep_4"); core.commandService.registerCombatCommand("fs_sweep_5"); core.commandService.registerCombatCommand("fs_sweep_6"); core.commandService.registerCombatCommand("fs_sweep_7"); core.commandService.registerCombatCommand("fs_dm_1"); core.commandService.registerCombatCommand("fs_dm_2"); core.commandService.registerCombatCommand("fs_dm_3"); core.commandService.registerCombatCommand("fs_dm_4"); core.commandService.registerCombatCommand("fs_dm_5"); core.commandService.registerCombatCommand("fs_dm_6"); core.commandService.registerCombatCommand("fs_dm_7"); core.commandService.registerCombatCommand("fs_dm_cc_1"); core.commandService.registerCombatCommand("fs_dm_cc_2"); core.commandService.registerCombatCommand("fs_dm_cc_3"); core.commandService.registerCombatCommand("fs_dm_cc_4"); core.commandService.registerCombatCommand("fs_dm_cc_5"); core.commandService.registerCombatCommand("fs_dm_cc_6"); core.commandService.registerCombatCommand("fs_ae_dm_cc_1"); core.commandService.registerCombatCommand("fs_ae_dm_cc_2"); core.commandService.registerCombatCommand("fs_ae_dm_cc_3"); core.commandService.registerCombatCommand("fs_ae_dm_cc_4"); core.commandService.registerCombatCommand("fs_ae_dm_cc_5"); core.commandService.registerCombatCommand("fs_ae_dm_cc_6"); core.commandService.registerCombatCommand("forceThrow"); core.commandService.registerCombatCommand("fs_dm_cc_crit_1"); core.commandService.registerCombatCommand("fs_dm_cc_crit_2"); core.commandService.registerCombatCommand("fs_dm_cc_crit_3"); core.commandService.registerCombatCommand("fs_dm_cc_crit_4"); core.commandService.registerCombatCommand("fs_dm_cc_crit_5"); core.commandService.registerCombatCommand("fs_drain_1"); core.commandService.registerCombatCommand("fs_drain_2"); core.commandService.registerCombatCommand("fs_drain_3"); core.commandService.registerCombatCommand("fs_drain_4"); core.commandService.registerCombatCommand("fs_drain_5"); core.commandService.registerCombatCommand("fs_flurry_1"); core.commandService.registerCombatCommand("fs_flurry_2"); core.commandService.registerCombatCommand("fs_flurry_3"); core.commandService.registerCombatCommand("fs_flurry_4"); core.commandService.registerCombatCommand("fs_flurry_5"); core.commandService.registerCombatCommand("fs_flurry_6"); core.commandService.registerCombatCommand("fs_flurry_7"); core.commandService.registerCombatCommand("fs_maelstrom_1"); core.commandService.registerCombatCommand("fs_maelstrom_2"); core.commandService.registerCombatCommand("fs_maelstrom_3"); core.commandService.registerCombatCommand("fs_maelstrom_4"); core.commandService.registerCombatCommand("fs_maelstrom_5"); core.commandService.registerCombatCommand("fs_sh_0"); core.commandService.registerCombatCommand("fs_sh_1"); core.commandService.registerCombatCommand("fs_sh_2"); core.commandService.registerCombatCommand("fs_sh_3"); core.commandService.registerCommand("fs_buff_def_1_1"); // Stance core.commandService.registerCommand("fs_buff_ca_1"); // Focus core.commandService.registerCommand("fs_saber_reflect_buff"); // Saber Reflect core.commandService.registerCommand("saberBlock"); // Saber Block core.commandService.registerCommand("forcerun"); // Force Run core.commandService.registerCommand("fs_buff_invis_1"); // Force Cloak core.commandService.registerCombatCommand("fs_force_throw_1"); core.commandService.registerCommand("forceThrow"); // Commando core.commandService.registerCombatCommand("co_ae_dm_1"); core.commandService.registerCombatCommand("co_ae_dm_2"); core.commandService.registerCombatCommand("co_ae_dm_3"); core.commandService.registerCombatCommand("co_ae_hw_dot_acid_1"); core.commandService.registerCombatCommand("co_ae_hw_dot_acid_2"); core.commandService.registerCombatCommand("co_ae_hw_dot_acid_3"); core.commandService.registerCombatCommand("co_ae_hw_dot_acid_4"); core.commandService.registerCombatCommand("co_ae_hw_dot_acid_5"); core.commandService.registerCombatCommand("co_ae_hw_dot_cold_1"); core.commandService.registerCombatCommand("co_ae_hw_dot_cold_2"); core.commandService.registerCombatCommand("co_ae_hw_dot_cold_3"); core.commandService.registerCombatCommand("co_ae_hw_dot_cold_4"); core.commandService.registerCombatCommand("co_ae_hw_dot_cold_5"); core.commandService.registerCombatCommand("co_ae_hw_dot_electrical_1"); core.commandService.registerCombatCommand("co_ae_hw_dot_electrical_2"); core.commandService.registerCombatCommand("co_ae_hw_dot_electrical_3"); core.commandService.registerCombatCommand("co_ae_hw_dot_electrical_4"); core.commandService.registerCombatCommand("co_ae_hw_dot_electrical_5"); core.commandService.registerCombatCommand("co_ae_hw_dot_energy_1"); core.commandService.registerCombatCommand("co_ae_hw_dot_energy_2"); core.commandService.registerCombatCommand("co_ae_hw_dot_energy_3"); core.commandService.registerCombatCommand("co_ae_hw_dot_energy_4"); core.commandService.registerCombatCommand("co_ae_hw_dot_energy_5"); core.commandService.registerCombatCommand("co_ae_hw_dot_fire_1"); core.commandService.registerCombatCommand("co_ae_hw_dot_fire_2"); core.commandService.registerCombatCommand("co_ae_hw_dot_fire_3"); core.commandService.registerCombatCommand("co_ae_hw_dot_fire_4"); core.commandService.registerCombatCommand("co_ae_hw_dot_fire_5"); core.commandService.registerCombatCommand("co_ae_hw_dot_kinetic_1"); core.commandService.registerCombatCommand("co_ae_hw_dot_kinetic_2"); core.commandService.registerCombatCommand("co_ae_hw_dot_kinetic_3"); core.commandService.registerCombatCommand("co_ae_hw_dot_kinetic_4"); core.commandService.registerCombatCommand("co_ae_hw_dot_kinetic_5"); core.commandService.registerCombatCommand("co_armor_cracker"); //core.commandService.registerCombatCommand("co_cluster_bomb"); //core.commandService.registerCombatCommand("co_cluster_bomblet"); core.commandService.registerCombatCommand("co_del_ae_cc_1_1"); core.commandService.registerCombatCommand("co_del_ae_cc_1_2"); core.commandService.registerCombatCommand("co_del_ae_cc_1_3"); core.commandService.registerCombatCommand("co_del_ae_cc_2_1"); core.commandService.registerCombatCommand("co_del_ae_cc_2_2"); core.commandService.registerCombatCommand("co_del_ae_dm_1"); core.commandService.registerCombatCommand("co_del_ae_dm_2"); core.commandService.registerCombatCommand("co_del_ae_dm_3"); core.commandService.registerCombatCommand("co_dm_1"); core.commandService.registerCombatCommand("co_dm_2"); core.commandService.registerCombatCommand("co_dm_3"); core.commandService.registerCombatCommand("co_dm_4"); core.commandService.registerCombatCommand("co_dm_5"); core.commandService.registerCombatCommand("co_dm_6"); core.commandService.registerCombatCommand("co_dm_7"); core.commandService.registerCombatCommand("co_dm_8"); core.commandService.registerCombatCommand("co_fld_dm_1"); core.commandService.registerCombatCommand("co_fld_dm_2"); core.commandService.registerCombatCommand("co_hw_dm_1"); core.commandService.registerCombatCommand("co_hw_dm_2"); core.commandService.registerCombatCommand("co_hw_dm_3"); core.commandService.registerCombatCommand("co_hw_dm_4"); core.commandService.registerCombatCommand("co_hw_dm_5"); core.commandService.registerCombatCommand("co_hw_dm_6"); core.commandService.registerCombatCommand("co_hw_dm_crit_1"); core.commandService.registerCombatCommand("co_hw_dm_crit_2"); core.commandService.registerCombatCommand("co_hw_dm_crit_3"); core.commandService.registerCombatCommand("co_hw_dm_crit_4"); core.commandService.registerCombatCommand("co_hw_dm_crit_5"); core.commandService.registerCombatCommand("co_hw_dm_crit_6"); core.commandService.registerCombatCommand("co_hw_dot_acid_1"); core.commandService.registerCombatCommand("co_hw_dot_acid_2"); core.commandService.registerCombatCommand("co_hw_dot_acid_3"); core.commandService.registerCombatCommand("co_hw_dot_acid_4"); core.commandService.registerCombatCommand("co_hw_dot_acid_5"); core.commandService.registerCombatCommand("co_hw_dot_cold_1"); core.commandService.registerCombatCommand("co_hw_dot_cold_2"); core.commandService.registerCombatCommand("co_hw_dot_cold_3"); core.commandService.registerCombatCommand("co_hw_dot_cold_4"); core.commandService.registerCombatCommand("co_hw_dot_cold_5"); core.commandService.registerCombatCommand("co_hw_dot_electrical_1"); core.commandService.registerCombatCommand("co_hw_dot_electrical_2"); core.commandService.registerCombatCommand("co_hw_dot_electrical_3"); core.commandService.registerCombatCommand("co_hw_dot_electrical_4"); core.commandService.registerCombatCommand("co_hw_dot_electrical_5"); core.commandService.registerCombatCommand("co_hw_dot_energy_1"); core.commandService.registerCombatCommand("co_hw_dot_energy_2"); core.commandService.registerCombatCommand("co_hw_dot_energy_3"); core.commandService.registerCombatCommand("co_hw_dot_energy_4"); core.commandService.registerCombatCommand("co_hw_dot_energy_5"); core.commandService.registerCombatCommand("co_hw_dot_fire_1"); core.commandService.registerCombatCommand("co_hw_dot_fire_2"); core.commandService.registerCombatCommand("co_hw_dot_fire_3"); core.commandService.registerCombatCommand("co_hw_dot_fire_4"); core.commandService.registerCombatCommand("co_hw_dot_fire_5"); core.commandService.registerCombatCommand("co_hw_dot_kinetic_1"); core.commandService.registerCombatCommand("co_hw_dot_kinetic_2"); core.commandService.registerCombatCommand("co_hw_dot_kinetic_3"); core.commandService.registerCombatCommand("co_hw_dot_kinetic_4"); core.commandService.registerCombatCommand("co_hw_dot_kinetic_5"); core.commandService.registerCombatCommand("co_remote_detonator_1"); core.commandService.registerCombatCommand("co_remote_detonator_2"); core.commandService.registerCombatCommand("co_remote_detonator_3"); core.commandService.registerCombatCommand("co_remote_detonator_4"); core.commandService.registerCombatCommand("co_remote_detonator_5"); core.commandService.registerCombatCommand("co_remote_detonator_5"); core.commandService.registerCombatCommand("co_riddle_armor"); core.commandService.registerCombatCommand("co_suppressing_fire"); core.commandService.registerCombatCommand("co_sh_0"); core.commandService.registerCombatCommand("co_sh_1"); core.commandService.registerCombatCommand("co_sh_2"); core.commandService.registerCombatCommand("co_sh_3"); core.commandService.registerCombatCommand("co_stand_fast"); core.commandService.registerCommand("co_hw_dot"); core.commandService.registerCommand("co_ae_hw_dot"); core.commandService.registerCommand("co_position_secured"); core.commandService.registerCommand("co_first_aid_training"); // Entertainer core.commandService.registerCombatCommand("en_dm_1"); core.commandService.registerCombatCommand("en_dm_2"); core.commandService.registerCombatCommand("en_dm_3"); core.commandService.registerCombatCommand("en_dm_4"); core.commandService.registerCombatCommand("en_dm_5"); core.commandService.registerCombatCommand("en_dm_6"); core.commandService.registerCombatCommand("en_dm_7"); core.commandService.registerCombatCommand("en_dm_8"); core.commandService.registerCombatCommand("en_project_will_0"); core.commandService.registerCombatCommand("en_project_will_1"); core.commandService.registerCombatCommand("en_project_will_2"); core.commandService.registerCombatCommand("en_project_will_3"); core.commandService.registerCombatCommand("en_project_will_4"); core.commandService.registerCombatCommand("en_project_will_5"); core.commandService.registerCombatCommand("en_project_will_6"); core.commandService.registerCombatCommand("en_spiral_kick_0"); core.commandService.registerCombatCommand("en_spiral_kick_1"); core.commandService.registerCombatCommand("en_spiral_kick_2"); core.commandService.registerCombatCommand("en_spiral_kick_3"); core.commandService.registerCombatCommand("en_spiral_kick_4"); core.commandService.registerCombatCommand("en_strike_0"); core.commandService.registerCombatCommand("en_strike_1"); core.commandService.registerCombatCommand("en_strike_2"); core.commandService.registerCombatCommand("en_strike_3"); core.commandService.registerCombatCommand("en_strike_4"); core.commandService.registerCombatCommand("en_strike_5"); core.commandService.registerCombatCommand("en_strike_6"); core.commandService.registerCombatCommand("en_sweeping_pirouette_0"); core.commandService.registerCombatCommand("en_sweeping_pirouette_1"); core.commandService.registerCombatCommand("en_sweeping_pirouette_2"); core.commandService.registerCombatCommand("en_sweeping_pirouette_3"); core.commandService.registerCombatCommand("en_sweeping_pirouette_4"); core.commandService.registerCombatCommand("en_sweeping_pirouette_5"); core.commandService.registerCombatCommand("en_unhealthy_fixation"); core.commandService.registerCombatCommand("en_void_dance"); core.commandService.registerCombatCommand("en_void_dance_1"); core.commandService.registerCombatCommand("en_void_dance_2"); core.commandService.registerCombatCommand("en_void_dance_3"); core.commandService.registerCombatCommand("en_sh_1"); core.commandService.registerCombatCommand("en_sh_2"); core.commandService.registerCombatCommand("en_sh_3"); core.commandService.registerCombatCommand("en_heal_1"); core.commandService.registerCombatCommand("en_heal_2"); core.commandService.registerCombatCommand("en_heal_3"); core.commandService.registerCombatCommand("en_heal_4"); // Medic core.commandService.registerCombatCommand("me_ae_heal_1"); core.commandService.registerCombatCommand("me_ae_heal_2"); core.commandService.registerCombatCommand("me_ae_heal_3"); core.commandService.registerCombatCommand("me_ae_heal_4"); core.commandService.registerCombatCommand("me_ae_heal_5"); core.commandService.registerCombatCommand("me_ae_heal_6"); core.commandService.registerCombatCommand("me_bacta_ampule_1"); core.commandService.registerCombatCommand("me_bacta_ampule_2"); core.commandService.registerCombatCommand("me_bacta_ampule_3"); core.commandService.registerCombatCommand("me_bacta_ampule_4"); core.commandService.registerCombatCommand("me_bacta_ampule_5"); core.commandService.registerCombatCommand("me_bacta_ampule_6"); core.commandService.registerCombatCommand("me_bacta_bomb_1"); core.commandService.registerCombatCommand("me_bacta_bomb_2"); core.commandService.registerCombatCommand("me_bacta_bomb_3"); core.commandService.registerCombatCommand("me_bacta_bomb_4"); core.commandService.registerCombatCommand("me_bacta_bomb_5"); core.commandService.registerCombatCommand("me_bacta_grenade_1"); core.commandService.registerCombatCommand("me_bacta_grenade_2"); core.commandService.registerCombatCommand("me_bacta_grenade_3"); core.commandService.registerCombatCommand("me_bacta_grenade_4"); core.commandService.registerCombatCommand("me_bacta_grenade_5"); core.commandService.registerCombatCommand("me_bacta_resistance_1"); core.commandService.registerCombatCommand("me_burst_1"); core.commandService.registerCombatCommand("me_burst_2"); core.commandService.registerCombatCommand("me_burst_3"); core.commandService.registerCombatCommand("me_burst_4"); core.commandService.registerCombatCommand("me_burst_5"); core.commandService.registerCombatCommand("me_cranial_smash_1"); core.commandService.registerCombatCommand("me_cranial_smash_2"); core.commandService.registerCombatCommand("me_cranial_smash_3"); core.commandService.registerCombatCommand("me_cranial_smash_4"); core.commandService.registerCombatCommand("me_cranial_smash_5"); core.commandService.registerCommand("me_cure_affliction_1"); core.commandService.registerCombatCommand("me_dm_1"); core.commandService.registerCombatCommand("me_dm_2"); core.commandService.registerCombatCommand("me_dm_3"); core.commandService.registerCombatCommand("me_dm_4"); core.commandService.registerCombatCommand("me_dm_5"); core.commandService.registerCombatCommand("me_dm_6"); core.commandService.registerCombatCommand("me_dm_8"); core.commandService.registerCombatCommand("me_dm_dot_1"); core.commandService.registerCombatCommand("me_dm_dot_2"); core.commandService.registerCombatCommand("me_dm_dot_3"); core.commandService.registerCombatCommand("me_dm_dot_4"); core.commandService.registerCombatCommand("me_dm_dot_5"); core.commandService.registerCombatCommand("me_dm_dot_6"); core.commandService.registerCombatCommand("me_electrolyte_drain_1"); core.commandService.registerCombatCommand("me_fld_dm_dot_1"); core.commandService.registerCombatCommand("me_fld_dm_dot_2"); core.commandService.registerCombatCommand("me_fld_dm_dot_3"); core.commandService.registerCombatCommand("me_induce_insanity_1"); core.commandService.registerCombatCommand("me_rv_area"); core.commandService.registerCombatCommand("me_rv_combat"); core.commandService.registerCombatCommand("me_rv_ooc"); core.commandService.registerCombatCommand("me_rv_pvp_area"); core.commandService.registerCombatCommand("me_rv_pvp_single"); core.commandService.registerCommand("me_serotonin_boost_1"); core.commandService.registerCombatCommand("me_serotonin_purge_1"); core.commandService.registerCombatCommand("me_sh_1"); core.commandService.registerCommand("me_stasis_1"); core.commandService.registerCommand("me_stasis_self_1"); core.commandService.registerCombatCommand("me_thyroid_rupture_1"); core.commandService.registerCombatCommand("me_traumatize_1"); core.commandService.registerCombatCommand("me_traumatize_2"); core.commandService.registerCombatCommand("me_traumatize_3"); core.commandService.registerCombatCommand("me_traumatize_4"); core.commandService.registerCombatCommand("me_traumatize_5"); core.commandService.registerCombatCommand("me_stasis_1"); core.commandService.registerCommand("me_drag_1"); core.commandService.registerCommand("me_enhance_action_1"); core.commandService.registerCommand("me_reckless_stimulation_1"); core.commandService.registerCommand("me_reckless_stimulation_2"); core.commandService.registerCommand("me_reckless_stimulation_3"); core.commandService.registerCommand("me_reckless_stimulation_4"); core.commandService.registerCommand("me_reckless_stimulation_5"); core.commandService.registerCommand("me_reckless_stimulation_6"); - core.commandService.registerCommand("me_stasis_self_1"); core.commandService.registerCommand("me_buff_health_1"); core.commandService.registerCommand("me_buff_health_2"); core.commandService.registerCommand("me_buff_health_3"); core.commandService.registerCommand("me_enhance_action_1"); core.commandService.registerCommand("me_enhance_action_2"); core.commandService.registerCommand("me_enhance_action_3"); core.commandService.registerCommand("me_enhance_agility_1"); core.commandService.registerCommand("me_enhance_agility_2"); core.commandService.registerCommand("me_enhance_agility_3"); core.commandService.registerCommand("me_enhance_block_1"); core.commandService.registerCommand("me_enhance_dodge_1"); core.commandService.registerCommand("me_enhance_precision_1"); core.commandService.registerCommand("me_enhance_precision_2"); core.commandService.registerCommand("me_enhance_precision_3"); core.commandService.registerCommand("me_enhance_strength_1"); core.commandService.registerCommand("me_enhance_strength_2"); core.commandService.registerCommand("me_enhance_strength_3"); core.commandService.registerCommand("me_evasion_1"); // Officer core.commandService.registerCombatCommand("of_ae_dm_boss"); core.commandService.registerCombatCommand("of_ae_dm_cc_1"); core.commandService.registerCombatCommand("of_ae_dm_cc_2"); core.commandService.registerCombatCommand("of_ae_dm_cc_3"); core.commandService.registerCombatCommand("of_alt_ae_dm_1"); core.commandService.registerCombatCommand("of_alt_ae_dm_2"); core.commandService.registerCombatCommand("of_alt_ae_dm_3"); core.commandService.registerCombatCommand("of_deb_def_1"); core.commandService.registerCombatCommand("of_deb_def_2"); core.commandService.registerCombatCommand("of_deb_def_3"); core.commandService.registerCombatCommand("of_deb_def_4"); core.commandService.registerCombatCommand("of_deb_def_5"); core.commandService.registerCombatCommand("of_deb_def_6"); core.commandService.registerCombatCommand("of_deb_def_7"); core.commandService.registerCombatCommand("of_deb_def_8"); core.commandService.registerCombatCommand("of_decapitate_1"); core.commandService.registerCombatCommand("of_decapitate_2"); core.commandService.registerCombatCommand("of_decapitate_3"); core.commandService.registerCombatCommand("of_decapitate_4"); core.commandService.registerCombatCommand("of_decapitate_5"); core.commandService.registerCombatCommand("of_decapitate_6"); core.commandService.registerCombatCommand("of_del_ae_dm_1"); core.commandService.registerCombatCommand("of_del_ae_dm_2"); core.commandService.registerCombatCommand("of_del_ae_dm_3"); core.commandService.registerCombatCommand("of_del_ae_dm_boss"); core.commandService.registerCombatCommand("of_del_ae_dm_dot_1"); core.commandService.registerCombatCommand("of_del_ae_dm_dot_2"); core.commandService.registerCombatCommand("of_del_ae_dm_dot_3"); core.commandService.registerCombatCommand("of_del_ae_dot_1"); core.commandService.registerCombatCommand("of_dm_1"); core.commandService.registerCombatCommand("of_dm_2"); core.commandService.registerCombatCommand("of_dm_3"); core.commandService.registerCombatCommand("of_dm_4"); core.commandService.registerCombatCommand("of_dm_5"); core.commandService.registerCombatCommand("of_dm_6"); core.commandService.registerCombatCommand("of_dm_7"); core.commandService.registerCombatCommand("of_dm_8"); core.commandService.registerCombatCommand("of_dm_boss"); core.commandService.registerCombatCommand("of_leg_strike_1"); core.commandService.registerCombatCommand("of_leg_strike_2"); core.commandService.registerCombatCommand("of_leg_strike_3"); core.commandService.registerCombatCommand("of_leg_strike_4"); core.commandService.registerCombatCommand("of_leg_strike_5"); core.commandService.registerCombatCommand("of_leg_strike_6"); core.commandService.registerCombatCommand("of_leg_strike_7"); core.commandService.registerCombatCommand("of_pistol_bleed"); core.commandService.registerCombatCommand("of_pistol_dm"); core.commandService.registerCombatCommand("of_sh_0"); core.commandService.registerCombatCommand("of_sh_1"); core.commandService.registerCombatCommand("of_sh_2"); core.commandService.registerCombatCommand("of_sh_3"); core.commandService.registerCombatCommand("of_vortex_1"); core.commandService.registerCombatCommand("of_vortex_2"); core.commandService.registerCombatCommand("of_vortex_3"); core.commandService.registerCombatCommand("of_vortex_4"); core.commandService.registerCombatCommand("of_vortex_5"); core.commandService.registerCommand("of_charge_1"); core.commandService.registerCommand("of_inspiration_1"); core.commandService.registerCommand("of_inspiration_2"); core.commandService.registerCommand("of_inspiration_3"); core.commandService.registerCommand("of_inspiration_4"); core.commandService.registerCommand("of_inspiration_5"); core.commandService.registerCommand("of_inspiration_6"); core.commandService.registerCommand("of_focus_fire_1"); core.commandService.registerCommand("of_focus_fire_2"); core.commandService.registerCommand("of_focus_fire_3"); core.commandService.registerCommand("of_focus_fire_4"); core.commandService.registerCommand("of_focus_fire_5"); core.commandService.registerCommand("of_focus_fire_6"); core.commandService.registerCommand("of_drillmaster_1"); core.commandService.registerCommand("of_buff_def_1"); core.commandService.registerCommand("of_buff_def_2"); core.commandService.registerCommand("of_buff_def_3"); core.commandService.registerCommand("of_buff_def_4"); core.commandService.registerCommand("of_buff_def_5"); core.commandService.registerCommand("of_buff_def_6"); core.commandService.registerCommand("of_buff_def_7"); core.commandService.registerCommand("of_buff_def_8"); core.commandService.registerCommand("of_buff_def_9"); core.commandService.registerCommand("of_emergency_shield"); core.commandService.registerCommand("of_firepower_1"); core.commandService.registerCommand("of_medical_sup_1"); core.commandService.registerCommand("of_purge_1"); core.commandService.registerCommand("of_scatter_1"); core.commandService.registerCommand("of_stimulator_1"); // Smuggler core.commandService.registerCombatCommand("sm_ae_cover_fire"); core.commandService.registerCombatCommand("sm_ae_dm_1"); core.commandService.registerCombatCommand("sm_ae_dm_2"); core.commandService.registerCombatCommand("sm_ae_dm_3"); core.commandService.registerCombatCommand("sm_ae_dm_4"); core.commandService.registerCombatCommand("sm_ae_dm_5"); core.commandService.registerCombatCommand("sm_ae_dm_6"); core.commandService.registerCombatCommand("sm_ae_dm_cc_1"); core.commandService.registerCombatCommand("sm_ae_dm_cc_2"); core.commandService.registerCombatCommand("sm_ae_dm_cc_3"); core.commandService.registerCombatCommand("sm_ae_dm_cc_4"); core.commandService.registerCombatCommand("sm_ae_dm_cc_5"); core.commandService.registerCombatCommand("sm_ae_dm_cc_melee_1"); core.commandService.registerCombatCommand("sm_ae_dm_cc_melee_2"); core.commandService.registerCombatCommand("sm_ae_dm_cc_melee_3"); core.commandService.registerCombatCommand("sm_ae_dm_cc_melee_4"); core.commandService.registerCombatCommand("sm_ae_dm_cc_melee_5"); core.commandService.registerCombatCommand("sm_ae_dm_melee_1"); core.commandService.registerCombatCommand("sm_ae_dm_melee_2"); core.commandService.registerCombatCommand("sm_ae_dm_melee_3"); core.commandService.registerCombatCommand("sm_ae_dm_melee_4"); core.commandService.registerCombatCommand("sm_ae_dm_melee_5"); core.commandService.registerCombatCommand("sm_ae_dm_melee_6"); core.commandService.registerCombatCommand("sm_ae_pin_down"); core.commandService.registerCombatCommand("sm_bad_odds_1"); core.commandService.registerCombatCommand("sm_bad_odds_2"); core.commandService.registerCombatCommand("sm_bad_odds_3"); core.commandService.registerCombatCommand("sm_bad_odds_4"); core.commandService.registerCombatCommand("sm_bad_odds_5"); core.commandService.registerCombatCommand("sm_break_the_deal"); core.commandService.registerCombatCommand("sm_concussion_shot"); core.commandService.registerCombatCommand("sm_del_dm_cc_1"); core.commandService.registerCombatCommand("sm_del_dm_cc_2"); core.commandService.registerCombatCommand("sm_del_dm_cc_3"); core.commandService.registerCombatCommand("sm_del_dm_cc_4"); core.commandService.registerCombatCommand("sm_del_dm_cc_5"); core.commandService.registerCombatCommand("sm_del_dm_cc_6"); core.commandService.registerCombatCommand("sm_dizzy"); core.commandService.registerCombatCommand("sm_dm_1"); core.commandService.registerCombatCommand("sm_dm_2"); core.commandService.registerCombatCommand("sm_dm_3"); core.commandService.registerCombatCommand("sm_dm_4"); core.commandService.registerCombatCommand("sm_dm_5"); core.commandService.registerCombatCommand("sm_dm_6"); core.commandService.registerCombatCommand("sm_dm_7"); core.commandService.registerCombatCommand("sm_dm_cc_1"); core.commandService.registerCombatCommand("sm_dm_cc_2"); core.commandService.registerCombatCommand("sm_dm_cc_3"); core.commandService.registerCombatCommand("sm_dm_cc_4"); core.commandService.registerCombatCommand("sm_dm_cc_5"); core.commandService.registerCombatCommand("sm_dm_cc_6"); core.commandService.registerCombatCommand("sm_dm_cc_melee_1"); core.commandService.registerCombatCommand("sm_dm_cc_melee_2"); core.commandService.registerCombatCommand("sm_dm_cc_melee_3"); core.commandService.registerCombatCommand("sm_dm_cc_melee_4"); core.commandService.registerCombatCommand("sm_dm_cc_melee_5"); core.commandService.registerCombatCommand("sm_dm_cc_melee_6"); core.commandService.registerCombatCommand("sm_dm_dot_1"); core.commandService.registerCombatCommand("sm_dm_dot_2"); core.commandService.registerCombatCommand("sm_dm_dot_3"); core.commandService.registerCombatCommand("sm_dm_dot_4"); core.commandService.registerCombatCommand("sm_dm_dot_melee_1"); core.commandService.registerCombatCommand("sm_dm_dot_melee_2"); core.commandService.registerCombatCommand("sm_dm_dot_melee_3"); core.commandService.registerCombatCommand("sm_dm_dot_melee_4"); core.commandService.registerCombatCommand("sm_dm_melee_1"); core.commandService.registerCombatCommand("sm_dm_melee_2"); core.commandService.registerCombatCommand("sm_dm_melee_3"); core.commandService.registerCombatCommand("sm_dm_melee_4"); core.commandService.registerCombatCommand("sm_dm_melee_5"); core.commandService.registerCombatCommand("sm_dm_melee_6"); core.commandService.registerCombatCommand("sm_dm_melee_7"); core.commandService.registerCombatCommand("sm_false_hope"); core.commandService.registerCombatCommand("sm_fast_draw"); core.commandService.registerCombatCommand("sm_how_are_you"); core.commandService.registerCombatCommand("sm_impossible_odds"); core.commandService.registerCombatCommand("sm_inspect_cargo"); core.commandService.registerCombatCommand("sm_pistol_whip_1"); core.commandService.registerCombatCommand("sm_pistol_whip_2"); core.commandService.registerCombatCommand("sm_pistol_whip_3"); core.commandService.registerCombatCommand("sm_pistol_whip_4"); core.commandService.registerCombatCommand("sm_precision_strike"); core.commandService.registerCombatCommand("sm_sh_0"); core.commandService.registerCombatCommand("sm_sh_1"); core.commandService.registerCombatCommand("sm_sh_2"); core.commandService.registerCombatCommand("sm_sh_3"); core.commandService.registerCombatCommand("sm_shoot_first_1"); core.commandService.registerCombatCommand("sm_shoot_first_2"); core.commandService.registerCombatCommand("sm_shoot_first_3"); core.commandService.registerCombatCommand("sm_shoot_first_4"); core.commandService.registerCombatCommand("sm_shoot_first_5"); core.commandService.registerCombatCommand("sm_skullduggery"); core.commandService.registerCombatCommand("sm_sly_lie"); core.commandService.registerCombatCommand("sm_spot_a_sucker_1"); core.commandService.registerCombatCommand("sm_spot_a_sucker_2"); core.commandService.registerCombatCommand("sm_spot_a_sucker_3"); core.commandService.registerCombatCommand("sm_spot_a_sucker_4"); // Spy core.commandService.registerCombatCommand("sp_action_regen"); core.commandService.registerCombatCommand("sp_assassins_mark"); core.commandService.registerCombatCommand("sp_cc_dot"); core.commandService.registerCombatCommand("sp_dm_1"); core.commandService.registerCombatCommand("sp_dm_2"); core.commandService.registerCombatCommand("sp_dm_3"); core.commandService.registerCombatCommand("sp_dm_4"); core.commandService.registerCombatCommand("sp_dm_5"); core.commandService.registerCombatCommand("sp_dm_6"); core.commandService.registerCombatCommand("sp_dm_7"); core.commandService.registerCombatCommand("sp_dm_8"); core.commandService.registerCombatCommand("sp_dot_0"); core.commandService.registerCombatCommand("sp_dot_1"); core.commandService.registerCombatCommand("sp_dot_2"); core.commandService.registerCombatCommand("sp_dot_3"); core.commandService.registerCombatCommand("sp_dot_4"); core.commandService.registerCombatCommand("sp_dot_5"); core.commandService.registerCombatCommand("sp_fld_debuff_ca"); core.commandService.registerCombatCommand("sp_fldmot_1"); core.commandService.registerCombatCommand("sp_fldmot_1_snare"); core.commandService.registerCombatCommand("sp_fldmot_2"); core.commandService.registerCombatCommand("sp_fldmot_2_snare"); core.commandService.registerCombatCommand("sp_fldmot_3"); core.commandService.registerCombatCommand("sp_fldmot_3_snare"); core.commandService.registerCombatCommand("sp_hd_melee_0"); core.commandService.registerCombatCommand("sp_hd_melee_1"); core.commandService.registerCombatCommand("sp_hd_melee_2"); core.commandService.registerCombatCommand("sp_hd_melee_3"); core.commandService.registerCombatCommand("sp_hd_melee_4"); core.commandService.registerCombatCommand("sp_hd_melee_5"); core.commandService.registerCombatCommand("sp_hd_melee_6"); core.commandService.registerCombatCommand("sp_hd_range_0"); core.commandService.registerCombatCommand("sp_hd_range_1"); core.commandService.registerCombatCommand("sp_hd_range_2"); core.commandService.registerCombatCommand("sp_hd_range_3"); core.commandService.registerCombatCommand("sp_hd_range_4"); core.commandService.registerCombatCommand("sp_hd_range_5"); core.commandService.registerCombatCommand("sp_hd_range_6"); core.commandService.registerCombatCommand("sp_improved_cc_dot_0"); core.commandService.registerCombatCommand("sp_improved_cc_dot_1"); core.commandService.registerCombatCommand("sp_improved_cc_dot_2"); core.commandService.registerCombatCommand("sp_improved_cc_dot_3"); core.commandService.registerCombatCommand("sp_run_its_course"); core.commandService.registerCombatCommand("sp_sh_0"); core.commandService.registerCombatCommand("sp_sh_1"); core.commandService.registerCombatCommand("sp_sh_2"); core.commandService.registerCombatCommand("sp_sh_3"); core.commandService.registerCombatCommand("sp_shifty_setup"); core.commandService.registerCombatCommand("sp_stealth_melee_0"); core.commandService.registerCombatCommand("sp_stealth_melee_1"); core.commandService.registerCombatCommand("sp_stealth_melee_2"); core.commandService.registerCombatCommand("sp_stealth_melee_3"); core.commandService.registerCombatCommand("sp_stealth_melee_4"); core.commandService.registerCombatCommand("sp_stealth_melee_5"); core.commandService.registerCombatCommand("sp_stealth_melee_6"); core.commandService.registerCombatCommand("sp_stealth_ranged_0"); core.commandService.registerCombatCommand("sp_stealth_ranged_1"); core.commandService.registerCombatCommand("sp_stealth_ranged_2"); core.commandService.registerCombatCommand("sp_stealth_ranged_3"); core.commandService.registerCombatCommand("sp_stealth_ranged_4"); core.commandService.registerCombatCommand("sp_stealth_ranged_5"); core.commandService.registerCombatCommand("sp_stealth_ranged_6"); } }
true
true
public static void registerCommands(NGECore core) { // Auto Attacks core.commandService.registerCombatCommand("rangedshotrifle"); core.commandService.registerCombatCommand("rangedshotpistol"); core.commandService.registerCombatCommand("rangedshotlightrifle"); core.commandService.registerCombatCommand("rangedshot"); core.commandService.registerCombatCommand("meleehit"); core.commandService.registerCombatCommand("saberhit"); core.commandService.registerCombatCommand("fireAcidBeam"); core.commandService.registerCombatCommand("fireAcidBeamAvatar"); core.commandService.registerCombatCommand("fireAcidBeamHeavy"); core.commandService.registerCombatCommand("fireAcidRifle"); core.commandService.registerCombatCommand("fireCr1BlastCannon"); core.commandService.registerCombatCommand("fireCrusaderHeavyRifle"); core.commandService.registerCombatCommand("fireElitePistolLauncher"); core.commandService.registerCombatCommand("fireFlameThrowerLight"); core.commandService.registerCombatCommand("fireHeavyShotgun"); core.commandService.registerCombatCommand("fireHeavyWeapon"); core.commandService.registerCombatCommand("fireIceGun"); core.commandService.registerCombatCommand("fireLavaCannon"); //core.commandService.registerCombatCommand("fireLavaCannonGeneric"); core.commandService.registerCombatCommand("fireLightningBeam"); core.commandService.registerCombatCommand("fireParticleBeam"); core.commandService.registerCombatCommand("firePistolLauncher"); //core.commandService.registerCombatCommand("firePistolLauncherGeneric"); core.commandService.registerCombatCommand("firePistolLauncherMedium"); core.commandService.registerCombatCommand("firePistolLauncherTargeting"); core.commandService.registerCombatCommand("firePlasmaFlameThrower"); core.commandService.registerCombatCommand("firePulseCannon"); core.commandService.registerCombatCommand("firePvpHeavy"); core.commandService.registerCombatCommand("fireRepublicFlameThrower"); //core.commandService.registerCombatCommand("fireRepublicFlameThrowerGeneric"); core.commandService.registerCombatCommand("fireRocketLauncher"); //core.commandService.registerCombatCommand("fireRocketLauncherGeneric"); core.commandService.registerCombatCommand("fireStunCannon"); core.commandService.registerCombatCommand("fireVoidRocketLauncher"); // Bounty Hunter core.commandService.registerCombatCommand("bh_ae_dm_1"); core.commandService.registerCombatCommand("bh_ae_dm_2"); core.commandService.registerCombatCommand("bh_armor_sprint_1"); core.commandService.registerCombatCommand("bh_cover_1"); core.commandService.registerCombatCommand("bh_dm_1"); core.commandService.registerCombatCommand("bh_dm_2"); core.commandService.registerCombatCommand("bh_dm_3"); core.commandService.registerCombatCommand("bh_dm_4"); core.commandService.registerCombatCommand("bh_dm_5"); core.commandService.registerCombatCommand("bh_dm_6"); core.commandService.registerCombatCommand("bh_dm_7"); core.commandService.registerCombatCommand("bh_dm_8"); core.commandService.registerCombatCommand("bh_dm_cc_1"); core.commandService.registerCombatCommand("bh_dm_cc_2"); core.commandService.registerCombatCommand("bh_dm_cc_3"); core.commandService.registerCombatCommand("bh_dm_crit_1"); core.commandService.registerCombatCommand("bh_dm_crit_2"); core.commandService.registerCombatCommand("bh_dm_crit_3"); core.commandService.registerCombatCommand("bh_dm_crit_4"); core.commandService.registerCombatCommand("bh_dm_crit_5"); core.commandService.registerCombatCommand("bh_dm_crit_6"); core.commandService.registerCombatCommand("bh_dm_crit_7"); core.commandService.registerCombatCommand("bh_dm_crit_8"); core.commandService.registerCombatCommand("bh_dread_strike_1"); core.commandService.registerCombatCommand("bh_dread_strike_2"); core.commandService.registerCombatCommand("bh_dread_strike_3"); core.commandService.registerCombatCommand("bh_dread_strike_4"); core.commandService.registerCombatCommand("bh_dread_strike_5"); core.commandService.registerCombatCommand("bh_flawless_strike"); core.commandService.registerCombatCommand("bh_fumble_1"); core.commandService.registerCombatCommand("bh_fumble_2"); core.commandService.registerCombatCommand("bh_fumble_3"); core.commandService.registerCombatCommand("bh_fumble_4"); core.commandService.registerCombatCommand("bh_fumble_5"); core.commandService.registerCombatCommand("bh_fumble_6"); core.commandService.registerCombatCommand("bh_intimidate_1"); core.commandService.registerCombatCommand("bh_intimidate_2"); core.commandService.registerCombatCommand("bh_intimidate_3"); core.commandService.registerCombatCommand("bh_intimidate_4"); core.commandService.registerCombatCommand("bh_intimidate_5"); core.commandService.registerCombatCommand("bh_intimidate_6"); core.commandService.registerCombatCommand("bh_sniper_1"); core.commandService.registerCombatCommand("bh_sniper_2"); core.commandService.registerCombatCommand("bh_sniper_3"); core.commandService.registerCombatCommand("bh_sniper_4"); core.commandService.registerCombatCommand("bh_sniper_5"); core.commandService.registerCombatCommand("bh_sniper_6"); core.commandService.registerCombatCommand("bh_stun_1"); core.commandService.registerCombatCommand("bh_stun_2"); core.commandService.registerCombatCommand("bh_stun_3"); core.commandService.registerCombatCommand("bh_stun_4"); core.commandService.registerCombatCommand("bh_stun_5"); core.commandService.registerCombatCommand("bh_stun_6"); core.commandService.registerCombatCommand("bh_taunt_1"); core.commandService.registerCombatCommand("bh_taunt_2"); core.commandService.registerCombatCommand("bh_taunt_3"); core.commandService.registerCombatCommand("bh_taunt_4"); core.commandService.registerCombatCommand("bh_taunt_5"); core.commandService.registerCombatCommand("bh_taunt_6"); core.commandService.registerCombatCommand("bh_return_fire_command_1"); core.commandService.registerCombatCommand("bh_sh_0"); core.commandService.registerCombatCommand("bh_sh_1"); core.commandService.registerCombatCommand("bh_sh_2"); core.commandService.registerCombatCommand("bh_sh_3"); // Jedi core.commandService.registerCombatCommand("fs_sweep_1"); core.commandService.registerCombatCommand("fs_sweep_2"); core.commandService.registerCombatCommand("fs_sweep_3"); core.commandService.registerCombatCommand("fs_sweep_4"); core.commandService.registerCombatCommand("fs_sweep_5"); core.commandService.registerCombatCommand("fs_sweep_6"); core.commandService.registerCombatCommand("fs_sweep_7"); core.commandService.registerCombatCommand("fs_dm_1"); core.commandService.registerCombatCommand("fs_dm_2"); core.commandService.registerCombatCommand("fs_dm_3"); core.commandService.registerCombatCommand("fs_dm_4"); core.commandService.registerCombatCommand("fs_dm_5"); core.commandService.registerCombatCommand("fs_dm_6"); core.commandService.registerCombatCommand("fs_dm_7"); core.commandService.registerCombatCommand("fs_dm_cc_1"); core.commandService.registerCombatCommand("fs_dm_cc_2"); core.commandService.registerCombatCommand("fs_dm_cc_3"); core.commandService.registerCombatCommand("fs_dm_cc_4"); core.commandService.registerCombatCommand("fs_dm_cc_5"); core.commandService.registerCombatCommand("fs_dm_cc_6"); core.commandService.registerCombatCommand("fs_ae_dm_cc_1"); core.commandService.registerCombatCommand("fs_ae_dm_cc_2"); core.commandService.registerCombatCommand("fs_ae_dm_cc_3"); core.commandService.registerCombatCommand("fs_ae_dm_cc_4"); core.commandService.registerCombatCommand("fs_ae_dm_cc_5"); core.commandService.registerCombatCommand("fs_ae_dm_cc_6"); core.commandService.registerCombatCommand("forceThrow"); core.commandService.registerCombatCommand("fs_dm_cc_crit_1"); core.commandService.registerCombatCommand("fs_dm_cc_crit_2"); core.commandService.registerCombatCommand("fs_dm_cc_crit_3"); core.commandService.registerCombatCommand("fs_dm_cc_crit_4"); core.commandService.registerCombatCommand("fs_dm_cc_crit_5"); core.commandService.registerCombatCommand("fs_drain_1"); core.commandService.registerCombatCommand("fs_drain_2"); core.commandService.registerCombatCommand("fs_drain_3"); core.commandService.registerCombatCommand("fs_drain_4"); core.commandService.registerCombatCommand("fs_drain_5"); core.commandService.registerCombatCommand("fs_flurry_1"); core.commandService.registerCombatCommand("fs_flurry_2"); core.commandService.registerCombatCommand("fs_flurry_3"); core.commandService.registerCombatCommand("fs_flurry_4"); core.commandService.registerCombatCommand("fs_flurry_5"); core.commandService.registerCombatCommand("fs_flurry_6"); core.commandService.registerCombatCommand("fs_flurry_7"); core.commandService.registerCombatCommand("fs_maelstrom_1"); core.commandService.registerCombatCommand("fs_maelstrom_2"); core.commandService.registerCombatCommand("fs_maelstrom_3"); core.commandService.registerCombatCommand("fs_maelstrom_4"); core.commandService.registerCombatCommand("fs_maelstrom_5"); core.commandService.registerCombatCommand("fs_sh_0"); core.commandService.registerCombatCommand("fs_sh_1"); core.commandService.registerCombatCommand("fs_sh_2"); core.commandService.registerCombatCommand("fs_sh_3"); core.commandService.registerCommand("fs_buff_def_1_1"); // Stance core.commandService.registerCommand("fs_buff_ca_1"); // Focus core.commandService.registerCommand("fs_saber_reflect_buff"); // Saber Reflect core.commandService.registerCommand("saberBlock"); // Saber Block core.commandService.registerCommand("forcerun"); // Force Run core.commandService.registerCommand("fs_buff_invis_1"); // Force Cloak core.commandService.registerCombatCommand("fs_force_throw_1"); core.commandService.registerCommand("forceThrow"); // Commando core.commandService.registerCombatCommand("co_ae_dm_1"); core.commandService.registerCombatCommand("co_ae_dm_2"); core.commandService.registerCombatCommand("co_ae_dm_3"); core.commandService.registerCombatCommand("co_ae_hw_dot_acid_1"); core.commandService.registerCombatCommand("co_ae_hw_dot_acid_2"); core.commandService.registerCombatCommand("co_ae_hw_dot_acid_3"); core.commandService.registerCombatCommand("co_ae_hw_dot_acid_4"); core.commandService.registerCombatCommand("co_ae_hw_dot_acid_5"); core.commandService.registerCombatCommand("co_ae_hw_dot_cold_1"); core.commandService.registerCombatCommand("co_ae_hw_dot_cold_2"); core.commandService.registerCombatCommand("co_ae_hw_dot_cold_3"); core.commandService.registerCombatCommand("co_ae_hw_dot_cold_4"); core.commandService.registerCombatCommand("co_ae_hw_dot_cold_5"); core.commandService.registerCombatCommand("co_ae_hw_dot_electrical_1"); core.commandService.registerCombatCommand("co_ae_hw_dot_electrical_2"); core.commandService.registerCombatCommand("co_ae_hw_dot_electrical_3"); core.commandService.registerCombatCommand("co_ae_hw_dot_electrical_4"); core.commandService.registerCombatCommand("co_ae_hw_dot_electrical_5"); core.commandService.registerCombatCommand("co_ae_hw_dot_energy_1"); core.commandService.registerCombatCommand("co_ae_hw_dot_energy_2"); core.commandService.registerCombatCommand("co_ae_hw_dot_energy_3"); core.commandService.registerCombatCommand("co_ae_hw_dot_energy_4"); core.commandService.registerCombatCommand("co_ae_hw_dot_energy_5"); core.commandService.registerCombatCommand("co_ae_hw_dot_fire_1"); core.commandService.registerCombatCommand("co_ae_hw_dot_fire_2"); core.commandService.registerCombatCommand("co_ae_hw_dot_fire_3"); core.commandService.registerCombatCommand("co_ae_hw_dot_fire_4"); core.commandService.registerCombatCommand("co_ae_hw_dot_fire_5"); core.commandService.registerCombatCommand("co_ae_hw_dot_kinetic_1"); core.commandService.registerCombatCommand("co_ae_hw_dot_kinetic_2"); core.commandService.registerCombatCommand("co_ae_hw_dot_kinetic_3"); core.commandService.registerCombatCommand("co_ae_hw_dot_kinetic_4"); core.commandService.registerCombatCommand("co_ae_hw_dot_kinetic_5"); core.commandService.registerCombatCommand("co_armor_cracker"); //core.commandService.registerCombatCommand("co_cluster_bomb"); //core.commandService.registerCombatCommand("co_cluster_bomblet"); core.commandService.registerCombatCommand("co_del_ae_cc_1_1"); core.commandService.registerCombatCommand("co_del_ae_cc_1_2"); core.commandService.registerCombatCommand("co_del_ae_cc_1_3"); core.commandService.registerCombatCommand("co_del_ae_cc_2_1"); core.commandService.registerCombatCommand("co_del_ae_cc_2_2"); core.commandService.registerCombatCommand("co_del_ae_dm_1"); core.commandService.registerCombatCommand("co_del_ae_dm_2"); core.commandService.registerCombatCommand("co_del_ae_dm_3"); core.commandService.registerCombatCommand("co_dm_1"); core.commandService.registerCombatCommand("co_dm_2"); core.commandService.registerCombatCommand("co_dm_3"); core.commandService.registerCombatCommand("co_dm_4"); core.commandService.registerCombatCommand("co_dm_5"); core.commandService.registerCombatCommand("co_dm_6"); core.commandService.registerCombatCommand("co_dm_7"); core.commandService.registerCombatCommand("co_dm_8"); core.commandService.registerCombatCommand("co_fld_dm_1"); core.commandService.registerCombatCommand("co_fld_dm_2"); core.commandService.registerCombatCommand("co_hw_dm_1"); core.commandService.registerCombatCommand("co_hw_dm_2"); core.commandService.registerCombatCommand("co_hw_dm_3"); core.commandService.registerCombatCommand("co_hw_dm_4"); core.commandService.registerCombatCommand("co_hw_dm_5"); core.commandService.registerCombatCommand("co_hw_dm_6"); core.commandService.registerCombatCommand("co_hw_dm_crit_1"); core.commandService.registerCombatCommand("co_hw_dm_crit_2"); core.commandService.registerCombatCommand("co_hw_dm_crit_3"); core.commandService.registerCombatCommand("co_hw_dm_crit_4"); core.commandService.registerCombatCommand("co_hw_dm_crit_5"); core.commandService.registerCombatCommand("co_hw_dm_crit_6"); core.commandService.registerCombatCommand("co_hw_dot_acid_1"); core.commandService.registerCombatCommand("co_hw_dot_acid_2"); core.commandService.registerCombatCommand("co_hw_dot_acid_3"); core.commandService.registerCombatCommand("co_hw_dot_acid_4"); core.commandService.registerCombatCommand("co_hw_dot_acid_5"); core.commandService.registerCombatCommand("co_hw_dot_cold_1"); core.commandService.registerCombatCommand("co_hw_dot_cold_2"); core.commandService.registerCombatCommand("co_hw_dot_cold_3"); core.commandService.registerCombatCommand("co_hw_dot_cold_4"); core.commandService.registerCombatCommand("co_hw_dot_cold_5"); core.commandService.registerCombatCommand("co_hw_dot_electrical_1"); core.commandService.registerCombatCommand("co_hw_dot_electrical_2"); core.commandService.registerCombatCommand("co_hw_dot_electrical_3"); core.commandService.registerCombatCommand("co_hw_dot_electrical_4"); core.commandService.registerCombatCommand("co_hw_dot_electrical_5"); core.commandService.registerCombatCommand("co_hw_dot_energy_1"); core.commandService.registerCombatCommand("co_hw_dot_energy_2"); core.commandService.registerCombatCommand("co_hw_dot_energy_3"); core.commandService.registerCombatCommand("co_hw_dot_energy_4"); core.commandService.registerCombatCommand("co_hw_dot_energy_5"); core.commandService.registerCombatCommand("co_hw_dot_fire_1"); core.commandService.registerCombatCommand("co_hw_dot_fire_2"); core.commandService.registerCombatCommand("co_hw_dot_fire_3"); core.commandService.registerCombatCommand("co_hw_dot_fire_4"); core.commandService.registerCombatCommand("co_hw_dot_fire_5"); core.commandService.registerCombatCommand("co_hw_dot_kinetic_1"); core.commandService.registerCombatCommand("co_hw_dot_kinetic_2"); core.commandService.registerCombatCommand("co_hw_dot_kinetic_3"); core.commandService.registerCombatCommand("co_hw_dot_kinetic_4"); core.commandService.registerCombatCommand("co_hw_dot_kinetic_5"); core.commandService.registerCombatCommand("co_remote_detonator_1"); core.commandService.registerCombatCommand("co_remote_detonator_2"); core.commandService.registerCombatCommand("co_remote_detonator_3"); core.commandService.registerCombatCommand("co_remote_detonator_4"); core.commandService.registerCombatCommand("co_remote_detonator_5"); core.commandService.registerCombatCommand("co_remote_detonator_5"); core.commandService.registerCombatCommand("co_riddle_armor"); core.commandService.registerCombatCommand("co_suppressing_fire"); core.commandService.registerCombatCommand("co_sh_0"); core.commandService.registerCombatCommand("co_sh_1"); core.commandService.registerCombatCommand("co_sh_2"); core.commandService.registerCombatCommand("co_sh_3"); core.commandService.registerCombatCommand("co_stand_fast"); core.commandService.registerCommand("co_hw_dot"); core.commandService.registerCommand("co_ae_hw_dot"); core.commandService.registerCommand("co_position_secured"); core.commandService.registerCommand("co_first_aid_training"); // Entertainer core.commandService.registerCombatCommand("en_dm_1"); core.commandService.registerCombatCommand("en_dm_2"); core.commandService.registerCombatCommand("en_dm_3"); core.commandService.registerCombatCommand("en_dm_4"); core.commandService.registerCombatCommand("en_dm_5"); core.commandService.registerCombatCommand("en_dm_6"); core.commandService.registerCombatCommand("en_dm_7"); core.commandService.registerCombatCommand("en_dm_8"); core.commandService.registerCombatCommand("en_project_will_0"); core.commandService.registerCombatCommand("en_project_will_1"); core.commandService.registerCombatCommand("en_project_will_2"); core.commandService.registerCombatCommand("en_project_will_3"); core.commandService.registerCombatCommand("en_project_will_4"); core.commandService.registerCombatCommand("en_project_will_5"); core.commandService.registerCombatCommand("en_project_will_6"); core.commandService.registerCombatCommand("en_spiral_kick_0"); core.commandService.registerCombatCommand("en_spiral_kick_1"); core.commandService.registerCombatCommand("en_spiral_kick_2"); core.commandService.registerCombatCommand("en_spiral_kick_3"); core.commandService.registerCombatCommand("en_spiral_kick_4"); core.commandService.registerCombatCommand("en_strike_0"); core.commandService.registerCombatCommand("en_strike_1"); core.commandService.registerCombatCommand("en_strike_2"); core.commandService.registerCombatCommand("en_strike_3"); core.commandService.registerCombatCommand("en_strike_4"); core.commandService.registerCombatCommand("en_strike_5"); core.commandService.registerCombatCommand("en_strike_6"); core.commandService.registerCombatCommand("en_sweeping_pirouette_0"); core.commandService.registerCombatCommand("en_sweeping_pirouette_1"); core.commandService.registerCombatCommand("en_sweeping_pirouette_2"); core.commandService.registerCombatCommand("en_sweeping_pirouette_3"); core.commandService.registerCombatCommand("en_sweeping_pirouette_4"); core.commandService.registerCombatCommand("en_sweeping_pirouette_5"); core.commandService.registerCombatCommand("en_unhealthy_fixation"); core.commandService.registerCombatCommand("en_void_dance"); core.commandService.registerCombatCommand("en_void_dance_1"); core.commandService.registerCombatCommand("en_void_dance_2"); core.commandService.registerCombatCommand("en_void_dance_3"); core.commandService.registerCombatCommand("en_sh_1"); core.commandService.registerCombatCommand("en_sh_2"); core.commandService.registerCombatCommand("en_sh_3"); core.commandService.registerCombatCommand("en_heal_1"); core.commandService.registerCombatCommand("en_heal_2"); core.commandService.registerCombatCommand("en_heal_3"); core.commandService.registerCombatCommand("en_heal_4"); // Medic core.commandService.registerCombatCommand("me_ae_heal_1"); core.commandService.registerCombatCommand("me_ae_heal_2"); core.commandService.registerCombatCommand("me_ae_heal_3"); core.commandService.registerCombatCommand("me_ae_heal_4"); core.commandService.registerCombatCommand("me_ae_heal_5"); core.commandService.registerCombatCommand("me_ae_heal_6"); core.commandService.registerCombatCommand("me_bacta_ampule_1"); core.commandService.registerCombatCommand("me_bacta_ampule_2"); core.commandService.registerCombatCommand("me_bacta_ampule_3"); core.commandService.registerCombatCommand("me_bacta_ampule_4"); core.commandService.registerCombatCommand("me_bacta_ampule_5"); core.commandService.registerCombatCommand("me_bacta_ampule_6"); core.commandService.registerCombatCommand("me_bacta_bomb_1"); core.commandService.registerCombatCommand("me_bacta_bomb_2"); core.commandService.registerCombatCommand("me_bacta_bomb_3"); core.commandService.registerCombatCommand("me_bacta_bomb_4"); core.commandService.registerCombatCommand("me_bacta_bomb_5"); core.commandService.registerCombatCommand("me_bacta_grenade_1"); core.commandService.registerCombatCommand("me_bacta_grenade_2"); core.commandService.registerCombatCommand("me_bacta_grenade_3"); core.commandService.registerCombatCommand("me_bacta_grenade_4"); core.commandService.registerCombatCommand("me_bacta_grenade_5"); core.commandService.registerCombatCommand("me_bacta_resistance_1"); core.commandService.registerCombatCommand("me_burst_1"); core.commandService.registerCombatCommand("me_burst_2"); core.commandService.registerCombatCommand("me_burst_3"); core.commandService.registerCombatCommand("me_burst_4"); core.commandService.registerCombatCommand("me_burst_5"); core.commandService.registerCombatCommand("me_cranial_smash_1"); core.commandService.registerCombatCommand("me_cranial_smash_2"); core.commandService.registerCombatCommand("me_cranial_smash_3"); core.commandService.registerCombatCommand("me_cranial_smash_4"); core.commandService.registerCombatCommand("me_cranial_smash_5"); core.commandService.registerCommand("me_cure_affliction_1"); core.commandService.registerCombatCommand("me_dm_1"); core.commandService.registerCombatCommand("me_dm_2"); core.commandService.registerCombatCommand("me_dm_3"); core.commandService.registerCombatCommand("me_dm_4"); core.commandService.registerCombatCommand("me_dm_5"); core.commandService.registerCombatCommand("me_dm_6"); core.commandService.registerCombatCommand("me_dm_8"); core.commandService.registerCombatCommand("me_dm_dot_1"); core.commandService.registerCombatCommand("me_dm_dot_2"); core.commandService.registerCombatCommand("me_dm_dot_3"); core.commandService.registerCombatCommand("me_dm_dot_4"); core.commandService.registerCombatCommand("me_dm_dot_5"); core.commandService.registerCombatCommand("me_dm_dot_6"); core.commandService.registerCombatCommand("me_electrolyte_drain_1"); core.commandService.registerCombatCommand("me_fld_dm_dot_1"); core.commandService.registerCombatCommand("me_fld_dm_dot_2"); core.commandService.registerCombatCommand("me_fld_dm_dot_3"); core.commandService.registerCombatCommand("me_induce_insanity_1"); core.commandService.registerCombatCommand("me_rv_area"); core.commandService.registerCombatCommand("me_rv_combat"); core.commandService.registerCombatCommand("me_rv_ooc"); core.commandService.registerCombatCommand("me_rv_pvp_area"); core.commandService.registerCombatCommand("me_rv_pvp_single"); core.commandService.registerCommand("me_serotonin_boost_1"); core.commandService.registerCombatCommand("me_serotonin_purge_1"); core.commandService.registerCombatCommand("me_sh_1"); core.commandService.registerCommand("me_stasis_1"); core.commandService.registerCommand("me_stasis_self_1"); core.commandService.registerCombatCommand("me_thyroid_rupture_1"); core.commandService.registerCombatCommand("me_traumatize_1"); core.commandService.registerCombatCommand("me_traumatize_2"); core.commandService.registerCombatCommand("me_traumatize_3"); core.commandService.registerCombatCommand("me_traumatize_4"); core.commandService.registerCombatCommand("me_traumatize_5"); core.commandService.registerCombatCommand("me_stasis_1"); core.commandService.registerCommand("me_drag_1"); core.commandService.registerCommand("me_enhance_action_1"); core.commandService.registerCommand("me_reckless_stimulation_1"); core.commandService.registerCommand("me_reckless_stimulation_2"); core.commandService.registerCommand("me_reckless_stimulation_3"); core.commandService.registerCommand("me_reckless_stimulation_4"); core.commandService.registerCommand("me_reckless_stimulation_5"); core.commandService.registerCommand("me_reckless_stimulation_6"); core.commandService.registerCommand("me_stasis_self_1"); core.commandService.registerCommand("me_buff_health_1"); core.commandService.registerCommand("me_buff_health_2"); core.commandService.registerCommand("me_buff_health_3"); core.commandService.registerCommand("me_enhance_action_1"); core.commandService.registerCommand("me_enhance_action_2"); core.commandService.registerCommand("me_enhance_action_3"); core.commandService.registerCommand("me_enhance_agility_1"); core.commandService.registerCommand("me_enhance_agility_2"); core.commandService.registerCommand("me_enhance_agility_3"); core.commandService.registerCommand("me_enhance_block_1"); core.commandService.registerCommand("me_enhance_dodge_1"); core.commandService.registerCommand("me_enhance_precision_1"); core.commandService.registerCommand("me_enhance_precision_2"); core.commandService.registerCommand("me_enhance_precision_3"); core.commandService.registerCommand("me_enhance_strength_1"); core.commandService.registerCommand("me_enhance_strength_2"); core.commandService.registerCommand("me_enhance_strength_3"); core.commandService.registerCommand("me_evasion_1"); // Officer core.commandService.registerCombatCommand("of_ae_dm_boss"); core.commandService.registerCombatCommand("of_ae_dm_cc_1"); core.commandService.registerCombatCommand("of_ae_dm_cc_2"); core.commandService.registerCombatCommand("of_ae_dm_cc_3"); core.commandService.registerCombatCommand("of_alt_ae_dm_1"); core.commandService.registerCombatCommand("of_alt_ae_dm_2"); core.commandService.registerCombatCommand("of_alt_ae_dm_3"); core.commandService.registerCombatCommand("of_deb_def_1"); core.commandService.registerCombatCommand("of_deb_def_2"); core.commandService.registerCombatCommand("of_deb_def_3"); core.commandService.registerCombatCommand("of_deb_def_4"); core.commandService.registerCombatCommand("of_deb_def_5"); core.commandService.registerCombatCommand("of_deb_def_6"); core.commandService.registerCombatCommand("of_deb_def_7"); core.commandService.registerCombatCommand("of_deb_def_8"); core.commandService.registerCombatCommand("of_decapitate_1"); core.commandService.registerCombatCommand("of_decapitate_2"); core.commandService.registerCombatCommand("of_decapitate_3"); core.commandService.registerCombatCommand("of_decapitate_4"); core.commandService.registerCombatCommand("of_decapitate_5"); core.commandService.registerCombatCommand("of_decapitate_6"); core.commandService.registerCombatCommand("of_del_ae_dm_1"); core.commandService.registerCombatCommand("of_del_ae_dm_2"); core.commandService.registerCombatCommand("of_del_ae_dm_3"); core.commandService.registerCombatCommand("of_del_ae_dm_boss"); core.commandService.registerCombatCommand("of_del_ae_dm_dot_1"); core.commandService.registerCombatCommand("of_del_ae_dm_dot_2"); core.commandService.registerCombatCommand("of_del_ae_dm_dot_3"); core.commandService.registerCombatCommand("of_del_ae_dot_1"); core.commandService.registerCombatCommand("of_dm_1"); core.commandService.registerCombatCommand("of_dm_2"); core.commandService.registerCombatCommand("of_dm_3"); core.commandService.registerCombatCommand("of_dm_4"); core.commandService.registerCombatCommand("of_dm_5"); core.commandService.registerCombatCommand("of_dm_6"); core.commandService.registerCombatCommand("of_dm_7"); core.commandService.registerCombatCommand("of_dm_8"); core.commandService.registerCombatCommand("of_dm_boss"); core.commandService.registerCombatCommand("of_leg_strike_1"); core.commandService.registerCombatCommand("of_leg_strike_2"); core.commandService.registerCombatCommand("of_leg_strike_3"); core.commandService.registerCombatCommand("of_leg_strike_4"); core.commandService.registerCombatCommand("of_leg_strike_5"); core.commandService.registerCombatCommand("of_leg_strike_6"); core.commandService.registerCombatCommand("of_leg_strike_7"); core.commandService.registerCombatCommand("of_pistol_bleed"); core.commandService.registerCombatCommand("of_pistol_dm"); core.commandService.registerCombatCommand("of_sh_0"); core.commandService.registerCombatCommand("of_sh_1"); core.commandService.registerCombatCommand("of_sh_2"); core.commandService.registerCombatCommand("of_sh_3"); core.commandService.registerCombatCommand("of_vortex_1"); core.commandService.registerCombatCommand("of_vortex_2"); core.commandService.registerCombatCommand("of_vortex_3"); core.commandService.registerCombatCommand("of_vortex_4"); core.commandService.registerCombatCommand("of_vortex_5"); core.commandService.registerCommand("of_charge_1"); core.commandService.registerCommand("of_inspiration_1"); core.commandService.registerCommand("of_inspiration_2"); core.commandService.registerCommand("of_inspiration_3"); core.commandService.registerCommand("of_inspiration_4"); core.commandService.registerCommand("of_inspiration_5"); core.commandService.registerCommand("of_inspiration_6"); core.commandService.registerCommand("of_focus_fire_1"); core.commandService.registerCommand("of_focus_fire_2"); core.commandService.registerCommand("of_focus_fire_3"); core.commandService.registerCommand("of_focus_fire_4"); core.commandService.registerCommand("of_focus_fire_5"); core.commandService.registerCommand("of_focus_fire_6"); core.commandService.registerCommand("of_drillmaster_1"); core.commandService.registerCommand("of_buff_def_1"); core.commandService.registerCommand("of_buff_def_2"); core.commandService.registerCommand("of_buff_def_3"); core.commandService.registerCommand("of_buff_def_4"); core.commandService.registerCommand("of_buff_def_5"); core.commandService.registerCommand("of_buff_def_6"); core.commandService.registerCommand("of_buff_def_7"); core.commandService.registerCommand("of_buff_def_8"); core.commandService.registerCommand("of_buff_def_9"); core.commandService.registerCommand("of_emergency_shield"); core.commandService.registerCommand("of_firepower_1"); core.commandService.registerCommand("of_medical_sup_1"); core.commandService.registerCommand("of_purge_1"); core.commandService.registerCommand("of_scatter_1"); core.commandService.registerCommand("of_stimulator_1"); // Smuggler core.commandService.registerCombatCommand("sm_ae_cover_fire"); core.commandService.registerCombatCommand("sm_ae_dm_1"); core.commandService.registerCombatCommand("sm_ae_dm_2"); core.commandService.registerCombatCommand("sm_ae_dm_3"); core.commandService.registerCombatCommand("sm_ae_dm_4"); core.commandService.registerCombatCommand("sm_ae_dm_5"); core.commandService.registerCombatCommand("sm_ae_dm_6"); core.commandService.registerCombatCommand("sm_ae_dm_cc_1"); core.commandService.registerCombatCommand("sm_ae_dm_cc_2"); core.commandService.registerCombatCommand("sm_ae_dm_cc_3"); core.commandService.registerCombatCommand("sm_ae_dm_cc_4"); core.commandService.registerCombatCommand("sm_ae_dm_cc_5"); core.commandService.registerCombatCommand("sm_ae_dm_cc_melee_1"); core.commandService.registerCombatCommand("sm_ae_dm_cc_melee_2"); core.commandService.registerCombatCommand("sm_ae_dm_cc_melee_3"); core.commandService.registerCombatCommand("sm_ae_dm_cc_melee_4"); core.commandService.registerCombatCommand("sm_ae_dm_cc_melee_5"); core.commandService.registerCombatCommand("sm_ae_dm_melee_1"); core.commandService.registerCombatCommand("sm_ae_dm_melee_2"); core.commandService.registerCombatCommand("sm_ae_dm_melee_3"); core.commandService.registerCombatCommand("sm_ae_dm_melee_4"); core.commandService.registerCombatCommand("sm_ae_dm_melee_5"); core.commandService.registerCombatCommand("sm_ae_dm_melee_6"); core.commandService.registerCombatCommand("sm_ae_pin_down"); core.commandService.registerCombatCommand("sm_bad_odds_1"); core.commandService.registerCombatCommand("sm_bad_odds_2"); core.commandService.registerCombatCommand("sm_bad_odds_3"); core.commandService.registerCombatCommand("sm_bad_odds_4"); core.commandService.registerCombatCommand("sm_bad_odds_5"); core.commandService.registerCombatCommand("sm_break_the_deal"); core.commandService.registerCombatCommand("sm_concussion_shot"); core.commandService.registerCombatCommand("sm_del_dm_cc_1"); core.commandService.registerCombatCommand("sm_del_dm_cc_2"); core.commandService.registerCombatCommand("sm_del_dm_cc_3"); core.commandService.registerCombatCommand("sm_del_dm_cc_4"); core.commandService.registerCombatCommand("sm_del_dm_cc_5"); core.commandService.registerCombatCommand("sm_del_dm_cc_6"); core.commandService.registerCombatCommand("sm_dizzy"); core.commandService.registerCombatCommand("sm_dm_1"); core.commandService.registerCombatCommand("sm_dm_2"); core.commandService.registerCombatCommand("sm_dm_3"); core.commandService.registerCombatCommand("sm_dm_4"); core.commandService.registerCombatCommand("sm_dm_5"); core.commandService.registerCombatCommand("sm_dm_6"); core.commandService.registerCombatCommand("sm_dm_7"); core.commandService.registerCombatCommand("sm_dm_cc_1"); core.commandService.registerCombatCommand("sm_dm_cc_2"); core.commandService.registerCombatCommand("sm_dm_cc_3"); core.commandService.registerCombatCommand("sm_dm_cc_4"); core.commandService.registerCombatCommand("sm_dm_cc_5"); core.commandService.registerCombatCommand("sm_dm_cc_6"); core.commandService.registerCombatCommand("sm_dm_cc_melee_1"); core.commandService.registerCombatCommand("sm_dm_cc_melee_2"); core.commandService.registerCombatCommand("sm_dm_cc_melee_3"); core.commandService.registerCombatCommand("sm_dm_cc_melee_4"); core.commandService.registerCombatCommand("sm_dm_cc_melee_5"); core.commandService.registerCombatCommand("sm_dm_cc_melee_6"); core.commandService.registerCombatCommand("sm_dm_dot_1"); core.commandService.registerCombatCommand("sm_dm_dot_2"); core.commandService.registerCombatCommand("sm_dm_dot_3"); core.commandService.registerCombatCommand("sm_dm_dot_4"); core.commandService.registerCombatCommand("sm_dm_dot_melee_1"); core.commandService.registerCombatCommand("sm_dm_dot_melee_2"); core.commandService.registerCombatCommand("sm_dm_dot_melee_3"); core.commandService.registerCombatCommand("sm_dm_dot_melee_4"); core.commandService.registerCombatCommand("sm_dm_melee_1"); core.commandService.registerCombatCommand("sm_dm_melee_2"); core.commandService.registerCombatCommand("sm_dm_melee_3"); core.commandService.registerCombatCommand("sm_dm_melee_4"); core.commandService.registerCombatCommand("sm_dm_melee_5"); core.commandService.registerCombatCommand("sm_dm_melee_6"); core.commandService.registerCombatCommand("sm_dm_melee_7"); core.commandService.registerCombatCommand("sm_false_hope"); core.commandService.registerCombatCommand("sm_fast_draw"); core.commandService.registerCombatCommand("sm_how_are_you"); core.commandService.registerCombatCommand("sm_impossible_odds"); core.commandService.registerCombatCommand("sm_inspect_cargo"); core.commandService.registerCombatCommand("sm_pistol_whip_1"); core.commandService.registerCombatCommand("sm_pistol_whip_2"); core.commandService.registerCombatCommand("sm_pistol_whip_3"); core.commandService.registerCombatCommand("sm_pistol_whip_4"); core.commandService.registerCombatCommand("sm_precision_strike"); core.commandService.registerCombatCommand("sm_sh_0"); core.commandService.registerCombatCommand("sm_sh_1"); core.commandService.registerCombatCommand("sm_sh_2"); core.commandService.registerCombatCommand("sm_sh_3"); core.commandService.registerCombatCommand("sm_shoot_first_1"); core.commandService.registerCombatCommand("sm_shoot_first_2"); core.commandService.registerCombatCommand("sm_shoot_first_3"); core.commandService.registerCombatCommand("sm_shoot_first_4"); core.commandService.registerCombatCommand("sm_shoot_first_5"); core.commandService.registerCombatCommand("sm_skullduggery"); core.commandService.registerCombatCommand("sm_sly_lie"); core.commandService.registerCombatCommand("sm_spot_a_sucker_1"); core.commandService.registerCombatCommand("sm_spot_a_sucker_2"); core.commandService.registerCombatCommand("sm_spot_a_sucker_3"); core.commandService.registerCombatCommand("sm_spot_a_sucker_4"); // Spy core.commandService.registerCombatCommand("sp_action_regen"); core.commandService.registerCombatCommand("sp_assassins_mark"); core.commandService.registerCombatCommand("sp_cc_dot"); core.commandService.registerCombatCommand("sp_dm_1"); core.commandService.registerCombatCommand("sp_dm_2"); core.commandService.registerCombatCommand("sp_dm_3"); core.commandService.registerCombatCommand("sp_dm_4"); core.commandService.registerCombatCommand("sp_dm_5"); core.commandService.registerCombatCommand("sp_dm_6"); core.commandService.registerCombatCommand("sp_dm_7"); core.commandService.registerCombatCommand("sp_dm_8"); core.commandService.registerCombatCommand("sp_dot_0"); core.commandService.registerCombatCommand("sp_dot_1"); core.commandService.registerCombatCommand("sp_dot_2"); core.commandService.registerCombatCommand("sp_dot_3"); core.commandService.registerCombatCommand("sp_dot_4"); core.commandService.registerCombatCommand("sp_dot_5"); core.commandService.registerCombatCommand("sp_fld_debuff_ca"); core.commandService.registerCombatCommand("sp_fldmot_1"); core.commandService.registerCombatCommand("sp_fldmot_1_snare"); core.commandService.registerCombatCommand("sp_fldmot_2"); core.commandService.registerCombatCommand("sp_fldmot_2_snare"); core.commandService.registerCombatCommand("sp_fldmot_3"); core.commandService.registerCombatCommand("sp_fldmot_3_snare"); core.commandService.registerCombatCommand("sp_hd_melee_0"); core.commandService.registerCombatCommand("sp_hd_melee_1"); core.commandService.registerCombatCommand("sp_hd_melee_2"); core.commandService.registerCombatCommand("sp_hd_melee_3"); core.commandService.registerCombatCommand("sp_hd_melee_4"); core.commandService.registerCombatCommand("sp_hd_melee_5"); core.commandService.registerCombatCommand("sp_hd_melee_6"); core.commandService.registerCombatCommand("sp_hd_range_0"); core.commandService.registerCombatCommand("sp_hd_range_1"); core.commandService.registerCombatCommand("sp_hd_range_2"); core.commandService.registerCombatCommand("sp_hd_range_3"); core.commandService.registerCombatCommand("sp_hd_range_4"); core.commandService.registerCombatCommand("sp_hd_range_5"); core.commandService.registerCombatCommand("sp_hd_range_6"); core.commandService.registerCombatCommand("sp_improved_cc_dot_0"); core.commandService.registerCombatCommand("sp_improved_cc_dot_1"); core.commandService.registerCombatCommand("sp_improved_cc_dot_2"); core.commandService.registerCombatCommand("sp_improved_cc_dot_3"); core.commandService.registerCombatCommand("sp_run_its_course"); core.commandService.registerCombatCommand("sp_sh_0"); core.commandService.registerCombatCommand("sp_sh_1"); core.commandService.registerCombatCommand("sp_sh_2"); core.commandService.registerCombatCommand("sp_sh_3"); core.commandService.registerCombatCommand("sp_shifty_setup"); core.commandService.registerCombatCommand("sp_stealth_melee_0"); core.commandService.registerCombatCommand("sp_stealth_melee_1"); core.commandService.registerCombatCommand("sp_stealth_melee_2"); core.commandService.registerCombatCommand("sp_stealth_melee_3"); core.commandService.registerCombatCommand("sp_stealth_melee_4"); core.commandService.registerCombatCommand("sp_stealth_melee_5"); core.commandService.registerCombatCommand("sp_stealth_melee_6"); core.commandService.registerCombatCommand("sp_stealth_ranged_0"); core.commandService.registerCombatCommand("sp_stealth_ranged_1"); core.commandService.registerCombatCommand("sp_stealth_ranged_2"); core.commandService.registerCombatCommand("sp_stealth_ranged_3"); core.commandService.registerCombatCommand("sp_stealth_ranged_4"); core.commandService.registerCombatCommand("sp_stealth_ranged_5"); core.commandService.registerCombatCommand("sp_stealth_ranged_6"); }
public static void registerCommands(NGECore core) { // Auto Attacks core.commandService.registerCombatCommand("rangedshotrifle"); core.commandService.registerCombatCommand("rangedshotpistol"); core.commandService.registerCombatCommand("rangedshotlightrifle"); core.commandService.registerCombatCommand("rangedshot"); core.commandService.registerCombatCommand("meleehit"); core.commandService.registerCombatCommand("saberhit"); core.commandService.registerCombatCommand("fireAcidBeam"); core.commandService.registerCombatCommand("fireAcidBeamAvatar"); core.commandService.registerCombatCommand("fireAcidBeamHeavy"); core.commandService.registerCombatCommand("fireAcidRifle"); core.commandService.registerCombatCommand("fireCr1BlastCannon"); core.commandService.registerCombatCommand("fireCrusaderHeavyRifle"); core.commandService.registerCombatCommand("fireElitePistolLauncher"); core.commandService.registerCombatCommand("fireFlameThrowerLight"); core.commandService.registerCombatCommand("fireHeavyShotgun"); core.commandService.registerCombatCommand("fireHeavyWeapon"); core.commandService.registerCombatCommand("fireIceGun"); core.commandService.registerCombatCommand("fireLavaCannon"); //core.commandService.registerCombatCommand("fireLavaCannonGeneric"); core.commandService.registerCombatCommand("fireLightningBeam"); core.commandService.registerCombatCommand("fireParticleBeam"); core.commandService.registerCombatCommand("firePistolLauncher"); //core.commandService.registerCombatCommand("firePistolLauncherGeneric"); core.commandService.registerCombatCommand("firePistolLauncherMedium"); core.commandService.registerCombatCommand("firePistolLauncherTargeting"); core.commandService.registerCombatCommand("firePlasmaFlameThrower"); core.commandService.registerCombatCommand("firePulseCannon"); core.commandService.registerCombatCommand("firePvpHeavy"); core.commandService.registerCombatCommand("fireRepublicFlameThrower"); //core.commandService.registerCombatCommand("fireRepublicFlameThrowerGeneric"); core.commandService.registerCombatCommand("fireRocketLauncher"); //core.commandService.registerCombatCommand("fireRocketLauncherGeneric"); core.commandService.registerCombatCommand("fireStunCannon"); core.commandService.registerCombatCommand("fireVoidRocketLauncher"); // Bounty Hunter core.commandService.registerCombatCommand("bh_ae_dm_1"); core.commandService.registerCombatCommand("bh_ae_dm_2"); core.commandService.registerCombatCommand("bh_armor_sprint_1"); core.commandService.registerCombatCommand("bh_cover_1"); core.commandService.registerCombatCommand("bh_dm_1"); core.commandService.registerCombatCommand("bh_dm_2"); core.commandService.registerCombatCommand("bh_dm_3"); core.commandService.registerCombatCommand("bh_dm_4"); core.commandService.registerCombatCommand("bh_dm_5"); core.commandService.registerCombatCommand("bh_dm_6"); core.commandService.registerCombatCommand("bh_dm_7"); core.commandService.registerCombatCommand("bh_dm_8"); core.commandService.registerCombatCommand("bh_dm_cc_1"); core.commandService.registerCombatCommand("bh_dm_cc_2"); core.commandService.registerCombatCommand("bh_dm_cc_3"); core.commandService.registerCombatCommand("bh_dm_crit_1"); core.commandService.registerCombatCommand("bh_dm_crit_2"); core.commandService.registerCombatCommand("bh_dm_crit_3"); core.commandService.registerCombatCommand("bh_dm_crit_4"); core.commandService.registerCombatCommand("bh_dm_crit_5"); core.commandService.registerCombatCommand("bh_dm_crit_6"); core.commandService.registerCombatCommand("bh_dm_crit_7"); core.commandService.registerCombatCommand("bh_dm_crit_8"); core.commandService.registerCombatCommand("bh_dread_strike_1"); core.commandService.registerCombatCommand("bh_dread_strike_2"); core.commandService.registerCombatCommand("bh_dread_strike_3"); core.commandService.registerCombatCommand("bh_dread_strike_4"); core.commandService.registerCombatCommand("bh_dread_strike_5"); core.commandService.registerCombatCommand("bh_flawless_strike"); core.commandService.registerCombatCommand("bh_fumble_1"); core.commandService.registerCombatCommand("bh_fumble_2"); core.commandService.registerCombatCommand("bh_fumble_3"); core.commandService.registerCombatCommand("bh_fumble_4"); core.commandService.registerCombatCommand("bh_fumble_5"); core.commandService.registerCombatCommand("bh_fumble_6"); core.commandService.registerCombatCommand("bh_intimidate_1"); core.commandService.registerCombatCommand("bh_intimidate_2"); core.commandService.registerCombatCommand("bh_intimidate_3"); core.commandService.registerCombatCommand("bh_intimidate_4"); core.commandService.registerCombatCommand("bh_intimidate_5"); core.commandService.registerCombatCommand("bh_intimidate_6"); core.commandService.registerCombatCommand("bh_sniper_1"); core.commandService.registerCombatCommand("bh_sniper_2"); core.commandService.registerCombatCommand("bh_sniper_3"); core.commandService.registerCombatCommand("bh_sniper_4"); core.commandService.registerCombatCommand("bh_sniper_5"); core.commandService.registerCombatCommand("bh_sniper_6"); core.commandService.registerCombatCommand("bh_stun_1"); core.commandService.registerCombatCommand("bh_stun_2"); core.commandService.registerCombatCommand("bh_stun_3"); core.commandService.registerCombatCommand("bh_stun_4"); core.commandService.registerCombatCommand("bh_stun_5"); core.commandService.registerCombatCommand("bh_stun_6"); core.commandService.registerCombatCommand("bh_taunt_1"); core.commandService.registerCombatCommand("bh_taunt_2"); core.commandService.registerCombatCommand("bh_taunt_3"); core.commandService.registerCombatCommand("bh_taunt_4"); core.commandService.registerCombatCommand("bh_taunt_5"); core.commandService.registerCombatCommand("bh_taunt_6"); core.commandService.registerCombatCommand("bh_return_fire_command_1"); core.commandService.registerCombatCommand("bh_sh_0"); core.commandService.registerCombatCommand("bh_sh_1"); core.commandService.registerCombatCommand("bh_sh_2"); core.commandService.registerCombatCommand("bh_sh_3"); // Jedi core.commandService.registerCombatCommand("fs_sweep_1"); core.commandService.registerCombatCommand("fs_sweep_2"); core.commandService.registerCombatCommand("fs_sweep_3"); core.commandService.registerCombatCommand("fs_sweep_4"); core.commandService.registerCombatCommand("fs_sweep_5"); core.commandService.registerCombatCommand("fs_sweep_6"); core.commandService.registerCombatCommand("fs_sweep_7"); core.commandService.registerCombatCommand("fs_dm_1"); core.commandService.registerCombatCommand("fs_dm_2"); core.commandService.registerCombatCommand("fs_dm_3"); core.commandService.registerCombatCommand("fs_dm_4"); core.commandService.registerCombatCommand("fs_dm_5"); core.commandService.registerCombatCommand("fs_dm_6"); core.commandService.registerCombatCommand("fs_dm_7"); core.commandService.registerCombatCommand("fs_dm_cc_1"); core.commandService.registerCombatCommand("fs_dm_cc_2"); core.commandService.registerCombatCommand("fs_dm_cc_3"); core.commandService.registerCombatCommand("fs_dm_cc_4"); core.commandService.registerCombatCommand("fs_dm_cc_5"); core.commandService.registerCombatCommand("fs_dm_cc_6"); core.commandService.registerCombatCommand("fs_ae_dm_cc_1"); core.commandService.registerCombatCommand("fs_ae_dm_cc_2"); core.commandService.registerCombatCommand("fs_ae_dm_cc_3"); core.commandService.registerCombatCommand("fs_ae_dm_cc_4"); core.commandService.registerCombatCommand("fs_ae_dm_cc_5"); core.commandService.registerCombatCommand("fs_ae_dm_cc_6"); core.commandService.registerCombatCommand("forceThrow"); core.commandService.registerCombatCommand("fs_dm_cc_crit_1"); core.commandService.registerCombatCommand("fs_dm_cc_crit_2"); core.commandService.registerCombatCommand("fs_dm_cc_crit_3"); core.commandService.registerCombatCommand("fs_dm_cc_crit_4"); core.commandService.registerCombatCommand("fs_dm_cc_crit_5"); core.commandService.registerCombatCommand("fs_drain_1"); core.commandService.registerCombatCommand("fs_drain_2"); core.commandService.registerCombatCommand("fs_drain_3"); core.commandService.registerCombatCommand("fs_drain_4"); core.commandService.registerCombatCommand("fs_drain_5"); core.commandService.registerCombatCommand("fs_flurry_1"); core.commandService.registerCombatCommand("fs_flurry_2"); core.commandService.registerCombatCommand("fs_flurry_3"); core.commandService.registerCombatCommand("fs_flurry_4"); core.commandService.registerCombatCommand("fs_flurry_5"); core.commandService.registerCombatCommand("fs_flurry_6"); core.commandService.registerCombatCommand("fs_flurry_7"); core.commandService.registerCombatCommand("fs_maelstrom_1"); core.commandService.registerCombatCommand("fs_maelstrom_2"); core.commandService.registerCombatCommand("fs_maelstrom_3"); core.commandService.registerCombatCommand("fs_maelstrom_4"); core.commandService.registerCombatCommand("fs_maelstrom_5"); core.commandService.registerCombatCommand("fs_sh_0"); core.commandService.registerCombatCommand("fs_sh_1"); core.commandService.registerCombatCommand("fs_sh_2"); core.commandService.registerCombatCommand("fs_sh_3"); core.commandService.registerCommand("fs_buff_def_1_1"); // Stance core.commandService.registerCommand("fs_buff_ca_1"); // Focus core.commandService.registerCommand("fs_saber_reflect_buff"); // Saber Reflect core.commandService.registerCommand("saberBlock"); // Saber Block core.commandService.registerCommand("forcerun"); // Force Run core.commandService.registerCommand("fs_buff_invis_1"); // Force Cloak core.commandService.registerCombatCommand("fs_force_throw_1"); core.commandService.registerCommand("forceThrow"); // Commando core.commandService.registerCombatCommand("co_ae_dm_1"); core.commandService.registerCombatCommand("co_ae_dm_2"); core.commandService.registerCombatCommand("co_ae_dm_3"); core.commandService.registerCombatCommand("co_ae_hw_dot_acid_1"); core.commandService.registerCombatCommand("co_ae_hw_dot_acid_2"); core.commandService.registerCombatCommand("co_ae_hw_dot_acid_3"); core.commandService.registerCombatCommand("co_ae_hw_dot_acid_4"); core.commandService.registerCombatCommand("co_ae_hw_dot_acid_5"); core.commandService.registerCombatCommand("co_ae_hw_dot_cold_1"); core.commandService.registerCombatCommand("co_ae_hw_dot_cold_2"); core.commandService.registerCombatCommand("co_ae_hw_dot_cold_3"); core.commandService.registerCombatCommand("co_ae_hw_dot_cold_4"); core.commandService.registerCombatCommand("co_ae_hw_dot_cold_5"); core.commandService.registerCombatCommand("co_ae_hw_dot_electrical_1"); core.commandService.registerCombatCommand("co_ae_hw_dot_electrical_2"); core.commandService.registerCombatCommand("co_ae_hw_dot_electrical_3"); core.commandService.registerCombatCommand("co_ae_hw_dot_electrical_4"); core.commandService.registerCombatCommand("co_ae_hw_dot_electrical_5"); core.commandService.registerCombatCommand("co_ae_hw_dot_energy_1"); core.commandService.registerCombatCommand("co_ae_hw_dot_energy_2"); core.commandService.registerCombatCommand("co_ae_hw_dot_energy_3"); core.commandService.registerCombatCommand("co_ae_hw_dot_energy_4"); core.commandService.registerCombatCommand("co_ae_hw_dot_energy_5"); core.commandService.registerCombatCommand("co_ae_hw_dot_fire_1"); core.commandService.registerCombatCommand("co_ae_hw_dot_fire_2"); core.commandService.registerCombatCommand("co_ae_hw_dot_fire_3"); core.commandService.registerCombatCommand("co_ae_hw_dot_fire_4"); core.commandService.registerCombatCommand("co_ae_hw_dot_fire_5"); core.commandService.registerCombatCommand("co_ae_hw_dot_kinetic_1"); core.commandService.registerCombatCommand("co_ae_hw_dot_kinetic_2"); core.commandService.registerCombatCommand("co_ae_hw_dot_kinetic_3"); core.commandService.registerCombatCommand("co_ae_hw_dot_kinetic_4"); core.commandService.registerCombatCommand("co_ae_hw_dot_kinetic_5"); core.commandService.registerCombatCommand("co_armor_cracker"); //core.commandService.registerCombatCommand("co_cluster_bomb"); //core.commandService.registerCombatCommand("co_cluster_bomblet"); core.commandService.registerCombatCommand("co_del_ae_cc_1_1"); core.commandService.registerCombatCommand("co_del_ae_cc_1_2"); core.commandService.registerCombatCommand("co_del_ae_cc_1_3"); core.commandService.registerCombatCommand("co_del_ae_cc_2_1"); core.commandService.registerCombatCommand("co_del_ae_cc_2_2"); core.commandService.registerCombatCommand("co_del_ae_dm_1"); core.commandService.registerCombatCommand("co_del_ae_dm_2"); core.commandService.registerCombatCommand("co_del_ae_dm_3"); core.commandService.registerCombatCommand("co_dm_1"); core.commandService.registerCombatCommand("co_dm_2"); core.commandService.registerCombatCommand("co_dm_3"); core.commandService.registerCombatCommand("co_dm_4"); core.commandService.registerCombatCommand("co_dm_5"); core.commandService.registerCombatCommand("co_dm_6"); core.commandService.registerCombatCommand("co_dm_7"); core.commandService.registerCombatCommand("co_dm_8"); core.commandService.registerCombatCommand("co_fld_dm_1"); core.commandService.registerCombatCommand("co_fld_dm_2"); core.commandService.registerCombatCommand("co_hw_dm_1"); core.commandService.registerCombatCommand("co_hw_dm_2"); core.commandService.registerCombatCommand("co_hw_dm_3"); core.commandService.registerCombatCommand("co_hw_dm_4"); core.commandService.registerCombatCommand("co_hw_dm_5"); core.commandService.registerCombatCommand("co_hw_dm_6"); core.commandService.registerCombatCommand("co_hw_dm_crit_1"); core.commandService.registerCombatCommand("co_hw_dm_crit_2"); core.commandService.registerCombatCommand("co_hw_dm_crit_3"); core.commandService.registerCombatCommand("co_hw_dm_crit_4"); core.commandService.registerCombatCommand("co_hw_dm_crit_5"); core.commandService.registerCombatCommand("co_hw_dm_crit_6"); core.commandService.registerCombatCommand("co_hw_dot_acid_1"); core.commandService.registerCombatCommand("co_hw_dot_acid_2"); core.commandService.registerCombatCommand("co_hw_dot_acid_3"); core.commandService.registerCombatCommand("co_hw_dot_acid_4"); core.commandService.registerCombatCommand("co_hw_dot_acid_5"); core.commandService.registerCombatCommand("co_hw_dot_cold_1"); core.commandService.registerCombatCommand("co_hw_dot_cold_2"); core.commandService.registerCombatCommand("co_hw_dot_cold_3"); core.commandService.registerCombatCommand("co_hw_dot_cold_4"); core.commandService.registerCombatCommand("co_hw_dot_cold_5"); core.commandService.registerCombatCommand("co_hw_dot_electrical_1"); core.commandService.registerCombatCommand("co_hw_dot_electrical_2"); core.commandService.registerCombatCommand("co_hw_dot_electrical_3"); core.commandService.registerCombatCommand("co_hw_dot_electrical_4"); core.commandService.registerCombatCommand("co_hw_dot_electrical_5"); core.commandService.registerCombatCommand("co_hw_dot_energy_1"); core.commandService.registerCombatCommand("co_hw_dot_energy_2"); core.commandService.registerCombatCommand("co_hw_dot_energy_3"); core.commandService.registerCombatCommand("co_hw_dot_energy_4"); core.commandService.registerCombatCommand("co_hw_dot_energy_5"); core.commandService.registerCombatCommand("co_hw_dot_fire_1"); core.commandService.registerCombatCommand("co_hw_dot_fire_2"); core.commandService.registerCombatCommand("co_hw_dot_fire_3"); core.commandService.registerCombatCommand("co_hw_dot_fire_4"); core.commandService.registerCombatCommand("co_hw_dot_fire_5"); core.commandService.registerCombatCommand("co_hw_dot_kinetic_1"); core.commandService.registerCombatCommand("co_hw_dot_kinetic_2"); core.commandService.registerCombatCommand("co_hw_dot_kinetic_3"); core.commandService.registerCombatCommand("co_hw_dot_kinetic_4"); core.commandService.registerCombatCommand("co_hw_dot_kinetic_5"); core.commandService.registerCombatCommand("co_remote_detonator_1"); core.commandService.registerCombatCommand("co_remote_detonator_2"); core.commandService.registerCombatCommand("co_remote_detonator_3"); core.commandService.registerCombatCommand("co_remote_detonator_4"); core.commandService.registerCombatCommand("co_remote_detonator_5"); core.commandService.registerCombatCommand("co_remote_detonator_5"); core.commandService.registerCombatCommand("co_riddle_armor"); core.commandService.registerCombatCommand("co_suppressing_fire"); core.commandService.registerCombatCommand("co_sh_0"); core.commandService.registerCombatCommand("co_sh_1"); core.commandService.registerCombatCommand("co_sh_2"); core.commandService.registerCombatCommand("co_sh_3"); core.commandService.registerCombatCommand("co_stand_fast"); core.commandService.registerCommand("co_hw_dot"); core.commandService.registerCommand("co_ae_hw_dot"); core.commandService.registerCommand("co_position_secured"); core.commandService.registerCommand("co_first_aid_training"); // Entertainer core.commandService.registerCombatCommand("en_dm_1"); core.commandService.registerCombatCommand("en_dm_2"); core.commandService.registerCombatCommand("en_dm_3"); core.commandService.registerCombatCommand("en_dm_4"); core.commandService.registerCombatCommand("en_dm_5"); core.commandService.registerCombatCommand("en_dm_6"); core.commandService.registerCombatCommand("en_dm_7"); core.commandService.registerCombatCommand("en_dm_8"); core.commandService.registerCombatCommand("en_project_will_0"); core.commandService.registerCombatCommand("en_project_will_1"); core.commandService.registerCombatCommand("en_project_will_2"); core.commandService.registerCombatCommand("en_project_will_3"); core.commandService.registerCombatCommand("en_project_will_4"); core.commandService.registerCombatCommand("en_project_will_5"); core.commandService.registerCombatCommand("en_project_will_6"); core.commandService.registerCombatCommand("en_spiral_kick_0"); core.commandService.registerCombatCommand("en_spiral_kick_1"); core.commandService.registerCombatCommand("en_spiral_kick_2"); core.commandService.registerCombatCommand("en_spiral_kick_3"); core.commandService.registerCombatCommand("en_spiral_kick_4"); core.commandService.registerCombatCommand("en_strike_0"); core.commandService.registerCombatCommand("en_strike_1"); core.commandService.registerCombatCommand("en_strike_2"); core.commandService.registerCombatCommand("en_strike_3"); core.commandService.registerCombatCommand("en_strike_4"); core.commandService.registerCombatCommand("en_strike_5"); core.commandService.registerCombatCommand("en_strike_6"); core.commandService.registerCombatCommand("en_sweeping_pirouette_0"); core.commandService.registerCombatCommand("en_sweeping_pirouette_1"); core.commandService.registerCombatCommand("en_sweeping_pirouette_2"); core.commandService.registerCombatCommand("en_sweeping_pirouette_3"); core.commandService.registerCombatCommand("en_sweeping_pirouette_4"); core.commandService.registerCombatCommand("en_sweeping_pirouette_5"); core.commandService.registerCombatCommand("en_unhealthy_fixation"); core.commandService.registerCombatCommand("en_void_dance"); core.commandService.registerCombatCommand("en_void_dance_1"); core.commandService.registerCombatCommand("en_void_dance_2"); core.commandService.registerCombatCommand("en_void_dance_3"); core.commandService.registerCombatCommand("en_sh_1"); core.commandService.registerCombatCommand("en_sh_2"); core.commandService.registerCombatCommand("en_sh_3"); core.commandService.registerCombatCommand("en_heal_1"); core.commandService.registerCombatCommand("en_heal_2"); core.commandService.registerCombatCommand("en_heal_3"); core.commandService.registerCombatCommand("en_heal_4"); // Medic core.commandService.registerCombatCommand("me_ae_heal_1"); core.commandService.registerCombatCommand("me_ae_heal_2"); core.commandService.registerCombatCommand("me_ae_heal_3"); core.commandService.registerCombatCommand("me_ae_heal_4"); core.commandService.registerCombatCommand("me_ae_heal_5"); core.commandService.registerCombatCommand("me_ae_heal_6"); core.commandService.registerCombatCommand("me_bacta_ampule_1"); core.commandService.registerCombatCommand("me_bacta_ampule_2"); core.commandService.registerCombatCommand("me_bacta_ampule_3"); core.commandService.registerCombatCommand("me_bacta_ampule_4"); core.commandService.registerCombatCommand("me_bacta_ampule_5"); core.commandService.registerCombatCommand("me_bacta_ampule_6"); core.commandService.registerCombatCommand("me_bacta_bomb_1"); core.commandService.registerCombatCommand("me_bacta_bomb_2"); core.commandService.registerCombatCommand("me_bacta_bomb_3"); core.commandService.registerCombatCommand("me_bacta_bomb_4"); core.commandService.registerCombatCommand("me_bacta_bomb_5"); core.commandService.registerCombatCommand("me_bacta_grenade_1"); core.commandService.registerCombatCommand("me_bacta_grenade_2"); core.commandService.registerCombatCommand("me_bacta_grenade_3"); core.commandService.registerCombatCommand("me_bacta_grenade_4"); core.commandService.registerCombatCommand("me_bacta_grenade_5"); core.commandService.registerCombatCommand("me_bacta_resistance_1"); core.commandService.registerCombatCommand("me_burst_1"); core.commandService.registerCombatCommand("me_burst_2"); core.commandService.registerCombatCommand("me_burst_3"); core.commandService.registerCombatCommand("me_burst_4"); core.commandService.registerCombatCommand("me_burst_5"); core.commandService.registerCombatCommand("me_cranial_smash_1"); core.commandService.registerCombatCommand("me_cranial_smash_2"); core.commandService.registerCombatCommand("me_cranial_smash_3"); core.commandService.registerCombatCommand("me_cranial_smash_4"); core.commandService.registerCombatCommand("me_cranial_smash_5"); core.commandService.registerCommand("me_cure_affliction_1"); core.commandService.registerCombatCommand("me_dm_1"); core.commandService.registerCombatCommand("me_dm_2"); core.commandService.registerCombatCommand("me_dm_3"); core.commandService.registerCombatCommand("me_dm_4"); core.commandService.registerCombatCommand("me_dm_5"); core.commandService.registerCombatCommand("me_dm_6"); core.commandService.registerCombatCommand("me_dm_8"); core.commandService.registerCombatCommand("me_dm_dot_1"); core.commandService.registerCombatCommand("me_dm_dot_2"); core.commandService.registerCombatCommand("me_dm_dot_3"); core.commandService.registerCombatCommand("me_dm_dot_4"); core.commandService.registerCombatCommand("me_dm_dot_5"); core.commandService.registerCombatCommand("me_dm_dot_6"); core.commandService.registerCombatCommand("me_electrolyte_drain_1"); core.commandService.registerCombatCommand("me_fld_dm_dot_1"); core.commandService.registerCombatCommand("me_fld_dm_dot_2"); core.commandService.registerCombatCommand("me_fld_dm_dot_3"); core.commandService.registerCombatCommand("me_induce_insanity_1"); core.commandService.registerCombatCommand("me_rv_area"); core.commandService.registerCombatCommand("me_rv_combat"); core.commandService.registerCombatCommand("me_rv_ooc"); core.commandService.registerCombatCommand("me_rv_pvp_area"); core.commandService.registerCombatCommand("me_rv_pvp_single"); core.commandService.registerCommand("me_serotonin_boost_1"); core.commandService.registerCombatCommand("me_serotonin_purge_1"); core.commandService.registerCombatCommand("me_sh_1"); core.commandService.registerCommand("me_stasis_1"); core.commandService.registerCommand("me_stasis_self_1"); core.commandService.registerCombatCommand("me_thyroid_rupture_1"); core.commandService.registerCombatCommand("me_traumatize_1"); core.commandService.registerCombatCommand("me_traumatize_2"); core.commandService.registerCombatCommand("me_traumatize_3"); core.commandService.registerCombatCommand("me_traumatize_4"); core.commandService.registerCombatCommand("me_traumatize_5"); core.commandService.registerCombatCommand("me_stasis_1"); core.commandService.registerCommand("me_drag_1"); core.commandService.registerCommand("me_enhance_action_1"); core.commandService.registerCommand("me_reckless_stimulation_1"); core.commandService.registerCommand("me_reckless_stimulation_2"); core.commandService.registerCommand("me_reckless_stimulation_3"); core.commandService.registerCommand("me_reckless_stimulation_4"); core.commandService.registerCommand("me_reckless_stimulation_5"); core.commandService.registerCommand("me_reckless_stimulation_6"); core.commandService.registerCommand("me_buff_health_1"); core.commandService.registerCommand("me_buff_health_2"); core.commandService.registerCommand("me_buff_health_3"); core.commandService.registerCommand("me_enhance_action_1"); core.commandService.registerCommand("me_enhance_action_2"); core.commandService.registerCommand("me_enhance_action_3"); core.commandService.registerCommand("me_enhance_agility_1"); core.commandService.registerCommand("me_enhance_agility_2"); core.commandService.registerCommand("me_enhance_agility_3"); core.commandService.registerCommand("me_enhance_block_1"); core.commandService.registerCommand("me_enhance_dodge_1"); core.commandService.registerCommand("me_enhance_precision_1"); core.commandService.registerCommand("me_enhance_precision_2"); core.commandService.registerCommand("me_enhance_precision_3"); core.commandService.registerCommand("me_enhance_strength_1"); core.commandService.registerCommand("me_enhance_strength_2"); core.commandService.registerCommand("me_enhance_strength_3"); core.commandService.registerCommand("me_evasion_1"); // Officer core.commandService.registerCombatCommand("of_ae_dm_boss"); core.commandService.registerCombatCommand("of_ae_dm_cc_1"); core.commandService.registerCombatCommand("of_ae_dm_cc_2"); core.commandService.registerCombatCommand("of_ae_dm_cc_3"); core.commandService.registerCombatCommand("of_alt_ae_dm_1"); core.commandService.registerCombatCommand("of_alt_ae_dm_2"); core.commandService.registerCombatCommand("of_alt_ae_dm_3"); core.commandService.registerCombatCommand("of_deb_def_1"); core.commandService.registerCombatCommand("of_deb_def_2"); core.commandService.registerCombatCommand("of_deb_def_3"); core.commandService.registerCombatCommand("of_deb_def_4"); core.commandService.registerCombatCommand("of_deb_def_5"); core.commandService.registerCombatCommand("of_deb_def_6"); core.commandService.registerCombatCommand("of_deb_def_7"); core.commandService.registerCombatCommand("of_deb_def_8"); core.commandService.registerCombatCommand("of_decapitate_1"); core.commandService.registerCombatCommand("of_decapitate_2"); core.commandService.registerCombatCommand("of_decapitate_3"); core.commandService.registerCombatCommand("of_decapitate_4"); core.commandService.registerCombatCommand("of_decapitate_5"); core.commandService.registerCombatCommand("of_decapitate_6"); core.commandService.registerCombatCommand("of_del_ae_dm_1"); core.commandService.registerCombatCommand("of_del_ae_dm_2"); core.commandService.registerCombatCommand("of_del_ae_dm_3"); core.commandService.registerCombatCommand("of_del_ae_dm_boss"); core.commandService.registerCombatCommand("of_del_ae_dm_dot_1"); core.commandService.registerCombatCommand("of_del_ae_dm_dot_2"); core.commandService.registerCombatCommand("of_del_ae_dm_dot_3"); core.commandService.registerCombatCommand("of_del_ae_dot_1"); core.commandService.registerCombatCommand("of_dm_1"); core.commandService.registerCombatCommand("of_dm_2"); core.commandService.registerCombatCommand("of_dm_3"); core.commandService.registerCombatCommand("of_dm_4"); core.commandService.registerCombatCommand("of_dm_5"); core.commandService.registerCombatCommand("of_dm_6"); core.commandService.registerCombatCommand("of_dm_7"); core.commandService.registerCombatCommand("of_dm_8"); core.commandService.registerCombatCommand("of_dm_boss"); core.commandService.registerCombatCommand("of_leg_strike_1"); core.commandService.registerCombatCommand("of_leg_strike_2"); core.commandService.registerCombatCommand("of_leg_strike_3"); core.commandService.registerCombatCommand("of_leg_strike_4"); core.commandService.registerCombatCommand("of_leg_strike_5"); core.commandService.registerCombatCommand("of_leg_strike_6"); core.commandService.registerCombatCommand("of_leg_strike_7"); core.commandService.registerCombatCommand("of_pistol_bleed"); core.commandService.registerCombatCommand("of_pistol_dm"); core.commandService.registerCombatCommand("of_sh_0"); core.commandService.registerCombatCommand("of_sh_1"); core.commandService.registerCombatCommand("of_sh_2"); core.commandService.registerCombatCommand("of_sh_3"); core.commandService.registerCombatCommand("of_vortex_1"); core.commandService.registerCombatCommand("of_vortex_2"); core.commandService.registerCombatCommand("of_vortex_3"); core.commandService.registerCombatCommand("of_vortex_4"); core.commandService.registerCombatCommand("of_vortex_5"); core.commandService.registerCommand("of_charge_1"); core.commandService.registerCommand("of_inspiration_1"); core.commandService.registerCommand("of_inspiration_2"); core.commandService.registerCommand("of_inspiration_3"); core.commandService.registerCommand("of_inspiration_4"); core.commandService.registerCommand("of_inspiration_5"); core.commandService.registerCommand("of_inspiration_6"); core.commandService.registerCommand("of_focus_fire_1"); core.commandService.registerCommand("of_focus_fire_2"); core.commandService.registerCommand("of_focus_fire_3"); core.commandService.registerCommand("of_focus_fire_4"); core.commandService.registerCommand("of_focus_fire_5"); core.commandService.registerCommand("of_focus_fire_6"); core.commandService.registerCommand("of_drillmaster_1"); core.commandService.registerCommand("of_buff_def_1"); core.commandService.registerCommand("of_buff_def_2"); core.commandService.registerCommand("of_buff_def_3"); core.commandService.registerCommand("of_buff_def_4"); core.commandService.registerCommand("of_buff_def_5"); core.commandService.registerCommand("of_buff_def_6"); core.commandService.registerCommand("of_buff_def_7"); core.commandService.registerCommand("of_buff_def_8"); core.commandService.registerCommand("of_buff_def_9"); core.commandService.registerCommand("of_emergency_shield"); core.commandService.registerCommand("of_firepower_1"); core.commandService.registerCommand("of_medical_sup_1"); core.commandService.registerCommand("of_purge_1"); core.commandService.registerCommand("of_scatter_1"); core.commandService.registerCommand("of_stimulator_1"); // Smuggler core.commandService.registerCombatCommand("sm_ae_cover_fire"); core.commandService.registerCombatCommand("sm_ae_dm_1"); core.commandService.registerCombatCommand("sm_ae_dm_2"); core.commandService.registerCombatCommand("sm_ae_dm_3"); core.commandService.registerCombatCommand("sm_ae_dm_4"); core.commandService.registerCombatCommand("sm_ae_dm_5"); core.commandService.registerCombatCommand("sm_ae_dm_6"); core.commandService.registerCombatCommand("sm_ae_dm_cc_1"); core.commandService.registerCombatCommand("sm_ae_dm_cc_2"); core.commandService.registerCombatCommand("sm_ae_dm_cc_3"); core.commandService.registerCombatCommand("sm_ae_dm_cc_4"); core.commandService.registerCombatCommand("sm_ae_dm_cc_5"); core.commandService.registerCombatCommand("sm_ae_dm_cc_melee_1"); core.commandService.registerCombatCommand("sm_ae_dm_cc_melee_2"); core.commandService.registerCombatCommand("sm_ae_dm_cc_melee_3"); core.commandService.registerCombatCommand("sm_ae_dm_cc_melee_4"); core.commandService.registerCombatCommand("sm_ae_dm_cc_melee_5"); core.commandService.registerCombatCommand("sm_ae_dm_melee_1"); core.commandService.registerCombatCommand("sm_ae_dm_melee_2"); core.commandService.registerCombatCommand("sm_ae_dm_melee_3"); core.commandService.registerCombatCommand("sm_ae_dm_melee_4"); core.commandService.registerCombatCommand("sm_ae_dm_melee_5"); core.commandService.registerCombatCommand("sm_ae_dm_melee_6"); core.commandService.registerCombatCommand("sm_ae_pin_down"); core.commandService.registerCombatCommand("sm_bad_odds_1"); core.commandService.registerCombatCommand("sm_bad_odds_2"); core.commandService.registerCombatCommand("sm_bad_odds_3"); core.commandService.registerCombatCommand("sm_bad_odds_4"); core.commandService.registerCombatCommand("sm_bad_odds_5"); core.commandService.registerCombatCommand("sm_break_the_deal"); core.commandService.registerCombatCommand("sm_concussion_shot"); core.commandService.registerCombatCommand("sm_del_dm_cc_1"); core.commandService.registerCombatCommand("sm_del_dm_cc_2"); core.commandService.registerCombatCommand("sm_del_dm_cc_3"); core.commandService.registerCombatCommand("sm_del_dm_cc_4"); core.commandService.registerCombatCommand("sm_del_dm_cc_5"); core.commandService.registerCombatCommand("sm_del_dm_cc_6"); core.commandService.registerCombatCommand("sm_dizzy"); core.commandService.registerCombatCommand("sm_dm_1"); core.commandService.registerCombatCommand("sm_dm_2"); core.commandService.registerCombatCommand("sm_dm_3"); core.commandService.registerCombatCommand("sm_dm_4"); core.commandService.registerCombatCommand("sm_dm_5"); core.commandService.registerCombatCommand("sm_dm_6"); core.commandService.registerCombatCommand("sm_dm_7"); core.commandService.registerCombatCommand("sm_dm_cc_1"); core.commandService.registerCombatCommand("sm_dm_cc_2"); core.commandService.registerCombatCommand("sm_dm_cc_3"); core.commandService.registerCombatCommand("sm_dm_cc_4"); core.commandService.registerCombatCommand("sm_dm_cc_5"); core.commandService.registerCombatCommand("sm_dm_cc_6"); core.commandService.registerCombatCommand("sm_dm_cc_melee_1"); core.commandService.registerCombatCommand("sm_dm_cc_melee_2"); core.commandService.registerCombatCommand("sm_dm_cc_melee_3"); core.commandService.registerCombatCommand("sm_dm_cc_melee_4"); core.commandService.registerCombatCommand("sm_dm_cc_melee_5"); core.commandService.registerCombatCommand("sm_dm_cc_melee_6"); core.commandService.registerCombatCommand("sm_dm_dot_1"); core.commandService.registerCombatCommand("sm_dm_dot_2"); core.commandService.registerCombatCommand("sm_dm_dot_3"); core.commandService.registerCombatCommand("sm_dm_dot_4"); core.commandService.registerCombatCommand("sm_dm_dot_melee_1"); core.commandService.registerCombatCommand("sm_dm_dot_melee_2"); core.commandService.registerCombatCommand("sm_dm_dot_melee_3"); core.commandService.registerCombatCommand("sm_dm_dot_melee_4"); core.commandService.registerCombatCommand("sm_dm_melee_1"); core.commandService.registerCombatCommand("sm_dm_melee_2"); core.commandService.registerCombatCommand("sm_dm_melee_3"); core.commandService.registerCombatCommand("sm_dm_melee_4"); core.commandService.registerCombatCommand("sm_dm_melee_5"); core.commandService.registerCombatCommand("sm_dm_melee_6"); core.commandService.registerCombatCommand("sm_dm_melee_7"); core.commandService.registerCombatCommand("sm_false_hope"); core.commandService.registerCombatCommand("sm_fast_draw"); core.commandService.registerCombatCommand("sm_how_are_you"); core.commandService.registerCombatCommand("sm_impossible_odds"); core.commandService.registerCombatCommand("sm_inspect_cargo"); core.commandService.registerCombatCommand("sm_pistol_whip_1"); core.commandService.registerCombatCommand("sm_pistol_whip_2"); core.commandService.registerCombatCommand("sm_pistol_whip_3"); core.commandService.registerCombatCommand("sm_pistol_whip_4"); core.commandService.registerCombatCommand("sm_precision_strike"); core.commandService.registerCombatCommand("sm_sh_0"); core.commandService.registerCombatCommand("sm_sh_1"); core.commandService.registerCombatCommand("sm_sh_2"); core.commandService.registerCombatCommand("sm_sh_3"); core.commandService.registerCombatCommand("sm_shoot_first_1"); core.commandService.registerCombatCommand("sm_shoot_first_2"); core.commandService.registerCombatCommand("sm_shoot_first_3"); core.commandService.registerCombatCommand("sm_shoot_first_4"); core.commandService.registerCombatCommand("sm_shoot_first_5"); core.commandService.registerCombatCommand("sm_skullduggery"); core.commandService.registerCombatCommand("sm_sly_lie"); core.commandService.registerCombatCommand("sm_spot_a_sucker_1"); core.commandService.registerCombatCommand("sm_spot_a_sucker_2"); core.commandService.registerCombatCommand("sm_spot_a_sucker_3"); core.commandService.registerCombatCommand("sm_spot_a_sucker_4"); // Spy core.commandService.registerCombatCommand("sp_action_regen"); core.commandService.registerCombatCommand("sp_assassins_mark"); core.commandService.registerCombatCommand("sp_cc_dot"); core.commandService.registerCombatCommand("sp_dm_1"); core.commandService.registerCombatCommand("sp_dm_2"); core.commandService.registerCombatCommand("sp_dm_3"); core.commandService.registerCombatCommand("sp_dm_4"); core.commandService.registerCombatCommand("sp_dm_5"); core.commandService.registerCombatCommand("sp_dm_6"); core.commandService.registerCombatCommand("sp_dm_7"); core.commandService.registerCombatCommand("sp_dm_8"); core.commandService.registerCombatCommand("sp_dot_0"); core.commandService.registerCombatCommand("sp_dot_1"); core.commandService.registerCombatCommand("sp_dot_2"); core.commandService.registerCombatCommand("sp_dot_3"); core.commandService.registerCombatCommand("sp_dot_4"); core.commandService.registerCombatCommand("sp_dot_5"); core.commandService.registerCombatCommand("sp_fld_debuff_ca"); core.commandService.registerCombatCommand("sp_fldmot_1"); core.commandService.registerCombatCommand("sp_fldmot_1_snare"); core.commandService.registerCombatCommand("sp_fldmot_2"); core.commandService.registerCombatCommand("sp_fldmot_2_snare"); core.commandService.registerCombatCommand("sp_fldmot_3"); core.commandService.registerCombatCommand("sp_fldmot_3_snare"); core.commandService.registerCombatCommand("sp_hd_melee_0"); core.commandService.registerCombatCommand("sp_hd_melee_1"); core.commandService.registerCombatCommand("sp_hd_melee_2"); core.commandService.registerCombatCommand("sp_hd_melee_3"); core.commandService.registerCombatCommand("sp_hd_melee_4"); core.commandService.registerCombatCommand("sp_hd_melee_5"); core.commandService.registerCombatCommand("sp_hd_melee_6"); core.commandService.registerCombatCommand("sp_hd_range_0"); core.commandService.registerCombatCommand("sp_hd_range_1"); core.commandService.registerCombatCommand("sp_hd_range_2"); core.commandService.registerCombatCommand("sp_hd_range_3"); core.commandService.registerCombatCommand("sp_hd_range_4"); core.commandService.registerCombatCommand("sp_hd_range_5"); core.commandService.registerCombatCommand("sp_hd_range_6"); core.commandService.registerCombatCommand("sp_improved_cc_dot_0"); core.commandService.registerCombatCommand("sp_improved_cc_dot_1"); core.commandService.registerCombatCommand("sp_improved_cc_dot_2"); core.commandService.registerCombatCommand("sp_improved_cc_dot_3"); core.commandService.registerCombatCommand("sp_run_its_course"); core.commandService.registerCombatCommand("sp_sh_0"); core.commandService.registerCombatCommand("sp_sh_1"); core.commandService.registerCombatCommand("sp_sh_2"); core.commandService.registerCombatCommand("sp_sh_3"); core.commandService.registerCombatCommand("sp_shifty_setup"); core.commandService.registerCombatCommand("sp_stealth_melee_0"); core.commandService.registerCombatCommand("sp_stealth_melee_1"); core.commandService.registerCombatCommand("sp_stealth_melee_2"); core.commandService.registerCombatCommand("sp_stealth_melee_3"); core.commandService.registerCombatCommand("sp_stealth_melee_4"); core.commandService.registerCombatCommand("sp_stealth_melee_5"); core.commandService.registerCombatCommand("sp_stealth_melee_6"); core.commandService.registerCombatCommand("sp_stealth_ranged_0"); core.commandService.registerCombatCommand("sp_stealth_ranged_1"); core.commandService.registerCombatCommand("sp_stealth_ranged_2"); core.commandService.registerCombatCommand("sp_stealth_ranged_3"); core.commandService.registerCombatCommand("sp_stealth_ranged_4"); core.commandService.registerCombatCommand("sp_stealth_ranged_5"); core.commandService.registerCombatCommand("sp_stealth_ranged_6"); }
diff --git a/gdx/src/com/badlogic/gdx/graphics/glutils/MipMapGenerator.java b/gdx/src/com/badlogic/gdx/graphics/glutils/MipMapGenerator.java index 0cda9fa6c..8fb034acb 100644 --- a/gdx/src/com/badlogic/gdx/graphics/glutils/MipMapGenerator.java +++ b/gdx/src/com/badlogic/gdx/graphics/glutils/MipMapGenerator.java @@ -1,109 +1,108 @@ /******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.graphics.glutils; import com.badlogic.gdx.Application.ApplicationType; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.GLCommon; import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.graphics.Pixmap.Blending; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.utils.GdxRuntimeException; public class MipMapGenerator { private static boolean useHWMipMap = true; static public void setUseHardwareMipMap (boolean useHWMipMap) { MipMapGenerator.useHWMipMap = useHWMipMap; } /** Sets the image data of the {@link Texture} based on the {@link Pixmap}. The texture must be bound for this to work. If * <code>disposePixmap</code> is true, the pixmap will be disposed at the end of the method. * @param pixmap the Pixmap * @param disposePixmap whether to dispose the Pixmap after upload */ public static void generateMipMap (Pixmap pixmap, int textureWidth, int textureHeight, boolean disposePixmap) { if (!useHWMipMap) { generateMipMapCPU(pixmap, textureWidth, textureHeight, disposePixmap); return; } if (Gdx.app.getType() == ApplicationType.Android) { if (Gdx.graphics.isGL20Available()) generateMipMapGLES20(pixmap, disposePixmap); else generateMipMapCPU(pixmap, textureWidth, textureHeight, disposePixmap); } else { generateMipMapDesktop(pixmap, textureWidth, textureHeight, disposePixmap); } } private static void generateMipMapGLES20 (Pixmap pixmap, boolean disposePixmap) { Gdx.gl.glTexImage2D(GL20.GL_TEXTURE_2D, 0, pixmap.getGLInternalFormat(), pixmap.getWidth(), pixmap.getHeight(), 0, pixmap.getGLFormat(), pixmap.getGLType(), pixmap.getPixels()); Gdx.gl20.glGenerateMipmap(GL20.GL_TEXTURE_2D); if (disposePixmap) pixmap.dispose(); } private static void generateMipMapDesktop (Pixmap pixmap, int textureWidth, int textureHeight, boolean disposePixmap) { if (Gdx.graphics.isGL20Available() && (Gdx.graphics.supportsExtension("GL_ARB_framebuffer_object") || Gdx.graphics .supportsExtension("GL_EXT_framebuffer_object"))) { Gdx.gl.glTexImage2D(GL20.GL_TEXTURE_2D, 0, pixmap.getGLInternalFormat(), pixmap.getWidth(), pixmap.getHeight(), 0, pixmap.getGLFormat(), pixmap.getGLType(), pixmap.getPixels()); Gdx.gl20.glGenerateMipmap(GL20.GL_TEXTURE_2D); if (disposePixmap) pixmap.dispose(); } else if (Gdx.graphics.supportsExtension("GL_SGIS_generate_mipmap")) { if ((Gdx.gl20 == null) && textureWidth != textureHeight) throw new GdxRuntimeException("texture width and height must be square when using mipmapping in OpenGL ES 1.x"); Gdx.gl.glTexParameterf(GL20.GL_TEXTURE_2D, GLCommon.GL_GENERATE_MIPMAP, GL10.GL_TRUE); Gdx.gl.glTexImage2D(GL20.GL_TEXTURE_2D, 0, pixmap.getGLInternalFormat(), pixmap.getWidth(), pixmap.getHeight(), 0, pixmap.getGLFormat(), pixmap.getGLType(), pixmap.getPixels()); if (disposePixmap) pixmap.dispose(); } else { generateMipMapCPU(pixmap, textureWidth, textureHeight, disposePixmap); } } private static void generateMipMapCPU (Pixmap pixmap, int textureWidth, int textureHeight, boolean disposePixmap) { Gdx.gl.glTexImage2D(GL10.GL_TEXTURE_2D, 0, pixmap.getGLInternalFormat(), pixmap.getWidth(), pixmap.getHeight(), 0, pixmap.getGLFormat(), pixmap.getGLType(), pixmap.getPixels()); if ((Gdx.gl20 == null) && textureWidth != textureHeight) throw new GdxRuntimeException("texture width and height must be square when using mipmapping."); int width = pixmap.getWidth() / 2; int height = pixmap.getHeight() / 2; int level = 1; Blending blending = Pixmap.getBlending(); Pixmap.setBlending(Blending.None); while (width > 0 && height > 0) { Pixmap tmp = new Pixmap(width, height, pixmap.getFormat()); tmp.drawPixmap(pixmap, 0, 0, pixmap.getWidth(), pixmap.getHeight(), 0, 0, width, height); if (level > 1 || disposePixmap) pixmap.dispose(); pixmap = tmp; Gdx.gl.glTexImage2D(GL10.GL_TEXTURE_2D, level, pixmap.getGLInternalFormat(), pixmap.getWidth(), pixmap.getHeight(), 0, pixmap.getGLFormat(), pixmap.getGLType(), pixmap.getPixels()); width = pixmap.getWidth() / 2; height = pixmap.getHeight() / 2; level++; } Pixmap.setBlending(blending); - pixmap.dispose(); } }
true
true
private static void generateMipMapCPU (Pixmap pixmap, int textureWidth, int textureHeight, boolean disposePixmap) { Gdx.gl.glTexImage2D(GL10.GL_TEXTURE_2D, 0, pixmap.getGLInternalFormat(), pixmap.getWidth(), pixmap.getHeight(), 0, pixmap.getGLFormat(), pixmap.getGLType(), pixmap.getPixels()); if ((Gdx.gl20 == null) && textureWidth != textureHeight) throw new GdxRuntimeException("texture width and height must be square when using mipmapping."); int width = pixmap.getWidth() / 2; int height = pixmap.getHeight() / 2; int level = 1; Blending blending = Pixmap.getBlending(); Pixmap.setBlending(Blending.None); while (width > 0 && height > 0) { Pixmap tmp = new Pixmap(width, height, pixmap.getFormat()); tmp.drawPixmap(pixmap, 0, 0, pixmap.getWidth(), pixmap.getHeight(), 0, 0, width, height); if (level > 1 || disposePixmap) pixmap.dispose(); pixmap = tmp; Gdx.gl.glTexImage2D(GL10.GL_TEXTURE_2D, level, pixmap.getGLInternalFormat(), pixmap.getWidth(), pixmap.getHeight(), 0, pixmap.getGLFormat(), pixmap.getGLType(), pixmap.getPixels()); width = pixmap.getWidth() / 2; height = pixmap.getHeight() / 2; level++; } Pixmap.setBlending(blending); pixmap.dispose(); }
private static void generateMipMapCPU (Pixmap pixmap, int textureWidth, int textureHeight, boolean disposePixmap) { Gdx.gl.glTexImage2D(GL10.GL_TEXTURE_2D, 0, pixmap.getGLInternalFormat(), pixmap.getWidth(), pixmap.getHeight(), 0, pixmap.getGLFormat(), pixmap.getGLType(), pixmap.getPixels()); if ((Gdx.gl20 == null) && textureWidth != textureHeight) throw new GdxRuntimeException("texture width and height must be square when using mipmapping."); int width = pixmap.getWidth() / 2; int height = pixmap.getHeight() / 2; int level = 1; Blending blending = Pixmap.getBlending(); Pixmap.setBlending(Blending.None); while (width > 0 && height > 0) { Pixmap tmp = new Pixmap(width, height, pixmap.getFormat()); tmp.drawPixmap(pixmap, 0, 0, pixmap.getWidth(), pixmap.getHeight(), 0, 0, width, height); if (level > 1 || disposePixmap) pixmap.dispose(); pixmap = tmp; Gdx.gl.glTexImage2D(GL10.GL_TEXTURE_2D, level, pixmap.getGLInternalFormat(), pixmap.getWidth(), pixmap.getHeight(), 0, pixmap.getGLFormat(), pixmap.getGLType(), pixmap.getPixels()); width = pixmap.getWidth() / 2; height = pixmap.getHeight() / 2; level++; } Pixmap.setBlending(blending); }
diff --git a/src/org/rascalmpl/interpreter/result/StringResult.java b/src/org/rascalmpl/interpreter/result/StringResult.java index 19c9fef8d8..58ca9ea691 100644 --- a/src/org/rascalmpl/interpreter/result/StringResult.java +++ b/src/org/rascalmpl/interpreter/result/StringResult.java @@ -1,208 +1,208 @@ /******************************************************************************* * Copyright (c) 2009-2013 CWI * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * * Jurgen J. Vinju - [email protected] - CWI * * Tijs van der Storm - [email protected] * * Paul Klint - [email protected] - CWI * * Arnold Lankamp - [email protected] *******************************************************************************/ package org.rascalmpl.interpreter.result; import static org.rascalmpl.interpreter.result.ResultFactory.bool; import static org.rascalmpl.interpreter.result.ResultFactory.makeResult; import java.util.Map; import org.eclipse.imp.pdb.facts.IBool; import org.eclipse.imp.pdb.facts.IInteger; import org.eclipse.imp.pdb.facts.IString; import org.eclipse.imp.pdb.facts.IValue; import org.eclipse.imp.pdb.facts.type.Type; import org.eclipse.imp.pdb.facts.type.TypeFactory; import org.eclipse.imp.pdb.facts.type.TypeStore; import org.rascalmpl.interpreter.IEvaluatorContext; import org.rascalmpl.interpreter.staticErrors.UnexpectedType; import org.rascalmpl.interpreter.staticErrors.UnsupportedSubscriptArity; import org.rascalmpl.interpreter.utils.RuntimeExceptionFactory; public class StringResult extends ElementResult<IString> { private IString string; public StringResult(Type type, IString string, IEvaluatorContext ctx) { super(type, string, ctx); this.string = string; } @Override public IString getValue() { return string; } protected int length() { return string.getValue().length(); } protected void yield(StringBuilder b) { b.append(string.getValue()); } @Override public <U extends IValue, V extends IValue> Result<U> add(Result<V> result) { return result.addString(this); } @Override public <V extends IValue> Result<IBool> equals(Result<V> that) { return that.equalToString(this); } @Override public <V extends IValue> Result<IBool> nonEquals(Result<V> that) { return that.nonEqualToString(this); } @Override public <V extends IValue> Result<IBool> lessThan(Result<V> result) { return result.lessThanString(this); } @Override public <V extends IValue> LessThanOrEqualResult lessThanOrEqual(Result<V> result) { return result.lessThanOrEqualString(this); } @Override public <V extends IValue> Result<IBool> greaterThan(Result<V> result) { return result.greaterThanString(this); } @Override public <V extends IValue> Result<IBool> greaterThanOrEqual(Result<V> result) { return result.greaterThanOrEqualString(this); } ////////////////////// // // @Override // protected <U extends IValue> Result<U> addString(StringResult s) { // // Note the reverse concat. // return makeResult(type, s.getValue().concat(getValue()), ctx); // } @SuppressWarnings("unchecked") @Override protected <U extends IValue> Result<U> addString(StringResult s) { // Note the reverse concat. return (Result<U>) new ConcatStringResult(getType(), s, this, ctx); } @Override protected Result<IBool> equalToString(StringResult that) { return that.equalityBoolean(this); } @Override protected Result<IBool> greaterThanString(StringResult that) { return bool(that.getValue().compare(getValue()) > 0, ctx); } @Override protected Result<IBool> greaterThanOrEqualString(StringResult that) { return bool(that.getValue().compare(getValue()) >= 0, ctx); } @Override protected Result<IBool> lessThanString(StringResult that) { return bool(that.getValue().compare(getValue()) < 0, ctx); } @Override public Result<IValue> call(Type[] argTypes, IValue[] argValues, Map<String, IValue> keyArgValues) { String name = getValue().getValue(); IValue node = this.getValueFactory().node(name, argValues, keyArgValues); return makeResult(getTypeFactory().nodeType(), node, ctx); } @Override protected Result<IBool> nonEqualToString(StringResult that) { return that.nonEqualityBoolean(this); } @Override protected LessThanOrEqualResult lessThanOrEqualString(StringResult that) { int cmp = that.getValue().compare(getValue()); return new LessThanOrEqualResult(cmp < 0, cmp == 0, ctx); } @Override protected <U extends IValue> Result<U> addSourceLocation( SourceLocationResult that) { Result<IValue> path = that.fieldAccess("path", new TypeStore()); String parent = ((IString) path.getValue()).getValue(); String child = getValue().getValue(); if (parent.endsWith("/")) { parent = parent.substring(0, parent.length() - 1); } if (!child.startsWith("/")) { child = "/" + child; } return that.fieldUpdate("path", makeResult(getTypeFactory().stringType(), getValueFactory().string(parent + child), ctx), new TypeStore()); } @Override @SuppressWarnings("unchecked") public <U extends IValue, V extends IValue> Result<U> subscript(Result<?>[] subscripts) { if (subscripts.length != 1) { throw new UnsupportedSubscriptArity(getType(), subscripts.length, ctx.getCurrentAST()); } Result<IValue> key = (Result<IValue>) subscripts[0]; if (!key.getType().isInteger()) { throw new UnexpectedType(TypeFactory.getInstance().integerType(), key.getType(), ctx.getCurrentAST()); } if (getValue().getValue().length() == 0) { throw RuntimeExceptionFactory.illegalArgument(ctx.getCurrentAST(), ctx.getStackTrace()); } IInteger index = ((IInteger)key.getValue()); int idx = index.intValue(); if(idx < 0){ - idx = idx + getValue().getValue().length(); + idx = idx + getValue().length(); } - if ( (idx >= getValue().getValue().length()) || (idx < 0) ) { + if ( (idx >= getValue().length()) || (idx < 0) ) { throw RuntimeExceptionFactory.indexOutOfBounds(index, ctx.getCurrentAST(), ctx.getStackTrace()); } - return makeResult(getType(), getValueFactory().string(getValue().getValue().substring(idx, idx + 1)), ctx); + return makeResult(getType(), getValue().substring(idx, idx + 1), ctx); } @Override public <U extends IValue, V extends IValue> Result<U> slice(Result<?> first, Result<?> second, Result<?> end) { return super.slice(first, second, end, getValue().length()); } public Result<IValue> makeSlice(int first, int second, int end){ StringBuilder buffer = new StringBuilder(); IString s = getValue(); int increment = second - first; if(first == end || increment == 0){ // nothing to be done } else if(first <= end){ for(int i = first; i >= 0 && i < end; i += increment){ buffer.appendCodePoint(s.charAt(i)); } } else { for(int j = first; j >= 0 && j > end && j < getValue().length(); j += increment){ buffer.appendCodePoint(s.charAt(j)); } } return makeResult(TypeFactory.getInstance().stringType(), getValueFactory().string(buffer.toString()), ctx); } }
false
true
public <U extends IValue, V extends IValue> Result<U> subscript(Result<?>[] subscripts) { if (subscripts.length != 1) { throw new UnsupportedSubscriptArity(getType(), subscripts.length, ctx.getCurrentAST()); } Result<IValue> key = (Result<IValue>) subscripts[0]; if (!key.getType().isInteger()) { throw new UnexpectedType(TypeFactory.getInstance().integerType(), key.getType(), ctx.getCurrentAST()); } if (getValue().getValue().length() == 0) { throw RuntimeExceptionFactory.illegalArgument(ctx.getCurrentAST(), ctx.getStackTrace()); } IInteger index = ((IInteger)key.getValue()); int idx = index.intValue(); if(idx < 0){ idx = idx + getValue().getValue().length(); } if ( (idx >= getValue().getValue().length()) || (idx < 0) ) { throw RuntimeExceptionFactory.indexOutOfBounds(index, ctx.getCurrentAST(), ctx.getStackTrace()); } return makeResult(getType(), getValueFactory().string(getValue().getValue().substring(idx, idx + 1)), ctx); }
public <U extends IValue, V extends IValue> Result<U> subscript(Result<?>[] subscripts) { if (subscripts.length != 1) { throw new UnsupportedSubscriptArity(getType(), subscripts.length, ctx.getCurrentAST()); } Result<IValue> key = (Result<IValue>) subscripts[0]; if (!key.getType().isInteger()) { throw new UnexpectedType(TypeFactory.getInstance().integerType(), key.getType(), ctx.getCurrentAST()); } if (getValue().getValue().length() == 0) { throw RuntimeExceptionFactory.illegalArgument(ctx.getCurrentAST(), ctx.getStackTrace()); } IInteger index = ((IInteger)key.getValue()); int idx = index.intValue(); if(idx < 0){ idx = idx + getValue().length(); } if ( (idx >= getValue().length()) || (idx < 0) ) { throw RuntimeExceptionFactory.indexOutOfBounds(index, ctx.getCurrentAST(), ctx.getStackTrace()); } return makeResult(getType(), getValue().substring(idx, idx + 1), ctx); }
diff --git a/src/main/java/com/pivotal/demos/upgrade/KnockKnockUpgradeHandler.java b/src/main/java/com/pivotal/demos/upgrade/KnockKnockUpgradeHandler.java index d13cb51..0a732f5 100644 --- a/src/main/java/com/pivotal/demos/upgrade/KnockKnockUpgradeHandler.java +++ b/src/main/java/com/pivotal/demos/upgrade/KnockKnockUpgradeHandler.java @@ -1,50 +1,50 @@ package com.pivotal.demos.upgrade; import java.io.BufferedReader; import java.io.InputStreamReader; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpUpgradeHandler; import javax.servlet.http.WebConnection; public class KnockKnockUpgradeHandler implements HttpUpgradeHandler { @Override public void init(WebConnection con) { // use input / output streams for communications (blocking or non-blocking api can be used) try ( BufferedReader input = new BufferedReader(new InputStreamReader(con.getInputStream())); ServletOutputStream output = con.getOutputStream(); ) { // read the client's standard greeting String greeting = input.readLine(); - if ("knock knock".equals(greeting.toLowerCase())) { + if (greeting != null && "knock knock".equals(greeting.toLowerCase())) { output.write("Who's there?\r\n".getBytes()); output.flush(); // read the joke name String jokeName = input.readLine(); output.write((jokeName + " who?\r\n").getBytes()); output.flush(); // read the punch line String punchLine = input.readLine(); System.out.println("Read punchline [" + punchLine + "]"); // end the session output.write("Lol. Bye!\r\n".getBytes()); output.flush(); } else { output.write("Invalid greeting, please follow proper etiquette.".getBytes()); } } catch (Exception ex) { ex.printStackTrace(System.err); } } @Override public void destroy() { // do nothing } }
true
true
public void init(WebConnection con) { // use input / output streams for communications (blocking or non-blocking api can be used) try ( BufferedReader input = new BufferedReader(new InputStreamReader(con.getInputStream())); ServletOutputStream output = con.getOutputStream(); ) { // read the client's standard greeting String greeting = input.readLine(); if ("knock knock".equals(greeting.toLowerCase())) { output.write("Who's there?\r\n".getBytes()); output.flush(); // read the joke name String jokeName = input.readLine(); output.write((jokeName + " who?\r\n").getBytes()); output.flush(); // read the punch line String punchLine = input.readLine(); System.out.println("Read punchline [" + punchLine + "]"); // end the session output.write("Lol. Bye!\r\n".getBytes()); output.flush(); } else { output.write("Invalid greeting, please follow proper etiquette.".getBytes()); } } catch (Exception ex) { ex.printStackTrace(System.err); } }
public void init(WebConnection con) { // use input / output streams for communications (blocking or non-blocking api can be used) try ( BufferedReader input = new BufferedReader(new InputStreamReader(con.getInputStream())); ServletOutputStream output = con.getOutputStream(); ) { // read the client's standard greeting String greeting = input.readLine(); if (greeting != null && "knock knock".equals(greeting.toLowerCase())) { output.write("Who's there?\r\n".getBytes()); output.flush(); // read the joke name String jokeName = input.readLine(); output.write((jokeName + " who?\r\n").getBytes()); output.flush(); // read the punch line String punchLine = input.readLine(); System.out.println("Read punchline [" + punchLine + "]"); // end the session output.write("Lol. Bye!\r\n".getBytes()); output.flush(); } else { output.write("Invalid greeting, please follow proper etiquette.".getBytes()); } } catch (Exception ex) { ex.printStackTrace(System.err); } }
diff --git a/src/main/java/at/yomi/Lazy.java b/src/main/java/at/yomi/Lazy.java index 96f385a..e9f5f93 100644 --- a/src/main/java/at/yomi/Lazy.java +++ b/src/main/java/at/yomi/Lazy.java @@ -1,47 +1,47 @@ package at.yomi; import java.lang.reflect.Field; import java.lang.reflect.Type; import java.util.HashMap; import java.util.List; import java.util.Map; import static at.yomi.util.ReflectUtil.getActualTypeArguments; public class Lazy<T> { private Map<String, T> cache = new HashMap<String, T>(); private Field field; private Injector injector; Lazy(Injector injector, Field field) { this.injector = injector; this.field = field; } @SuppressWarnings("unchecked") public T bind(String hint) { if (cache.containsKey(hint)) { return cache.get(hint); } Type type = field.getGenericType(); List<Class<?>> args = getActualTypeArguments(type); if (args.size() == 1) { Object instance = injector.getService(args.get(0), hint); if (instance != null) { cache.put(hint, (T) instance); return cache.get(hint); } } Inject injAnn = field.getAnnotation(Inject.class); if (injAnn.required()) { - throw new at.yomi.ServiceNotFoundException(field); + throw new ServiceNotFoundException(field); } return null; } }
true
true
public T bind(String hint) { if (cache.containsKey(hint)) { return cache.get(hint); } Type type = field.getGenericType(); List<Class<?>> args = getActualTypeArguments(type); if (args.size() == 1) { Object instance = injector.getService(args.get(0), hint); if (instance != null) { cache.put(hint, (T) instance); return cache.get(hint); } } Inject injAnn = field.getAnnotation(Inject.class); if (injAnn.required()) { throw new at.yomi.ServiceNotFoundException(field); } return null; }
public T bind(String hint) { if (cache.containsKey(hint)) { return cache.get(hint); } Type type = field.getGenericType(); List<Class<?>> args = getActualTypeArguments(type); if (args.size() == 1) { Object instance = injector.getService(args.get(0), hint); if (instance != null) { cache.put(hint, (T) instance); return cache.get(hint); } } Inject injAnn = field.getAnnotation(Inject.class); if (injAnn.required()) { throw new ServiceNotFoundException(field); } return null; }
diff --git a/src/main/java/net/aetherteam/aether/client/gui/dungeons/GuiDungeonEntrance.java b/src/main/java/net/aetherteam/aether/client/gui/dungeons/GuiDungeonEntrance.java index 3024e48..d1dcc24 100644 --- a/src/main/java/net/aetherteam/aether/client/gui/dungeons/GuiDungeonEntrance.java +++ b/src/main/java/net/aetherteam/aether/client/gui/dungeons/GuiDungeonEntrance.java @@ -1,325 +1,326 @@ package net.aetherteam.aether.client.gui.dungeons; import cpw.mods.fml.client.FMLClientHandler; import java.util.ArrayList; import java.util.List; import net.aetherteam.aether.dungeons.Dungeon; import net.aetherteam.aether.dungeons.DungeonHandler; import net.aetherteam.aether.party.Party; import net.aetherteam.aether.party.PartyController; import net.aetherteam.aether.tile_entities.TileEntityEntranceController; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityClientPlayerMP; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.GuiTextField; import net.minecraft.client.gui.ScaledResolution; import net.minecraft.client.multiplayer.NetClientHandler; import net.minecraft.client.renderer.RenderEngine; import net.minecraft.client.settings.GameSettings; import net.minecraft.client.settings.KeyBinding; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.MathHelper; import org.lwjgl.opengl.GL11; public class GuiDungeonEntrance extends GuiScreen { private int backgroundTexture; private int easterTexture; private int xParty; private int yParty; private int wParty; private int hParty; Minecraft mc; public String[] description; private GuiTextField partyNameField; private EntityPlayer player; private GuiScreen parent; private TileEntityEntranceController controller; public GuiDungeonEntrance(EntityPlayer player, GuiScreen parent, TileEntityEntranceController controller) { this.parent = parent; this.player = player; this.mc = FMLClientHandler.instance().getClient(); this.backgroundTexture = this.mc.renderEngine.getTexture("/net/aetherteam/aether/client/sprites/gui/partyMain.png"); this.easterTexture = this.mc.renderEngine.getTexture("/net/aetherteam/aether/client/sprites/gui/partyMain.png"); this.wParty = 256; this.hParty = 256; updateScreen(); this.controller = controller; } public void initGui() { updateScreen(); this.buttonList.clear(); List playerList = this.mc.thePlayer.sendQueue.playerInfoList; if ((playerList.size() > 1) || (playerList.size() == 0)) { this.buttonList.add(new GuiButton(0, this.xParty - 60, this.yParty + 8 - 28, 120, 20, "加入")); this.buttonList.add(new GuiButton(1, this.xParty - 60, this.yParty + 8 - 28, 120, 20, "离开")); } } protected void actionPerformed(GuiButton button) { Party party = PartyController.instance().getParty(this.player); switch (button.id) { case 0: if ((this.controller != null) && (this.controller.getDungeon() != null) && (!this.controller.getDungeon().hasQueuedParty())) { if (party != null) { int x = MathHelper.floor_double(this.controller.xCoord); int y = MathHelper.floor_double(this.controller.yCoord); int z = MathHelper.floor_double(this.controller.zCoord); DungeonHandler.instance().queueParty(this.controller.getDungeon(), party, x, y, z, true); this.mc.displayGuiScreen((GuiScreen) null); } else { this.mc.displayGuiScreen(new GuiCreateDungeonParty(this.player, this, this.controller)); } } break; case 1: if ((party != null) && (this.controller != null) && (this.controller.getDungeon() != null) && (this.controller.getDungeon().hasMember(PartyController.instance().getMember(this.player)))) { DungeonHandler.instance().disbandMember(this.controller.getDungeon(), PartyController.instance().getMember(this.player), true); } this.mc.displayGuiScreen((GuiScreen) null); } } public boolean doesGuiPauseGame() { return false; } private boolean isQueuedParty(Party party) { if ((party != null) && (this.controller != null) && (this.controller.getDungeon() != null) && (this.controller.getDungeon().isActive()) && (this.controller.getDungeon().isQueuedParty(party))) { return true; } return false; } private boolean hasQueuedParty() { if ((this.controller != null) && (this.controller.getDungeon() != null) && (this.controller.getDungeon().isActive()) && (this.controller.getDungeon().hasQueuedParty())) { return true; } return false; } protected void keyTyped(char charTyped, int keyTyped) { super.keyTyped(charTyped, keyTyped); if (keyTyped == Minecraft.getMinecraft().gameSettings.keyBindInventory.keyCode) { this.mc.displayGuiScreen((GuiScreen) null); this.mc.setIngameFocus(); } } public void drawScreen(int x, int y, float partialTick) { this.buttonList.clear(); drawDefaultBackground(); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); GL11.glBindTexture(3553, this.backgroundTexture); int centerX = this.xParty - 70; int centerY = this.yParty - 84; ScaledResolution sr = new ScaledResolution(this.mc.gameSettings, this.mc.displayWidth, this.mc.displayHeight); drawTexturedModalRect(centerX, centerY, 0, 0, 141, this.hParty); Party party = PartyController.instance().getParty(this.player); boolean isLeader = PartyController.instance().isLeader(this.player); GuiButton sendButton = new GuiButton(0, this.xParty - 59, this.yParty + 55, 55, 20, (party == null) || (party.getSize() <= 1) ? "进入" : "发送"); GuiButton leaveButton = new GuiButton(1, this.xParty + 6 - (hasQueuedParty() ? 32 : 0), this.yParty + 55, 55, 20, "离开"); if ((this.controller.getDungeon() != null) && (!this.controller.getDungeon().isActive()) && (this.controller != null)) { this.buttonList.add(sendButton); if ((party != null) && ((this.controller.getDungeon().isQueuedParty(party)) || (this.controller.getDungeon().hasAnyConqueredDungeon(party.getMembers())) || (!isLeader))) { sendButton.enabled = false; } } this.buttonList.add(leaveButton); this.mc.renderEngine.resetBoundTexture(); this.partyNameField = new GuiTextField(this.fontRenderer, this.xParty - 63, this.yParty - 58, 125, 107); this.partyNameField.setFocused(false); this.partyNameField.setMaxStringLength(5000); this.partyNameField.drawTextBox(); drawString(this.fontRenderer, "警告!!!", centerX + 70 - this.fontRenderer.getStringWidth("警告!!!") / 2, centerY + 10, 15658734); if ((this.controller != null) && (this.controller.hasDungeon())) { if (((party == null) && (!isLeader)) || ((isLeader) && (party.getSize() <= 1) && (party != null) && (!this.controller.getDungeon().hasAnyConqueredDungeon(party.getMembers())) && (!this.controller.getDungeon().hasQueuedParty()))) { GL11.glBindTexture(3553, this.backgroundTexture); this.mc.renderEngine.resetBoundTexture(); this.description = new String[10]; this.description[0] = "你试图独闯滑行者的迷宫. "; this.description[1] = "这个迷宫危险无比, "; this.description[2] = "你随时可能付出生命"; this.description[3] = "并且损失掉全部的物品"; this.description[4] = "你将因此失去一切"; this.description[5] = "但地牢深处有值得探索的宝藏"; + this.description[6] = ""; this.description[7] = ""; this.description[8] = "那么, "; this.description[9] = "你是否已经准备好进入地牢?"; int count = 0; for (String string : this.description) { drawString(this.fontRenderer, string, centerX + 70 - this.fontRenderer.getStringWidth(string) / 2, centerY + 30 + count * 10, 15658734); count++; } } else { this.mc.renderEngine.resetBoundTexture(); ArrayList members = new ArrayList(); if (party != null) { members = party.getMembers(); } if ((this.controller.getDungeon().hasQueuedParty()) && ((!this.controller.getDungeon().isQueuedParty(party)) || ((this.controller.getDungeon().isQueuedParty(party)) && (!this.controller.getDungeon().hasMember(PartyController.instance().getMember(this.player)))))) { this.description = new String[6]; this.description[0] = "抱歉, 此时此刻, 地牢"; this.description[1] = "已经被人闯入, 攻略者来自"; if ((this.controller.getDungeon().isQueuedParty(party)) && (!this.controller.getDungeon().hasMember(PartyController.instance().getMember(this.player)))) { this.description[2] = "你的公会"; } else this.description[2] = "其他公会"; this.description[3] = ""; this.description[4] = "请稍等一会"; this.description[5] = "儿再来试试"; } else if ((this.controller.getDungeon().isQueuedParty(party)) && (this.controller.getDungeon().hasMember(PartyController.instance().getMember(this.player)))) { if (this.controller.getDungeon().isActive()) { this.description = new String[8]; this.description[0] = "你真的想要离开"; this.description[1] = "这个地牢?"; this.description[2] = "你还有"; this.description[3] = (3 - this.controller.getDungeon().getMemberLeaves(PartyController.instance().getMember(this.player)) + "/3 次离开机会."); this.description[4] = ""; this.description[5] = "在彻底重置之前"; this.description[6] = "每个地牢仅仅允许"; this.description[7] = "离开三次"; } else { this.description = new String[7]; this.description[0] = "你的公会正排队"; this.description[1] = "进入地牢中"; this.description[2] = ""; this.description[3] = ""; this.description[4] = "请等待你的其他队友"; this.description[5] = "接受组队探险的"; this.description[6] = "邀请"; } } else if (this.controller.getDungeon().hasAnyConqueredDungeon(members)) { this.description = new String[8]; this.description[0] = "抱歉, 该地牢正"; this.description[1] = "被你的公会成员"; this.description[2] = "努力攻略中"; this.description[3] = ""; this.description[4] = ""; this.description[5] = ""; this.description[6] = "请你去其他地方探索或者等待"; this.description[7] = "队友凯旋而归"; } else if (isLeader) { this.description = new String[7]; this.description[0] = "你是否想要和你的公会"; this.description[1] = "一起勇闯滑行者的迷宫?"; this.description[2] = ""; this.description[3] = ""; this.description[4] = ""; this.description[5] = "如果是这样的话, 请发送"; this.description[6] = "邀请给你的队友"; } else { this.description = new String[8]; this.description[0] = "你是否想要和你的公会"; this.description[1] = "一起勇闯滑行者的迷宫?"; this.description[2] = ""; this.description[3] = ""; this.description[4] = ""; this.description[5] = "如果是这样的话, 请发送"; this.description[6] = "邀请给你的队长, "; this.description[7] = "让他申请进入地牢"; } int count = 0; for (String string : this.description) { drawString(this.fontRenderer, string, centerX + 70 - this.fontRenderer.getStringWidth(string) / 2, centerY + (isLeader ? 30 : 40) + count * 10, 15658734); count++; } } } super.drawScreen(x, y, partialTick); } public void updateScreen() { super.updateScreen(); ScaledResolution scaledresolution = new ScaledResolution(this.mc.gameSettings, this.mc.displayWidth, this.mc.displayHeight); int width = scaledresolution.getScaledWidth(); int height = scaledresolution.getScaledHeight(); this.xParty = (width / 2); this.yParty = (height / 2); } } /* Location: D:\Dev\Mc\forge_orl\mcp\jars\bin\aether.jar * Qualified Name: net.aetherteam.aether.client.gui.dungeons.GuiDungeonEntrance * JD-Core Version: 0.6.2 */
true
true
public void drawScreen(int x, int y, float partialTick) { this.buttonList.clear(); drawDefaultBackground(); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); GL11.glBindTexture(3553, this.backgroundTexture); int centerX = this.xParty - 70; int centerY = this.yParty - 84; ScaledResolution sr = new ScaledResolution(this.mc.gameSettings, this.mc.displayWidth, this.mc.displayHeight); drawTexturedModalRect(centerX, centerY, 0, 0, 141, this.hParty); Party party = PartyController.instance().getParty(this.player); boolean isLeader = PartyController.instance().isLeader(this.player); GuiButton sendButton = new GuiButton(0, this.xParty - 59, this.yParty + 55, 55, 20, (party == null) || (party.getSize() <= 1) ? "进入" : "发送"); GuiButton leaveButton = new GuiButton(1, this.xParty + 6 - (hasQueuedParty() ? 32 : 0), this.yParty + 55, 55, 20, "离开"); if ((this.controller.getDungeon() != null) && (!this.controller.getDungeon().isActive()) && (this.controller != null)) { this.buttonList.add(sendButton); if ((party != null) && ((this.controller.getDungeon().isQueuedParty(party)) || (this.controller.getDungeon().hasAnyConqueredDungeon(party.getMembers())) || (!isLeader))) { sendButton.enabled = false; } } this.buttonList.add(leaveButton); this.mc.renderEngine.resetBoundTexture(); this.partyNameField = new GuiTextField(this.fontRenderer, this.xParty - 63, this.yParty - 58, 125, 107); this.partyNameField.setFocused(false); this.partyNameField.setMaxStringLength(5000); this.partyNameField.drawTextBox(); drawString(this.fontRenderer, "警告!!!", centerX + 70 - this.fontRenderer.getStringWidth("警告!!!") / 2, centerY + 10, 15658734); if ((this.controller != null) && (this.controller.hasDungeon())) { if (((party == null) && (!isLeader)) || ((isLeader) && (party.getSize() <= 1) && (party != null) && (!this.controller.getDungeon().hasAnyConqueredDungeon(party.getMembers())) && (!this.controller.getDungeon().hasQueuedParty()))) { GL11.glBindTexture(3553, this.backgroundTexture); this.mc.renderEngine.resetBoundTexture(); this.description = new String[10]; this.description[0] = "你试图独闯滑行者的迷宫. "; this.description[1] = "这个迷宫危险无比, "; this.description[2] = "你随时可能付出生命"; this.description[3] = "并且损失掉全部的物品"; this.description[4] = "你将因此失去一切"; this.description[5] = "但地牢深处有值得探索的宝藏"; this.description[7] = ""; this.description[8] = "那么, "; this.description[9] = "你是否已经准备好进入地牢?"; int count = 0; for (String string : this.description) { drawString(this.fontRenderer, string, centerX + 70 - this.fontRenderer.getStringWidth(string) / 2, centerY + 30 + count * 10, 15658734); count++; } } else { this.mc.renderEngine.resetBoundTexture(); ArrayList members = new ArrayList(); if (party != null) { members = party.getMembers(); } if ((this.controller.getDungeon().hasQueuedParty()) && ((!this.controller.getDungeon().isQueuedParty(party)) || ((this.controller.getDungeon().isQueuedParty(party)) && (!this.controller.getDungeon().hasMember(PartyController.instance().getMember(this.player)))))) { this.description = new String[6]; this.description[0] = "抱歉, 此时此刻, 地牢"; this.description[1] = "已经被人闯入, 攻略者来自"; if ((this.controller.getDungeon().isQueuedParty(party)) && (!this.controller.getDungeon().hasMember(PartyController.instance().getMember(this.player)))) { this.description[2] = "你的公会"; } else this.description[2] = "其他公会"; this.description[3] = ""; this.description[4] = "请稍等一会"; this.description[5] = "儿再来试试"; } else if ((this.controller.getDungeon().isQueuedParty(party)) && (this.controller.getDungeon().hasMember(PartyController.instance().getMember(this.player)))) { if (this.controller.getDungeon().isActive()) { this.description = new String[8]; this.description[0] = "你真的想要离开"; this.description[1] = "这个地牢?"; this.description[2] = "你还有"; this.description[3] = (3 - this.controller.getDungeon().getMemberLeaves(PartyController.instance().getMember(this.player)) + "/3 次离开机会."); this.description[4] = ""; this.description[5] = "在彻底重置之前"; this.description[6] = "每个地牢仅仅允许"; this.description[7] = "离开三次"; } else { this.description = new String[7]; this.description[0] = "你的公会正排队"; this.description[1] = "进入地牢中"; this.description[2] = ""; this.description[3] = ""; this.description[4] = "请等待你的其他队友"; this.description[5] = "接受组队探险的"; this.description[6] = "邀请"; } } else if (this.controller.getDungeon().hasAnyConqueredDungeon(members)) { this.description = new String[8]; this.description[0] = "抱歉, 该地牢正"; this.description[1] = "被你的公会成员"; this.description[2] = "努力攻略中"; this.description[3] = ""; this.description[4] = ""; this.description[5] = ""; this.description[6] = "请你去其他地方探索或者等待"; this.description[7] = "队友凯旋而归"; } else if (isLeader) { this.description = new String[7]; this.description[0] = "你是否想要和你的公会"; this.description[1] = "一起勇闯滑行者的迷宫?"; this.description[2] = ""; this.description[3] = ""; this.description[4] = ""; this.description[5] = "如果是这样的话, 请发送"; this.description[6] = "邀请给你的队友"; } else { this.description = new String[8]; this.description[0] = "你是否想要和你的公会"; this.description[1] = "一起勇闯滑行者的迷宫?"; this.description[2] = ""; this.description[3] = ""; this.description[4] = ""; this.description[5] = "如果是这样的话, 请发送"; this.description[6] = "邀请给你的队长, "; this.description[7] = "让他申请进入地牢"; } int count = 0; for (String string : this.description) { drawString(this.fontRenderer, string, centerX + 70 - this.fontRenderer.getStringWidth(string) / 2, centerY + (isLeader ? 30 : 40) + count * 10, 15658734); count++; } } } super.drawScreen(x, y, partialTick); }
public void drawScreen(int x, int y, float partialTick) { this.buttonList.clear(); drawDefaultBackground(); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); GL11.glBindTexture(3553, this.backgroundTexture); int centerX = this.xParty - 70; int centerY = this.yParty - 84; ScaledResolution sr = new ScaledResolution(this.mc.gameSettings, this.mc.displayWidth, this.mc.displayHeight); drawTexturedModalRect(centerX, centerY, 0, 0, 141, this.hParty); Party party = PartyController.instance().getParty(this.player); boolean isLeader = PartyController.instance().isLeader(this.player); GuiButton sendButton = new GuiButton(0, this.xParty - 59, this.yParty + 55, 55, 20, (party == null) || (party.getSize() <= 1) ? "进入" : "发送"); GuiButton leaveButton = new GuiButton(1, this.xParty + 6 - (hasQueuedParty() ? 32 : 0), this.yParty + 55, 55, 20, "离开"); if ((this.controller.getDungeon() != null) && (!this.controller.getDungeon().isActive()) && (this.controller != null)) { this.buttonList.add(sendButton); if ((party != null) && ((this.controller.getDungeon().isQueuedParty(party)) || (this.controller.getDungeon().hasAnyConqueredDungeon(party.getMembers())) || (!isLeader))) { sendButton.enabled = false; } } this.buttonList.add(leaveButton); this.mc.renderEngine.resetBoundTexture(); this.partyNameField = new GuiTextField(this.fontRenderer, this.xParty - 63, this.yParty - 58, 125, 107); this.partyNameField.setFocused(false); this.partyNameField.setMaxStringLength(5000); this.partyNameField.drawTextBox(); drawString(this.fontRenderer, "警告!!!", centerX + 70 - this.fontRenderer.getStringWidth("警告!!!") / 2, centerY + 10, 15658734); if ((this.controller != null) && (this.controller.hasDungeon())) { if (((party == null) && (!isLeader)) || ((isLeader) && (party.getSize() <= 1) && (party != null) && (!this.controller.getDungeon().hasAnyConqueredDungeon(party.getMembers())) && (!this.controller.getDungeon().hasQueuedParty()))) { GL11.glBindTexture(3553, this.backgroundTexture); this.mc.renderEngine.resetBoundTexture(); this.description = new String[10]; this.description[0] = "你试图独闯滑行者的迷宫. "; this.description[1] = "这个迷宫危险无比, "; this.description[2] = "你随时可能付出生命"; this.description[3] = "并且损失掉全部的物品"; this.description[4] = "你将因此失去一切"; this.description[5] = "但地牢深处有值得探索的宝藏"; this.description[6] = ""; this.description[7] = ""; this.description[8] = "那么, "; this.description[9] = "你是否已经准备好进入地牢?"; int count = 0; for (String string : this.description) { drawString(this.fontRenderer, string, centerX + 70 - this.fontRenderer.getStringWidth(string) / 2, centerY + 30 + count * 10, 15658734); count++; } } else { this.mc.renderEngine.resetBoundTexture(); ArrayList members = new ArrayList(); if (party != null) { members = party.getMembers(); } if ((this.controller.getDungeon().hasQueuedParty()) && ((!this.controller.getDungeon().isQueuedParty(party)) || ((this.controller.getDungeon().isQueuedParty(party)) && (!this.controller.getDungeon().hasMember(PartyController.instance().getMember(this.player)))))) { this.description = new String[6]; this.description[0] = "抱歉, 此时此刻, 地牢"; this.description[1] = "已经被人闯入, 攻略者来自"; if ((this.controller.getDungeon().isQueuedParty(party)) && (!this.controller.getDungeon().hasMember(PartyController.instance().getMember(this.player)))) { this.description[2] = "你的公会"; } else this.description[2] = "其他公会"; this.description[3] = ""; this.description[4] = "请稍等一会"; this.description[5] = "儿再来试试"; } else if ((this.controller.getDungeon().isQueuedParty(party)) && (this.controller.getDungeon().hasMember(PartyController.instance().getMember(this.player)))) { if (this.controller.getDungeon().isActive()) { this.description = new String[8]; this.description[0] = "你真的想要离开"; this.description[1] = "这个地牢?"; this.description[2] = "你还有"; this.description[3] = (3 - this.controller.getDungeon().getMemberLeaves(PartyController.instance().getMember(this.player)) + "/3 次离开机会."); this.description[4] = ""; this.description[5] = "在彻底重置之前"; this.description[6] = "每个地牢仅仅允许"; this.description[7] = "离开三次"; } else { this.description = new String[7]; this.description[0] = "你的公会正排队"; this.description[1] = "进入地牢中"; this.description[2] = ""; this.description[3] = ""; this.description[4] = "请等待你的其他队友"; this.description[5] = "接受组队探险的"; this.description[6] = "邀请"; } } else if (this.controller.getDungeon().hasAnyConqueredDungeon(members)) { this.description = new String[8]; this.description[0] = "抱歉, 该地牢正"; this.description[1] = "被你的公会成员"; this.description[2] = "努力攻略中"; this.description[3] = ""; this.description[4] = ""; this.description[5] = ""; this.description[6] = "请你去其他地方探索或者等待"; this.description[7] = "队友凯旋而归"; } else if (isLeader) { this.description = new String[7]; this.description[0] = "你是否想要和你的公会"; this.description[1] = "一起勇闯滑行者的迷宫?"; this.description[2] = ""; this.description[3] = ""; this.description[4] = ""; this.description[5] = "如果是这样的话, 请发送"; this.description[6] = "邀请给你的队友"; } else { this.description = new String[8]; this.description[0] = "你是否想要和你的公会"; this.description[1] = "一起勇闯滑行者的迷宫?"; this.description[2] = ""; this.description[3] = ""; this.description[4] = ""; this.description[5] = "如果是这样的话, 请发送"; this.description[6] = "邀请给你的队长, "; this.description[7] = "让他申请进入地牢"; } int count = 0; for (String string : this.description) { drawString(this.fontRenderer, string, centerX + 70 - this.fontRenderer.getStringWidth(string) / 2, centerY + (isLeader ? 30 : 40) + count * 10, 15658734); count++; } } } super.drawScreen(x, y, partialTick); }
diff --git a/src/simpleserver/stream/StreamTunnel.java b/src/simpleserver/stream/StreamTunnel.java index 29322ae..41f73b9 100644 --- a/src/simpleserver/stream/StreamTunnel.java +++ b/src/simpleserver/stream/StreamTunnel.java @@ -1,780 +1,781 @@ /******************************************************************************* * Open Source Initiative OSI - The MIT License:Licensing * The MIT License * Copyright (c) 2010 Charles Wagner Jr. ([email protected]) * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ package simpleserver.stream; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.DataInput; import java.io.DataInputStream; import java.io.DataOutput; import java.io.DataOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.IllegalFormatException; import java.util.regex.Matcher; import java.util.regex.Pattern; import simpleserver.Group; import simpleserver.Player; import simpleserver.Server; public class StreamTunnel { private static final boolean EXPENSIVE_DEBUG_LOGGING = Boolean.getBoolean("EXPENSIVE_DEBUG_LOGGING"); private static final int IDLE_TIME = 30000; private static final int BUFFER_SIZE = 1024; private static final int DESTROY_HITS = 14; private static final byte BLOCK_DESTROYED_STATUS = 3; private static final Pattern MESSAGE_PATTERN = Pattern.compile("^<([^>]+)> (.*)$"); private final boolean isServerTunnel; private final String streamType; private final Player player; private final Server server; private final byte[] buffer; private final Tunneler tunneler; private DataInput in; private DataOutput out; private StreamDumper inputDumper; private StreamDumper outputDumper; private int motionCounter = 0; private boolean inGame = false; private volatile long lastRead; private volatile boolean run = true; public StreamTunnel(InputStream in, OutputStream out, boolean isServerTunnel, Player player) { this.isServerTunnel = isServerTunnel; if (isServerTunnel) { streamType = "ServerStream"; } else { streamType = "PlayerStream"; } this.player = player; server = player.getServer(); DataInputStream dIn = new DataInputStream(new BufferedInputStream(in)); DataOutputStream dOut = new DataOutputStream(new BufferedOutputStream(out)); if (EXPENSIVE_DEBUG_LOGGING) { try { OutputStream dump = new FileOutputStream(streamType + "Input.debug"); InputStreamDumper dumper = new InputStreamDumper(dIn, dump); inputDumper = dumper; this.in = dumper; } catch (FileNotFoundException e) { System.out.println("Unable to open input debug dump!"); throw new RuntimeException(e); } try { OutputStream dump = new FileOutputStream(streamType + "Output.debug"); OutputStreamDumper dumper = new OutputStreamDumper(dOut, dump); outputDumper = dumper; this.out = dumper; } catch (FileNotFoundException e) { System.out.println("Unable to open output debug dump!"); throw new RuntimeException(e); } } else { this.in = dIn; this.out = dOut; } buffer = new byte[BUFFER_SIZE]; tunneler = new Tunneler(); tunneler.start(); lastRead = System.currentTimeMillis(); } public void stop() { run = false; } public boolean isAlive() { return tunneler.isAlive(); } public boolean isActive() { return System.currentTimeMillis() - lastRead < IDLE_TIME || player.isRobot(); } private void handlePacket() throws IOException { Byte packetId = in.readByte(); switch (packetId) { case 0x00: // Keep Alive write(packetId); break; case 0x01: // Login Request/Response write(packetId); write(in.readInt()); write(in.readUTF()); write(in.readUTF()); write(in.readLong()); write(in.readByte()); break; case 0x02: // Handshake String name = in.readUTF(); if (isServerTunnel || player.setName(name)) { tunneler.setName(streamType + "-" + player.getName()); write(packetId); write(name); } break; case 0x03: // Chat Message String message = in.readUTF(); if (isServerTunnel && server.options.getBoolean("useMsgFormats")) { Matcher messageMatcher = MESSAGE_PATTERN.matcher(message); if (messageMatcher.find()) { Player friend = server.findPlayerExact(messageMatcher.group(1)); if (friend != null) { String color = "f"; String title = ""; String format = server.options.get("msgFormat"); Group group = friend.getGroup(); if (group != null) { color = group.getColor(); if (group.showTitle()) { title = group.getName(); format = server.options.get("msgTitleFormat"); } } try { message = String.format(format, friend.getName(), title, color) + messageMatcher.group(2); } catch (IllegalFormatException e) { System.out.println("[SimpleServer] There is an error in your msgFormat/msgTitleFormat settings!"); } } } } if (!isServerTunnel) { if (player.isMuted() && !message.startsWith("/") && !message.startsWith("!")) { player.addMessage("You are muted! You may not send messages to all players."); break; } if (server.options.getBoolean("useSlashes") && message.startsWith("/") || message.startsWith("!") && player.parseCommand(message)) { break; } } write(packetId); write(message); break; case 0x04: // Time Update write(packetId); copyNBytes(8); break; case 0x05: // Player Inventory write(packetId); write(in.readInt()); write(in.readShort()); write(in.readShort()); break; /* boolean guest = player.getGroupId() < 0; int inventoryType = in.readInt(); short itemCount = in.readShort(); if (!guest) { write(packetId); write(inventoryType); write(itemCount); } for (int c = 0; c < itemCount; ++c) { short itemId = in.readShort(); if (!guest) { write(itemId); } if (itemId != -1) { byte itemAmount = in.readByte(); short itemUses = in.readShort(); if (!guest) { write(itemAmount); write(itemUses); } if (!server.itemWatch.playerAllowed(player, itemId, itemAmount)) { server.adminLog("ItemWatchList banned player:\t" + player.getName()); server.banKick(player.getName()); } } } break; */ case 0x06: // Spawn Position write(packetId); copyNBytes(12); break; case 0x07: // Use Entity? write(packetId); copyNBytes(9); break; case 0x08: // Update Health write(packetId); copyNBytes(2); break; case 0x09: // Respawn write(packetId); break; case 0x0a: // Player write(packetId); copyNBytes(1); if (!inGame && !isServerTunnel) { player.sendMOTD(); inGame = true; } break; case 0x0b: // Player Position write(packetId); copyPlayerLocation(); break; case 0x0c: // Player Look write(packetId); copyNBytes(9); break; case 0x0d: // Player Position & Look write(packetId); copyPlayerLocation(); copyNBytes(8); break; case 0x0e: // Player Digging if (!isServerTunnel) { if (player.getGroupId() < 0) { skipNBytes(11); } else { byte status = in.readByte(); int x = in.readInt(); byte y = in.readByte(); int z = in.readInt(); byte face = in.readByte(); if (!server.chests.hasLock(x, y, z) || player.isAdmin()) { if (server.chests.hasLock(x, y, z) && status == BLOCK_DESTROYED_STATUS) { server.chests.releaseLock(x, y, z); } write(packetId); write(status); write(x); write(y); write(z); write(face); if (player.instantDestroyEnabled()) { for (int c = 1; c < DESTROY_HITS; ++c) { packetFinished(); write(packetId); write(status); write(x); write(y); write(z); write(face); } packetFinished(); write(packetId); write(BLOCK_DESTROYED_STATUS); write(x); write(y); write(z); write(face); } } } } else { write(packetId); copyNBytes(11); } break; case 0x0f: // Player Block Placement write(packetId); write(in.readInt()); write(in.readByte()); write(in.readInt()); write(in.readByte()); short dropItem = in.readShort(); write(dropItem); if (dropItem != -1) { write(in.readByte()); write(in.readByte()); } break; /* short blockId = in.readShort(); if (!isServerTunnel && (player.getGroupId() < 0) || !server.blockFirewall.playerAllowed(player, blockId)) { int x = in.readInt(); skipNBytes(6); if (x != -1) { server.runCommand("say", String.format(server.l.get("BAD_BLOCK"), player.getName(), Short.toString(blockId))); } } else if (!isServerTunnel && (blockId == 54) && player.isAttemptLock()) { int x = in.readInt(); byte y = in.readByte(); int z = in.readInt(); byte direction = in.readByte(); write(packetId); write(blockId); write(x); write(y); write(z); write(direction); switch (direction) { case 0: y--; break; case 1: y++; break; case 2: z--; break; case 3: z++; break; case 4: x--; break; case 5: x++; break; } // create chest entry if (server.chests.hasLock(x, y, z)) { player.addMessage("This block is locked already!"); } else if (server.chests.giveLock(player.getName(), x, y, z, false)) { player.addMessage("Your locked chest is created! Do not add another chest to it!"); } else { player.addMessage("You already have a lock, or this block is locked already!"); } player.setAttemptLock(false); } else { write(packetId); write(blockId); copyNBytes(10); } break; */ case 0x10: // Holding Change write(packetId); copyNBytes(2); break; case 0x12: // Animation write(packetId); copyNBytes(5); break; case 0x14: // Named Entity Spawn write(packetId); write(in.readInt()); write(in.readUTF()); copyNBytes(16); break; case 0x15: // Pickup spawn if (player.getGroupId() < 0) { skipNBytes(22); break; } write(packetId); copyNBytes(22); break; case 0x16: // Collect Item write(packetId); copyNBytes(8); break; case 0x17: // Add Object/Vehicle write(packetId); copyNBytes(17); break; case 0x18: // Mob Spawn write(packetId); copyNBytes(19); break; case 0x1c: // Entity Velocity? write(packetId); copyNBytes(10); break; case 0x1D: // Destroy Entity write(packetId); copyNBytes(4); break; case 0x1E: // Entity write(packetId); copyNBytes(4); break; case 0x1F: // Entity Relative Move write(packetId); copyNBytes(7); break; case 0x20: // Entity Look write(packetId); copyNBytes(6); break; case 0x21: // Entity Look and Relative Move write(packetId); copyNBytes(9); break; case 0x22: // Entity Teleport write(packetId); copyNBytes(18); break; case 0x26: // Entity status? write(packetId); copyNBytes(5); break; case 0x27: // Attach Entity? write(packetId); copyNBytes(8); break; case 0x32: // Pre-Chunk write(packetId); copyNBytes(9); break; case 0x33: // Map Chunk write(packetId); copyNBytes(13); int chunkSize = in.readInt(); write(chunkSize); copyNBytes(chunkSize); break; case 0x34: // Multi Block Change write(packetId); copyNBytes(8); short arraySize = in.readShort(); write(arraySize); copyNBytes(arraySize * 4); break; case 0x35: // Block Change write(packetId); copyNBytes(11); break; /* case 0x3b: // Complex Entities int x = in.readInt(); short y = in.readShort(); int z = in.readInt(); short payloadSize = in.readShort(); if (server.chests.hasLock(x, (byte) y, z) && !player.isAdmin() && !server.chests.ownsLock(player.getName(), x, (byte) y, z)) { skipNBytes(payloadSize); } else if (player.getGroupId() < 0 && !server.options.getBoolean("guestsCanViewComplex")) { skipNBytes(payloadSize); } else { write(packetId); write(x); write(y); write(z); write(payloadSize); copyNBytes(payloadSize); } break; */ case 0x3c: // Explosion write(packetId); copyNBytes(28); int recordCount = in.readInt(); write(recordCount); copyNBytes(recordCount * 3); break; case 0x64: write(packetId); write(in.readByte()); write(in.readByte()); write(in.readInt()); write(in.readByte()); break; case 0x65: write(packetId); write(in.readByte()); break; case 0x66: // Inventory Item Move write(packetId); write(in.readByte()); write(in.readShort()); write(in.readByte()); write(in.readShort()); short moveItem = in.readShort(); write(moveItem); if (moveItem != -1) { write(in.readByte()); write(in.readByte()); } break; case 0x67: // Inventory Item Update write(packetId); write(in.readByte()); write(in.readShort()); short setItem = in.readShort(); write(setItem); if (setItem != -1) { write(in.readByte()); write(in.readByte()); } break; case 0x68: // Inventory write(packetId); write(in.readByte()); short count = in.readShort(); write(count); for (int c = 0; c < count; ++c) { short item = in.readShort(); write(item); if (item != -1) { write(in.readByte()); write(in.readShort()); } } break; case 0x69: write(packetId); write(in.readByte()); write(in.readShort()); write(in.readShort()); break; case 0x6a: write(packetId); write(in.readByte()); write(in.readShort()); write(in.readByte()); break; case (byte) 0x82: // Update Sign write(packetId); write(in.readInt()); write(in.readShort()); write(in.readInt()); write(in.readUTF()); write(in.readUTF()); write(in.readUTF()); + write(in.readUTF()); break; case (byte) 0xff: // Disconnect/Kick write(packetId); String reason = in.readUTF(); write(reason); if (reason.startsWith("Took too long")) { server.addRobot(player); } player.close(); break; default: if (EXPENSIVE_DEBUG_LOGGING) { while (true) { skipNBytes(1); flushAll(); } } else { throw new IOException("Unable to parse unknown " + streamType + " packet 0x" + Integer.toHexString(packetId) + " for player " + player.getName()); } } packetFinished(); } private void copyPlayerLocation() throws IOException { if (!isServerTunnel) { motionCounter++; } if (!isServerTunnel && motionCounter % 8 == 0) { double x = in.readDouble(); double y = in.readDouble(); double stance = in.readDouble(); double z = in.readDouble(); player.updateLocation(x, y, z, stance); write(x); write(y); write(stance); write(z); copyNBytes(1); } else { copyNBytes(33); } } private void write(byte b) throws IOException { out.writeByte(b); } private void write(short s) throws IOException { out.writeShort(s); } private void write(int i) throws IOException { out.writeInt(i); } private void write(long l) throws IOException { out.writeLong(l); } @SuppressWarnings("unused") private void write(float f) throws IOException { out.writeFloat(f); } private void write(double d) throws IOException { out.writeDouble(d); } private void write(String s) throws IOException { out.writeUTF(s); } @SuppressWarnings("unused") private void write(boolean b) throws IOException { out.writeBoolean(b); } private void skipNBytes(int bytes) throws IOException { int overflow = bytes / buffer.length; for (int c = 0; c < overflow; ++c) { in.readFully(buffer, 0, buffer.length); } in.readFully(buffer, 0, bytes % buffer.length); } private void copyNBytes(int bytes) throws IOException { int overflow = bytes / buffer.length; for (int c = 0; c < overflow; ++c) { in.readFully(buffer, 0, buffer.length); out.write(buffer, 0, buffer.length); } in.readFully(buffer, 0, bytes % buffer.length); out.write(buffer, 0, bytes % buffer.length); } private void kick(String reason) throws IOException { write((byte) 0xff); write(reason); packetFinished(); } private void sendMessage(String message) throws IOException { write(0x03); write(message); packetFinished(); } private void packetFinished() throws IOException { if (EXPENSIVE_DEBUG_LOGGING) { inputDumper.packetFinished(); outputDumper.packetFinished(); } } private void flushAll() throws IOException { try { ((OutputStream) out).flush(); } finally { if (EXPENSIVE_DEBUG_LOGGING) { inputDumper.flush(); } } } private final class Tunneler extends Thread { @Override public void run() { try { while (run) { lastRead = System.currentTimeMillis(); try { handlePacket(); if (isServerTunnel) { while (player.hasMessages()) { sendMessage(player.getMessage()); } } flushAll(); } catch (IOException e) { if (run) { e.printStackTrace(); System.out.println(streamType + " error handling traffic for " + player.getName()); } break; } } try { if (player.isKicked()) { kick(player.getKickMsg()); } flushAll(); } catch (IOException e) { } } finally { if (EXPENSIVE_DEBUG_LOGGING) { inputDumper.cleanup(); outputDumper.cleanup(); } } } } }
true
true
private void handlePacket() throws IOException { Byte packetId = in.readByte(); switch (packetId) { case 0x00: // Keep Alive write(packetId); break; case 0x01: // Login Request/Response write(packetId); write(in.readInt()); write(in.readUTF()); write(in.readUTF()); write(in.readLong()); write(in.readByte()); break; case 0x02: // Handshake String name = in.readUTF(); if (isServerTunnel || player.setName(name)) { tunneler.setName(streamType + "-" + player.getName()); write(packetId); write(name); } break; case 0x03: // Chat Message String message = in.readUTF(); if (isServerTunnel && server.options.getBoolean("useMsgFormats")) { Matcher messageMatcher = MESSAGE_PATTERN.matcher(message); if (messageMatcher.find()) { Player friend = server.findPlayerExact(messageMatcher.group(1)); if (friend != null) { String color = "f"; String title = ""; String format = server.options.get("msgFormat"); Group group = friend.getGroup(); if (group != null) { color = group.getColor(); if (group.showTitle()) { title = group.getName(); format = server.options.get("msgTitleFormat"); } } try { message = String.format(format, friend.getName(), title, color) + messageMatcher.group(2); } catch (IllegalFormatException e) { System.out.println("[SimpleServer] There is an error in your msgFormat/msgTitleFormat settings!"); } } } } if (!isServerTunnel) { if (player.isMuted() && !message.startsWith("/") && !message.startsWith("!")) { player.addMessage("You are muted! You may not send messages to all players."); break; } if (server.options.getBoolean("useSlashes") && message.startsWith("/") || message.startsWith("!") && player.parseCommand(message)) { break; } } write(packetId); write(message); break; case 0x04: // Time Update write(packetId); copyNBytes(8); break; case 0x05: // Player Inventory write(packetId); write(in.readInt()); write(in.readShort()); write(in.readShort()); break; /* boolean guest = player.getGroupId() < 0; int inventoryType = in.readInt(); short itemCount = in.readShort(); if (!guest) { write(packetId); write(inventoryType); write(itemCount); } for (int c = 0; c < itemCount; ++c) { short itemId = in.readShort(); if (!guest) { write(itemId); } if (itemId != -1) { byte itemAmount = in.readByte(); short itemUses = in.readShort(); if (!guest) { write(itemAmount); write(itemUses); } if (!server.itemWatch.playerAllowed(player, itemId, itemAmount)) { server.adminLog("ItemWatchList banned player:\t" + player.getName()); server.banKick(player.getName()); } } } break; */ case 0x06: // Spawn Position write(packetId); copyNBytes(12); break; case 0x07: // Use Entity? write(packetId); copyNBytes(9); break; case 0x08: // Update Health write(packetId); copyNBytes(2); break; case 0x09: // Respawn write(packetId); break; case 0x0a: // Player write(packetId); copyNBytes(1); if (!inGame && !isServerTunnel) { player.sendMOTD(); inGame = true; } break; case 0x0b: // Player Position write(packetId); copyPlayerLocation(); break; case 0x0c: // Player Look write(packetId); copyNBytes(9); break; case 0x0d: // Player Position & Look write(packetId); copyPlayerLocation(); copyNBytes(8); break; case 0x0e: // Player Digging if (!isServerTunnel) { if (player.getGroupId() < 0) { skipNBytes(11); } else { byte status = in.readByte(); int x = in.readInt(); byte y = in.readByte(); int z = in.readInt(); byte face = in.readByte(); if (!server.chests.hasLock(x, y, z) || player.isAdmin()) { if (server.chests.hasLock(x, y, z) && status == BLOCK_DESTROYED_STATUS) { server.chests.releaseLock(x, y, z); } write(packetId); write(status); write(x); write(y); write(z); write(face); if (player.instantDestroyEnabled()) { for (int c = 1; c < DESTROY_HITS; ++c) { packetFinished(); write(packetId); write(status); write(x); write(y); write(z); write(face); } packetFinished(); write(packetId); write(BLOCK_DESTROYED_STATUS); write(x); write(y); write(z); write(face); } } } } else { write(packetId); copyNBytes(11); } break; case 0x0f: // Player Block Placement write(packetId); write(in.readInt()); write(in.readByte()); write(in.readInt()); write(in.readByte()); short dropItem = in.readShort(); write(dropItem); if (dropItem != -1) { write(in.readByte()); write(in.readByte()); } break; /* short blockId = in.readShort(); if (!isServerTunnel && (player.getGroupId() < 0) || !server.blockFirewall.playerAllowed(player, blockId)) { int x = in.readInt(); skipNBytes(6); if (x != -1) { server.runCommand("say", String.format(server.l.get("BAD_BLOCK"), player.getName(), Short.toString(blockId))); } } else if (!isServerTunnel && (blockId == 54) && player.isAttemptLock()) { int x = in.readInt(); byte y = in.readByte(); int z = in.readInt(); byte direction = in.readByte(); write(packetId); write(blockId); write(x); write(y); write(z); write(direction); switch (direction) { case 0: y--; break; case 1: y++; break; case 2: z--; break; case 3: z++; break; case 4: x--; break; case 5: x++; break; } // create chest entry if (server.chests.hasLock(x, y, z)) { player.addMessage("This block is locked already!"); } else if (server.chests.giveLock(player.getName(), x, y, z, false)) { player.addMessage("Your locked chest is created! Do not add another chest to it!"); } else { player.addMessage("You already have a lock, or this block is locked already!"); } player.setAttemptLock(false); } else { write(packetId); write(blockId); copyNBytes(10); } break; */ case 0x10: // Holding Change write(packetId); copyNBytes(2); break; case 0x12: // Animation write(packetId); copyNBytes(5); break; case 0x14: // Named Entity Spawn write(packetId); write(in.readInt()); write(in.readUTF()); copyNBytes(16); break; case 0x15: // Pickup spawn if (player.getGroupId() < 0) { skipNBytes(22); break; } write(packetId); copyNBytes(22); break; case 0x16: // Collect Item write(packetId); copyNBytes(8); break; case 0x17: // Add Object/Vehicle write(packetId); copyNBytes(17); break; case 0x18: // Mob Spawn write(packetId); copyNBytes(19); break; case 0x1c: // Entity Velocity? write(packetId); copyNBytes(10); break; case 0x1D: // Destroy Entity write(packetId); copyNBytes(4); break; case 0x1E: // Entity write(packetId); copyNBytes(4); break; case 0x1F: // Entity Relative Move write(packetId); copyNBytes(7); break; case 0x20: // Entity Look write(packetId); copyNBytes(6); break; case 0x21: // Entity Look and Relative Move write(packetId); copyNBytes(9); break; case 0x22: // Entity Teleport write(packetId); copyNBytes(18); break; case 0x26: // Entity status? write(packetId); copyNBytes(5); break; case 0x27: // Attach Entity? write(packetId); copyNBytes(8); break; case 0x32: // Pre-Chunk write(packetId); copyNBytes(9); break; case 0x33: // Map Chunk write(packetId); copyNBytes(13); int chunkSize = in.readInt(); write(chunkSize); copyNBytes(chunkSize); break; case 0x34: // Multi Block Change write(packetId); copyNBytes(8); short arraySize = in.readShort(); write(arraySize); copyNBytes(arraySize * 4); break; case 0x35: // Block Change write(packetId); copyNBytes(11); break; /* case 0x3b: // Complex Entities int x = in.readInt(); short y = in.readShort(); int z = in.readInt(); short payloadSize = in.readShort(); if (server.chests.hasLock(x, (byte) y, z) && !player.isAdmin() && !server.chests.ownsLock(player.getName(), x, (byte) y, z)) { skipNBytes(payloadSize); } else if (player.getGroupId() < 0 && !server.options.getBoolean("guestsCanViewComplex")) { skipNBytes(payloadSize); } else { write(packetId); write(x); write(y); write(z); write(payloadSize); copyNBytes(payloadSize); } break; */ case 0x3c: // Explosion write(packetId); copyNBytes(28); int recordCount = in.readInt(); write(recordCount); copyNBytes(recordCount * 3); break; case 0x64: write(packetId); write(in.readByte()); write(in.readByte()); write(in.readInt()); write(in.readByte()); break; case 0x65: write(packetId); write(in.readByte()); break; case 0x66: // Inventory Item Move write(packetId); write(in.readByte()); write(in.readShort()); write(in.readByte()); write(in.readShort()); short moveItem = in.readShort(); write(moveItem); if (moveItem != -1) { write(in.readByte()); write(in.readByte()); } break; case 0x67: // Inventory Item Update write(packetId); write(in.readByte()); write(in.readShort()); short setItem = in.readShort(); write(setItem); if (setItem != -1) { write(in.readByte()); write(in.readByte()); } break; case 0x68: // Inventory write(packetId); write(in.readByte()); short count = in.readShort(); write(count); for (int c = 0; c < count; ++c) { short item = in.readShort(); write(item); if (item != -1) { write(in.readByte()); write(in.readShort()); } } break; case 0x69: write(packetId); write(in.readByte()); write(in.readShort()); write(in.readShort()); break; case 0x6a: write(packetId); write(in.readByte()); write(in.readShort()); write(in.readByte()); break; case (byte) 0x82: // Update Sign write(packetId); write(in.readInt()); write(in.readShort()); write(in.readInt()); write(in.readUTF()); write(in.readUTF()); write(in.readUTF()); break; case (byte) 0xff: // Disconnect/Kick write(packetId); String reason = in.readUTF(); write(reason); if (reason.startsWith("Took too long")) { server.addRobot(player); } player.close(); break; default: if (EXPENSIVE_DEBUG_LOGGING) { while (true) { skipNBytes(1); flushAll(); } } else { throw new IOException("Unable to parse unknown " + streamType + " packet 0x" + Integer.toHexString(packetId) + " for player " + player.getName()); } } packetFinished(); }
private void handlePacket() throws IOException { Byte packetId = in.readByte(); switch (packetId) { case 0x00: // Keep Alive write(packetId); break; case 0x01: // Login Request/Response write(packetId); write(in.readInt()); write(in.readUTF()); write(in.readUTF()); write(in.readLong()); write(in.readByte()); break; case 0x02: // Handshake String name = in.readUTF(); if (isServerTunnel || player.setName(name)) { tunneler.setName(streamType + "-" + player.getName()); write(packetId); write(name); } break; case 0x03: // Chat Message String message = in.readUTF(); if (isServerTunnel && server.options.getBoolean("useMsgFormats")) { Matcher messageMatcher = MESSAGE_PATTERN.matcher(message); if (messageMatcher.find()) { Player friend = server.findPlayerExact(messageMatcher.group(1)); if (friend != null) { String color = "f"; String title = ""; String format = server.options.get("msgFormat"); Group group = friend.getGroup(); if (group != null) { color = group.getColor(); if (group.showTitle()) { title = group.getName(); format = server.options.get("msgTitleFormat"); } } try { message = String.format(format, friend.getName(), title, color) + messageMatcher.group(2); } catch (IllegalFormatException e) { System.out.println("[SimpleServer] There is an error in your msgFormat/msgTitleFormat settings!"); } } } } if (!isServerTunnel) { if (player.isMuted() && !message.startsWith("/") && !message.startsWith("!")) { player.addMessage("You are muted! You may not send messages to all players."); break; } if (server.options.getBoolean("useSlashes") && message.startsWith("/") || message.startsWith("!") && player.parseCommand(message)) { break; } } write(packetId); write(message); break; case 0x04: // Time Update write(packetId); copyNBytes(8); break; case 0x05: // Player Inventory write(packetId); write(in.readInt()); write(in.readShort()); write(in.readShort()); break; /* boolean guest = player.getGroupId() < 0; int inventoryType = in.readInt(); short itemCount = in.readShort(); if (!guest) { write(packetId); write(inventoryType); write(itemCount); } for (int c = 0; c < itemCount; ++c) { short itemId = in.readShort(); if (!guest) { write(itemId); } if (itemId != -1) { byte itemAmount = in.readByte(); short itemUses = in.readShort(); if (!guest) { write(itemAmount); write(itemUses); } if (!server.itemWatch.playerAllowed(player, itemId, itemAmount)) { server.adminLog("ItemWatchList banned player:\t" + player.getName()); server.banKick(player.getName()); } } } break; */ case 0x06: // Spawn Position write(packetId); copyNBytes(12); break; case 0x07: // Use Entity? write(packetId); copyNBytes(9); break; case 0x08: // Update Health write(packetId); copyNBytes(2); break; case 0x09: // Respawn write(packetId); break; case 0x0a: // Player write(packetId); copyNBytes(1); if (!inGame && !isServerTunnel) { player.sendMOTD(); inGame = true; } break; case 0x0b: // Player Position write(packetId); copyPlayerLocation(); break; case 0x0c: // Player Look write(packetId); copyNBytes(9); break; case 0x0d: // Player Position & Look write(packetId); copyPlayerLocation(); copyNBytes(8); break; case 0x0e: // Player Digging if (!isServerTunnel) { if (player.getGroupId() < 0) { skipNBytes(11); } else { byte status = in.readByte(); int x = in.readInt(); byte y = in.readByte(); int z = in.readInt(); byte face = in.readByte(); if (!server.chests.hasLock(x, y, z) || player.isAdmin()) { if (server.chests.hasLock(x, y, z) && status == BLOCK_DESTROYED_STATUS) { server.chests.releaseLock(x, y, z); } write(packetId); write(status); write(x); write(y); write(z); write(face); if (player.instantDestroyEnabled()) { for (int c = 1; c < DESTROY_HITS; ++c) { packetFinished(); write(packetId); write(status); write(x); write(y); write(z); write(face); } packetFinished(); write(packetId); write(BLOCK_DESTROYED_STATUS); write(x); write(y); write(z); write(face); } } } } else { write(packetId); copyNBytes(11); } break; case 0x0f: // Player Block Placement write(packetId); write(in.readInt()); write(in.readByte()); write(in.readInt()); write(in.readByte()); short dropItem = in.readShort(); write(dropItem); if (dropItem != -1) { write(in.readByte()); write(in.readByte()); } break; /* short blockId = in.readShort(); if (!isServerTunnel && (player.getGroupId() < 0) || !server.blockFirewall.playerAllowed(player, blockId)) { int x = in.readInt(); skipNBytes(6); if (x != -1) { server.runCommand("say", String.format(server.l.get("BAD_BLOCK"), player.getName(), Short.toString(blockId))); } } else if (!isServerTunnel && (blockId == 54) && player.isAttemptLock()) { int x = in.readInt(); byte y = in.readByte(); int z = in.readInt(); byte direction = in.readByte(); write(packetId); write(blockId); write(x); write(y); write(z); write(direction); switch (direction) { case 0: y--; break; case 1: y++; break; case 2: z--; break; case 3: z++; break; case 4: x--; break; case 5: x++; break; } // create chest entry if (server.chests.hasLock(x, y, z)) { player.addMessage("This block is locked already!"); } else if (server.chests.giveLock(player.getName(), x, y, z, false)) { player.addMessage("Your locked chest is created! Do not add another chest to it!"); } else { player.addMessage("You already have a lock, or this block is locked already!"); } player.setAttemptLock(false); } else { write(packetId); write(blockId); copyNBytes(10); } break; */ case 0x10: // Holding Change write(packetId); copyNBytes(2); break; case 0x12: // Animation write(packetId); copyNBytes(5); break; case 0x14: // Named Entity Spawn write(packetId); write(in.readInt()); write(in.readUTF()); copyNBytes(16); break; case 0x15: // Pickup spawn if (player.getGroupId() < 0) { skipNBytes(22); break; } write(packetId); copyNBytes(22); break; case 0x16: // Collect Item write(packetId); copyNBytes(8); break; case 0x17: // Add Object/Vehicle write(packetId); copyNBytes(17); break; case 0x18: // Mob Spawn write(packetId); copyNBytes(19); break; case 0x1c: // Entity Velocity? write(packetId); copyNBytes(10); break; case 0x1D: // Destroy Entity write(packetId); copyNBytes(4); break; case 0x1E: // Entity write(packetId); copyNBytes(4); break; case 0x1F: // Entity Relative Move write(packetId); copyNBytes(7); break; case 0x20: // Entity Look write(packetId); copyNBytes(6); break; case 0x21: // Entity Look and Relative Move write(packetId); copyNBytes(9); break; case 0x22: // Entity Teleport write(packetId); copyNBytes(18); break; case 0x26: // Entity status? write(packetId); copyNBytes(5); break; case 0x27: // Attach Entity? write(packetId); copyNBytes(8); break; case 0x32: // Pre-Chunk write(packetId); copyNBytes(9); break; case 0x33: // Map Chunk write(packetId); copyNBytes(13); int chunkSize = in.readInt(); write(chunkSize); copyNBytes(chunkSize); break; case 0x34: // Multi Block Change write(packetId); copyNBytes(8); short arraySize = in.readShort(); write(arraySize); copyNBytes(arraySize * 4); break; case 0x35: // Block Change write(packetId); copyNBytes(11); break; /* case 0x3b: // Complex Entities int x = in.readInt(); short y = in.readShort(); int z = in.readInt(); short payloadSize = in.readShort(); if (server.chests.hasLock(x, (byte) y, z) && !player.isAdmin() && !server.chests.ownsLock(player.getName(), x, (byte) y, z)) { skipNBytes(payloadSize); } else if (player.getGroupId() < 0 && !server.options.getBoolean("guestsCanViewComplex")) { skipNBytes(payloadSize); } else { write(packetId); write(x); write(y); write(z); write(payloadSize); copyNBytes(payloadSize); } break; */ case 0x3c: // Explosion write(packetId); copyNBytes(28); int recordCount = in.readInt(); write(recordCount); copyNBytes(recordCount * 3); break; case 0x64: write(packetId); write(in.readByte()); write(in.readByte()); write(in.readInt()); write(in.readByte()); break; case 0x65: write(packetId); write(in.readByte()); break; case 0x66: // Inventory Item Move write(packetId); write(in.readByte()); write(in.readShort()); write(in.readByte()); write(in.readShort()); short moveItem = in.readShort(); write(moveItem); if (moveItem != -1) { write(in.readByte()); write(in.readByte()); } break; case 0x67: // Inventory Item Update write(packetId); write(in.readByte()); write(in.readShort()); short setItem = in.readShort(); write(setItem); if (setItem != -1) { write(in.readByte()); write(in.readByte()); } break; case 0x68: // Inventory write(packetId); write(in.readByte()); short count = in.readShort(); write(count); for (int c = 0; c < count; ++c) { short item = in.readShort(); write(item); if (item != -1) { write(in.readByte()); write(in.readShort()); } } break; case 0x69: write(packetId); write(in.readByte()); write(in.readShort()); write(in.readShort()); break; case 0x6a: write(packetId); write(in.readByte()); write(in.readShort()); write(in.readByte()); break; case (byte) 0x82: // Update Sign write(packetId); write(in.readInt()); write(in.readShort()); write(in.readInt()); write(in.readUTF()); write(in.readUTF()); write(in.readUTF()); write(in.readUTF()); break; case (byte) 0xff: // Disconnect/Kick write(packetId); String reason = in.readUTF(); write(reason); if (reason.startsWith("Took too long")) { server.addRobot(player); } player.close(); break; default: if (EXPENSIVE_DEBUG_LOGGING) { while (true) { skipNBytes(1); flushAll(); } } else { throw new IOException("Unable to parse unknown " + streamType + " packet 0x" + Integer.toHexString(packetId) + " for player " + player.getName()); } } packetFinished(); }
diff --git a/calabash-driver-client/src/main/java/sh/calaba/driver/client/model/impl/TextFieldImpl.java b/calabash-driver-client/src/main/java/sh/calaba/driver/client/model/impl/TextFieldImpl.java index 9c97ede..b255834 100644 --- a/calabash-driver-client/src/main/java/sh/calaba/driver/client/model/impl/TextFieldImpl.java +++ b/calabash-driver-client/src/main/java/sh/calaba/driver/client/model/impl/TextFieldImpl.java @@ -1,40 +1,40 @@ package sh.calaba.driver.client.model.impl; import sh.calaba.driver.client.CalabashCommands; import sh.calaba.driver.client.RemoteCalabashAndroidDriver; import sh.calaba.driver.model.By; import sh.calaba.driver.model.TextFieldSupport; public class TextFieldImpl extends RemoteObject implements TextFieldSupport { private By by; public TextFieldImpl(RemoteCalabashAndroidDriver driver, By by) { super(driver); this.by = by; } public void clear() { if (by instanceof By.Index) { executeCalabashCommand(CalabashCommands.CLEAR_NUMBERED_FIELD, by.getIndentifier()); } else if (by instanceof By.ContentDescription) { executeCalabashCommand(CalabashCommands.CLEAR_NAMED_FIELD, by.getIndentifier()); } else { throw new IllegalArgumentException("By not available."); } } public void enterText(String text) { if (by instanceof By.Index) { executeCalabashCommand(CalabashCommands.ENTER_TEXT_INTO_NUMBERED_FIELD, text, by.getIndentifier()); - } else if (by instanceof By.ContentDescription || by instanceof By.Id) { + } else if (by instanceof By.ContentDescription) { executeCalabashCommand(CalabashCommands.ENTER_TEXT_INTO_NAMED_FIELD, text, by.getIndentifier()); } else if (by instanceof By.Id) { executeCalabashCommand(CalabashCommands.ENTER_TEXT_BY_NAME, text, by.getIndentifier()); } else { throw new IllegalArgumentException("By not available."); } } }
true
true
public void enterText(String text) { if (by instanceof By.Index) { executeCalabashCommand(CalabashCommands.ENTER_TEXT_INTO_NUMBERED_FIELD, text, by.getIndentifier()); } else if (by instanceof By.ContentDescription || by instanceof By.Id) { executeCalabashCommand(CalabashCommands.ENTER_TEXT_INTO_NAMED_FIELD, text, by.getIndentifier()); } else if (by instanceof By.Id) { executeCalabashCommand(CalabashCommands.ENTER_TEXT_BY_NAME, text, by.getIndentifier()); } else { throw new IllegalArgumentException("By not available."); } }
public void enterText(String text) { if (by instanceof By.Index) { executeCalabashCommand(CalabashCommands.ENTER_TEXT_INTO_NUMBERED_FIELD, text, by.getIndentifier()); } else if (by instanceof By.ContentDescription) { executeCalabashCommand(CalabashCommands.ENTER_TEXT_INTO_NAMED_FIELD, text, by.getIndentifier()); } else if (by instanceof By.Id) { executeCalabashCommand(CalabashCommands.ENTER_TEXT_BY_NAME, text, by.getIndentifier()); } else { throw new IllegalArgumentException("By not available."); } }
diff --git a/core/src/processing/core/PApplet.java b/core/src/processing/core/PApplet.java index fce0463b2..7dd826336 100644 --- a/core/src/processing/core/PApplet.java +++ b/core/src/processing/core/PApplet.java @@ -1,15515 +1,15515 @@ /* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* Part of the Processing project - http://processing.org Copyright (c) 2004-12 Ben Fry and Casey Reas Copyright (c) 2001-04 Massachusetts Institute of Technology This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, version 2.1. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package processing.core; import processing.data.*; import processing.event.*; import processing.event.Event; import processing.opengl.*; import java.applet.*; import java.awt.*; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.InputEvent; import java.awt.event.KeyListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.*; import java.io.*; import java.lang.reflect.*; import java.net.*; import java.text.*; import java.util.*; import java.util.regex.*; import java.util.zip.*; import javax.imageio.ImageIO; import javax.swing.JFileChooser; /** * Base class for all sketches that use processing.core. * <p/> * Note that you should not use AWT or Swing components inside a Processing * applet. The surface is made to automatically update itself, and will cause * problems with redraw of components drawn above it. If you'd like to * integrate other Java components, see below. * <p/> * The <A HREF="http://wiki.processing.org/w/Window_Size_and_Full_Screen"> * Window Size and Full Screen</A> page on the Wiki has useful information * about sizing, multiple displays, full screen, etc. * <p/> * As of release 0145, Processing uses active mode rendering in all cases. * All animation tasks happen on the "Processing Animation Thread". The * setup() and draw() methods are handled by that thread, and events (like * mouse movement and key presses, which are fired by the event dispatch * thread or EDT) are queued to be (safely) handled at the end of draw(). * For code that needs to run on the EDT, use SwingUtilities.invokeLater(). * When doing so, be careful to synchronize between that code (since * invokeLater() will make your code run from the EDT) and the Processing * animation thread. Use of a callback function or the registerXxx() methods * in PApplet can help ensure that your code doesn't do something naughty. * <p/> * As of Processing 2.0, we have discontinued support for versions of Java * prior to 1.6. We don't have enough people to support it, and for a * project of our (tiny) size, we should be focusing on the future, rather * than working around legacy Java code. * <p/> * This class extends Applet instead of JApplet because 1) historically, * we supported Java 1.1, which does not include Swing (without an * additional, sizable, download), and 2) Swing is a bloated piece of crap. * A Processing applet is a heavyweight AWT component, and can be used the * same as any other AWT component, with or without Swing. * <p/> * Similarly, Processing runs in a Frame and not a JFrame. However, there's * nothing to prevent you from embedding a PApplet into a JFrame, it's just * that the base version uses a regular AWT frame because there's simply * no need for Swing in that context. If people want to use Swing, they can * embed themselves as they wish. * <p/> * It is possible to use PApplet, along with core.jar in other projects. * This also allows you to embed a Processing drawing area into another Java * application. This means you can use standard GUI controls with a Processing * sketch. Because AWT and Swing GUI components cannot be used on top of a * PApplet, you can instead embed the PApplet inside another GUI the way you * would any other Component. * <p/> * Because the default animation thread will run at 60 frames per second, * an embedded PApplet can make the parent application sluggish. You can use * frameRate() to make it update less often, or you can use noLoop() and loop() * to disable and then re-enable looping. If you want to only update the sketch * intermittently, use noLoop() inside setup(), and redraw() whenever the * screen needs to be updated once (or loop() to re-enable the animation * thread). The following example embeds a sketch and also uses the noLoop() * and redraw() methods. You need not use noLoop() and redraw() when embedding * if you want your application to animate continuously. * <PRE> * public class ExampleFrame extends Frame { * * public ExampleFrame() { * super("Embedded PApplet"); * * setLayout(new BorderLayout()); * PApplet embed = new Embedded(); * add(embed, BorderLayout.CENTER); * * // important to call this whenever embedding a PApplet. * // It ensures that the animation thread is started and * // that other internal variables are properly set. * embed.init(); * } * } * * public class Embedded extends PApplet { * * public void setup() { * // original setup code here ... * size(400, 400); * * // prevent thread from starving everything else * noLoop(); * } * * public void draw() { * // drawing code goes here * } * * public void mousePressed() { * // do something based on mouse movement * * // update the screen (run draw once) * redraw(); * } * } * </PRE> * @usage Web &amp; Application */ public class PApplet extends Applet implements PConstants, Runnable, MouseListener, MouseWheelListener, MouseMotionListener, KeyListener, FocusListener { /** * Full name of the Java version (i.e. 1.5.0_11). * Prior to 0125, this was only the first three digits. */ public static final String javaVersionName = System.getProperty("java.version"); /** * Version of Java that's in use, whether 1.1 or 1.3 or whatever, * stored as a float. * <p> * Note that because this is stored as a float, the values may * not be <EM>exactly</EM> 1.3 or 1.4. Instead, make sure you're * comparing against 1.3f or 1.4f, which will have the same amount * of error (i.e. 1.40000001). This could just be a double, but * since Processing only uses floats, it's safer for this to be a float * because there's no good way to specify a double with the preproc. */ public static final float javaVersion = new Float(javaVersionName.substring(0, 3)).floatValue(); /** * Current platform in use. * <p> * Equivalent to System.getProperty("os.name"), just used internally. */ /** * Current platform in use, one of the * PConstants WINDOWS, MACOSX, MACOS9, LINUX or OTHER. */ static public int platform; /** * Name associated with the current 'platform' (see PConstants.platformNames) */ //static public String platformName; static { String osname = System.getProperty("os.name"); if (osname.indexOf("Mac") != -1) { platform = MACOSX; } else if (osname.indexOf("Windows") != -1) { platform = WINDOWS; } else if (osname.equals("Linux")) { // true for the ibm vm platform = LINUX; } else { platform = OTHER; } } /** * Setting for whether to use the Quartz renderer on OS X. The Quartz * renderer is on its way out for OS X, but Processing uses it by default * because it's much faster than the Sun renderer. In some cases, however, * the Quartz renderer is preferred. For instance, fonts are less thick * when using the Sun renderer, so to improve how fonts look, * change this setting before you call PApplet.main(). * <pre> * static public void main(String[] args) { * PApplet.useQuartz = false; * PApplet.main(new String[] { "YourSketch" }); * } * </pre> * This setting must be called before any AWT work happens, so that's why * it's such a terrible hack in how it's employed here. Calling setProperty() * inside setup() is a joke, since it's long since the AWT has been invoked. * <p/> * On OS X with a retina display, this option is ignored, because Apple's * Java implementation takes over and forces the Quartz renderer. */ // static public boolean useQuartz = true; static public boolean useQuartz = false; /** * Whether to use native (AWT) dialogs for selectInput and selectOutput. * The native dialogs on Linux tend to be pretty awful. With selectFolder() * this is ignored, because there is no native folder selector, except on * Mac OS X. On OS X, the native folder selector will be used unless * useNativeSelect is set to false. */ static public boolean useNativeSelect = (platform != LINUX); // /** // * Modifier flags for the shortcut key used to trigger menus. // * (Cmd on Mac OS X, Ctrl on Linux and Windows) // */ // static public final int MENU_SHORTCUT = // Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); /** The PGraphics renderer associated with this PApplet */ public PGraphics g; /** The frame containing this applet (if any) */ public Frame frame; // disabled on retina inside init() boolean useActive = true; // boolean useActive = false; // boolean useStrategy = true; boolean useStrategy = false; Canvas canvas; // /** // * Usually just 0, but with multiple displays, the X and Y coordinates of // * the screen will depend on the current screen's position relative to // * the other displays. // */ // public int displayX; // public int displayY; /** * ( begin auto-generated from screenWidth.xml ) * * System variable which stores the width of the computer screen. For * example, if the current screen resolution is 1024x768, * <b>displayWidth</b> is 1024 and <b>displayHeight</b> is 768. These * dimensions are useful when exporting full-screen applications. * <br /><br /> * To ensure that the sketch takes over the entire screen, use "Present" * instead of "Run". Otherwise the window will still have a frame border * around it and not be placed in the upper corner of the screen. On Mac OS * X, the menu bar will remain present unless "Present" mode is used. * * ( end auto-generated ) * @webref environment */ public int displayWidth; /** * ( begin auto-generated from screenHeight.xml ) * * System variable that stores the height of the computer screen. For * example, if the current screen resolution is 1024x768, * <b>screenWidth</b> is 1024 and <b>screenHeight</b> is 768. These * dimensions are useful when exporting full-screen applications. * <br /><br /> * To ensure that the sketch takes over the entire screen, use "Present" * instead of "Run". Otherwise the window will still have a frame border * around it and not be placed in the upper corner of the screen. On Mac OS * X, the menu bar will remain present unless "Present" mode is used. * * ( end auto-generated ) * @webref environment */ public int displayHeight; /** * A leech graphics object that is echoing all events. */ public PGraphics recorder; /** * Command line options passed in from main(). * <p> * This does not include the arguments passed in to PApplet itself. */ public String[] args; /** Path to sketch folder */ public String sketchPath; //folder; static final boolean DEBUG = false; // static final boolean DEBUG = true; /** Default width and height for applet when not specified */ static public final int DEFAULT_WIDTH = 100; static public final int DEFAULT_HEIGHT = 100; /** * Minimum dimensions for the window holding an applet. This varies between * platforms, Mac OS X 10.3 (confirmed with 10.7 and Java 6) can do any * height but requires at least 128 pixels width. Windows XP has another * set of limitations. And for all I know, Linux probably lets you make * windows with negative sizes. */ static public final int MIN_WINDOW_WIDTH = 128; static public final int MIN_WINDOW_HEIGHT = 128; /** * Gets set by main() if --present (old) or --full-screen (newer) are used, * and is returned by sketchFullscreen() when initializing in main(). */ // protected boolean fullScreen = false; /** * Exception thrown when size() is called the first time. * <p> * This is used internally so that setup() is forced to run twice * when the renderer is changed. This is the only way for us to handle * invoking the new renderer while also in the midst of rendering. */ static public class RendererChangeException extends RuntimeException { } /** * true if no size() command has been executed. This is used to wait until * a size has been set before placing in the window and showing it. */ public boolean defaultSize; /** Storage for the current renderer size to avoid re-allocation. */ Dimension currentSize = new Dimension(); // volatile boolean resizeRequest; // volatile int resizeWidth; // volatile int resizeHeight; /** * ( begin auto-generated from pixels.xml ) * * Array containing the values for all the pixels in the display window. * These values are of the color datatype. This array is the size of the * display window. For example, if the image is 100x100 pixels, there will * be 10000 values and if the window is 200x300 pixels, there will be 60000 * values. The <b>index</b> value defines the position of a value within * the array. For example, the statement <b>color b = pixels[230]</b> will * set the variable <b>b</b> to be equal to the value at that location in * the array.<br /> * <br /> * Before accessing this array, the data must loaded with the * <b>loadPixels()</b> function. After the array data has been modified, * the <b>updatePixels()</b> function must be run to update the changes. * Without <b>loadPixels()</b>, running the code may (or will in future * releases) result in a NullPointerException. * * ( end auto-generated ) * * @webref image:pixels * @see PApplet#loadPixels() * @see PApplet#updatePixels() * @see PApplet#get(int, int, int, int) * @see PApplet#set(int, int, int) * @see PImage */ public int pixels[]; /** * ( begin auto-generated from width.xml ) * * System variable which stores the width of the display window. This value * is set by the first parameter of the <b>size()</b> function. For * example, the function call <b>size(320, 240)</b> sets the <b>width</b> * variable to the value 320. The value of <b>width</b> is zero until * <b>size()</b> is called. * * ( end auto-generated ) * @webref environment */ public int width; /** * ( begin auto-generated from height.xml ) * * System variable which stores the height of the display window. This * value is set by the second parameter of the <b>size()</b> function. For * example, the function call <b>size(320, 240)</b> sets the <b>height</b> * variable to the value 240. The value of <b>height</b> is zero until * <b>size()</b> is called. * * ( end auto-generated ) * @webref environment * */ public int height; /** * ( begin auto-generated from mouseX.xml ) * * The system variable <b>mouseX</b> always contains the current horizontal * coordinate of the mouse. * * ( end auto-generated ) * @webref input:mouse * @see PApplet#mouseY * @see PApplet#mousePressed * @see PApplet#mousePressed() * @see PApplet#mouseReleased() * @see PApplet#mouseMoved() * @see PApplet#mouseDragged() * * */ public int mouseX; /** * ( begin auto-generated from mouseY.xml ) * * The system variable <b>mouseY</b> always contains the current vertical * coordinate of the mouse. * * ( end auto-generated ) * @webref input:mouse * @see PApplet#mouseX * @see PApplet#mousePressed * @see PApplet#mousePressed() * @see PApplet#mouseReleased() * @see PApplet#mouseMoved() * @see PApplet#mouseDragged() * */ public int mouseY; /** * ( begin auto-generated from pmouseX.xml ) * * The system variable <b>pmouseX</b> always contains the horizontal * position of the mouse in the frame previous to the current frame.<br /> * <br /> * You may find that <b>pmouseX</b> and <b>pmouseY</b> have different * values inside <b>draw()</b> and inside events like <b>mousePressed()</b> * and <b>mouseMoved()</b>. This is because they're used for different * roles, so don't mix them. Inside <b>draw()</b>, <b>pmouseX</b> and * <b>pmouseY</b> update only once per frame (once per trip through your * <b>draw()</b>). But, inside mouse events, they update each time the * event is called. If they weren't separated, then the mouse would be read * only once per frame, making response choppy. If the mouse variables were * always updated multiple times per frame, using <NOBR><b>line(pmouseX, * pmouseY, mouseX, mouseY)</b></NOBR> inside <b>draw()</b> would have lots * of gaps, because <b>pmouseX</b> may have changed several times in * between the calls to <b>line()</b>. Use <b>pmouseX</b> and * <b>pmouseY</b> inside <b>draw()</b> if you want values relative to the * previous frame. Use <b>pmouseX</b> and <b>pmouseY</b> inside the mouse * functions if you want continuous response. * * ( end auto-generated ) * @webref input:mouse * @see PApplet#pmouseY * @see PApplet#mouseX * @see PApplet#mouseY */ public int pmouseX; /** * ( begin auto-generated from pmouseY.xml ) * * The system variable <b>pmouseY</b> always contains the vertical position * of the mouse in the frame previous to the current frame. More detailed * information about how <b>pmouseY</b> is updated inside of <b>draw()</b> * and mouse events is explained in the reference for <b>pmouseX</b>. * * ( end auto-generated ) * @webref input:mouse * @see PApplet#pmouseX * @see PApplet#mouseX * @see PApplet#mouseY */ public int pmouseY; /** * previous mouseX/Y for the draw loop, separated out because this is * separate from the pmouseX/Y when inside the mouse event handlers. */ protected int dmouseX, dmouseY; /** * pmouseX/Y for the event handlers (mousePressed(), mouseDragged() etc) * these are different because mouse events are queued to the end of * draw, so the previous position has to be updated on each event, * as opposed to the pmouseX/Y that's used inside draw, which is expected * to be updated once per trip through draw(). */ protected int emouseX, emouseY; /** * Used to set pmouseX/Y to mouseX/Y the first time mouseX/Y are used, * otherwise pmouseX/Y are always zero, causing a nasty jump. * <p> * Just using (frameCount == 0) won't work since mouseXxxxx() * may not be called until a couple frames into things. * <p> * @deprecated Please refrain from using this variable, it will be removed * from future releases of Processing because it cannot be used consistently * across platforms and input methods. */ @Deprecated public boolean firstMouse; /** * ( begin auto-generated from mouseButton.xml ) * * Processing automatically tracks if the mouse button is pressed and which * button is pressed. The value of the system variable <b>mouseButton</b> * is either <b>LEFT</b>, <b>RIGHT</b>, or <b>CENTER</b> depending on which * button is pressed. * * ( end auto-generated ) * * <h3>Advanced:</h3> * * If running on Mac OS, a ctrl-click will be interpreted as the right-hand * mouse button (unlike Java, which reports it as the left mouse). * @webref input:mouse * @see PApplet#mouseX * @see PApplet#mouseY * @see PApplet#mousePressed() * @see PApplet#mouseReleased() * @see PApplet#mouseMoved() * @see PApplet#mouseDragged() */ public int mouseButton; /** * ( begin auto-generated from mousePressed_var.xml ) * * Variable storing if a mouse button is pressed. The value of the system * variable <b>mousePressed</b> is true if a mouse button is pressed and * false if a button is not pressed. * * ( end auto-generated ) * @webref input:mouse * @see PApplet#mouseX * @see PApplet#mouseY * @see PApplet#mouseReleased() * @see PApplet#mouseMoved() * @see PApplet#mouseDragged() */ public boolean mousePressed; /** * @deprecated Use a mouse event handler that passes an event instead. */ @Deprecated public MouseEvent mouseEvent; /** * ( begin auto-generated from key.xml ) * * The system variable <b>key</b> always contains the value of the most * recent key on the keyboard that was used (either pressed or released). * <br/> <br/> * For non-ASCII keys, use the <b>keyCode</b> variable. The keys included * in the ASCII specification (BACKSPACE, TAB, ENTER, RETURN, ESC, and * DELETE) do not require checking to see if they key is coded, and you * should simply use the <b>key</b> variable instead of <b>keyCode</b> If * you're making cross-platform projects, note that the ENTER key is * commonly used on PCs and Unix and the RETURN key is used instead on * Macintosh. Check for both ENTER and RETURN to make sure your program * will work for all platforms. * * ( end auto-generated ) * * <h3>Advanced</h3> * * Last key pressed. * <p> * If it's a coded key, i.e. UP/DOWN/CTRL/SHIFT/ALT, * this will be set to CODED (0xffff or 65535). * * @webref input:keyboard * @see PApplet#keyCode * @see PApplet#keyPressed * @see PApplet#keyPressed() * @see PApplet#keyReleased() */ public char key; /** * ( begin auto-generated from keyCode.xml ) * * The variable <b>keyCode</b> is used to detect special keys such as the * UP, DOWN, LEFT, RIGHT arrow keys and ALT, CONTROL, SHIFT. When checking * for these keys, it's first necessary to check and see if the key is * coded. This is done with the conditional "if (key == CODED)" as shown in * the example. * <br/> <br/> * The keys included in the ASCII specification (BACKSPACE, TAB, ENTER, * RETURN, ESC, and DELETE) do not require checking to see if they key is * coded, and you should simply use the <b>key</b> variable instead of * <b>keyCode</b> If you're making cross-platform projects, note that the * ENTER key is commonly used on PCs and Unix and the RETURN key is used * instead on Macintosh. Check for both ENTER and RETURN to make sure your * program will work for all platforms. * <br/> <br/> * For users familiar with Java, the values for UP and DOWN are simply * shorter versions of Java's KeyEvent.VK_UP and KeyEvent.VK_DOWN. Other * keyCode values can be found in the Java <a * href="http://download.oracle.com/javase/6/docs/api/java/awt/event/KeyEvent.html">KeyEvent</a> reference. * * ( end auto-generated ) * * <h3>Advanced</h3> * When "key" is set to CODED, this will contain a Java key code. * <p> * For the arrow keys, keyCode will be one of UP, DOWN, LEFT and RIGHT. * Also available are ALT, CONTROL and SHIFT. A full set of constants * can be obtained from java.awt.event.KeyEvent, from the VK_XXXX variables. * * @webref input:keyboard * @see PApplet#key * @see PApplet#keyPressed * @see PApplet#keyPressed() * @see PApplet#keyReleased() */ public int keyCode; /** * ( begin auto-generated from keyPressed_var.xml ) * * The boolean system variable <b>keyPressed</b> is <b>true</b> if any key * is pressed and <b>false</b> if no keys are pressed. * * ( end auto-generated ) * @webref input:keyboard * @see PApplet#key * @see PApplet#keyCode * @see PApplet#keyPressed() * @see PApplet#keyReleased() */ public boolean keyPressed; /** * The last KeyEvent object passed into a mouse function. * @deprecated Use a key event handler that passes an event instead. */ @Deprecated public KeyEvent keyEvent; /** * ( begin auto-generated from focused.xml ) * * Confirms if a Processing program is "focused", meaning that it is active * and will accept input from mouse or keyboard. This variable is "true" if * it is focused and "false" if not. This variable is often used when you * want to warn people they need to click on or roll over an applet before * it will work. * * ( end auto-generated ) * @webref environment */ public boolean focused = false; /** * Confirms if a Processing program is running inside a web browser. This * variable is "true" if the program is online and "false" if not. */ @Deprecated public boolean online = false; // This is deprecated because it's poorly named (and even more poorly // understood). Further, we'll probably be removing applets soon, in which // case this won't work at all. If you want this feature, you can check // whether getAppletContext() returns null. /** * Time in milliseconds when the applet was started. * <p> * Used by the millis() function. */ long millisOffset = System.currentTimeMillis(); /** * ( begin auto-generated from frameRate_var.xml ) * * The system variable <b>frameRate</b> contains the approximate frame rate * of the software as it executes. The initial value is 10 fps and is * updated with each frame. The value is averaged (integrated) over several * frames. As such, this value won't be valid until after 5-10 frames. * * ( end auto-generated ) * @webref environment * @see PApplet#frameRate(float) */ public float frameRate = 10; /** Last time in nanoseconds that frameRate was checked */ protected long frameRateLastNanos = 0; /** As of release 0116, frameRate(60) is called as a default */ protected float frameRateTarget = 60; protected long frameRatePeriod = 1000000000L / 60L; protected boolean looping; /** flag set to true when a redraw is asked for by the user */ protected boolean redraw; /** * ( begin auto-generated from frameCount.xml ) * * The system variable <b>frameCount</b> contains the number of frames * displayed since the program started. Inside <b>setup()</b> the value is * 0 and and after the first iteration of draw it is 1, etc. * * ( end auto-generated ) * @webref environment * @see PApplet#frameRate(float) */ public int frameCount; /** true if the sketch has stopped permanently. */ public volatile boolean finished; /** * true if the animation thread is paused. */ public volatile boolean paused; /** * true if exit() has been called so that things shut down * once the main thread kicks off. */ protected boolean exitCalled; Object pauseObject = new Object(); Thread thread; // messages to send if attached as an external vm /** * Position of the upper-lefthand corner of the editor window * that launched this applet. */ static public final String ARGS_EDITOR_LOCATION = "--editor-location"; /** * Location for where to position the applet window on screen. * <p> * This is used by the editor to when saving the previous applet * location, or could be used by other classes to launch at a * specific position on-screen. */ static public final String ARGS_EXTERNAL = "--external"; static public final String ARGS_LOCATION = "--location"; static public final String ARGS_DISPLAY = "--display"; static public final String ARGS_BGCOLOR = "--bgcolor"; /** @deprecated use --full-screen instead. */ static public final String ARGS_PRESENT = "--present"; static public final String ARGS_FULL_SCREEN = "--full-screen"; // static public final String ARGS_EXCLUSIVE = "--exclusive"; static public final String ARGS_STOP_COLOR = "--stop-color"; static public final String ARGS_HIDE_STOP = "--hide-stop"; /** * Allows the user or PdeEditor to set a specific sketch folder path. * <p> * Used by PdeEditor to pass in the location where saveFrame() * and all that stuff should write things. */ static public final String ARGS_SKETCH_FOLDER = "--sketch-path"; /** * When run externally to a PdeEditor, * this is sent by the applet when it quits. */ //static public final String EXTERNAL_QUIT = "__QUIT__"; static public final String EXTERNAL_STOP = "__STOP__"; /** * When run externally to a PDE Editor, this is sent by the applet * whenever the window is moved. * <p> * This is used so that the editor can re-open the sketch window * in the same position as the user last left it. */ static public final String EXTERNAL_MOVE = "__MOVE__"; /** true if this sketch is being run by the PDE */ boolean external = false; /** * Not official API, using internally because of the tweaks required. */ boolean retina; static final String ERROR_MIN_MAX = "Cannot use min() or max() on an empty array."; // during rev 0100 dev cycle, working on new threading model, // but need to disable and go conservative with changes in order // to get pdf and audio working properly first. // for 0116, the CRUSTY_THREADS are being disabled to fix lots of bugs. //static final boolean CRUSTY_THREADS = false; //true; /** * Applet initialization. This can do GUI work because the components have * not been 'realized' yet: things aren't visible, displayed, etc. */ @Override public void init() { // println("init() called " + Integer.toHexString(hashCode())); // using a local version here since the class variable is deprecated // Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); // screenWidth = screen.width; // screenHeight = screen.height; if (platform == MACOSX) { Float prop = (Float) getToolkit().getDesktopProperty("apple.awt.contentScaleFactor"); if (prop != null) { retina = prop == 2; if (retina) { // The active-mode rendering seems to be 2x slower, so disable it // with retina. On a non-retina machine, however, useActive seems // the only (or best?) way to handle the rendering. useActive = false; } } } // send tab keys through to the PApplet setFocusTraversalKeysEnabled(false); //millisOffset = System.currentTimeMillis(); // moved to the variable declaration finished = false; // just for clarity // this will be cleared by draw() if it is not overridden looping = true; redraw = true; // draw this guy once firstMouse = true; // these need to be inited before setup // sizeMethods = new RegisteredMethods(); // pauseMethods = new RegisteredMethods(); // resumeMethods = new RegisteredMethods(); // preMethods = new RegisteredMethods(); // drawMethods = new RegisteredMethods(); // postMethods = new RegisteredMethods(); // mouseEventMethods = new RegisteredMethods(); // keyEventMethods = new RegisteredMethods(); // disposeMethods = new RegisteredMethods(); try { getAppletContext(); online = true; } catch (NullPointerException e) { online = false; } try { if (sketchPath == null) { sketchPath = System.getProperty("user.dir"); } } catch (Exception e) { } // may be a security problem Dimension size = getSize(); if ((size.width != 0) && (size.height != 0)) { // When this PApplet is embedded inside a Java application with other // Component objects, its size() may already be set externally (perhaps // by a LayoutManager). In this case, honor that size as the default. // Size of the component is set, just create a renderer. g = makeGraphics(size.width, size.height, sketchRenderer(), null, true); // This doesn't call setSize() or setPreferredSize() because the fact // that a size was already set means that someone is already doing it. } else { // Set the default size, until the user specifies otherwise this.defaultSize = true; int w = sketchWidth(); int h = sketchHeight(); g = makeGraphics(w, h, sketchRenderer(), null, true); // Fire component resize event setSize(w, h); setPreferredSize(new Dimension(w, h)); } width = g.width; height = g.height; // addListeners(); // 2.0a6 // moved out of addListeners() in 2.0a6 addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { // Component c = e.getComponent(); // //System.out.println("componentResized() " + c); // Rectangle bounds = c.getBounds(); // resizeRequest = true; // resizeWidth = bounds.width; // resizeHeight = bounds.height; if (!looping) { redraw(); } } }); // if (thread == null) { // paused = true; thread = new Thread(this, "Animation Thread"); thread.start(); // } // this is automatically called in applets // though it's here for applications anyway // start(); } public int sketchQuality() { return 2; } public int sketchWidth() { return DEFAULT_WIDTH; } public int sketchHeight() { return DEFAULT_HEIGHT; } public String sketchRenderer() { return JAVA2D; } public boolean sketchFullScreen() { // return fullScreen; return false; } public void orientation(int which) { // ignore calls to the orientation command } /** * Called by the browser or applet viewer to inform this applet that it * should start its execution. It is called after the init method and * each time the applet is revisited in a Web page. * <p/> * Called explicitly via the first call to PApplet.paint(), because * PAppletGL needs to have a usable screen before getting things rolling. */ @Override public void start() { debug("start() called"); // new Exception().printStackTrace(System.out); paused = false; // unpause the thread resume(); // resumeMethods.handle(); handleMethods("resume"); debug("un-pausing thread"); synchronized (pauseObject) { debug("start() calling pauseObject.notifyAll()"); // try { pauseObject.notifyAll(); // wake up the animation thread debug("un-pausing thread 3"); // } catch (InterruptedException e) { } } } /** * Called by the browser or applet viewer to inform * this applet that it should stop its execution. * <p/> * Unfortunately, there are no guarantees from the Java spec * when or if stop() will be called (i.e. on browser quit, * or when moving between web pages), and it's not always called. */ @Override public void stop() { // this used to shut down the sketch, but that code has // been moved to destroy/dispose() // if (paused) { // synchronized (pauseObject) { // try { // pauseObject.wait(); // } catch (InterruptedException e) { // // waiting for this interrupt on a start() (resume) call // } // } // } // on the next trip through the animation thread, things will go sleepy-by paused = true; // causes animation thread to sleep pause(); handleMethods("pause"); // actual pause will happen in the run() method // synchronized (pauseObject) { // debug("stop() calling pauseObject.wait()"); // try { // pauseObject.wait(); // } catch (InterruptedException e) { // // waiting for this interrupt on a start() (resume) call // } // } } /** * Sketch has been paused. Called when switching tabs in a browser or * swapping to a different application on Android. Also called just before * quitting. Use to safely disable things like serial, sound, or sensors. */ public void pause() { } /** * Sketch has resumed. Called when switching tabs in a browser or * swapping to this application on Android. Also called on startup. * Use this to safely disable things like serial, sound, or sensors. */ public void resume() { } /** * Called by the browser or applet viewer to inform this applet * that it is being reclaimed and that it should destroy * any resources that it has allocated. * <p/> * destroy() supposedly gets called as the applet viewer * is shutting down the applet. stop() is called * first, and then destroy() to really get rid of things. * no guarantees on when they're run (on browser quit, or * when moving between pages), though. */ @Override public void destroy() { this.dispose(); } ////////////////////////////////////////////////////////////// /** Map of registered methods, stored by name. */ HashMap<String, RegisteredMethods> registerMap = new HashMap<String, PApplet.RegisteredMethods>(); class RegisteredMethods { int count; Object[] objects; // Because the Method comes from the class being called, // it will be unique for most, if not all, objects. Method[] methods; Object[] emptyArgs = new Object[] { }; void handle() { handle(emptyArgs); } void handle(Object[] args) { for (int i = 0; i < count; i++) { try { methods[i].invoke(objects[i], args); } catch (Exception e) { // check for wrapped exception, get root exception Throwable t; if (e instanceof InvocationTargetException) { InvocationTargetException ite = (InvocationTargetException) e; t = ite.getCause(); } else { t = e; } // check for RuntimeException, and allow to bubble up if (t instanceof RuntimeException) { // re-throw exception throw (RuntimeException) t; } else { // trap and print as usual t.printStackTrace(); } } } } void add(Object object, Method method) { if (findIndex(object) == -1) { if (objects == null) { objects = new Object[5]; methods = new Method[5]; } else if (count == objects.length) { objects = (Object[]) PApplet.expand(objects); methods = (Method[]) PApplet.expand(methods); } objects[count] = object; methods[count] = method; count++; } else { die(method.getName() + "() already added for this instance of " + object.getClass().getName()); } } /** * Removes first object/method pair matched (and only the first, * must be called multiple times if object is registered multiple times). * Does not shrink array afterwards, silently returns if method not found. */ // public void remove(Object object, Method method) { // int index = findIndex(object, method); public void remove(Object object) { int index = findIndex(object); if (index != -1) { // shift remaining methods by one to preserve ordering count--; for (int i = index; i < count; i++) { objects[i] = objects[i+1]; methods[i] = methods[i+1]; } // clean things out for the gc's sake objects[count] = null; methods[count] = null; } } // protected int findIndex(Object object, Method method) { protected int findIndex(Object object) { for (int i = 0; i < count; i++) { if (objects[i] == object) { // if (objects[i] == object && methods[i].equals(method)) { //objects[i].equals() might be overridden, so use == for safety // since here we do care about actual object identity //methods[i]==method is never true even for same method, so must use // equals(), this should be safe because of object identity return i; } } return -1; } } /** * Register a built-in event so that it can be fired for libraries, etc. * Supported events include: * <ul> * <li>pre – at the very top of the draw() method (safe to draw) * <li>draw – at the end of the draw() method (safe to draw) * <li>post – after draw() has exited (not safe to draw) * <li>pause – called when the sketch is paused * <li>resume – called when the sketch is resumed * <li>dispose – when the sketch is shutting down (definitely not safe to draw) * <ul> * In addition, the new (for 2.0) processing.event classes are passed to * the following event types: * <ul> * <li>mouseEvent * <li>keyEvent * <li>touchEvent * </ul> * The older java.awt events are no longer supported. * See the Library Wiki page for more details. * @param methodName name of the method to be called * @param target the target object that should receive the event */ public void registerMethod(String methodName, Object target) { if (methodName.equals("mouseEvent")) { registerWithArgs("mouseEvent", target, new Class[] { processing.event.MouseEvent.class }); } else if (methodName.equals("keyEvent")) { registerWithArgs("keyEvent", target, new Class[] { processing.event.KeyEvent.class }); } else if (methodName.equals("touchEvent")) { registerWithArgs("touchEvent", target, new Class[] { processing.event.TouchEvent.class }); } else { registerNoArgs(methodName, target); } } private void registerNoArgs(String name, Object o) { RegisteredMethods meth = registerMap.get(name); if (meth == null) { meth = new RegisteredMethods(); registerMap.put(name, meth); } Class<?> c = o.getClass(); try { Method method = c.getMethod(name, new Class[] {}); meth.add(o, method); } catch (NoSuchMethodException nsme) { die("There is no public " + name + "() method in the class " + o.getClass().getName()); } catch (Exception e) { die("Could not register " + name + " + () for " + o, e); } } private void registerWithArgs(String name, Object o, Class<?> cargs[]) { RegisteredMethods meth = registerMap.get(name); if (meth == null) { meth = new RegisteredMethods(); registerMap.put(name, meth); } Class<?> c = o.getClass(); try { Method method = c.getMethod(name, cargs); meth.add(o, method); } catch (NoSuchMethodException nsme) { die("There is no public " + name + "() method in the class " + o.getClass().getName()); } catch (Exception e) { die("Could not register " + name + " + () for " + o, e); } } // public void registerMethod(String methodName, Object target, Object... args) { // registerWithArgs(methodName, target, args); // } public void unregisterMethod(String name, Object target) { RegisteredMethods meth = registerMap.get(name); if (meth == null) { die("No registered methods with the name " + name + "() were found."); } try { // Method method = o.getClass().getMethod(name, new Class[] {}); // meth.remove(o, method); meth.remove(target); } catch (Exception e) { die("Could not unregister " + name + "() for " + target, e); } } protected void handleMethods(String methodName) { RegisteredMethods meth = registerMap.get(methodName); if (meth != null) { meth.handle(); } } protected void handleMethods(String methodName, Object[] args) { RegisteredMethods meth = registerMap.get(methodName); if (meth != null) { meth.handle(args); } } @Deprecated public void registerSize(Object o) { System.err.println("The registerSize() command is no longer supported."); // Class<?> methodArgs[] = new Class[] { Integer.TYPE, Integer.TYPE }; // registerWithArgs(sizeMethods, "size", o, methodArgs); } @Deprecated public void registerPre(Object o) { registerNoArgs("pre", o); } @Deprecated public void registerDraw(Object o) { registerNoArgs("draw", o); } @Deprecated public void registerPost(Object o) { registerNoArgs("post", o); } @Deprecated public void registerDispose(Object o) { registerNoArgs("dispose", o); } @Deprecated public void unregisterSize(Object o) { System.err.println("The unregisterSize() command is no longer supported."); // Class<?> methodArgs[] = new Class[] { Integer.TYPE, Integer.TYPE }; // unregisterWithArgs(sizeMethods, "size", o, methodArgs); } @Deprecated public void unregisterPre(Object o) { unregisterMethod("pre", o); } @Deprecated public void unregisterDraw(Object o) { unregisterMethod("draw", o); } @Deprecated public void unregisterPost(Object o) { unregisterMethod("post", o); } @Deprecated public void unregisterDispose(Object o) { unregisterMethod("dispose", o); } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . // Old methods with AWT API that should not be used. // These were never implemented on Android so they're stored separately. RegisteredMethods mouseEventMethods, keyEventMethods; protected void reportDeprecation(Class<?> c, boolean mouse) { if (g != null) { PGraphics.showWarning("The class " + c.getName() + " is incompatible with Processing 2.0."); PGraphics.showWarning("A library (or other code) is using register" + (mouse ? "Mouse" : "Key") + "Event() " + "which is no longer available."); // This will crash with OpenGL, so quit anyway if (g instanceof PGraphicsOpenGL) { PGraphics.showWarning("Stopping the sketch because this code will " + "not work correctly with OpenGL."); throw new RuntimeException("This sketch uses a library that " + "needs to be updated for Processing 2.0."); } } } @Deprecated public void registerMouseEvent(Object o) { Class<?> c = o.getClass(); reportDeprecation(c, true); try { Method method = c.getMethod("mouseEvent", new Class[] { java.awt.event.MouseEvent.class }); if (mouseEventMethods == null) { mouseEventMethods = new RegisteredMethods(); } mouseEventMethods.add(o, method); } catch (Exception e) { die("Could not register mouseEvent() for " + o, e); } } @Deprecated public void unregisterMouseEvent(Object o) { try { // Method method = o.getClass().getMethod("mouseEvent", new Class[] { MouseEvent.class }); // mouseEventMethods.remove(o, method); mouseEventMethods.remove(o); } catch (Exception e) { die("Could not unregister mouseEvent() for " + o, e); } } @Deprecated public void registerKeyEvent(Object o) { Class<?> c = o.getClass(); reportDeprecation(c, false); try { Method method = c.getMethod("keyEvent", new Class[] { java.awt.event.KeyEvent.class }); if (keyEventMethods == null) { keyEventMethods = new RegisteredMethods(); } keyEventMethods.add(o, method); } catch (Exception e) { die("Could not register keyEvent() for " + o, e); } } @Deprecated public void unregisterKeyEvent(Object o) { try { // Method method = o.getClass().getMethod("keyEvent", new Class[] { KeyEvent.class }); // keyEventMethods.remove(o, method); keyEventMethods.remove(o); } catch (Exception e) { die("Could not unregister keyEvent() for " + o, e); } } ////////////////////////////////////////////////////////////// /** * ( begin auto-generated from setup.xml ) * * The <b>setup()</b> function is called once when the program starts. It's * used to define initial * enviroment properties such as screen size and background color and to * load media such as images * and fonts as the program starts. There can only be one <b>setup()</b> * function for each program and * it shouldn't be called again after its initial execution. Note: * Variables declared within * <b>setup()</b> are not accessible within other functions, including * <b>draw()</b>. * * ( end auto-generated ) * @webref structure * @usage web_application * @see PApplet#size(int, int) * @see PApplet#loop() * @see PApplet#noLoop() * @see PApplet#draw() */ public void setup() { } /** * ( begin auto-generated from draw.xml ) * * Called directly after <b>setup()</b> and continuously executes the lines * of code contained inside its block until the program is stopped or * <b>noLoop()</b> is called. The <b>draw()</b> function is called * automatically and should never be called explicitly. It should always be * controlled with <b>noLoop()</b>, <b>redraw()</b> and <b>loop()</b>. * After <b>noLoop()</b> stops the code in <b>draw()</b> from executing, * <b>redraw()</b> causes the code inside <b>draw()</b> to execute once and * <b>loop()</b> will causes the code inside <b>draw()</b> to execute * continuously again. The number of times <b>draw()</b> executes in each * second may be controlled with <b>frameRate()</b> function. * There can only be one <b>draw()</b> function for each sketch * and <b>draw()</b> must exist if you want the code to run continuously or * to process events such as <b>mousePressed()</b>. Sometimes, you might * have an empty call to <b>draw()</b> in your program as shown in the * above example. * * ( end auto-generated ) * @webref structure * @usage web_application * @see PApplet#setup() * @see PApplet#loop() * @see PApplet#noLoop() * @see PApplet#redraw() * @see PApplet#frameRate(float) */ public void draw() { // if no draw method, then shut things down //System.out.println("no draw method, goodbye"); finished = true; } ////////////////////////////////////////////////////////////// protected void resizeRenderer(int newWidth, int newHeight) { debug("resizeRenderer request for " + newWidth + " " + newHeight); if (width != newWidth || height != newHeight) { debug(" former size was " + width + " " + height); g.setSize(newWidth, newHeight); width = newWidth; height = newHeight; } } /** * ( begin auto-generated from size.xml ) * * Defines the dimension of the display window in units of pixels. The * <b>size()</b> function must be the first line in <b>setup()</b>. If * <b>size()</b> is not used, the default size of the window is 100x100 * pixels. The system variables <b>width</b> and <b>height</b> are set by * the parameters passed to this function.<br /> * <br /> * Do not use variables as the parameters to <b>size()</b> function, * because it will cause problems when exporting your sketch. When * variables are used, the dimensions of your sketch cannot be determined * during export. Instead, employ numeric values in the <b>size()</b> * statement, and then use the built-in <b>width</b> and <b>height</b> * variables inside your program when the dimensions of the display window * are needed.<br /> * <br /> * The <b>size()</b> function can only be used once inside a sketch, and * cannot be used for resizing.<br/> * <br/> <b>renderer</b> parameter selects which rendering engine to use. * For example, if you will be drawing 3D shapes, use <b>P3D</b>, if you * want to export images from a program as a PDF file use <b>PDF</b>. A * brief description of the three primary renderers follows:<br /> * <br /> * <b>P2D</b> (Processing 2D) - The default renderer that supports two * dimensional drawing.<br /> * <br /> * <b>P3D</b> (Processing 3D) - 3D graphics renderer that makes use of * OpenGL-compatible graphics hardware.<br /> * <br /> * <b>PDF</b> - The PDF renderer draws 2D graphics directly to an Acrobat * PDF file. This produces excellent results when you need vector shapes * for high resolution output or printing. You must first use Import * Library &rarr; PDF to make use of the library. More information can be * found in the PDF library reference.<br /> * <br /> * The P3D renderer doesn't support <b>strokeCap()</b> or * <b>strokeJoin()</b>, which can lead to ugly results when using * <b>strokeWeight()</b>. (<a * href="http://code.google.com/p/processing/issues/detail?id=123">Issue * 123</a>) <br /> * <br /> * The maximum width and height is limited by your operating system, and is * usually the width and height of your actual screen. On some machines it * may simply be the number of pixels on your current screen, meaning that * a screen of 800x600 could support <b>size(1600, 300)</b>, since it's the * same number of pixels. This varies widely so you'll have to try * different rendering modes and sizes until you get what you're looking * for. If you need something larger, use <b>createGraphics</b> to create a * non-visible drawing surface.<br /> * <br /> * Again, the <b>size()</b> function must be the first line of the code (or * first item inside setup). Any code that appears before the <b>size()</b> * command may run more than once, which can lead to confusing results. * * ( end auto-generated ) * * <h3>Advanced</h3> * If using Java 1.3 or later, this will default to using * PGraphics2, the Java2D-based renderer. If using Java 1.1, * or if PGraphics2 is not available, then PGraphics will be used. * To set your own renderer, use the other version of the size() * method that takes a renderer as its last parameter. * <p> * If called once a renderer has already been set, this will * use the previous renderer and simply resize it. * * @webref environment * @param w width of the display window in units of pixels * @param h height of the display window in units of pixels */ public void size(int w, int h) { size(w, h, JAVA2D, null); } /** * @param renderer Either P2D, P3D, or PDF */ public void size(int w, int h, String renderer) { size(w, h, renderer, null); } /** * @nowebref */ public void size(final int w, final int h, String renderer, String path) { // Run this from the EDT, just cuz it's AWT stuff (or maybe later Swing) EventQueue.invokeLater(new Runnable() { public void run() { // Set the preferred size so that the layout managers can handle it setPreferredSize(new Dimension(w, h)); setSize(w, h); } }); // ensure that this is an absolute path if (path != null) path = savePath(path); String currentRenderer = g.getClass().getName(); if (currentRenderer.equals(renderer)) { // Avoid infinite loop of throwing exception to reset renderer resizeRenderer(w, h); //redraw(); // will only be called insize draw() } else { // renderer is being changed // otherwise ok to fall through and create renderer below // the renderer is changing, so need to create a new object g = makeGraphics(w, h, renderer, path, true); this.width = w; this.height = h; // fire resize event to make sure the applet is the proper size // setSize(iwidth, iheight); // this is the function that will run if the user does their own // size() command inside setup, so set defaultSize to false. defaultSize = false; // throw an exception so that setup() is called again // but with a properly sized render // this is for opengl, which needs a valid, properly sized // display before calling anything inside setup(). throw new RendererChangeException(); } } public PGraphics createGraphics(int w, int h) { return createGraphics(w, h, JAVA2D); } /** * ( begin auto-generated from createGraphics.xml ) * * Creates and returns a new <b>PGraphics</b> object of the types P2D or * P3D. Use this class if you need to draw into an off-screen graphics * buffer. The PDF renderer requires the filename parameter. The DXF * renderer should not be used with <b>createGraphics()</b>, it's only * built for use with <b>beginRaw()</b> and <b>endRaw()</b>.<br /> * <br /> * It's important to call any drawing functions between <b>beginDraw()</b> * and <b>endDraw()</b> statements. This is also true for any functions * that affect drawing, such as <b>smooth()</b> or <b>colorMode()</b>.<br/> * <br/> the main drawing surface which is completely opaque, surfaces * created with <b>createGraphics()</b> can have transparency. This makes * it possible to draw into a graphics and maintain the alpha channel. By * using <b>save()</b> to write a PNG or TGA file, the transparency of the * graphics object will be honored. Note that transparency levels are * binary: pixels are either complete opaque or transparent. For the time * being, this means that text characters will be opaque blocks. This will * be fixed in a future release (<a * href="http://code.google.com/p/processing/issues/detail?id=80">Issue 80</a>). * * ( end auto-generated ) * <h3>Advanced</h3> * Create an offscreen PGraphics object for drawing. This can be used * for bitmap or vector images drawing or rendering. * <UL> * <LI>Do not use "new PGraphicsXxxx()", use this method. This method * ensures that internal variables are set up properly that tie the * new graphics context back to its parent PApplet. * <LI>The basic way to create bitmap images is to use the <A * HREF="http://processing.org/reference/saveFrame_.html">saveFrame()</A> * function. * <LI>If you want to create a really large scene and write that, * first make sure that you've allocated a lot of memory in the Preferences. * <LI>If you want to create images that are larger than the screen, * you should create your own PGraphics object, draw to that, and use * <A HREF="http://processing.org/reference/save_.html">save()</A>. * <PRE> * * PGraphics big; * * void setup() { * big = createGraphics(3000, 3000); * * big.beginDraw(); * big.background(128); * big.line(20, 1800, 1800, 900); * // etc.. * big.endDraw(); * * // make sure the file is written to the sketch folder * big.save("big.tif"); * } * * </PRE> * <LI>It's important to always wrap drawing to createGraphics() with * beginDraw() and endDraw() (beginFrame() and endFrame() prior to * revision 0115). The reason is that the renderer needs to know when * drawing has stopped, so that it can update itself internally. * This also handles calling the defaults() method, for people familiar * with that. * <LI>With Processing 0115 and later, it's possible to write images in * formats other than the default .tga and .tiff. The exact formats and * background information can be found in the developer's reference for * <A HREF="http://dev.processing.org/reference/core/javadoc/processing/core/PImage.html#save(java.lang.String)">PImage.save()</A>. * </UL> * * @webref rendering * @param w width in pixels * @param h height in pixels * @param renderer Either P2D, P3D, or PDF * * @see PGraphics#PGraphics * */ public PGraphics createGraphics(int w, int h, String renderer) { PGraphics pg = makeGraphics(w, h, renderer, null, false); //pg.parent = this; // make save() work return pg; } /** * Create an offscreen graphics surface for drawing, in this case * for a renderer that writes to a file (such as PDF or DXF). * @param path the name of the file (can be an absolute or relative path) */ public PGraphics createGraphics(int w, int h, String renderer, String path) { if (path != null) { path = savePath(path); } PGraphics pg = makeGraphics(w, h, renderer, path, false); pg.parent = this; // make save() work return pg; } /** * Version of createGraphics() used internally. */ protected PGraphics makeGraphics(int w, int h, String renderer, String path, boolean primary) { String openglError = external ? "Before using OpenGL, first select " + "Import Library > OpenGL from the Sketch menu." : "The Java classpath and native library path is not " + // welcome to Java programming! "properly set for using the OpenGL library."; if (!primary && !g.isGL()) { if (renderer.equals(P2D)) { throw new RuntimeException("createGraphics() with P2D requires size() to use P2D or P3D"); } else if (renderer.equals(P3D)) { throw new RuntimeException("createGraphics() with P3D or OPENGL requires size() to use P2D or P3D"); } } try { Class<?> rendererClass = Thread.currentThread().getContextClassLoader().loadClass(renderer); Constructor<?> constructor = rendererClass.getConstructor(new Class[] { }); PGraphics pg = (PGraphics) constructor.newInstance(); pg.setParent(this); pg.setPrimary(primary); if (path != null) pg.setPath(path); // pg.setQuality(sketchQuality()); pg.setSize(w, h); // everything worked, return it return pg; } catch (InvocationTargetException ite) { String msg = ite.getTargetException().getMessage(); if ((msg != null) && (msg.indexOf("no jogl in java.library.path") != -1)) { throw new RuntimeException(openglError + " (The native library is missing.)"); } else { ite.getTargetException().printStackTrace(); Throwable target = ite.getTargetException(); if (platform == MACOSX) target.printStackTrace(System.out); // bug // neither of these help, or work //target.printStackTrace(System.err); //System.err.flush(); //System.out.println(System.err); // and the object isn't null throw new RuntimeException(target.getMessage()); } } catch (ClassNotFoundException cnfe) { if (cnfe.getMessage().indexOf("processing.opengl.PGraphicsOpenGL") != -1) { throw new RuntimeException(openglError + " (The library .jar file is missing.)"); } else { throw new RuntimeException("You need to use \"Import Library\" " + "to add " + renderer + " to your sketch."); } } catch (Exception e) { if ((e instanceof IllegalArgumentException) || (e instanceof NoSuchMethodException) || (e instanceof IllegalAccessException)) { if (e.getMessage().contains("cannot be <= 0")) { // IllegalArgumentException will be thrown if w/h is <= 0 // http://code.google.com/p/processing/issues/detail?id=983 throw new RuntimeException(e); } else { e.printStackTrace(); String msg = renderer + " needs to be updated " + "for the current release of Processing."; throw new RuntimeException(msg); } } else { if (platform == MACOSX) e.printStackTrace(System.out); throw new RuntimeException(e.getMessage()); } } } /** * ( begin auto-generated from createImage.xml ) * * Creates a new PImage (the datatype for storing images). This provides a * fresh buffer of pixels to play with. Set the size of the buffer with the * <b>width</b> and <b>height</b> parameters. The <b>format</b> parameter * defines how the pixels are stored. See the PImage reference for more information. * <br/> <br/> * Be sure to include all three parameters, specifying only the width and * height (but no format) will produce a strange error. * <br/> <br/> * Advanced users please note that createImage() should be used instead of * the syntax <tt>new PImage()</tt>. * * ( end auto-generated ) * <h3>Advanced</h3> * Preferred method of creating new PImage objects, ensures that a * reference to the parent PApplet is included, which makes save() work * without needing an absolute path. * * @webref image * @param w width in pixels * @param h height in pixels * @param format Either RGB, ARGB, ALPHA (grayscale alpha channel) * @see PImage * @see PGraphics */ public PImage createImage(int w, int h, int format) { PImage image = new PImage(w, h, format); image.parent = this; // make save() work return image; } /* public PImage createImage(int w, int h, int format) { return createImage(w, h, format, null); } // unapproved public PImage createImage(int w, int h, int format, Object params) { PImage image = new PImage(w, h, format); if (params != null) { image.setParams(g, params); } image.parent = this; // make save() work return image; } */ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . @Override public void update(Graphics screen) { paint(screen); } @Override public void paint(Graphics screen) { // int r = (int) random(10000); // System.out.println("into paint " + r); //super.paint(screen); // ignore the very first call to paint, since it's coming // from the o.s., and the applet will soon update itself anyway. if (frameCount == 0) { // println("Skipping frame"); // paint() may be called more than once before things // are finally painted to the screen and the thread gets going return; } // without ignoring the first call, the first several frames // are confused because paint() gets called in the midst of // the initial nextFrame() call, so there are multiple // updates fighting with one another. // make sure the screen is visible and usable // (also prevents over-drawing when using PGraphicsOpenGL) /* the 1.5.x version if (g != null) { // added synchronization for 0194 because of flicker issues with JAVA2D // http://code.google.com/p/processing/issues/detail?id=558 // g.image is synchronized so that draw/loop and paint don't // try to fight over it. this was causing a randomized slowdown // that would cut the frameRate into a third on macosx, // and is probably related to the windows sluggishness bug too if (g.image != null) { System.out.println("ui paint"); synchronized (g.image) { screen.drawImage(g.image, 0, 0, null); } } } */ // if (useActive) { // return; // } // if (insideDraw) { // new Exception().printStackTrace(System.out); // } if (!insideDraw && (g != null) && (g.image != null)) { if (useStrategy) { render(); } else { // System.out.println("drawing to screen"); //screen.drawImage(g.image, 0, 0, null); // not retina friendly screen.drawImage(g.image, 0, 0, width, height, null); } } else { debug(insideDraw + " " + g + " " + ((g != null) ? g.image : "-")); } } protected synchronized void render() { if (canvas == null) { removeListeners(this); canvas = new Canvas(); add(canvas); setIgnoreRepaint(true); canvas.setIgnoreRepaint(true); addListeners(canvas); // add(canvas, BorderLayout.CENTER); // doLayout(); } canvas.setBounds(0, 0, width, height); // System.out.println("render(), canvas bounds are " + canvas.getBounds()); if (canvas.getBufferStrategy() == null) { // whole block [121222] // System.out.println("creating a strategy"); canvas.createBufferStrategy(2); } BufferStrategy strategy = canvas.getBufferStrategy(); if (strategy == null) { return; } // Render single frame do { // The following loop ensures that the contents of the drawing buffer // are consistent in case the underlying surface was recreated do { Graphics draw = strategy.getDrawGraphics(); draw.drawImage(g.image, 0, 0, width, height, null); draw.dispose(); // Repeat the rendering if the drawing buffer contents // were restored // System.out.println("restored " + strategy.contentsRestored()); } while (strategy.contentsRestored()); // Display the buffer // System.out.println("showing"); strategy.show(); // Repeat the rendering if the drawing buffer was lost // System.out.println("lost " + strategy.contentsLost()); // System.out.println(); } while (strategy.contentsLost()); } /* // active paint method (also the 1.2.1 version) protected void paint() { try { Graphics screen = this.getGraphics(); if (screen != null) { if ((g != null) && (g.image != null)) { screen.drawImage(g.image, 0, 0, null); } Toolkit.getDefaultToolkit().sync(); } } catch (Exception e) { // Seen on applet destroy, maybe can ignore? e.printStackTrace(); // } finally { // if (g != null) { // g.dispose(); // } } } protected void paint_1_5_1() { try { Graphics screen = getGraphics(); if (screen != null) { if (g != null) { // added synchronization for 0194 because of flicker issues with JAVA2D // http://code.google.com/p/processing/issues/detail?id=558 if (g.image != null) { System.out.println("active paint"); synchronized (g.image) { screen.drawImage(g.image, 0, 0, null); } Toolkit.getDefaultToolkit().sync(); } } } } catch (Exception e) { // Seen on applet destroy, maybe can ignore? e.printStackTrace(); } } */ ////////////////////////////////////////////////////////////// /** * Main method for the primary animation thread. * * <A HREF="http://java.sun.com/products/jfc/tsc/articles/painting/">Painting in AWT and Swing</A> */ public void run() { // not good to make this synchronized, locks things up long beforeTime = System.nanoTime(); long overSleepTime = 0L; int noDelays = 0; // Number of frames with a delay of 0 ms before the // animation thread yields to other running threads. final int NO_DELAYS_PER_YIELD = 15; /* // this has to be called after the exception is thrown, // otherwise the supporting libs won't have a valid context to draw to Object methodArgs[] = new Object[] { new Integer(width), new Integer(height) }; sizeMethods.handle(methodArgs); */ if (!online) { start(); } while ((Thread.currentThread() == thread) && !finished) { if (paused) { debug("PApplet.run() paused, calling object wait..."); synchronized (pauseObject) { try { pauseObject.wait(); debug("out of wait"); } catch (InterruptedException e) { // waiting for this interrupt on a start() (resume) call } } } debug("done with pause"); // while (paused) { // debug("paused..."); // try { // Thread.sleep(100L); // } catch (InterruptedException e) { } // ignored // } // Don't resize the renderer from the EDT (i.e. from a ComponentEvent), // otherwise it may attempt a resize mid-render. // if (resizeRequest) { // resizeRenderer(resizeWidth, resizeHeight); // resizeRequest = false; // } if (g != null) { getSize(currentSize); if (currentSize.width != g.width || currentSize.height != g.height) { resizeRenderer(currentSize.width, currentSize.height); } } // render a single frame //handleDraw(); if (g != null) g.requestDraw(); if (frameCount == 1) { // for 2.0a6, moving this request to the EDT EventQueue.invokeLater(new Runnable() { public void run() { // Call the request focus event once the image is sure to be on // screen and the component is valid. The OpenGL renderer will // request focus for its canvas inside beginDraw(). // http://java.sun.com/j2se/1.4.2/docs/api/java/awt/doc-files/FocusSpec.html // Disabling for 0185, because it causes an assertion failure on OS X // http://code.google.com/p/processing/issues/detail?id=258 // requestFocus(); // Changing to this version for 0187 // http://code.google.com/p/processing/issues/detail?id=279 requestFocusInWindow(); } }); } // wait for update & paint to happen before drawing next frame // this is necessary since the drawing is sometimes in a // separate thread, meaning that the next frame will start // before the update/paint is completed long afterTime = System.nanoTime(); long timeDiff = afterTime - beforeTime; //System.out.println("time diff is " + timeDiff); long sleepTime = (frameRatePeriod - timeDiff) - overSleepTime; if (sleepTime > 0) { // some time left in this cycle try { // Thread.sleep(sleepTime / 1000000L); // nanoseconds -> milliseconds Thread.sleep(sleepTime / 1000000L, (int) (sleepTime % 1000000L)); noDelays = 0; // Got some sleep, not delaying anymore } catch (InterruptedException ex) { } overSleepTime = (System.nanoTime() - afterTime) - sleepTime; //System.out.println(" oversleep is " + overSleepTime); } else { // sleepTime <= 0; the frame took longer than the period // excess -= sleepTime; // store excess time value overSleepTime = 0L; noDelays++; if (noDelays > NO_DELAYS_PER_YIELD) { Thread.yield(); // give another thread a chance to run noDelays = 0; } } beforeTime = System.nanoTime(); } dispose(); // call to shutdown libs? // If the user called the exit() function, the window should close, // rather than the sketch just halting. if (exitCalled) { exitActual(); } } protected boolean insideDraw; //synchronized public void handleDisplay() { public void handleDraw() { debug("handleDraw() " + g + " " + looping + " " + redraw + " valid:" + this.isValid() + " visible:" + this.isVisible()); if (canDraw()) { if (!g.canDraw()) { debug("g.canDraw() is false"); // Don't draw if the renderer is not yet ready. // (e.g. OpenGL has to wait for a peer to be on screen) return; } insideDraw = true; g.beginDraw(); if (recorder != null) { recorder.beginDraw(); } long now = System.nanoTime(); if (frameCount == 0) { GraphicsConfiguration gc = getGraphicsConfiguration(); if (gc == null) return; GraphicsDevice displayDevice = getGraphicsConfiguration().getDevice(); if (displayDevice == null) return; Rectangle screenRect = displayDevice.getDefaultConfiguration().getBounds(); // screenX = screenRect.x; // screenY = screenRect.y; displayWidth = screenRect.width; displayHeight = screenRect.height; try { //println("Calling setup()"); setup(); //println("Done with setup()"); } catch (RendererChangeException e) { // Give up, instead set the new renderer and re-attempt setup() return; } this.defaultSize = false; } else { // frameCount > 0, meaning an actual draw() // update the current frameRate double rate = 1000000.0 / ((now - frameRateLastNanos) / 1000000.0); float instantaneousRate = (float) rate / 1000.0f; frameRate = (frameRate * 0.9f) + (instantaneousRate * 0.1f); if (frameCount != 0) { handleMethods("pre"); } // use dmouseX/Y as previous mouse pos, since this is the // last position the mouse was in during the previous draw. pmouseX = dmouseX; pmouseY = dmouseY; //println("Calling draw()"); draw(); //println("Done calling draw()"); // dmouseX/Y is updated only once per frame (unlike emouseX/Y) dmouseX = mouseX; dmouseY = mouseY; // these are called *after* loop so that valid // drawing commands can be run inside them. it can't // be before, since a call to background() would wipe // out anything that had been drawn so far. dequeueEvents(); // dequeueMouseEvents(); // dequeueKeyEvents(); handleMethods("draw"); redraw = false; // unset 'redraw' flag in case it was set // (only do this once draw() has run, not just setup()) } g.endDraw(); if (recorder != null) { recorder.endDraw(); } insideDraw = false; if (useActive) { if (useStrategy) { render(); } else { Graphics screen = getGraphics(); screen.drawImage(g.image, 0, 0, width, height, null); } } else { repaint(); } // getToolkit().sync(); // force repaint now (proper method) if (frameCount != 0) { handleMethods("post"); } frameRateLastNanos = now; frameCount++; } } /** Not official API, not guaranteed to work in the future. */ public boolean canDraw() { return g != null && (looping || redraw); } ////////////////////////////////////////////////////////////// /** * ( begin auto-generated from redraw.xml ) * * Executes the code within <b>draw()</b> one time. This functions allows * the program to update the display window only when necessary, for * example when an event registered by <b>mousePressed()</b> or * <b>keyPressed()</b> occurs. * <br/><br/> structuring a program, it only makes sense to call redraw() * within events such as <b>mousePressed()</b>. This is because * <b>redraw()</b> does not run <b>draw()</b> immediately (it only sets a * flag that indicates an update is needed). * <br/><br/> <b>redraw()</b> within <b>draw()</b> has no effect because * <b>draw()</b> is continuously called anyway. * * ( end auto-generated ) * @webref structure * @usage web_application * @see PApplet#draw() * @see PApplet#loop() * @see PApplet#noLoop() * @see PApplet#frameRate(float) */ synchronized public void redraw() { if (!looping) { redraw = true; // if (thread != null) { // // wake from sleep (necessary otherwise it'll be // // up to 10 seconds before update) // if (CRUSTY_THREADS) { // thread.interrupt(); // } else { // synchronized (blocker) { // blocker.notifyAll(); // } // } // } } } /** * ( begin auto-generated from loop.xml ) * * Causes Processing to continuously execute the code within <b>draw()</b>. * If <b>noLoop()</b> is called, the code in <b>draw()</b> stops executing. * * ( end auto-generated ) * @webref structure * @usage web_application * @see PApplet#noLoop() * @see PApplet#redraw() * @see PApplet#draw() */ synchronized public void loop() { if (!looping) { looping = true; } } /** * ( begin auto-generated from noLoop.xml ) * * Stops Processing from continuously executing the code within * <b>draw()</b>. If <b>loop()</b> is called, the code in <b>draw()</b> * begin to run continuously again. If using <b>noLoop()</b> in * <b>setup()</b>, it should be the last line inside the block. * <br/> <br/> * When <b>noLoop()</b> is used, it's not possible to manipulate or access * the screen inside event handling functions such as <b>mousePressed()</b> * or <b>keyPressed()</b>. Instead, use those functions to call * <b>redraw()</b> or <b>loop()</b>, which will run <b>draw()</b>, which * can update the screen properly. This means that when noLoop() has been * called, no drawing can happen, and functions like saveFrame() or * loadPixels() may not be used. * <br/> <br/> * Note that if the sketch is resized, <b>redraw()</b> will be called to * update the sketch, even after <b>noLoop()</b> has been specified. * Otherwise, the sketch would enter an odd state until <b>loop()</b> was called. * * ( end auto-generated ) * @webref structure * @usage web_application * @see PApplet#loop() * @see PApplet#redraw() * @see PApplet#draw() */ synchronized public void noLoop() { if (looping) { looping = false; } } ////////////////////////////////////////////////////////////// // public void addListeners() { // addMouseListener(this); // addMouseMotionListener(this); // addKeyListener(this); // addFocusListener(this); // // addComponentListener(new ComponentAdapter() { // public void componentResized(ComponentEvent e) { // Component c = e.getComponent(); // //System.out.println("componentResized() " + c); // Rectangle bounds = c.getBounds(); // resizeRequest = true; // resizeWidth = bounds.width; // resizeHeight = bounds.height; // // if (!looping) { // redraw(); // } // } // }); // } // // // public void removeListeners() { // removeMouseListener(this); // removeMouseMotionListener(this); // removeKeyListener(this); // removeFocusListener(this); // //// removeComponentListener(??); //// addComponentListener(new ComponentAdapter() { //// public void componentResized(ComponentEvent e) { //// Component c = e.getComponent(); //// //System.out.println("componentResized() " + c); //// Rectangle bounds = c.getBounds(); //// resizeRequest = true; //// resizeWidth = bounds.width; //// resizeHeight = bounds.height; //// //// if (!looping) { //// redraw(); //// } //// } //// }); // } public void addListeners(Component comp) { comp.addMouseListener(this); comp.addMouseWheelListener(this); comp.addMouseMotionListener(this); comp.addKeyListener(this); comp.addFocusListener(this); // canvas.addComponentListener(new ComponentAdapter() { // public void componentResized(ComponentEvent e) { // Component c = e.getComponent(); // //System.out.println("componentResized() " + c); // Rectangle bounds = c.getBounds(); // resizeRequest = true; // resizeWidth = bounds.width; // resizeHeight = bounds.height; // // if (!looping) { // redraw(); // } // } // }); } public void removeListeners(Component comp) { comp.removeMouseListener(this); comp.removeMouseWheelListener(this); comp.removeMouseMotionListener(this); comp.removeKeyListener(this); comp.removeFocusListener(this); } /** * Call to remove, then add, listeners to a component. * Avoids issues with double-adding. */ public void updateListeners(Component comp) { removeListeners(comp); addListeners(comp); } ////////////////////////////////////////////////////////////// // protected Event eventQueue[] = new Event[10]; // protected int eventCount; class InternalEventQueue { protected Event queue[] = new Event[10]; protected int offset; protected int count; synchronized void add(Event e) { if (count == queue.length) { queue = (Event[]) expand(queue); } queue[count++] = e; } synchronized Event remove() { if (offset == count) { throw new RuntimeException("Nothing left on the event queue."); } Event outgoing = queue[offset++]; if (offset == count) { // All done, time to reset offset = 0; count = 0; } return outgoing; } synchronized boolean available() { return count != 0; } } InternalEventQueue eventQueue = new InternalEventQueue(); /** * Add an event to the internal event queue, or process it immediately if * the sketch is not currently looping. */ public void postEvent(processing.event.Event pe) { // if (pe instanceof MouseEvent) { //// switch (pe.getFlavor()) { //// case Event.MOUSE: // if (looping) { // enqueueMouseEvent((MouseEvent) pe); // } else { // handleMouseEvent((MouseEvent) pe); // enqueueEvent(pe); // } // } else if (pe instanceof KeyEvent) { // if (looping) { // enqueueKeyEvent((KeyEvent) pe); // } else { // handleKeyEvent((KeyEvent) pe); // } // } // synchronized (eventQueue) { // if (eventCount == eventQueue.length) { // eventQueue = (Event[]) expand(eventQueue); // } // eventQueue[eventCount++] = pe; // } eventQueue.add(pe); if (!looping) { dequeueEvents(); } } // protected void enqueueEvent(Event e) { // synchronized (eventQueue) { // if (eventCount == eventQueue.length) { // eventQueue = (Event[]) expand(eventQueue); // } // eventQueue[eventCount++] = e; // } // } protected void dequeueEvents() { // can't do this.. thread lock // synchronized (eventQueue) { // for (int i = 0; i < eventCount; i++) { // Event e = eventQueue[i]; while (eventQueue.available()) { Event e = eventQueue.remove(); switch (e.getFlavor()) { case Event.MOUSE: handleMouseEvent((MouseEvent) e); break; case Event.KEY: handleKeyEvent((KeyEvent) e); break; } // } // eventCount = 0; } } ////////////////////////////////////////////////////////////// // MouseEvent mouseEventQueue[] = new MouseEvent[10]; // int mouseEventCount; // // protected void enqueueMouseEvent(MouseEvent e) { // synchronized (mouseEventQueue) { // if (mouseEventCount == mouseEventQueue.length) { // MouseEvent temp[] = new MouseEvent[mouseEventCount << 1]; // System.arraycopy(mouseEventQueue, 0, temp, 0, mouseEventCount); // mouseEventQueue = temp; // } // mouseEventQueue[mouseEventCount++] = e; // } // } // // protected void dequeueMouseEvents() { // synchronized (mouseEventQueue) { // for (int i = 0; i < mouseEventCount; i++) { // handleMouseEvent(mouseEventQueue[i]); // } // mouseEventCount = 0; // } // } /** * Actually take action based on a mouse event. * Internally updates mouseX, mouseY, mousePressed, and mouseEvent. * Then it calls the event type with no params, * i.e. mousePressed() or mouseReleased() that the user may have * overloaded to do something more useful. */ protected void handleMouseEvent(MouseEvent event) { // http://dev.processing.org/bugs/show_bug.cgi?id=170 // also prevents mouseExited() on the mac from hosing the mouse // position, because x/y are bizarre values on the exit event. // see also the id check below.. both of these go together. // Not necessary to set mouseX/Y on PRESS or RELEASE events because the // actual position will have been set by a MOVE or DRAG event. if (event.getAction() == MouseEvent.DRAG || event.getAction() == MouseEvent.MOVE) { pmouseX = emouseX; pmouseY = emouseY; mouseX = event.getX(); mouseY = event.getY(); } // Get the (already processed) button code mouseButton = event.getButton(); // Compatibility for older code (these have AWT object params, not P5) if (mouseEventMethods != null) { // Probably also good to check this, in case anyone tries to call // postEvent() with an artificial event they've created. if (event.getNative() != null) { mouseEventMethods.handle(new Object[] { event.getNative() }); } } // this used to only be called on mouseMoved and mouseDragged // change it back if people run into trouble if (firstMouse) { pmouseX = mouseX; pmouseY = mouseY; dmouseX = mouseX; dmouseY = mouseY; firstMouse = false; } mouseEvent = event; // Do this up here in case a registered method relies on the // boolean for mousePressed. switch (event.getAction()) { case MouseEvent.PRESS: mousePressed = true; break; case MouseEvent.RELEASE: mousePressed = false; break; } handleMethods("mouseEvent", new Object[] { event }); switch (event.getAction()) { case MouseEvent.PRESS: // mousePressed = true; mousePressed(event); break; case MouseEvent.RELEASE: // mousePressed = false; mouseReleased(event); break; case MouseEvent.CLICK: mouseClicked(event); break; case MouseEvent.DRAG: mouseDragged(event); break; case MouseEvent.MOVE: mouseMoved(event); break; case MouseEvent.ENTER: mouseEntered(event); break; case MouseEvent.EXIT: mouseExited(event); break; case MouseEvent.WHEEL: mouseWheel(event); break; } if ((event.getAction() == MouseEvent.DRAG) || (event.getAction() == MouseEvent.MOVE)) { emouseX = mouseX; emouseY = mouseY; } } /* // disabling for now; requires Java 1.7 and "precise" semantics are odd... // returns 0.1 for tick-by-tick scrolling on OS X, but it's not a matter of // calling ceil() on the value: 1.5 goes to 1, but 2.3 goes to 2. // "precise" is a whole different animal, so add later API to shore that up. static protected Method preciseWheelMethod; static { try { preciseWheelMethod = MouseWheelEvent.class.getMethod("getPreciseWheelRotation", new Class[] { }); } catch (Exception e) { // ignored, the method will just be set to null } } */ /** * Figure out how to process a mouse event. When loop() has been * called, the events will be queued up until drawing is complete. * If noLoop() has been called, then events will happen immediately. */ protected void nativeMouseEvent(java.awt.event.MouseEvent nativeEvent) { // the 'amount' is the number of button clicks for a click event, // or the number of steps/clicks on the wheel for a mouse wheel event. int peCount = nativeEvent.getClickCount(); int peAction = 0; switch (nativeEvent.getID()) { case java.awt.event.MouseEvent.MOUSE_PRESSED: peAction = MouseEvent.PRESS; break; case java.awt.event.MouseEvent.MOUSE_RELEASED: peAction = MouseEvent.RELEASE; break; case java.awt.event.MouseEvent.MOUSE_CLICKED: peAction = MouseEvent.CLICK; break; case java.awt.event.MouseEvent.MOUSE_DRAGGED: peAction = MouseEvent.DRAG; break; case java.awt.event.MouseEvent.MOUSE_MOVED: peAction = MouseEvent.MOVE; break; case java.awt.event.MouseEvent.MOUSE_ENTERED: peAction = MouseEvent.ENTER; break; case java.awt.event.MouseEvent.MOUSE_EXITED: peAction = MouseEvent.EXIT; break; //case java.awt.event.MouseWheelEvent.WHEEL_UNIT_SCROLL: case java.awt.event.MouseEvent.MOUSE_WHEEL: peAction = MouseEvent.WHEEL; /* if (preciseWheelMethod != null) { try { peAmount = ((Double) preciseWheelMethod.invoke(nativeEvent, (Object[]) null)).floatValue(); } catch (Exception e) { preciseWheelMethod = null; } } */ peCount = ((MouseWheelEvent) nativeEvent).getWheelRotation(); break; } //System.out.println(nativeEvent); //int modifiers = nativeEvent.getModifiersEx(); // If using getModifiersEx(), the regular modifiers don't set properly. int modifiers = nativeEvent.getModifiers(); int peModifiers = modifiers & (InputEvent.SHIFT_MASK | InputEvent.CTRL_MASK | InputEvent.META_MASK | InputEvent.ALT_MASK); // Windows and OS X seem to disagree on how to handle this. Windows only // sets BUTTON1_DOWN_MASK, while OS X seems to set BUTTON1_MASK. // This is an issue in particular with mouse release events: // http://code.google.com/p/processing/issues/detail?id=1294 // The fix for which led to a regression (fixed here by checking both): // http://code.google.com/p/processing/issues/detail?id=1332 int peButton = 0; // if ((modifiers & InputEvent.BUTTON1_MASK) != 0 || // (modifiers & InputEvent.BUTTON1_DOWN_MASK) != 0) { // peButton = LEFT; // } else if ((modifiers & InputEvent.BUTTON2_MASK) != 0 || // (modifiers & InputEvent.BUTTON2_DOWN_MASK) != 0) { // peButton = CENTER; // } else if ((modifiers & InputEvent.BUTTON3_MASK) != 0 || // (modifiers & InputEvent.BUTTON3_DOWN_MASK) != 0) { // peButton = RIGHT; // } if ((modifiers & InputEvent.BUTTON1_MASK) != 0) { peButton = LEFT; } else if ((modifiers & InputEvent.BUTTON2_MASK) != 0) { peButton = CENTER; } else if ((modifiers & InputEvent.BUTTON3_MASK) != 0) { peButton = RIGHT; } // If running on macos, allow ctrl-click as right mouse. Prior to 0215, // this used isPopupTrigger() on the native event, but that doesn't work // for mouseClicked and mouseReleased (or others). if (platform == MACOSX) { //if (nativeEvent.isPopupTrigger()) { if ((modifiers & InputEvent.CTRL_MASK) != 0) { peButton = RIGHT; } } postEvent(new MouseEvent(nativeEvent, nativeEvent.getWhen(), peAction, peModifiers, nativeEvent.getX(), nativeEvent.getY(), peButton, peCount)); } /** * If you override this or any function that takes a "MouseEvent e" * without calling its super.mouseXxxx() then mouseX, mouseY, * mousePressed, and mouseEvent will no longer be set. * * @nowebref */ public void mousePressed(java.awt.event.MouseEvent e) { nativeMouseEvent(e); } /** * @nowebref */ public void mouseReleased(java.awt.event.MouseEvent e) { nativeMouseEvent(e); } /** * @nowebref */ public void mouseClicked(java.awt.event.MouseEvent e) { nativeMouseEvent(e); } /** * @nowebref */ public void mouseEntered(java.awt.event.MouseEvent e) { nativeMouseEvent(e); } /** * @nowebref */ public void mouseExited(java.awt.event.MouseEvent e) { nativeMouseEvent(e); } /** * @nowebref */ public void mouseDragged(java.awt.event.MouseEvent e) { nativeMouseEvent(e); } /** * @nowebref */ public void mouseMoved(java.awt.event.MouseEvent e) { nativeMouseEvent(e); } /** * @nowebref */ public void mouseWheelMoved(java.awt.event.MouseWheelEvent e) { nativeMouseEvent(e); } /** * ( begin auto-generated from mousePressed.xml ) * * The <b>mousePressed()</b> function is called once after every time a * mouse button is pressed. The <b>mouseButton</b> variable (see the * related reference entry) can be used to determine which button has been pressed. * * ( end auto-generated ) * <h3>Advanced</h3> * * If you must, use * int button = mouseEvent.getButton(); * to figure out which button was clicked. It will be one of: * MouseEvent.BUTTON1, MouseEvent.BUTTON2, MouseEvent.BUTTON3 * Note, however, that this is completely inconsistent across * platforms. * @webref input:mouse * @see PApplet#mouseX * @see PApplet#mouseY * @see PApplet#mousePressed * @see PApplet#mouseButton * @see PApplet#mouseReleased() * @see PApplet#mouseMoved() * @see PApplet#mouseDragged() */ public void mousePressed() { } public void mousePressed(MouseEvent event) { mousePressed(); } /** * ( begin auto-generated from mouseReleased.xml ) * * The <b>mouseReleased()</b> function is called every time a mouse button * is released. * * ( end auto-generated ) * @webref input:mouse * @see PApplet#mouseX * @see PApplet#mouseY * @see PApplet#mousePressed * @see PApplet#mouseButton * @see PApplet#mousePressed() * @see PApplet#mouseMoved() * @see PApplet#mouseDragged() */ public void mouseReleased() { } public void mouseReleased(MouseEvent event) { mouseReleased(); } /** * ( begin auto-generated from mouseClicked.xml ) * * The <b>mouseClicked()</b> function is called once after a mouse button * has been pressed and then released. * * ( end auto-generated ) * <h3>Advanced</h3> * When the mouse is clicked, mousePressed() will be called, * then mouseReleased(), then mouseClicked(). Note that * mousePressed is already false inside of mouseClicked(). * @webref input:mouse * @see PApplet#mouseX * @see PApplet#mouseY * @see PApplet#mouseButton * @see PApplet#mousePressed() * @see PApplet#mouseReleased() * @see PApplet#mouseMoved() * @see PApplet#mouseDragged() */ public void mouseClicked() { } public void mouseClicked(MouseEvent event) { mouseClicked(); } /** * ( begin auto-generated from mouseDragged.xml ) * * The <b>mouseDragged()</b> function is called once every time the mouse * moves and a mouse button is pressed. * * ( end auto-generated ) * @webref input:mouse * @see PApplet#mouseX * @see PApplet#mouseY * @see PApplet#mousePressed * @see PApplet#mousePressed() * @see PApplet#mouseReleased() * @see PApplet#mouseMoved() */ public void mouseDragged() { } public void mouseDragged(MouseEvent event) { mouseDragged(); } /** * ( begin auto-generated from mouseMoved.xml ) * * The <b>mouseMoved()</b> function is called every time the mouse moves * and a mouse button is not pressed. * * ( end auto-generated ) * @webref input:mouse * @see PApplet#mouseX * @see PApplet#mouseY * @see PApplet#mousePressed * @see PApplet#mousePressed() * @see PApplet#mouseReleased() * @see PApplet#mouseDragged() */ public void mouseMoved() { } public void mouseMoved(MouseEvent event) { mouseMoved(); } public void mouseEntered() { } public void mouseEntered(MouseEvent event) { mouseEntered(); } public void mouseExited() { } public void mouseExited(MouseEvent event) { mouseExited(); } /** * @nowebref */ public void mouseWheel() { } /** * The event.getAmount() method returns negative values if the mouse wheel * if rotated up or away from the user and positive in the other direction. * On OS X with "natural" scrolling enabled, the values are opposite. * * @webref input:mouse * @param event the MouseEvent */ public void mouseWheel(MouseEvent event) { mouseWheel(); } ////////////////////////////////////////////////////////////// // KeyEvent keyEventQueue[] = new KeyEvent[10]; // int keyEventCount; // // protected void enqueueKeyEvent(KeyEvent e) { // synchronized (keyEventQueue) { // if (keyEventCount == keyEventQueue.length) { // KeyEvent temp[] = new KeyEvent[keyEventCount << 1]; // System.arraycopy(keyEventQueue, 0, temp, 0, keyEventCount); // keyEventQueue = temp; // } // keyEventQueue[keyEventCount++] = e; // } // } // // protected void dequeueKeyEvents() { // synchronized (keyEventQueue) { // for (int i = 0; i < keyEventCount; i++) { // keyEvent = keyEventQueue[i]; // handleKeyEvent(keyEvent); // } // keyEventCount = 0; // } // } // protected void handleKeyEvent(java.awt.event.KeyEvent event) { // keyEvent = event; // key = event.getKeyChar(); // keyCode = event.getKeyCode(); // // if (keyEventMethods != null) { // keyEventMethods.handle(new Object[] { event }); // } // // switch (event.getID()) { // case KeyEvent.KEY_PRESSED: // keyPressed = true; // keyPressed(); // break; // case KeyEvent.KEY_RELEASED: // keyPressed = false; // keyReleased(); // break; // case KeyEvent.KEY_TYPED: // keyTyped(); // break; // } // // // if someone else wants to intercept the key, they should // // set key to zero (or something besides the ESC). // if (event.getID() == java.awt.event.KeyEvent.KEY_PRESSED) { // if (key == java.awt.event.KeyEvent.VK_ESCAPE) { // exit(); // } // // When running tethered to the Processing application, respond to // // Ctrl-W (or Cmd-W) events by closing the sketch. Disable this behavior // // when running independently, because this sketch may be one component // // embedded inside an application that has its own close behavior. // if (external && // event.getModifiers() == MENU_SHORTCUT && // event.getKeyCode() == 'W') { // exit(); // } // } // } protected void handleKeyEvent(KeyEvent event) { keyEvent = event; key = event.getKey(); keyCode = event.getKeyCode(); switch (event.getAction()) { case KeyEvent.PRESS: keyPressed = true; keyPressed(keyEvent); break; case KeyEvent.RELEASE: keyPressed = false; keyReleased(keyEvent); break; case KeyEvent.TYPE: keyTyped(keyEvent); break; } if (keyEventMethods != null) { keyEventMethods.handle(new Object[] { event.getNative() }); } handleMethods("keyEvent", new Object[] { event }); // if someone else wants to intercept the key, they should // set key to zero (or something besides the ESC). if (event.getAction() == KeyEvent.PRESS) { //if (key == java.awt.event.KeyEvent.VK_ESCAPE) { if (key == ESC) { exit(); } // When running tethered to the Processing application, respond to // Ctrl-W (or Cmd-W) events by closing the sketch. Not enabled when // running independently, because this sketch may be one component // embedded inside an application that has its own close behavior. if (external && event.getKeyCode() == 'W' && ((event.isMetaDown() && platform == MACOSX) || (event.isControlDown() && platform != MACOSX))) { // Can't use this native stuff b/c the native event might be NEWT // if (external && event.getNative() instanceof java.awt.event.KeyEvent && // ((java.awt.event.KeyEvent) event.getNative()).getModifiers() == // Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() && // event.getKeyCode() == 'W') { exit(); } } } protected void nativeKeyEvent(java.awt.event.KeyEvent event) { int peAction = 0; switch (event.getID()) { case java.awt.event.KeyEvent.KEY_PRESSED: peAction = KeyEvent.PRESS; break; case java.awt.event.KeyEvent.KEY_RELEASED: peAction = KeyEvent.RELEASE; break; case java.awt.event.KeyEvent.KEY_TYPED: peAction = KeyEvent.TYPE; break; } // int peModifiers = event.getModifiersEx() & // (InputEvent.SHIFT_DOWN_MASK | // InputEvent.CTRL_DOWN_MASK | // InputEvent.META_DOWN_MASK | // InputEvent.ALT_DOWN_MASK); int peModifiers = event.getModifiers() & (InputEvent.SHIFT_MASK | InputEvent.CTRL_MASK | InputEvent.META_MASK | InputEvent.ALT_MASK); postEvent(new KeyEvent(event, event.getWhen(), peAction, peModifiers, event.getKeyChar(), event.getKeyCode())); } /** * Overriding keyXxxxx(KeyEvent e) functions will cause the 'key', * 'keyCode', and 'keyEvent' variables to no longer work; * key events will no longer be queued until the end of draw(); * and the keyPressed(), keyReleased() and keyTyped() methods * will no longer be called. * * @nowebref */ public void keyPressed(java.awt.event.KeyEvent e) { nativeKeyEvent(e); } /** * @nowebref */ public void keyReleased(java.awt.event.KeyEvent e) { nativeKeyEvent(e); } /** * @nowebref */ public void keyTyped(java.awt.event.KeyEvent e) { nativeKeyEvent(e); } /** * * ( begin auto-generated from keyPressed.xml ) * * The <b>keyPressed()</b> function is called once every time a key is * pressed. The key that was pressed is stored in the <b>key</b> variable. * <br/> <br/> * For non-ASCII keys, use the <b>keyCode</b> variable. The keys included * in the ASCII specification (BACKSPACE, TAB, ENTER, RETURN, ESC, and * DELETE) do not require checking to see if they key is coded, and you * should simply use the <b>key</b> variable instead of <b>keyCode</b> If * you're making cross-platform projects, note that the ENTER key is * commonly used on PCs and Unix and the RETURN key is used instead on * Macintosh. Check for both ENTER and RETURN to make sure your program * will work for all platforms. * <br/> <br/> * Because of how operating systems handle key repeats, holding down a key * may cause multiple calls to keyPressed() (and keyReleased() as well). * The rate of repeat is set by the operating system and how each computer * is configured. * * ( end auto-generated ) * <h3>Advanced</h3> * * Called each time a single key on the keyboard is pressed. * Because of how operating systems handle key repeats, holding * down a key will cause multiple calls to keyPressed(), because * the OS repeat takes over. * <p> * Examples for key handling: * (Tested on Windows XP, please notify if different on other * platforms, I have a feeling Mac OS and Linux may do otherwise) * <PRE> * 1. Pressing 'a' on the keyboard: * keyPressed with key == 'a' and keyCode == 'A' * keyTyped with key == 'a' and keyCode == 0 * keyReleased with key == 'a' and keyCode == 'A' * * 2. Pressing 'A' on the keyboard: * keyPressed with key == 'A' and keyCode == 'A' * keyTyped with key == 'A' and keyCode == 0 * keyReleased with key == 'A' and keyCode == 'A' * * 3. Pressing 'shift', then 'a' on the keyboard (caps lock is off): * keyPressed with key == CODED and keyCode == SHIFT * keyPressed with key == 'A' and keyCode == 'A' * keyTyped with key == 'A' and keyCode == 0 * keyReleased with key == 'A' and keyCode == 'A' * keyReleased with key == CODED and keyCode == SHIFT * * 4. Holding down the 'a' key. * The following will happen several times, * depending on your machine's "key repeat rate" settings: * keyPressed with key == 'a' and keyCode == 'A' * keyTyped with key == 'a' and keyCode == 0 * When you finally let go, you'll get: * keyReleased with key == 'a' and keyCode == 'A' * * 5. Pressing and releasing the 'shift' key * keyPressed with key == CODED and keyCode == SHIFT * keyReleased with key == CODED and keyCode == SHIFT * (note there is no keyTyped) * * 6. Pressing the tab key in an applet with Java 1.4 will * normally do nothing, but PApplet dynamically shuts * this behavior off if Java 1.4 is in use (tested 1.4.2_05 Windows). * Java 1.1 (Microsoft VM) passes the TAB key through normally. * Not tested on other platforms or for 1.3. * </PRE> * @webref input:keyboard * @see PApplet#key * @see PApplet#keyCode * @see PApplet#keyPressed * @see PApplet#keyReleased() */ public void keyPressed() { } public void keyPressed(KeyEvent event) { keyPressed(); } /** * ( begin auto-generated from keyReleased.xml ) * * The <b>keyReleased()</b> function is called once every time a key is * released. The key that was released will be stored in the <b>key</b> * variable. See <b>key</b> and <b>keyReleased</b> for more information. * * ( end auto-generated ) * @webref input:keyboard * @see PApplet#key * @see PApplet#keyCode * @see PApplet#keyPressed * @see PApplet#keyPressed() */ public void keyReleased() { } public void keyReleased(KeyEvent event) { keyReleased(); } /** * ( begin auto-generated from keyTyped.xml ) * * The <b>keyTyped()</b> function is called once every time a key is * pressed, but action keys such as Ctrl, Shift, and Alt are ignored. * Because of how operating systems handle key repeats, holding down a key * will cause multiple calls to <b>keyTyped()</b>, the rate is set by the * operating system and how each computer is configured. * * ( end auto-generated ) * @webref input:keyboard * @see PApplet#keyPressed * @see PApplet#key * @see PApplet#keyCode * @see PApplet#keyReleased() */ public void keyTyped() { } public void keyTyped(KeyEvent event) { keyTyped(); } ////////////////////////////////////////////////////////////// // i am focused man, and i'm not afraid of death. // and i'm going all out. i circle the vultures in a van // and i run the block. public void focusGained() { } public void focusGained(FocusEvent e) { focused = true; focusGained(); } public void focusLost() { } public void focusLost(FocusEvent e) { focused = false; focusLost(); } ////////////////////////////////////////////////////////////// // getting the time /** * ( begin auto-generated from millis.xml ) * * Returns the number of milliseconds (thousandths of a second) since * starting an applet. This information is often used for timing animation * sequences. * * ( end auto-generated ) * * <h3>Advanced</h3> * <p> * This is a function, rather than a variable, because it may * change multiple times per frame. * * @webref input:time_date * @see PApplet#second() * @see PApplet#minute() * @see PApplet#hour() * @see PApplet#day() * @see PApplet#month() * @see PApplet#year() * */ public int millis() { return (int) (System.currentTimeMillis() - millisOffset); } /** * ( begin auto-generated from second.xml ) * * Processing communicates with the clock on your computer. The * <b>second()</b> function returns the current second as a value from 0 - 59. * * ( end auto-generated ) * @webref input:time_date * @see PApplet#millis() * @see PApplet#minute() * @see PApplet#hour() * @see PApplet#day() * @see PApplet#month() * @see PApplet#year() * */ static public int second() { return Calendar.getInstance().get(Calendar.SECOND); } /** * ( begin auto-generated from minute.xml ) * * Processing communicates with the clock on your computer. The * <b>minute()</b> function returns the current minute as a value from 0 - 59. * * ( end auto-generated ) * * @webref input:time_date * @see PApplet#millis() * @see PApplet#second() * @see PApplet#hour() * @see PApplet#day() * @see PApplet#month() * @see PApplet#year() * * */ static public int minute() { return Calendar.getInstance().get(Calendar.MINUTE); } /** * ( begin auto-generated from hour.xml ) * * Processing communicates with the clock on your computer. The * <b>hour()</b> function returns the current hour as a value from 0 - 23. * * ( end auto-generated ) * @webref input:time_date * @see PApplet#millis() * @see PApplet#second() * @see PApplet#minute() * @see PApplet#day() * @see PApplet#month() * @see PApplet#year() * */ static public int hour() { return Calendar.getInstance().get(Calendar.HOUR_OF_DAY); } /** * ( begin auto-generated from day.xml ) * * Processing communicates with the clock on your computer. The * <b>day()</b> function returns the current day as a value from 1 - 31. * * ( end auto-generated ) * <h3>Advanced</h3> * Get the current day of the month (1 through 31). * <p> * If you're looking for the day of the week (M-F or whatever) * or day of the year (1..365) then use java's Calendar.get() * * @webref input:time_date * @see PApplet#millis() * @see PApplet#second() * @see PApplet#minute() * @see PApplet#hour() * @see PApplet#month() * @see PApplet#year() */ static public int day() { return Calendar.getInstance().get(Calendar.DAY_OF_MONTH); } /** * ( begin auto-generated from month.xml ) * * Processing communicates with the clock on your computer. The * <b>month()</b> function returns the current month as a value from 1 - 12. * * ( end auto-generated ) * * @webref input:time_date * @see PApplet#millis() * @see PApplet#second() * @see PApplet#minute() * @see PApplet#hour() * @see PApplet#day() * @see PApplet#year() */ static public int month() { // months are number 0..11 so change to colloquial 1..12 return Calendar.getInstance().get(Calendar.MONTH) + 1; } /** * ( begin auto-generated from year.xml ) * * Processing communicates with the clock on your computer. The * <b>year()</b> function returns the current year as an integer (2003, * 2004, 2005, etc). * * ( end auto-generated ) * The <b>year()</b> function returns the current year as an integer (2003, 2004, 2005, etc). * * @webref input:time_date * @see PApplet#millis() * @see PApplet#second() * @see PApplet#minute() * @see PApplet#hour() * @see PApplet#day() * @see PApplet#month() */ static public int year() { return Calendar.getInstance().get(Calendar.YEAR); } ////////////////////////////////////////////////////////////// // controlling time (playing god) /** * The delay() function causes the program to halt for a specified time. * Delay times are specified in thousandths of a second. For example, * running delay(3000) will stop the program for three seconds and * delay(500) will stop the program for a half-second. * * The screen only updates when the end of draw() is reached, so delay() * cannot be used to slow down drawing. For instance, you cannot use delay() * to control the timing of an animation. * * The delay() function should only be used for pausing scripts (i.e. * a script that needs to pause a few seconds before attempting a download, * or a sketch that needs to wait a few milliseconds before reading from * the serial port). */ public void delay(int napTime) { //if (frameCount != 0) { //if (napTime > 0) { try { Thread.sleep(napTime); } catch (InterruptedException e) { } //} //} } /** * ( begin auto-generated from frameRate.xml ) * * Specifies the number of frames to be displayed every second. If the * processor is not fast enough to maintain the specified rate, it will not * be achieved. For example, the function call <b>frameRate(30)</b> will * attempt to refresh 30 times a second. It is recommended to set the frame * rate within <b>setup()</b>. The default rate is 60 frames per second. * * ( end auto-generated ) * @webref environment * @param fps number of desired frames per second * @see PApplet#setup() * @see PApplet#draw() * @see PApplet#loop() * @see PApplet#noLoop() * @see PApplet#redraw() */ public void frameRate(float fps) { frameRateTarget = fps; frameRatePeriod = (long) (1000000000.0 / frameRateTarget); g.setFrameRate(fps); } ////////////////////////////////////////////////////////////// /** * Reads the value of a param. Values are always read as a String so if you * want them to be an integer or other datatype they must be converted. The * <b>param()</b> function will only work in a web browser. The function * should be called inside <b>setup()</b>, otherwise the applet may not yet * be initialized and connected to its parent web browser. * * @param name name of the param to read * @deprecated no more applet support */ public String param(String name) { if (online) { return getParameter(name); } else { System.err.println("param() only works inside a web browser"); } return null; } /** * <h3>Advanced</h3> * Show status in the status bar of a web browser, or in the * System.out console. Eventually this might show status in the * p5 environment itself, rather than relying on the console. * * @deprecated no more applet support */ public void status(String value) { if (online) { showStatus(value); } else { System.out.println(value); // something more interesting? } } public void link(String url) { // link(url, null); try { if (Desktop.isDesktopSupported()) { Desktop.getDesktop().browse(new URI(url)); } else { // Just pass it off to open() and hope for the best open(url); } } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } } /** * Links to a webpage either in the same window or in a new window. The * complete URL must be specified. * * <h3>Advanced</h3> * Link to an external page without all the muss. * <p> * When run with an applet, uses the browser to open the url, * for applications, attempts to launch a browser with the url. * <p> * Works on Mac OS X and Windows. For Linux, use: * <PRE>open(new String[] { "firefox", url });</PRE> * or whatever you want as your browser, since Linux doesn't * yet have a standard method for launching URLs. * * @param url the complete URL, as a String in quotes * @param target the name of the window in which to load the URL, as a String in quotes * @deprecated the 'target' parameter is no longer relevant with the removal of applets */ public void link(String url, String target) { link(url); /* try { if (platform == WINDOWS) { // the following uses a shell execute to launch the .html file // note that under cygwin, the .html files have to be chmodded +x // after they're unpacked from the zip file. i don't know why, // and don't understand what this does in terms of windows // permissions. without the chmod, the command prompt says // "Access is denied" in both cygwin and the "dos" prompt. //Runtime.getRuntime().exec("cmd /c " + currentDir + "\\reference\\" + // referenceFile + ".html"); // replace ampersands with control sequence for DOS. // solution contributed by toxi on the bugs board. url = url.replaceAll("&","^&"); // open dos prompt, give it 'start' command, which will // open the url properly. start by itself won't work since // it appears to need cmd Runtime.getRuntime().exec("cmd /c start " + url); } else if (platform == MACOSX) { //com.apple.mrj.MRJFileUtils.openURL(url); try { // Class<?> mrjFileUtils = Class.forName("com.apple.mrj.MRJFileUtils"); // Method openMethod = // mrjFileUtils.getMethod("openURL", new Class[] { String.class }); Class<?> eieio = Class.forName("com.apple.eio.FileManager"); Method openMethod = eieio.getMethod("openURL", new Class[] { String.class }); openMethod.invoke(null, new Object[] { url }); } catch (Exception e) { e.printStackTrace(); } } else { //throw new RuntimeException("Can't open URLs for this platform"); // Just pass it off to open() and hope for the best open(url); } } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("Could not open " + url); } */ } /** * ( begin auto-generated from open.xml ) * * Attempts to open an application or file using your platform's launcher. * The <b>file</b> parameter is a String specifying the file name and * location. The location parameter must be a full path name, or the name * of an executable in the system's PATH. In most cases, using a full path * is the best option, rather than relying on the system PATH. Be sure to * make the file executable before attempting to open it (chmod +x). * <br/> <br/> * The <b>args</b> parameter is a String or String array which is passed to * the command line. If you have multiple parameters, e.g. an application * and a document, or a command with multiple switches, use the version * that takes a String array, and place each individual item in a separate * element. * <br/> <br/> * If args is a String (not an array), then it can only be a single file or * application with no parameters. It's not the same as executing that * String using a shell. For instance, open("jikes -help") will not work properly. * <br/> <br/> * This function behaves differently on each platform. On Windows, the * parameters are sent to the Windows shell via "cmd /c". On Mac OS X, the * "open" command is used (type "man open" in Terminal.app for * documentation). On Linux, it first tries gnome-open, then kde-open, but * if neither are available, it sends the command to the shell without any * alterations. * <br/> <br/> * For users familiar with Java, this is not quite the same as * Runtime.exec(), because the launcher command is prepended. Instead, the * <b>exec(String[])</b> function is a shortcut for * Runtime.getRuntime.exec(String[]). * * ( end auto-generated ) * @webref input:files * @param filename name of the file * @usage Application */ static public void open(String filename) { open(new String[] { filename }); } static String openLauncher; /** * Launch a process using a platforms shell. This version uses an array * to make it easier to deal with spaces in the individual elements. * (This avoids the situation of trying to put single or double quotes * around different bits). * * @param argv list of commands passed to the command line */ static public Process open(String argv[]) { String[] params = null; if (platform == WINDOWS) { // just launching the .html file via the shell works // but make sure to chmod +x the .html files first // also place quotes around it in case there's a space // in the user.dir part of the url params = new String[] { "cmd", "/c" }; } else if (platform == MACOSX) { params = new String[] { "open" }; } else if (platform == LINUX) { if (openLauncher == null) { // Attempt to use gnome-open try { Process p = Runtime.getRuntime().exec(new String[] { "gnome-open" }); /*int result =*/ p.waitFor(); // Not installed will throw an IOException (JDK 1.4.2, Ubuntu 7.04) openLauncher = "gnome-open"; } catch (Exception e) { } } if (openLauncher == null) { // Attempt with kde-open try { Process p = Runtime.getRuntime().exec(new String[] { "kde-open" }); /*int result =*/ p.waitFor(); openLauncher = "kde-open"; } catch (Exception e) { } } if (openLauncher == null) { System.err.println("Could not find gnome-open or kde-open, " + "the open() command may not work."); } if (openLauncher != null) { params = new String[] { openLauncher }; } //} else { // give up and just pass it to Runtime.exec() //open(new String[] { filename }); //params = new String[] { filename }; } if (params != null) { // If the 'open', 'gnome-open' or 'cmd' are already included if (params[0].equals(argv[0])) { // then don't prepend those params again return exec(argv); } else { params = concat(params, argv); return exec(params); } } else { return exec(argv); } } static public Process exec(String[] argv) { try { return Runtime.getRuntime().exec(argv); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Could not open " + join(argv, ' ')); } } ////////////////////////////////////////////////////////////// /** * Function for an applet/application to kill itself and * display an error. Mostly this is here to be improved later. */ public void die(String what) { dispose(); throw new RuntimeException(what); } /** * Same as above but with an exception. Also needs work. */ public void die(String what, Exception e) { if (e != null) e.printStackTrace(); die(what); } /** * ( begin auto-generated from exit.xml ) * * Quits/stops/exits the program. Programs without a <b>draw()</b> function * exit automatically after the last line has run, but programs with * <b>draw()</b> run continuously until the program is manually stopped or * <b>exit()</b> is run.<br /> * <br /> * Rather than terminating immediately, <b>exit()</b> will cause the sketch * to exit after <b>draw()</b> has completed (or after <b>setup()</b> * completes if called during the <b>setup()</b> function).<br /> * <br /> * For Java programmers, this is <em>not</em> the same as System.exit(). * Further, System.exit() should not be used because closing out an * application while <b>draw()</b> is running may cause a crash * (particularly with P3D). * * ( end auto-generated ) * @webref structure */ public void exit() { if (thread == null) { // exit immediately, dispose() has already been called, // meaning that the main thread has long since exited exitActual(); } else if (looping) { // dispose() will be called as the thread exits finished = true; // tell the code to call exit2() to do a System.exit() // once the next draw() has completed exitCalled = true; } else if (!looping) { // if not looping, shut down things explicitly, // because the main thread will be sleeping dispose(); // now get out exitActual(); } } void exitActual() { try { System.exit(0); } catch (SecurityException e) { // don't care about applet security exceptions } } /** * Called to dispose of resources and shut down the sketch. * Destroys the thread, dispose the renderer,and notify listeners. * <p> * Not to be called or overriden by users. If called multiple times, * will only notify listeners once. Register a dispose listener instead. */ public void dispose() { // moved here from stop() finished = true; // let the sketch know it is shut down time // don't run the disposers twice if (thread != null) { thread = null; // shut down renderer if (g != null) { g.dispose(); } // run dispose() methods registered by libraries handleMethods("dispose"); } } ////////////////////////////////////////////////////////////// /** * Call a method in the current class based on its name. * <p/> * Note that the function being called must be public. Inside the PDE, * 'public' is automatically added, but when used without the preprocessor, * (like from Eclipse) you'll have to do it yourself. */ public void method(String name) { try { Method method = getClass().getMethod(name, new Class[] {}); method.invoke(this, new Object[] { }); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.getTargetException().printStackTrace(); } catch (NoSuchMethodException nsme) { System.err.println("There is no public " + name + "() method " + "in the class " + getClass().getName()); } catch (Exception e) { e.printStackTrace(); } } /** * Launch a new thread and call the specified function from that new thread. * This is a very simple way to do a thread without needing to get into * classes, runnables, etc. * <p/> * Note that the function being called must be public. Inside the PDE, * 'public' is automatically added, but when used without the preprocessor, * (like from Eclipse) you'll have to do it yourself. */ public void thread(final String name) { Thread later = new Thread() { @Override public void run() { method(name); } }; later.start(); } ////////////////////////////////////////////////////////////// // SCREEN GRABASS /** * ( begin auto-generated from save.xml ) * * Saves an image from the display window. Images are saved in TIFF, TARGA, * JPEG, and PNG format depending on the extension within the * <b>filename</b> parameter. For example, "image.tif" will have a TIFF * image and "image.png" will save a PNG image. If no extension is included * in the filename, the image will save in TIFF format and <b>.tif</b> will * be added to the name. These files are saved to the sketch's folder, * which may be opened by selecting "Show sketch folder" from the "Sketch" * menu. It is not possible to use <b>save()</b> while running the program * in a web browser. * <br/> images saved from the main drawing window will be opaque. To save * images without a background, use <b>createGraphics()</b>. * * ( end auto-generated ) * @webref output:image * @param filename any sequence of letters and numbers * @see PApplet#saveFrame() * @see PApplet#createGraphics(int, int, String) */ public void save(String filename) { g.save(savePath(filename)); } /** */ public void saveFrame() { try { g.save(savePath("screen-" + nf(frameCount, 4) + ".tif")); } catch (SecurityException se) { System.err.println("Can't use saveFrame() when running in a browser, " + "unless using a signed applet."); } } /** * ( begin auto-generated from saveFrame.xml ) * * Saves a numbered sequence of images, one image each time the function is * run. To save an image that is identical to the display window, run the * function at the end of <b>draw()</b> or within mouse and key events such * as <b>mousePressed()</b> and <b>keyPressed()</b>. If <b>saveFrame()</b> * is called without parameters, it will save the files as screen-0000.tif, * screen-0001.tif, etc. It is possible to specify the name of the sequence * with the <b>filename</b> parameter and make the choice of saving TIFF, * TARGA, PNG, or JPEG files with the <b>ext</b> parameter. These image * sequences can be loaded into programs such as Apple's QuickTime software * and made into movies. These files are saved to the sketch's folder, * which may be opened by selecting "Show sketch folder" from the "Sketch" * menu.<br /> * <br /> * It is not possible to use saveXxxxx() functions inside a web browser * unless the sketch is <a * href="http://wiki.processing.org/w/Sign_an_Applet">signed applet</A>. To * save a file back to a server, see the <a * href="http://wiki.processing.org/w/Saving_files_to_a_web-server">save to * web</A> code snippet on the Processing Wiki.<br/> * <br/ > * All images saved from the main drawing window will be opaque. To save * images without a background, use <b>createGraphics()</b>. * * ( end auto-generated ) * @webref output:image * @see PApplet#save(String) * @see PApplet#createGraphics(int, int, String, String) * @param filename any sequence of letters or numbers that ends with either ".tif", ".tga", ".jpg", or ".png" */ public void saveFrame(String filename) { try { g.save(savePath(insertFrame(filename))); } catch (SecurityException se) { System.err.println("Can't use saveFrame() when running in a browser, " + "unless using a signed applet."); } } /** * Check a string for #### signs to see if the frame number should be * inserted. Used for functions like saveFrame() and beginRecord() to * replace the # marks with the frame number. If only one # is used, * it will be ignored, under the assumption that it's probably not * intended to be the frame number. */ public String insertFrame(String what) { int first = what.indexOf('#'); int last = what.lastIndexOf('#'); if ((first != -1) && (last - first > 0)) { String prefix = what.substring(0, first); int count = last - first + 1; String suffix = what.substring(last + 1); return prefix + nf(frameCount, count) + suffix; } return what; // no change } ////////////////////////////////////////////////////////////// // CURSOR // int cursorType = ARROW; // cursor type boolean cursorVisible = true; // cursor visibility flag // PImage invisibleCursor; Cursor invisibleCursor; /** * Set the cursor type * @param kind either ARROW, CROSS, HAND, MOVE, TEXT, or WAIT */ public void cursor(int kind) { setCursor(Cursor.getPredefinedCursor(kind)); cursorVisible = true; this.cursorType = kind; } /** * Replace the cursor with the specified PImage. The x- and y- * coordinate of the center will be the center of the image. */ public void cursor(PImage img) { cursor(img, img.width/2, img.height/2); } /** * ( begin auto-generated from cursor.xml ) * * Sets the cursor to a predefined symbol, an image, or makes it visible if * already hidden. If you are trying to set an image as the cursor, it is * recommended to make the size 16x16 or 32x32 pixels. It is not possible * to load an image as the cursor if you are exporting your program for the * Web and not all MODES work with all Web browsers. The values for * parameters <b>x</b> and <b>y</b> must be less than the dimensions of the image. * <br /> <br /> * Setting or hiding the cursor generally does not work with "Present" mode * (when running full-screen). * * ( end auto-generated ) * <h3>Advanced</h3> * Set a custom cursor to an image with a specific hotspot. * Only works with JDK 1.2 and later. * Currently seems to be broken on Java 1.4 for Mac OS X * <p> * Based on code contributed by Amit Pitaru, plus additional * code to handle Java versions via reflection by Jonathan Feinberg. * Reflection removed for release 0128 and later. * @webref environment * @see PApplet#noCursor() * @param img any variable of type PImage * @param x the horizontal active spot of the cursor * @param y the vertical active spot of the cursor */ public void cursor(PImage img, int x, int y) { // don't set this as cursor type, instead use cursor_type // to save the last cursor used in case cursor() is called //cursor_type = Cursor.CUSTOM_CURSOR; Image jimage = createImage(new MemoryImageSource(img.width, img.height, img.pixels, 0, img.width)); Point hotspot = new Point(x, y); Toolkit tk = Toolkit.getDefaultToolkit(); Cursor cursor = tk.createCustomCursor(jimage, hotspot, "Custom Cursor"); setCursor(cursor); cursorVisible = true; } /** * Show the cursor after noCursor() was called. * Notice that the program remembers the last set cursor type */ public void cursor() { // maybe should always set here? seems dangerous, since // it's likely that java will set the cursor to something // else on its own, and the applet will be stuck b/c bagel // thinks that the cursor is set to one particular thing if (!cursorVisible) { cursorVisible = true; setCursor(Cursor.getPredefinedCursor(cursorType)); } } /** * ( begin auto-generated from noCursor.xml ) * * Hides the cursor from view. Will not work when running the program in a * web browser or when running in full screen (Present) mode. * * ( end auto-generated ) * <h3>Advanced</h3> * Hide the cursor by creating a transparent image * and using it as a custom cursor. * @webref environment * @see PApplet#cursor() * @usage Application */ public void noCursor() { // in 0216, just re-hide it? // if (!cursorVisible) return; // don't hide if already hidden. if (invisibleCursor == null) { BufferedImage cursorImg = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB); invisibleCursor = getToolkit().createCustomCursor(cursorImg, new Point(8, 8), "blank"); } // was formerly 16x16, but the 0x0 was added by jdf as a fix // for macosx, which wasn't honoring the invisible cursor // cursor(invisibleCursor, 8, 8); setCursor(invisibleCursor); cursorVisible = false; } ////////////////////////////////////////////////////////////// /** * ( begin auto-generated from print.xml ) * * Writes to the console area of the Processing environment. This is often * helpful for looking at the data a program is producing. The companion * function <b>println()</b> works like <b>print()</b>, but creates a new * line of text for each call to the function. Individual elements can be * separated with quotes ("") and joined with the addition operator (+).<br /> * <br /> * Beginning with release 0125, to print the contents of an array, use * println(). There's no sensible way to do a <b>print()</b> of an array, * because there are too many possibilities for how to separate the data * (spaces, commas, etc). If you want to print an array as a single line, * use <b>join()</b>. With <b>join()</b>, you can choose any delimiter you * like and <b>print()</b> the result.<br /> * <br /> * Using <b>print()</b> on an object will output <b>null</b>, a memory * location that may look like "@10be08," or the result of the * <b>toString()</b> method from the object that's being printed. Advanced * users who want more useful output when calling <b>print()</b> on their * own classes can add a <b>toString()</b> method to the class that returns * a String. * * ( end auto-generated ) * @webref output:text_area * @usage IDE * @param what boolean, byte, char, color, int, float, String, Object * @see PApplet#println(byte) * @see PApplet#join(String[], char) */ static public void print(byte what) { System.out.print(what); System.out.flush(); } static public void print(boolean what) { System.out.print(what); System.out.flush(); } static public void print(char what) { System.out.print(what); System.out.flush(); } static public void print(int what) { System.out.print(what); System.out.flush(); } static public void print(long what) { System.out.print(what); System.out.flush(); } static public void print(float what) { System.out.print(what); System.out.flush(); } static public void print(double what) { System.out.print(what); System.out.flush(); } static public void print(String what) { System.out.print(what); System.out.flush(); } static public void print(Object what) { if (what == null) { // special case since this does fuggly things on > 1.1 System.out.print("null"); } else { System.out.println(what.toString()); } } // /** * ( begin auto-generated from println.xml ) * * Writes to the text area of the Processing environment's console. This is * often helpful for looking at the data a program is producing. Each call * to this function creates a new line of output. Individual elements can * be separated with quotes ("") and joined with the string concatenation * operator (+). See <b>print()</b> for more about what to expect in the output. * <br/><br/> <b>println()</b> on an array (by itself) will write the * contents of the array to the console. This is often helpful for looking * at the data a program is producing. A new line is put between each * element of the array. This function can only print one dimensional * arrays. For arrays with higher dimensions, the result will be closer to * that of <b>print()</b>. * * ( end auto-generated ) * @webref output:text_area * @usage IDE * @see PApplet#print(byte) */ static public void println() { System.out.println(); } // /** * @param what boolean, byte, char, color, int, float, String, Object */ static public void println(byte what) { System.out.println(what); System.out.flush(); } static public void println(boolean what) { System.out.println(what); System.out.flush(); } static public void println(char what) { System.out.println(what); System.out.flush(); } static public void println(int what) { System.out.println(what); System.out.flush(); } static public void println(long what) { System.out.println(what); System.out.flush(); } static public void println(float what) { System.out.println(what); System.out.flush(); } static public void println(double what) { System.out.println(what); System.out.flush(); } static public void println(String what) { System.out.println(what); System.out.flush(); } static public void println(Object what) { if (what == null) { // special case since this does fuggly things on > 1.1 System.out.println("null"); } else { String name = what.getClass().getName(); if (name.charAt(0) == '[') { switch (name.charAt(1)) { case '[': // don't even mess with multi-dimensional arrays (case '[') // or anything else that's not int, float, boolean, char System.out.println(what); break; case 'L': // print a 1D array of objects as individual elements Object poo[] = (Object[]) what; for (int i = 0; i < poo.length; i++) { if (poo[i] instanceof String) { System.out.println("[" + i + "] \"" + poo[i] + "\""); } else { System.out.println("[" + i + "] " + poo[i]); } } break; case 'Z': // boolean boolean zz[] = (boolean[]) what; for (int i = 0; i < zz.length; i++) { System.out.println("[" + i + "] " + zz[i]); } break; case 'B': // byte byte bb[] = (byte[]) what; for (int i = 0; i < bb.length; i++) { System.out.println("[" + i + "] " + bb[i]); } break; case 'C': // char char cc[] = (char[]) what; for (int i = 0; i < cc.length; i++) { System.out.println("[" + i + "] '" + cc[i] + "'"); } break; case 'I': // int int ii[] = (int[]) what; for (int i = 0; i < ii.length; i++) { System.out.println("[" + i + "] " + ii[i]); } break; case 'J': // int long jj[] = (long[]) what; for (int i = 0; i < jj.length; i++) { System.out.println("[" + i + "] " + jj[i]); } break; case 'F': // float float ff[] = (float[]) what; for (int i = 0; i < ff.length; i++) { System.out.println("[" + i + "] " + ff[i]); } break; case 'D': // double double dd[] = (double[]) what; for (int i = 0; i < dd.length; i++) { System.out.println("[" + i + "] " + dd[i]); } break; default: System.out.println(what); } } else { // not an array System.out.println(what); } } } static public void debug(String msg) { if (DEBUG) println(msg); } // /* // not very useful, because it only works for public (and protected?) // fields of a class, not local variables to methods public void printvar(String name) { try { Field field = getClass().getDeclaredField(name); println(name + " = " + field.get(this)); } catch (Exception e) { e.printStackTrace(); } } */ ////////////////////////////////////////////////////////////// // MATH // lots of convenience methods for math with floats. // doubles are overkill for processing applets, and casting // things all the time is annoying, thus the functions below. /** * ( begin auto-generated from abs.xml ) * * Calculates the absolute value (magnitude) of a number. The absolute * value of a number is always positive. * * ( end auto-generated ) * @webref math:calculation * @param n number to compute */ static public final float abs(float n) { return (n < 0) ? -n : n; } static public final int abs(int n) { return (n < 0) ? -n : n; } /** * ( begin auto-generated from sq.xml ) * * Squares a number (multiplies a number by itself). The result is always a * positive number, as multiplying two negative numbers always yields a * positive result. For example, -1 * -1 = 1. * * ( end auto-generated ) * @webref math:calculation * @param n number to square * @see PApplet#sqrt(float) */ static public final float sq(float n) { return n*n; } /** * ( begin auto-generated from sqrt.xml ) * * Calculates the square root of a number. The square root of a number is * always positive, even though there may be a valid negative root. The * square root <b>s</b> of number <b>a</b> is such that <b>s*s = a</b>. It * is the opposite of squaring. * * ( end auto-generated ) * @webref math:calculation * @param n non-negative number * @see PApplet#pow(float, float) * @see PApplet#sq(float) */ static public final float sqrt(float n) { return (float)Math.sqrt(n); } /** * ( begin auto-generated from log.xml ) * * Calculates the natural logarithm (the base-<i>e</i> logarithm) of a * number. This function expects the values greater than 0.0. * * ( end auto-generated ) * @webref math:calculation * @param n number greater than 0.0 */ static public final float log(float n) { return (float)Math.log(n); } /** * ( begin auto-generated from exp.xml ) * * Returns Euler's number <i>e</i> (2.71828...) raised to the power of the * <b>value</b> parameter. * * ( end auto-generated ) * @webref math:calculation * @param n exponent to raise */ static public final float exp(float n) { return (float)Math.exp(n); } /** * ( begin auto-generated from pow.xml ) * * Facilitates exponential expressions. The <b>pow()</b> function is an * efficient way of multiplying numbers by themselves (or their reciprocal) * in large quantities. For example, <b>pow(3, 5)</b> is equivalent to the * expression 3*3*3*3*3 and <b>pow(3, -5)</b> is equivalent to 1 / 3*3*3*3*3. * * ( end auto-generated ) * @webref math:calculation * @param n base of the exponential expression * @param e power by which to raise the base * @see PApplet#sqrt(float) */ static public final float pow(float n, float e) { return (float)Math.pow(n, e); } /** * ( begin auto-generated from max.xml ) * * Determines the largest value in a sequence of numbers. * * ( end auto-generated ) * @webref math:calculation * @param a first number to compare * @param b second number to compare * @see PApplet#min(float, float, float) */ static public final int max(int a, int b) { return (a > b) ? a : b; } static public final float max(float a, float b) { return (a > b) ? a : b; } /* static public final double max(double a, double b) { return (a > b) ? a : b; } */ /** * @param c third number to compare */ static public final int max(int a, int b, int c) { return (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c); } static public final float max(float a, float b, float c) { return (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c); } /** * @param list array of numbers to compare */ static public final int max(int[] list) { if (list.length == 0) { throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX); } int max = list[0]; for (int i = 1; i < list.length; i++) { if (list[i] > max) max = list[i]; } return max; } static public final float max(float[] list) { if (list.length == 0) { throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX); } float max = list[0]; for (int i = 1; i < list.length; i++) { if (list[i] > max) max = list[i]; } return max; } /** * Find the maximum value in an array. * Throws an ArrayIndexOutOfBoundsException if the array is length 0. * @param list the source array * @return The maximum value */ /* static public final double max(double[] list) { if (list.length == 0) { throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX); } double max = list[0]; for (int i = 1; i < list.length; i++) { if (list[i] > max) max = list[i]; } return max; } */ static public final int min(int a, int b) { return (a < b) ? a : b; } static public final float min(float a, float b) { return (a < b) ? a : b; } /* static public final double min(double a, double b) { return (a < b) ? a : b; } */ static public final int min(int a, int b, int c) { return (a < b) ? ((a < c) ? a : c) : ((b < c) ? b : c); } /** * ( begin auto-generated from min.xml ) * * Determines the smallest value in a sequence of numbers. * * ( end auto-generated ) * @webref math:calculation * @param a first number * @param b second number * @param c third number * @see PApplet#max(float, float, float) */ static public final float min(float a, float b, float c) { return (a < b) ? ((a < c) ? a : c) : ((b < c) ? b : c); } /* static public final double min(double a, double b, double c) { return (a < b) ? ((a < c) ? a : c) : ((b < c) ? b : c); } */ /** * @param list array of numbers to compare */ static public final int min(int[] list) { if (list.length == 0) { throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX); } int min = list[0]; for (int i = 1; i < list.length; i++) { if (list[i] < min) min = list[i]; } return min; } static public final float min(float[] list) { if (list.length == 0) { throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX); } float min = list[0]; for (int i = 1; i < list.length; i++) { if (list[i] < min) min = list[i]; } return min; } /** * Find the minimum value in an array. * Throws an ArrayIndexOutOfBoundsException if the array is length 0. * @param list the source array * @return The minimum value */ /* static public final double min(double[] list) { if (list.length == 0) { throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX); } double min = list[0]; for (int i = 1; i < list.length; i++) { if (list[i] < min) min = list[i]; } return min; } */ static public final int constrain(int amt, int low, int high) { return (amt < low) ? low : ((amt > high) ? high : amt); } /** * ( begin auto-generated from constrain.xml ) * * Constrains a value to not exceed a maximum and minimum value. * * ( end auto-generated ) * @webref math:calculation * @param amt the value to constrain * @param low minimum limit * @param high maximum limit * @see PApplet#max(float, float, float) * @see PApplet#min(float, float, float) */ static public final float constrain(float amt, float low, float high) { return (amt < low) ? low : ((amt > high) ? high : amt); } /** * ( begin auto-generated from sin.xml ) * * Calculates the sine of an angle. This function expects the values of the * <b>angle</b> parameter to be provided in radians (values from 0 to * 6.28). Values are returned in the range -1 to 1. * * ( end auto-generated ) * @webref math:trigonometry * @param angle an angle in radians * @see PApplet#cos(float) * @see PApplet#tan(float) * @see PApplet#radians(float) */ static public final float sin(float angle) { return (float)Math.sin(angle); } /** * ( begin auto-generated from cos.xml ) * * Calculates the cosine of an angle. This function expects the values of * the <b>angle</b> parameter to be provided in radians (values from 0 to * PI*2). Values are returned in the range -1 to 1. * * ( end auto-generated ) * @webref math:trigonometry * @param angle an angle in radians * @see PApplet#sin(float) * @see PApplet#tan(float) * @see PApplet#radians(float) */ static public final float cos(float angle) { return (float)Math.cos(angle); } /** * ( begin auto-generated from tan.xml ) * * Calculates the ratio of the sine and cosine of an angle. This function * expects the values of the <b>angle</b> parameter to be provided in * radians (values from 0 to PI*2). Values are returned in the range * <b>infinity</b> to <b>-infinity</b>. * * ( end auto-generated ) * @webref math:trigonometry * @param angle an angle in radians * @see PApplet#cos(float) * @see PApplet#sin(float) * @see PApplet#radians(float) */ static public final float tan(float angle) { return (float)Math.tan(angle); } /** * ( begin auto-generated from asin.xml ) * * The inverse of <b>sin()</b>, returns the arc sine of a value. This * function expects the values in the range of -1 to 1 and values are * returned in the range <b>-PI/2</b> to <b>PI/2</b>. * * ( end auto-generated ) * @webref math:trigonometry * @param value the value whose arc sine is to be returned * @see PApplet#sin(float) * @see PApplet#acos(float) * @see PApplet#atan(float) */ static public final float asin(float value) { return (float)Math.asin(value); } /** * ( begin auto-generated from acos.xml ) * * The inverse of <b>cos()</b>, returns the arc cosine of a value. This * function expects the values in the range of -1 to 1 and values are * returned in the range <b>0</b> to <b>PI (3.1415927)</b>. * * ( end auto-generated ) * @webref math:trigonometry * @param value the value whose arc cosine is to be returned * @see PApplet#cos(float) * @see PApplet#asin(float) * @see PApplet#atan(float) */ static public final float acos(float value) { return (float)Math.acos(value); } /** * ( begin auto-generated from atan.xml ) * * The inverse of <b>tan()</b>, returns the arc tangent of a value. This * function expects the values in the range of -Infinity to Infinity * (exclusive) and values are returned in the range <b>-PI/2</b> to <b>PI/2 </b>. * * ( end auto-generated ) * @webref math:trigonometry * @param value -Infinity to Infinity (exclusive) * @see PApplet#tan(float) * @see PApplet#asin(float) * @see PApplet#acos(float) */ static public final float atan(float value) { return (float)Math.atan(value); } /** * ( begin auto-generated from atan2.xml ) * * Calculates the angle (in radians) from a specified point to the * coordinate origin as measured from the positive x-axis. Values are * returned as a <b>float</b> in the range from <b>PI</b> to <b>-PI</b>. * The <b>atan2()</b> function is most often used for orienting geometry to * the position of the cursor. Note: The y-coordinate of the point is the * first parameter and the x-coordinate is the second due the the structure * of calculating the tangent. * * ( end auto-generated ) * @webref math:trigonometry * @param y y-coordinate of the point * @param x x-coordinate of the point * @see PApplet#tan(float) */ static public final float atan2(float y, float x) { return (float)Math.atan2(y, x); } /** * ( begin auto-generated from degrees.xml ) * * Converts a radian measurement to its corresponding value in degrees. * Radians and degrees are two ways of measuring the same thing. There are * 360 degrees in a circle and 2*PI radians in a circle. For example, * 90&deg; = PI/2 = 1.5707964. All trigonometric functions in Processing * require their parameters to be specified in radians. * * ( end auto-generated ) * @webref math:trigonometry * @param radians radian value to convert to degrees * @see PApplet#radians(float) */ static public final float degrees(float radians) { return radians * RAD_TO_DEG; } /** * ( begin auto-generated from radians.xml ) * * Converts a degree measurement to its corresponding value in radians. * Radians and degrees are two ways of measuring the same thing. There are * 360 degrees in a circle and 2*PI radians in a circle. For example, * 90&deg; = PI/2 = 1.5707964. All trigonometric functions in Processing * require their parameters to be specified in radians. * * ( end auto-generated ) * @webref math:trigonometry * @param degrees degree value to convert to radians * @see PApplet#degrees(float) */ static public final float radians(float degrees) { return degrees * DEG_TO_RAD; } /** * ( begin auto-generated from ceil.xml ) * * Calculates the closest int value that is greater than or equal to the * value of the parameter. For example, <b>ceil(9.03)</b> returns the value 10. * * ( end auto-generated ) * @webref math:calculation * @param n number to round up * @see PApplet#floor(float) * @see PApplet#round(float) */ static public final int ceil(float n) { return (int) Math.ceil(n); } /** * ( begin auto-generated from floor.xml ) * * Calculates the closest int value that is less than or equal to the value * of the parameter. * * ( end auto-generated ) * @webref math:calculation * @param n number to round down * @see PApplet#ceil(float) * @see PApplet#round(float) */ static public final int floor(float n) { return (int) Math.floor(n); } /** * ( begin auto-generated from round.xml ) * * Calculates the integer closest to the <b>value</b> parameter. For * example, <b>round(9.2)</b> returns the value 9. * * ( end auto-generated ) * @webref math:calculation * @param n number to round * @see PApplet#floor(float) * @see PApplet#ceil(float) */ static public final int round(float n) { return Math.round(n); } static public final float mag(float a, float b) { return (float)Math.sqrt(a*a + b*b); } /** * ( begin auto-generated from mag.xml ) * * Calculates the magnitude (or length) of a vector. A vector is a * direction in space commonly used in computer graphics and linear * algebra. Because it has no "start" position, the magnitude of a vector * can be thought of as the distance from coordinate (0,0) to its (x,y) * value. Therefore, mag() is a shortcut for writing "dist(0, 0, x, y)". * * ( end auto-generated ) * @webref math:calculation * @param a first value * @param b second value * @param c third value * @see PApplet#dist(float, float, float, float) */ static public final float mag(float a, float b, float c) { return (float)Math.sqrt(a*a + b*b + c*c); } static public final float dist(float x1, float y1, float x2, float y2) { return sqrt(sq(x2-x1) + sq(y2-y1)); } /** * ( begin auto-generated from dist.xml ) * * Calculates the distance between two points. * * ( end auto-generated ) * @webref math:calculation * @param x1 x-coordinate of the first point * @param y1 y-coordinate of the first point * @param z1 z-coordinate of the first point * @param x2 x-coordinate of the second point * @param y2 y-coordinate of the second point * @param z2 z-coordinate of the second point */ static public final float dist(float x1, float y1, float z1, float x2, float y2, float z2) { return sqrt(sq(x2-x1) + sq(y2-y1) + sq(z2-z1)); } /** * ( begin auto-generated from lerp.xml ) * * Calculates a number between two numbers at a specific increment. The * <b>amt</b> parameter is the amount to interpolate between the two values * where 0.0 equal to the first point, 0.1 is very near the first point, * 0.5 is half-way in between, etc. The lerp function is convenient for * creating motion along a straight path and for drawing dotted lines. * * ( end auto-generated ) * @webref math:calculation * @param start first value * @param stop second value * @param amt float between 0.0 and 1.0 * @see PGraphics#curvePoint(float, float, float, float, float) * @see PGraphics#bezierPoint(float, float, float, float, float) */ static public final float lerp(float start, float stop, float amt) { return start + (stop-start) * amt; } /** * ( begin auto-generated from norm.xml ) * * Normalizes a number from another range into a value between 0 and 1. * <br/> <br/> * Identical to map(value, low, high, 0, 1); * <br/> <br/> * Numbers outside the range are not clamped to 0 and 1, because * out-of-range values are often intentional and useful. * * ( end auto-generated ) * @webref math:calculation * @param value the incoming value to be converted * @param start lower bound of the value's current range * @param stop upper bound of the value's current range * @see PApplet#map(float, float, float, float, float) * @see PApplet#lerp(float, float, float) */ static public final float norm(float value, float start, float stop) { return (value - start) / (stop - start); } /** * ( begin auto-generated from map.xml ) * * Re-maps a number from one range to another. In the example above, * the number '25' is converted from a value in the range 0..100 into * a value that ranges from the left edge (0) to the right edge (width) * of the screen. * <br/> <br/> * Numbers outside the range are not clamped to 0 and 1, because * out-of-range values are often intentional and useful. * * ( end auto-generated ) * @webref math:calculation * @param value the incoming value to be converted * @param start1 lower bound of the value's current range * @param stop1 upper bound of the value's current range * @param start2 lower bound of the value's target range * @param stop2 upper bound of the value's target range * @see PApplet#norm(float, float, float) * @see PApplet#lerp(float, float, float) */ static public final float map(float value, float start1, float stop1, float start2, float stop2) { return start2 + (stop2 - start2) * ((value - start1) / (stop1 - start1)); } /* static public final double map(double value, double istart, double istop, double ostart, double ostop) { return ostart + (ostop - ostart) * ((value - istart) / (istop - istart)); } */ ////////////////////////////////////////////////////////////// // RANDOM NUMBERS Random internalRandom; /** * */ public final float random(float high) { // avoid an infinite loop when 0 or NaN are passed in if (high == 0 || high != high) { return 0; } if (internalRandom == null) { internalRandom = new Random(); } // for some reason (rounding error?) Math.random() * 3 // can sometimes return '3' (once in ~30 million tries) // so a check was added to avoid the inclusion of 'howbig' float value = 0; do { value = internalRandom.nextFloat() * high; } while (value == high); return value; } /** * ( begin auto-generated from randomGaussian.xml ) * * Returns a float from a random series of numbers having a mean of 0 * and standard deviation of 1. Each time the <b>randomGaussian()</b> * function is called, it returns a number fitting a Gaussian, or * normal, distribution. There is theoretically no minimum or maximum * value that <b>randomGaussian()</b> might return. Rather, there is * just a very low probability that values far from the mean will be * returned; and a higher probability that numbers near the mean will * be returned. * * ( end auto-generated ) * @webref math:random * @see PApplet#random(float,float) * @see PApplet#noise(float, float, float) */ public final float randomGaussian() { if (internalRandom == null) { internalRandom = new Random(); } return (float) internalRandom.nextGaussian(); } /** * ( begin auto-generated from random.xml ) * * Generates random numbers. Each time the <b>random()</b> function is * called, it returns an unexpected value within the specified range. If * one parameter is passed to the function it will return a <b>float</b> * between zero and the value of the <b>high</b> parameter. The function * call <b>random(5)</b> returns values between 0 and 5 (starting at zero, * up to but not including 5). If two parameters are passed, it will return * a <b>float</b> with a value between the the parameters. The function * call <b>random(-5, 10.2)</b> returns values starting at -5 up to (but * not including) 10.2. To convert a floating-point random number to an * integer, use the <b>int()</b> function. * * ( end auto-generated ) * @webref math:random * @param low lower limit * @param high upper limit * @see PApplet#randomSeed(long) * @see PApplet#noise(float, float, float) */ public final float random(float low, float high) { if (low >= high) return low; float diff = high - low; return random(diff) + low; } /** * ( begin auto-generated from randomSeed.xml ) * * Sets the seed value for <b>random()</b>. By default, <b>random()</b> * produces different results each time the program is run. Set the * <b>value</b> parameter to a constant to return the same pseudo-random * numbers each time the software is run. * * ( end auto-generated ) * @webref math:random * @param seed seed value * @see PApplet#random(float,float) * @see PApplet#noise(float, float, float) * @see PApplet#noiseSeed(long) */ public final void randomSeed(long seed) { if (internalRandom == null) { internalRandom = new Random(); } internalRandom.setSeed(seed); } ////////////////////////////////////////////////////////////// // PERLIN NOISE // [toxi 040903] // octaves and amplitude amount per octave are now user controlled // via the noiseDetail() function. // [toxi 030902] // cleaned up code and now using bagel's cosine table to speed up // [toxi 030901] // implementation by the german demo group farbrausch // as used in their demo "art": http://www.farb-rausch.de/fr010src.zip static final int PERLIN_YWRAPB = 4; static final int PERLIN_YWRAP = 1<<PERLIN_YWRAPB; static final int PERLIN_ZWRAPB = 8; static final int PERLIN_ZWRAP = 1<<PERLIN_ZWRAPB; static final int PERLIN_SIZE = 4095; int perlin_octaves = 4; // default to medium smooth float perlin_amp_falloff = 0.5f; // 50% reduction/octave // [toxi 031112] // new vars needed due to recent change of cos table in PGraphics int perlin_TWOPI, perlin_PI; float[] perlin_cosTable; float[] perlin; Random perlinRandom; /** */ public float noise(float x) { // is this legit? it's a dumb way to do it (but repair it later) return noise(x, 0f, 0f); } /** */ public float noise(float x, float y) { return noise(x, y, 0f); } /** * ( begin auto-generated from noise.xml ) * * Returns the Perlin noise value at specified coordinates. Perlin noise is * a random sequence generator producing a more natural ordered, harmonic * succession of numbers compared to the standard <b>random()</b> function. * It was invented by Ken Perlin in the 1980s and been used since in * graphical applications to produce procedural textures, natural motion, * shapes, terrains etc.<br /><br /> The main difference to the * <b>random()</b> function is that Perlin noise is defined in an infinite * n-dimensional space where each pair of coordinates corresponds to a * fixed semi-random value (fixed only for the lifespan of the program). * The resulting value will always be between 0.0 and 1.0. Processing can * compute 1D, 2D and 3D noise, depending on the number of coordinates * given. The noise value can be animated by moving through the noise space * as demonstrated in the example above. The 2nd and 3rd dimension can also * be interpreted as time.<br /><br />The actual noise is structured * similar to an audio signal, in respect to the function's use of * frequencies. Similar to the concept of harmonics in physics, perlin * noise is computed over several octaves which are added together for the * final result. <br /><br />Another way to adjust the character of the * resulting sequence is the scale of the input coordinates. As the * function works within an infinite space the value of the coordinates * doesn't matter as such, only the distance between successive coordinates * does (eg. when using <b>noise()</b> within a loop). As a general rule * the smaller the difference between coordinates, the smoother the * resulting noise sequence will be. Steps of 0.005-0.03 work best for most * applications, but this will differ depending on use. * * ( end auto-generated ) * * @webref math:random * @param x x-coordinate in noise space * @param y y-coordinate in noise space * @param z z-coordinate in noise space * @see PApplet#noiseSeed(long) * @see PApplet#noiseDetail(int, float) * @see PApplet#random(float,float) */ public float noise(float x, float y, float z) { if (perlin == null) { if (perlinRandom == null) { perlinRandom = new Random(); } perlin = new float[PERLIN_SIZE + 1]; for (int i = 0; i < PERLIN_SIZE + 1; i++) { perlin[i] = perlinRandom.nextFloat(); //(float)Math.random(); } // [toxi 031112] // noise broke due to recent change of cos table in PGraphics // this will take care of it perlin_cosTable = PGraphics.cosLUT; perlin_TWOPI = perlin_PI = PGraphics.SINCOS_LENGTH; perlin_PI >>= 1; } if (x<0) x=-x; if (y<0) y=-y; if (z<0) z=-z; int xi=(int)x, yi=(int)y, zi=(int)z; float xf = x - xi; float yf = y - yi; float zf = z - zi; float rxf, ryf; float r=0; float ampl=0.5f; float n1,n2,n3; for (int i=0; i<perlin_octaves; i++) { int of=xi+(yi<<PERLIN_YWRAPB)+(zi<<PERLIN_ZWRAPB); rxf=noise_fsc(xf); ryf=noise_fsc(yf); n1 = perlin[of&PERLIN_SIZE]; n1 += rxf*(perlin[(of+1)&PERLIN_SIZE]-n1); n2 = perlin[(of+PERLIN_YWRAP)&PERLIN_SIZE]; n2 += rxf*(perlin[(of+PERLIN_YWRAP+1)&PERLIN_SIZE]-n2); n1 += ryf*(n2-n1); of += PERLIN_ZWRAP; n2 = perlin[of&PERLIN_SIZE]; n2 += rxf*(perlin[(of+1)&PERLIN_SIZE]-n2); n3 = perlin[(of+PERLIN_YWRAP)&PERLIN_SIZE]; n3 += rxf*(perlin[(of+PERLIN_YWRAP+1)&PERLIN_SIZE]-n3); n2 += ryf*(n3-n2); n1 += noise_fsc(zf)*(n2-n1); r += n1*ampl; ampl *= perlin_amp_falloff; xi<<=1; xf*=2; yi<<=1; yf*=2; zi<<=1; zf*=2; if (xf>=1.0f) { xi++; xf--; } if (yf>=1.0f) { yi++; yf--; } if (zf>=1.0f) { zi++; zf--; } } return r; } // [toxi 031112] // now adjusts to the size of the cosLUT used via // the new variables, defined above private float noise_fsc(float i) { // using bagel's cosine table instead return 0.5f*(1.0f-perlin_cosTable[(int)(i*perlin_PI)%perlin_TWOPI]); } // [toxi 040903] // make perlin noise quality user controlled to allow // for different levels of detail. lower values will produce // smoother results as higher octaves are surpressed /** * ( begin auto-generated from noiseDetail.xml ) * * Adjusts the character and level of detail produced by the Perlin noise * function. Similar to harmonics in physics, noise is computed over * several octaves. Lower octaves contribute more to the output signal and * as such define the overal intensity of the noise, whereas higher octaves * create finer grained details in the noise sequence. By default, noise is * computed over 4 octaves with each octave contributing exactly half than * its predecessor, starting at 50% strength for the 1st octave. This * falloff amount can be changed by adding an additional function * parameter. Eg. a falloff factor of 0.75 means each octave will now have * 75% impact (25% less) of the previous lower octave. Any value between * 0.0 and 1.0 is valid, however note that values greater than 0.5 might * result in greater than 1.0 values returned by <b>noise()</b>.<br /><br * />By changing these parameters, the signal created by the <b>noise()</b> * function can be adapted to fit very specific needs and characteristics. * * ( end auto-generated ) * @webref math:random * @param lod number of octaves to be used by the noise * @param falloff falloff factor for each octave * @see PApplet#noise(float, float, float) */ public void noiseDetail(int lod) { if (lod>0) perlin_octaves=lod; } /** * @param falloff falloff factor for each octave */ public void noiseDetail(int lod, float falloff) { if (lod>0) perlin_octaves=lod; if (falloff>0) perlin_amp_falloff=falloff; } /** * ( begin auto-generated from noiseSeed.xml ) * * Sets the seed value for <b>noise()</b>. By default, <b>noise()</b> * produces different results each time the program is run. Set the * <b>value</b> parameter to a constant to return the same pseudo-random * numbers each time the software is run. * * ( end auto-generated ) * @webref math:random * @param seed seed value * @see PApplet#noise(float, float, float) * @see PApplet#noiseDetail(int, float) * @see PApplet#random(float,float) * @see PApplet#randomSeed(long) */ public void noiseSeed(long seed) { if (perlinRandom == null) perlinRandom = new Random(); perlinRandom.setSeed(seed); // force table reset after changing the random number seed [0122] perlin = null; } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . protected String[] loadImageFormats; /** * ( begin auto-generated from loadImage.xml ) * * Loads an image into a variable of type <b>PImage</b>. Four types of * images ( <b>.gif</b>, <b>.jpg</b>, <b>.tga</b>, <b>.png</b>) images may * be loaded. To load correctly, images must be located in the data * directory of the current sketch. In most cases, load all images in * <b>setup()</b> to preload them at the start of the program. Loading * images inside <b>draw()</b> will reduce the speed of a program.<br/> * <br/> <b>filename</b> parameter can also be a URL to a file found * online. For security reasons, a Processing sketch found online can only * download files from the same server from which it came. Getting around * this restriction requires a <a * href="http://wiki.processing.org/w/Sign_an_Applet">signed * applet</a>.<br/> * <br/> <b>extension</b> parameter is used to determine the image type in * cases where the image filename does not end with a proper extension. * Specify the extension as the second parameter to <b>loadImage()</b>, as * shown in the third example on this page.<br/> * <br/> an image is not loaded successfully, the <b>null</b> value is * returned and an error message will be printed to the console. The error * message does not halt the program, however the null value may cause a * NullPointerException if your code does not check whether the value * returned from <b>loadImage()</b> is null.<br/> * <br/> on the type of error, a <b>PImage</b> object may still be * returned, but the width and height of the image will be set to -1. This * happens if bad image data is returned or cannot be decoded properly. * Sometimes this happens with image URLs that produce a 403 error or that * redirect to a password prompt, because <b>loadImage()</b> will attempt * to interpret the HTML as image data. * * ( end auto-generated ) * * @webref image:loading_displaying * @param filename name of file to load, can be .gif, .jpg, .tga, or a handful of other image types depending on your platform * @see PImage * @see PGraphics#image(PImage, float, float, float, float) * @see PGraphics#imageMode(int) * @see PGraphics#background(float, float, float, float) */ public PImage loadImage(String filename) { // return loadImage(filename, null, null); return loadImage(filename, null); } // /** // * @param extension the type of image to load, for example "png", "gif", "jpg" // */ // public PImage loadImage(String filename, String extension) { // return loadImage(filename, extension, null); // } // /** // * @nowebref // */ // public PImage loadImage(String filename, Object params) { // return loadImage(filename, null, params); // } /** * @param extension type of image to load, for example "png", "gif", "jpg" */ public PImage loadImage(String filename, String extension) { //, Object params) { if (extension == null) { String lower = filename.toLowerCase(); int dot = filename.lastIndexOf('.'); if (dot == -1) { extension = "unknown"; // no extension found } extension = lower.substring(dot + 1); // check for, and strip any parameters on the url, i.e. // filename.jpg?blah=blah&something=that int question = extension.indexOf('?'); if (question != -1) { extension = extension.substring(0, question); } } // just in case. them users will try anything! extension = extension.toLowerCase(); if (extension.equals("tga")) { try { PImage image = loadImageTGA(filename); // if (params != null) { // image.setParams(g, params); // } return image; } catch (IOException e) { e.printStackTrace(); return null; } } if (extension.equals("tif") || extension.equals("tiff")) { byte bytes[] = loadBytes(filename); PImage image = (bytes == null) ? null : PImage.loadTIFF(bytes); // if (params != null) { // image.setParams(g, params); // } return image; } // For jpeg, gif, and png, load them using createImage(), // because the javax.imageio code was found to be much slower. // http://dev.processing.org/bugs/show_bug.cgi?id=392 try { if (extension.equals("jpg") || extension.equals("jpeg") || extension.equals("gif") || extension.equals("png") || extension.equals("unknown")) { byte bytes[] = loadBytes(filename); if (bytes == null) { return null; } else { Image awtImage = Toolkit.getDefaultToolkit().createImage(bytes); PImage image = loadImageMT(awtImage); if (image.width == -1) { System.err.println("The file " + filename + " contains bad image data, or may not be an image."); } // if it's a .gif image, test to see if it has transparency if (extension.equals("gif") || extension.equals("png")) { image.checkAlpha(); } // if (params != null) { // image.setParams(g, params); // } return image; } } } catch (Exception e) { // show error, but move on to the stuff below, see if it'll work e.printStackTrace(); } if (loadImageFormats == null) { loadImageFormats = ImageIO.getReaderFormatNames(); } if (loadImageFormats != null) { for (int i = 0; i < loadImageFormats.length; i++) { if (extension.equals(loadImageFormats[i])) { return loadImageIO(filename); // PImage image = loadImageIO(filename); // if (params != null) { // image.setParams(g, params); // } // return image; } } } // failed, could not load image after all those attempts System.err.println("Could not find a method to load " + filename); return null; } public PImage requestImage(String filename) { // return requestImage(filename, null, null); return requestImage(filename, null); } /** * ( begin auto-generated from requestImage.xml ) * * This function load images on a separate thread so that your sketch does * not freeze while images load during <b>setup()</b>. While the image is * loading, its width and height will be 0. If an error occurs while * loading the image, its width and height will be set to -1. You'll know * when the image has loaded properly because its width and height will be * greater than 0. Asynchronous image loading (particularly when * downloading from a server) can dramatically improve performance.<br /> * <br/> <b>extension</b> parameter is used to determine the image type in * cases where the image filename does not end with a proper extension. * Specify the extension as the second parameter to <b>requestImage()</b>. * * ( end auto-generated ) * * @webref image:loading_displaying * @param filename name of the file to load, can be .gif, .jpg, .tga, or a handful of other image types depending on your platform * @param extension the type of image to load, for example "png", "gif", "jpg" * @see PImage * @see PApplet#loadImage(String, String) */ public PImage requestImage(String filename, String extension) { PImage vessel = createImage(0, 0, ARGB); AsyncImageLoader ail = new AsyncImageLoader(filename, extension, vessel); ail.start(); return vessel; } // /** // * @nowebref // */ // public PImage requestImage(String filename, String extension, Object params) { // PImage vessel = createImage(0, 0, ARGB, params); // AsyncImageLoader ail = // new AsyncImageLoader(filename, extension, vessel); // ail.start(); // return vessel; // } /** * By trial and error, four image loading threads seem to work best when * loading images from online. This is consistent with the number of open * connections that web browsers will maintain. The variable is made public * (however no accessor has been added since it's esoteric) if you really * want to have control over the value used. For instance, when loading local * files, it might be better to only have a single thread (or two) loading * images so that you're disk isn't simply jumping around. */ public int requestImageMax = 4; volatile int requestImageCount; class AsyncImageLoader extends Thread { String filename; String extension; PImage vessel; public AsyncImageLoader(String filename, String extension, PImage vessel) { this.filename = filename; this.extension = extension; this.vessel = vessel; } @Override public void run() { while (requestImageCount == requestImageMax) { try { Thread.sleep(10); } catch (InterruptedException e) { } } requestImageCount++; PImage actual = loadImage(filename, extension); // An error message should have already printed if (actual == null) { vessel.width = -1; vessel.height = -1; } else { vessel.width = actual.width; vessel.height = actual.height; vessel.format = actual.format; vessel.pixels = actual.pixels; } requestImageCount--; } } /** * Load an AWT image synchronously by setting up a MediaTracker for * a single image, and blocking until it has loaded. */ protected PImage loadImageMT(Image awtImage) { MediaTracker tracker = new MediaTracker(this); tracker.addImage(awtImage, 0); try { tracker.waitForAll(); } catch (InterruptedException e) { //e.printStackTrace(); // non-fatal, right? } PImage image = new PImage(awtImage); image.parent = this; return image; } /** * Use Java 1.4 ImageIO methods to load an image. */ protected PImage loadImageIO(String filename) { InputStream stream = createInput(filename); if (stream == null) { System.err.println("The image " + filename + " could not be found."); return null; } try { BufferedImage bi = ImageIO.read(stream); PImage outgoing = new PImage(bi.getWidth(), bi.getHeight()); outgoing.parent = this; bi.getRGB(0, 0, outgoing.width, outgoing.height, outgoing.pixels, 0, outgoing.width); // check the alpha for this image // was gonna call getType() on the image to see if RGB or ARGB, // but it's not actually useful, since gif images will come through // as TYPE_BYTE_INDEXED, which means it'll still have to check for // the transparency. also, would have to iterate through all the other // types and guess whether alpha was in there, so.. just gonna stick // with the old method. outgoing.checkAlpha(); // return the image return outgoing; } catch (Exception e) { e.printStackTrace(); return null; } } /** * Targa image loader for RLE-compressed TGA files. * <p> * Rewritten for 0115 to read/write RLE-encoded targa images. * For 0125, non-RLE encoded images are now supported, along with * images whose y-order is reversed (which is standard for TGA files). */ protected PImage loadImageTGA(String filename) throws IOException { InputStream is = createInput(filename); if (is == null) return null; byte header[] = new byte[18]; int offset = 0; do { int count = is.read(header, offset, header.length - offset); if (count == -1) return null; offset += count; } while (offset < 18); /* header[2] image type code 2 (0x02) - Uncompressed, RGB images. 3 (0x03) - Uncompressed, black and white images. 10 (0x0A) - Runlength encoded RGB images. 11 (0x0B) - Compressed, black and white images. (grayscale?) header[16] is the bit depth (8, 24, 32) header[17] image descriptor (packed bits) 0x20 is 32 = origin upper-left 0x28 is 32 + 8 = origin upper-left + 32 bits 7 6 5 4 3 2 1 0 128 64 32 16 8 4 2 1 */ int format = 0; if (((header[2] == 3) || (header[2] == 11)) && // B&W, plus RLE or not (header[16] == 8) && // 8 bits ((header[17] == 0x8) || (header[17] == 0x28))) { // origin, 32 bit format = ALPHA; } else if (((header[2] == 2) || (header[2] == 10)) && // RGB, RLE or not (header[16] == 24) && // 24 bits ((header[17] == 0x20) || (header[17] == 0))) { // origin format = RGB; } else if (((header[2] == 2) || (header[2] == 10)) && (header[16] == 32) && ((header[17] == 0x8) || (header[17] == 0x28))) { // origin, 32 format = ARGB; } if (format == 0) { System.err.println("Unknown .tga file format for " + filename); //" (" + header[2] + " " + //(header[16] & 0xff) + " " + //hex(header[17], 2) + ")"); return null; } int w = ((header[13] & 0xff) << 8) + (header[12] & 0xff); int h = ((header[15] & 0xff) << 8) + (header[14] & 0xff); PImage outgoing = createImage(w, h, format); // where "reversed" means upper-left corner (normal for most of // the modernized world, but "reversed" for the tga spec) //boolean reversed = (header[17] & 0x20) != 0; // https://github.com/processing/processing/issues/1682 boolean reversed = (header[17] & 0x20) == 0; if ((header[2] == 2) || (header[2] == 3)) { // not RLE encoded if (reversed) { int index = (h-1) * w; switch (format) { case ALPHA: for (int y = h-1; y >= 0; y--) { for (int x = 0; x < w; x++) { outgoing.pixels[index + x] = is.read(); } index -= w; } break; case RGB: for (int y = h-1; y >= 0; y--) { for (int x = 0; x < w; x++) { outgoing.pixels[index + x] = is.read() | (is.read() << 8) | (is.read() << 16) | 0xff000000; } index -= w; } break; case ARGB: for (int y = h-1; y >= 0; y--) { for (int x = 0; x < w; x++) { outgoing.pixels[index + x] = is.read() | (is.read() << 8) | (is.read() << 16) | (is.read() << 24); } index -= w; } } } else { // not reversed int count = w * h; switch (format) { case ALPHA: for (int i = 0; i < count; i++) { outgoing.pixels[i] = is.read(); } break; case RGB: for (int i = 0; i < count; i++) { outgoing.pixels[i] = is.read() | (is.read() << 8) | (is.read() << 16) | 0xff000000; } break; case ARGB: for (int i = 0; i < count; i++) { outgoing.pixels[i] = is.read() | (is.read() << 8) | (is.read() << 16) | (is.read() << 24); } break; } } } else { // header[2] is 10 or 11 int index = 0; int px[] = outgoing.pixels; while (index < px.length) { int num = is.read(); boolean isRLE = (num & 0x80) != 0; if (isRLE) { num -= 127; // (num & 0x7F) + 1 int pixel = 0; switch (format) { case ALPHA: pixel = is.read(); break; case RGB: pixel = 0xFF000000 | is.read() | (is.read() << 8) | (is.read() << 16); //(is.read() << 16) | (is.read() << 8) | is.read(); break; case ARGB: pixel = is.read() | (is.read() << 8) | (is.read() << 16) | (is.read() << 24); break; } for (int i = 0; i < num; i++) { px[index++] = pixel; if (index == px.length) break; } } else { // write up to 127 bytes as uncompressed num += 1; switch (format) { case ALPHA: for (int i = 0; i < num; i++) { px[index++] = is.read(); } break; case RGB: for (int i = 0; i < num; i++) { px[index++] = 0xFF000000 | is.read() | (is.read() << 8) | (is.read() << 16); //(is.read() << 16) | (is.read() << 8) | is.read(); } break; case ARGB: for (int i = 0; i < num; i++) { px[index++] = is.read() | //(is.read() << 24) | (is.read() << 8) | (is.read() << 16) | (is.read() << 24); //(is.read() << 16) | (is.read() << 8) | is.read(); } break; } } } if (!reversed) { int[] temp = new int[w]; for (int y = 0; y < h/2; y++) { int z = (h-1) - y; System.arraycopy(px, y*w, temp, 0, w); System.arraycopy(px, z*w, px, y*w, w); System.arraycopy(temp, 0, px, z*w, w); } } } return outgoing; } ////////////////////////////////////////////////////////////// // DATA I/O // /** // * @webref input:files // * @brief Creates a new XML object // * @param name the name to be given to the root element of the new XML object // * @return an XML object, or null // * @see XML // * @see PApplet#loadXML(String) // * @see PApplet#parseXML(String) // * @see PApplet#saveXML(XML, String) // */ // public XML createXML(String name) { // try { // return new XML(name); // } catch (Exception e) { // e.printStackTrace(); // return null; // } // } /** * @webref input:files * @param filename name of a file in the data folder or a URL. * @see XML * @see PApplet#parseXML(String) * @see PApplet#saveXML(XML, String) * @see PApplet#loadBytes(String) * @see PApplet#loadStrings(String) * @see PApplet#loadTable(String) */ public XML loadXML(String filename) { return loadXML(filename, null); } // version that uses 'options' though there are currently no supported options /** * @nowebref */ public XML loadXML(String filename, String options) { try { return new XML(createReader(filename), options); } catch (Exception e) { e.printStackTrace(); return null; } } /** * @webref input:files * @brief Converts String content to an XML object * @param data the content to be parsed as XML * @return an XML object, or null * @see XML * @see PApplet#loadXML(String) * @see PApplet#saveXML(XML, String) */ public XML parseXML(String xmlString) { return parseXML(xmlString, null); } public XML parseXML(String xmlString, String options) { try { return XML.parse(xmlString, options); } catch (Exception e) { e.printStackTrace(); return null; } } /** * @webref output:files * @param xml the XML object to save to disk * @param filename name of the file to write to * @see XML * @see PApplet#loadXML(String) * @see PApplet#parseXML(String) */ public boolean saveXML(XML xml, String filename) { return saveXML(xml, filename, null); } public boolean saveXML(XML xml, String filename, String options) { return xml.save(saveFile(filename), options); } public JSONObject parseJSONObject(String input) { return new JSONObject(new StringReader(input)); } /** * @webref output:files * @param filename name of a file in the data folder or a URL * @see JSONObject * @see JSONArray * @see PApplet#loadJSONArray(String) * @see PApplet#saveJSONObject(JSONObject, String) * @see PApplet#saveJSONArray(JSONArray, String) */ public JSONObject loadJSONObject(String filename) { return new JSONObject(createReader(filename)); } /** * @webref output:files * @see JSONObject * @see JSONArray * @see PApplet#loadJSONObject(String) * @see PApplet#loadJSONArray(String) * @see PApplet#saveJSONArray(JSONArray, String) */ public boolean saveJSONObject(JSONObject json, String filename) { return saveJSONObject(json, filename, null); } public boolean saveJSONObject(JSONObject json, String filename, String options) { return json.save(saveFile(filename), options); } public JSONArray parseJSONArray(String input) { return new JSONArray(new StringReader(input)); } /** * @webref output:files * @param filename name of a file in the data folder or a URL * @see JSONObject * @see JSONArray * @see PApplet#loadJSONObject(String) * @see PApplet#saveJSONObject(JSONObject, String) * @see PApplet#saveJSONArray(JSONArray, String) */ public JSONArray loadJSONArray(String filename) { return new JSONArray(createReader(filename)); } /** * @webref output:files * @see JSONObject * @see JSONArray * @see PApplet#loadJSONObject(String) * @see PApplet#loadJSONArray(String) * @see PApplet#saveJSONObject(JSONObject, String) */ public boolean saveJSONArray(JSONArray json, String filename) { - return saveJSONArray(json, filename); + return saveJSONArray(json, filename, null); } public boolean saveJSONArray(JSONArray json, String filename, String options) { return json.save(saveFile(filename), options); } // /** // * @webref input:files // * @see Table // * @see PApplet#loadTable(String) // * @see PApplet#saveTable(Table, String) // */ // public Table createTable() { // return new Table(); // } /** * @webref input:files * @param filename name of a file in the data folder or a URL. * @see Table * @see PApplet#saveTable(Table, String) * @see PApplet#loadBytes(String) * @see PApplet#loadStrings(String) * @see PApplet#loadXML(String) */ public Table loadTable(String filename) { return loadTable(filename, null); } /** * @param options may contain "header", "tsv", "csv", or "bin" separated by commas */ public Table loadTable(String filename, String options) { try { // String ext = checkExtension(filename); // if (ext != null) { // if (ext.equals("csv") || ext.equals("tsv") || ext.equals("bin")) { // if (options == null) { // options = ext; // } else { // options = ext + "," + options; // } // } // } return new Table(createInput(filename), Table.extensionOptions(true, filename, options)); } catch (IOException e) { e.printStackTrace(); return null; } } /** * @webref input:files * @param table the Table object to save to a file * @param filename the filename to which the Table should be saved * @see Table * @see PApplet#loadTable(String) */ public boolean saveTable(Table table, String filename) { return saveTable(table, filename, null); } /** * @param options can be one of "tsv", "csv", "bin", or "html" */ public boolean saveTable(Table table, String filename, String options) { // String ext = checkExtension(filename); // if (ext != null) { // if (ext.equals("csv") || ext.equals("tsv") || ext.equals("bin") || ext.equals("html")) { // if (options == null) { // options = ext; // } else { // options = ext + "," + options; // } // } // } try { // Figure out location and make sure the target path exists File outputFile = saveFile(filename); // Open a stream and take care of .gz if necessary return table.save(outputFile, options); } catch (IOException e) { e.printStackTrace(); return false; } } ////////////////////////////////////////////////////////////// // FONT I/O /** * ( begin auto-generated from loadFont.xml ) * * Loads a font into a variable of type <b>PFont</b>. To load correctly, * fonts must be located in the data directory of the current sketch. To * create a font to use with Processing, select "Create Font..." from the * Tools menu. This will create a font in the format Processing requires * and also adds it to the current sketch's data directory.<br /> * <br /> * Like <b>loadImage()</b> and other functions that load data, the * <b>loadFont()</b> function should not be used inside <b>draw()</b>, * because it will slow down the sketch considerably, as the font will be * re-loaded from the disk (or network) on each frame.<br /> * <br /> * For most renderers, Processing displays fonts using the .vlw font * format, which uses images for each letter, rather than defining them * through vector data. When <b>hint(ENABLE_NATIVE_FONTS)</b> is used with * the JAVA2D renderer, the native version of a font will be used if it is * installed on the user's machine.<br /> * <br /> * Using <b>createFont()</b> (instead of loadFont) enables vector data to * be used with the JAVA2D (default) renderer setting. This can be helpful * when many font sizes are needed, or when using any renderer based on * JAVA2D, such as the PDF library. * * ( end auto-generated ) * @webref typography:loading_displaying * @param filename name of the font to load * @see PFont * @see PGraphics#textFont(PFont, float) * @see PApplet#createFont(String, float, boolean, char[]) */ public PFont loadFont(String filename) { try { InputStream input = createInput(filename); return new PFont(input); } catch (Exception e) { die("Could not load font " + filename + ". " + "Make sure that the font has been copied " + "to the data folder of your sketch.", e); } return null; } /** * Used by PGraphics to remove the requirement for loading a font! */ protected PFont createDefaultFont(float size) { // Font f = new Font("SansSerif", Font.PLAIN, 12); // println("n: " + f.getName()); // println("fn: " + f.getFontName()); // println("ps: " + f.getPSName()); return createFont("Lucida Sans", size, true, null); } public PFont createFont(String name, float size) { return createFont(name, size, true, null); } public PFont createFont(String name, float size, boolean smooth) { return createFont(name, size, smooth, null); } /** * ( begin auto-generated from createFont.xml ) * * Dynamically converts a font to the format used by Processing from either * a font name that's installed on the computer, or from a .ttf or .otf * file inside the sketches "data" folder. This function is an advanced * feature for precise control. On most occasions you should create fonts * through selecting "Create Font..." from the Tools menu. * <br /><br /> * Use the <b>PFont.list()</b> method to first determine the names for the * fonts recognized by the computer and are compatible with this function. * Because of limitations in Java, not all fonts can be used and some might * work with one operating system and not others. When sharing a sketch * with other people or posting it on the web, you may need to include a * .ttf or .otf version of your font in the data directory of the sketch * because other people might not have the font installed on their * computer. Only fonts that can legally be distributed should be included * with a sketch. * <br /><br /> * The <b>size</b> parameter states the font size you want to generate. The * <b>smooth</b> parameter specifies if the font should be antialiased or * not, and the <b>charset</b> parameter is an array of chars that * specifies the characters to generate. * <br /><br /> * This function creates a bitmapped version of a font in the same manner * as the Create Font tool. It loads a font by name, and converts it to a * series of images based on the size of the font. When possible, the * <b>text()</b> function will use a native font rather than the bitmapped * version created behind the scenes with <b>createFont()</b>. For * instance, when using P2D, the actual native version of the font will be * employed by the sketch, improving drawing quality and performance. With * the P3D renderer, the bitmapped version will be used. While this can * drastically improve speed and appearance, results are poor when * exporting if the sketch does not include the .otf or .ttf file, and the * requested font is not available on the machine running the sketch. * * ( end auto-generated ) * @webref typography:loading_displaying * @param name name of the font to load * @param size point size of the font * @param smooth true for an antialiased font, false for aliased * @param charset array containing characters to be generated * @see PFont * @see PGraphics#textFont(PFont, float) * @see PGraphics#text(String, float, float, float, float, float) * @see PApplet#loadFont(String) */ public PFont createFont(String name, float size, boolean smooth, char charset[]) { String lowerName = name.toLowerCase(); Font baseFont = null; try { InputStream stream = null; if (lowerName.endsWith(".otf") || lowerName.endsWith(".ttf")) { stream = createInput(name); if (stream == null) { System.err.println("The font \"" + name + "\" " + "is missing or inaccessible, make sure " + "the URL is valid or that the file has been " + "added to your sketch and is readable."); return null; } baseFont = Font.createFont(Font.TRUETYPE_FONT, createInput(name)); } else { baseFont = PFont.findFont(name); } return new PFont(baseFont.deriveFont(size), smooth, charset, stream != null); } catch (Exception e) { System.err.println("Problem createFont(" + name + ")"); e.printStackTrace(); return null; } } ////////////////////////////////////////////////////////////// // FILE/FOLDER SELECTION private Frame selectFrame; private Frame selectFrame() { if (frame != null) { selectFrame = frame; } else if (selectFrame == null) { Component comp = getParent(); while (comp != null) { if (comp instanceof Frame) { selectFrame = (Frame) comp; break; } comp = comp.getParent(); } // Who you callin' a hack? if (selectFrame == null) { selectFrame = new Frame(); } } return selectFrame; } /** * Open a platform-specific file chooser dialog to select a file for input. * After the selection is made, the selected File will be passed to the * 'callback' function. If the dialog is closed or canceled, null will be * sent to the function, so that the program is not waiting for additional * input. The callback is necessary because of how threading works. * * <pre> * void setup() { * selectInput("Select a file to process:", "fileSelected"); * } * * void fileSelected(File selection) { * if (selection == null) { * println("Window was closed or the user hit cancel."); * } else { * println("User selected " + fileSeleted.getAbsolutePath()); * } * } * </pre> * * For advanced users, the method must be 'public', which is true for all * methods inside a sketch when run from the PDE, but must explicitly be * set when using Eclipse or other development environments. * * @webref input:files * @param prompt message to the user * @param callback name of the method to be called when the selection is made */ public void selectInput(String prompt, String callback) { selectInput(prompt, callback, null); } public void selectInput(String prompt, String callback, File file) { selectInput(prompt, callback, file, this); } public void selectInput(String prompt, String callback, File file, Object callbackObject) { selectInput(prompt, callback, file, callbackObject, selectFrame()); } static public void selectInput(String prompt, String callbackMethod, File file, Object callbackObject, Frame parent) { selectImpl(prompt, callbackMethod, file, callbackObject, parent, FileDialog.LOAD); } /** * See selectInput() for details. * * @webref output:files * @param prompt message to the user * @param callback name of the method to be called when the selection is made */ public void selectOutput(String prompt, String callback) { selectOutput(prompt, callback, null); } public void selectOutput(String prompt, String callback, File file) { selectOutput(prompt, callback, file, this); } public void selectOutput(String prompt, String callback, File file, Object callbackObject) { selectOutput(prompt, callback, file, callbackObject, selectFrame()); } static public void selectOutput(String prompt, String callbackMethod, File file, Object callbackObject, Frame parent) { selectImpl(prompt, callbackMethod, file, callbackObject, parent, FileDialog.SAVE); } static protected void selectImpl(final String prompt, final String callbackMethod, final File defaultSelection, final Object callbackObject, final Frame parentFrame, final int mode) { EventQueue.invokeLater(new Runnable() { public void run() { File selectedFile = null; if (useNativeSelect) { FileDialog dialog = new FileDialog(parentFrame, prompt, mode); if (defaultSelection != null) { dialog.setDirectory(defaultSelection.getParent()); dialog.setFile(defaultSelection.getName()); } dialog.setVisible(true); String directory = dialog.getDirectory(); String filename = dialog.getFile(); if (filename != null) { selectedFile = new File(directory, filename); } } else { JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle(prompt); if (defaultSelection != null) { chooser.setSelectedFile(defaultSelection); } int result = -1; if (mode == FileDialog.SAVE) { result = chooser.showSaveDialog(parentFrame); } else if (mode == FileDialog.LOAD) { result = chooser.showOpenDialog(parentFrame); } if (result == JFileChooser.APPROVE_OPTION) { selectedFile = chooser.getSelectedFile(); } } selectCallback(selectedFile, callbackMethod, callbackObject); } }); } /** * See selectInput() for details. * * @webref input:files * @param prompt message to the user * @param callback name of the method to be called when the selection is made */ public void selectFolder(String prompt, String callback) { selectFolder(prompt, callback, null); } public void selectFolder(String prompt, String callback, File file) { selectFolder(prompt, callback, file, this); } public void selectFolder(String prompt, String callback, File file, Object callbackObject) { selectFolder(prompt, callback, file, callbackObject, selectFrame()); } static public void selectFolder(final String prompt, final String callbackMethod, final File defaultSelection, final Object callbackObject, final Frame parentFrame) { EventQueue.invokeLater(new Runnable() { public void run() { File selectedFile = null; if (platform == MACOSX && useNativeSelect != false) { FileDialog fileDialog = new FileDialog(parentFrame, prompt, FileDialog.LOAD); System.setProperty("apple.awt.fileDialogForDirectories", "true"); fileDialog.setVisible(true); System.setProperty("apple.awt.fileDialogForDirectories", "false"); String filename = fileDialog.getFile(); if (filename != null) { selectedFile = new File(fileDialog.getDirectory(), fileDialog.getFile()); } } else { JFileChooser fileChooser = new JFileChooser(); fileChooser.setDialogTitle(prompt); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); if (defaultSelection != null) { fileChooser.setSelectedFile(defaultSelection); } int result = fileChooser.showOpenDialog(parentFrame); if (result == JFileChooser.APPROVE_OPTION) { selectedFile = fileChooser.getSelectedFile(); } } selectCallback(selectedFile, callbackMethod, callbackObject); } }); } static private void selectCallback(File selectedFile, String callbackMethod, Object callbackObject) { try { Class<?> callbackClass = callbackObject.getClass(); Method selectMethod = callbackClass.getMethod(callbackMethod, new Class[] { File.class }); selectMethod.invoke(callbackObject, new Object[] { selectedFile }); } catch (IllegalAccessException iae) { System.err.println(callbackMethod + "() must be public"); } catch (InvocationTargetException ite) { ite.printStackTrace(); } catch (NoSuchMethodException nsme) { System.err.println(callbackMethod + "() could not be found"); } } ////////////////////////////////////////////////////////////// // EXTENSIONS /** * Get the compression-free extension for this filename. * @param filename The filename to check * @return an extension, skipping past .gz if it's present */ static public String checkExtension(String filename) { // Don't consider the .gz as part of the name, createInput() // and createOuput() will take care of fixing that up. if (filename.toLowerCase().endsWith(".gz")) { filename = filename.substring(0, filename.length() - 3); } int dotIndex = filename.lastIndexOf('.'); if (dotIndex != -1) { return filename.substring(dotIndex + 1).toLowerCase(); } return null; } ////////////////////////////////////////////////////////////// // READERS AND WRITERS /** * ( begin auto-generated from createReader.xml ) * * Creates a <b>BufferedReader</b> object that can be used to read files * line-by-line as individual <b>String</b> objects. This is the complement * to the <b>createWriter()</b> function. * <br/> <br/> * Starting with Processing release 0134, all files loaded and saved by the * Processing API use UTF-8 encoding. In previous releases, the default * encoding for your platform was used, which causes problems when files * are moved to other platforms. * * ( end auto-generated ) * @webref input:files * @param filename name of the file to be opened * @see BufferedReader * @see PApplet#createWriter(String) * @see PrintWriter */ public BufferedReader createReader(String filename) { try { InputStream is = createInput(filename); if (is == null) { System.err.println(filename + " does not exist or could not be read"); return null; } return createReader(is); } catch (Exception e) { if (filename == null) { System.err.println("Filename passed to reader() was null"); } else { System.err.println("Couldn't create a reader for " + filename); } } return null; } /** * @nowebref */ static public BufferedReader createReader(File file) { try { InputStream is = new FileInputStream(file); if (file.getName().toLowerCase().endsWith(".gz")) { is = new GZIPInputStream(is); } return createReader(is); } catch (Exception e) { if (file == null) { throw new RuntimeException("File passed to createReader() was null"); } else { e.printStackTrace(); throw new RuntimeException("Couldn't create a reader for " + file.getAbsolutePath()); } } //return null; } /** * @nowebref * I want to read lines from a stream. If I have to type the * following lines any more I'm gonna send Sun my medical bills. */ static public BufferedReader createReader(InputStream input) { InputStreamReader isr = null; try { isr = new InputStreamReader(input, "UTF-8"); } catch (UnsupportedEncodingException e) { } // not gonna happen return new BufferedReader(isr); } /** * ( begin auto-generated from createWriter.xml ) * * Creates a new file in the sketch folder, and a <b>PrintWriter</b> object * to write to it. For the file to be made correctly, it should be flushed * and must be closed with its <b>flush()</b> and <b>close()</b> methods * (see above example). * <br/> <br/> * Starting with Processing release 0134, all files loaded and saved by the * Processing API use UTF-8 encoding. In previous releases, the default * encoding for your platform was used, which causes problems when files * are moved to other platforms. * * ( end auto-generated ) * * @webref output:files * @param filename name of the file to be created * @see PrintWriter * @see PApplet#createReader * @see BufferedReader */ public PrintWriter createWriter(String filename) { return createWriter(saveFile(filename)); } /** * @nowebref * I want to print lines to a file. I have RSI from typing these * eight lines of code so many times. */ static public PrintWriter createWriter(File file) { try { createPath(file); // make sure in-between folders exist OutputStream output = new FileOutputStream(file); if (file.getName().toLowerCase().endsWith(".gz")) { output = new GZIPOutputStream(output); } return createWriter(output); } catch (Exception e) { if (file == null) { throw new RuntimeException("File passed to createWriter() was null"); } else { e.printStackTrace(); throw new RuntimeException("Couldn't create a writer for " + file.getAbsolutePath()); } } //return null; } /** * @nowebref * I want to print lines to a file. Why am I always explaining myself? * It's the JavaSoft API engineers who need to explain themselves. */ static public PrintWriter createWriter(OutputStream output) { try { BufferedOutputStream bos = new BufferedOutputStream(output, 8192); OutputStreamWriter osw = new OutputStreamWriter(bos, "UTF-8"); return new PrintWriter(osw); } catch (UnsupportedEncodingException e) { } // not gonna happen return null; } ////////////////////////////////////////////////////////////// // FILE INPUT /** * @deprecated As of release 0136, use createInput() instead. */ public InputStream openStream(String filename) { return createInput(filename); } /** * ( begin auto-generated from createInput.xml ) * * This is a function for advanced programmers to open a Java InputStream. * It's useful if you want to use the facilities provided by PApplet to * easily open files from the data folder or from a URL, but want an * InputStream object so that you can use other parts of Java to take more * control of how the stream is read.<br /> * <br /> * The filename passed in can be:<br /> * - A URL, for instance <b>openStream("http://processing.org/")</b><br /> * - A file in the sketch's <b>data</b> folder<br /> * - The full path to a file to be opened locally (when running as an * application)<br /> * <br /> * If the requested item doesn't exist, null is returned. If not online, * this will also check to see if the user is asking for a file whose name * isn't properly capitalized. If capitalization is different, an error * will be printed to the console. This helps prevent issues that appear * when a sketch is exported to the web, where case sensitivity matters, as * opposed to running from inside the Processing Development Environment on * Windows or Mac OS, where case sensitivity is preserved but ignored.<br /> * <br /> * If the file ends with <b>.gz</b>, the stream will automatically be gzip * decompressed. If you don't want the automatic decompression, use the * related function <b>createInputRaw()</b>. * <br /> * In earlier releases, this function was called <b>openStream()</b>.<br /> * <br /> * * ( end auto-generated ) * * <h3>Advanced</h3> * Simplified method to open a Java InputStream. * <p> * This method is useful if you want to use the facilities provided * by PApplet to easily open things from the data folder or from a URL, * but want an InputStream object so that you can use other Java * methods to take more control of how the stream is read. * <p> * If the requested item doesn't exist, null is returned. * (Prior to 0096, die() would be called, killing the applet) * <p> * For 0096+, the "data" folder is exported intact with subfolders, * and openStream() properly handles subdirectories from the data folder * <p> * If not online, this will also check to see if the user is asking * for a file whose name isn't properly capitalized. This helps prevent * issues when a sketch is exported to the web, where case sensitivity * matters, as opposed to Windows and the Mac OS default where * case sensitivity is preserved but ignored. * <p> * It is strongly recommended that libraries use this method to open * data files, so that the loading sequence is handled in the same way * as functions like loadBytes(), loadImage(), etc. * <p> * The filename passed in can be: * <UL> * <LI>A URL, for instance openStream("http://processing.org/"); * <LI>A file in the sketch's data folder * <LI>Another file to be opened locally (when running as an application) * </UL> * * @webref input:files * @param filename the name of the file to use as input * @see PApplet#createOutput(String) * @see PApplet#selectOutput(String) * @see PApplet#selectInput(String) * */ public InputStream createInput(String filename) { InputStream input = createInputRaw(filename); if ((input != null) && filename.toLowerCase().endsWith(".gz")) { try { return new GZIPInputStream(input); } catch (IOException e) { e.printStackTrace(); return null; } } return input; } /** * Call openStream() without automatic gzip decompression. */ public InputStream createInputRaw(String filename) { InputStream stream = null; if (filename == null) return null; if (filename.length() == 0) { // an error will be called by the parent function //System.err.println("The filename passed to openStream() was empty."); return null; } // safe to check for this as a url first. this will prevent online // access logs from being spammed with GET /sketchfolder/http://blahblah if (filename.contains(":")) { // at least smells like URL try { URL url = new URL(filename); stream = url.openStream(); return stream; } catch (MalformedURLException mfue) { // not a url, that's fine } catch (FileNotFoundException fnfe) { // Java 1.5 likes to throw this when URL not available. (fix for 0119) // http://dev.processing.org/bugs/show_bug.cgi?id=403 } catch (IOException e) { // changed for 0117, shouldn't be throwing exception e.printStackTrace(); //System.err.println("Error downloading from URL " + filename); return null; //throw new RuntimeException("Error downloading from URL " + filename); } } // Moved this earlier than the getResourceAsStream() checks, because // calling getResourceAsStream() on a directory lists its contents. // http://dev.processing.org/bugs/show_bug.cgi?id=716 try { // First see if it's in a data folder. This may fail by throwing // a SecurityException. If so, this whole block will be skipped. File file = new File(dataPath(filename)); if (!file.exists()) { // next see if it's just in the sketch folder file = sketchFile(filename); } if (file.isDirectory()) { return null; } if (file.exists()) { try { // handle case sensitivity check String filePath = file.getCanonicalPath(); String filenameActual = new File(filePath).getName(); // make sure there isn't a subfolder prepended to the name String filenameShort = new File(filename).getName(); // if the actual filename is the same, but capitalized // differently, warn the user. //if (filenameActual.equalsIgnoreCase(filenameShort) && //!filenameActual.equals(filenameShort)) { if (!filenameActual.equals(filenameShort)) { throw new RuntimeException("This file is named " + filenameActual + " not " + filename + ". Rename the file " + "or change your code."); } } catch (IOException e) { } } // if this file is ok, may as well just load it stream = new FileInputStream(file); if (stream != null) return stream; // have to break these out because a general Exception might // catch the RuntimeException being thrown above } catch (IOException ioe) { } catch (SecurityException se) { } // Using getClassLoader() prevents java from converting dots // to slashes or requiring a slash at the beginning. // (a slash as a prefix means that it'll load from the root of // the jar, rather than trying to dig into the package location) ClassLoader cl = getClass().getClassLoader(); // by default, data files are exported to the root path of the jar. // (not the data folder) so check there first. stream = cl.getResourceAsStream("data/" + filename); if (stream != null) { String cn = stream.getClass().getName(); // this is an irritation of sun's java plug-in, which will return // a non-null stream for an object that doesn't exist. like all good // things, this is probably introduced in java 1.5. awesome! // http://dev.processing.org/bugs/show_bug.cgi?id=359 if (!cn.equals("sun.plugin.cache.EmptyInputStream")) { return stream; } } // When used with an online script, also need to check without the // data folder, in case it's not in a subfolder called 'data'. // http://dev.processing.org/bugs/show_bug.cgi?id=389 stream = cl.getResourceAsStream(filename); if (stream != null) { String cn = stream.getClass().getName(); if (!cn.equals("sun.plugin.cache.EmptyInputStream")) { return stream; } } // Finally, something special for the Internet Explorer users. Turns out // that we can't get files that are part of the same folder using the // methods above when using IE, so we have to resort to the old skool // getDocumentBase() from teh applet dayz. 1996, my brotha. try { URL base = getDocumentBase(); if (base != null) { URL url = new URL(base, filename); URLConnection conn = url.openConnection(); return conn.getInputStream(); // if (conn instanceof HttpURLConnection) { // HttpURLConnection httpConnection = (HttpURLConnection) conn; // // test for 401 result (HTTP only) // int responseCode = httpConnection.getResponseCode(); // } } } catch (Exception e) { } // IO or NPE or... // Now try it with a 'data' subfolder. getting kinda desperate for data... try { URL base = getDocumentBase(); if (base != null) { URL url = new URL(base, "data/" + filename); URLConnection conn = url.openConnection(); return conn.getInputStream(); } } catch (Exception e) { } try { // attempt to load from a local file, used when running as // an application, or as a signed applet try { // first try to catch any security exceptions try { stream = new FileInputStream(dataPath(filename)); if (stream != null) return stream; } catch (IOException e2) { } try { stream = new FileInputStream(sketchPath(filename)); if (stream != null) return stream; } catch (Exception e) { } // ignored try { stream = new FileInputStream(filename); if (stream != null) return stream; } catch (IOException e1) { } } catch (SecurityException se) { } // online, whups } catch (Exception e) { //die(e.getMessage(), e); e.printStackTrace(); } return null; } /** * @nowebref */ static public InputStream createInput(File file) { if (file == null) { throw new IllegalArgumentException("File passed to createInput() was null"); } try { InputStream input = new FileInputStream(file); if (file.getName().toLowerCase().endsWith(".gz")) { return new GZIPInputStream(input); } return input; } catch (IOException e) { System.err.println("Could not createInput() for " + file); e.printStackTrace(); return null; } } /** * ( begin auto-generated from loadBytes.xml ) * * Reads the contents of a file or url and places it in a byte array. If a * file is specified, it must be located in the sketch's "data" * directory/folder.<br /> * <br /> * The filename parameter can also be a URL to a file found online. For * security reasons, a Processing sketch found online can only download * files from the same server from which it came. Getting around this * restriction requires a <a * href="http://wiki.processing.org/w/Sign_an_Applet">signed applet</a>. * * ( end auto-generated ) * @webref input:files * @param filename name of a file in the data folder or a URL. * @see PApplet#loadStrings(String) * @see PApplet#saveStrings(String, String[]) * @see PApplet#saveBytes(String, byte[]) * */ public byte[] loadBytes(String filename) { InputStream is = createInput(filename); if (is != null) { byte[] outgoing = loadBytes(is); try { is.close(); } catch (IOException e) { e.printStackTrace(); // shouldn't happen } return outgoing; } System.err.println("The file \"" + filename + "\" " + "is missing or inaccessible, make sure " + "the URL is valid or that the file has been " + "added to your sketch and is readable."); return null; } /** * @nowebref */ static public byte[] loadBytes(InputStream input) { try { BufferedInputStream bis = new BufferedInputStream(input); ByteArrayOutputStream out = new ByteArrayOutputStream(); int c = bis.read(); while (c != -1) { out.write(c); c = bis.read(); } return out.toByteArray(); } catch (IOException e) { e.printStackTrace(); //throw new RuntimeException("Couldn't load bytes from stream"); } return null; } /** * @nowebref */ static public byte[] loadBytes(File file) { InputStream is = createInput(file); return loadBytes(is); } /** * @nowebref */ static public String[] loadStrings(File file) { InputStream is = createInput(file); if (is != null) { String[] outgoing = loadStrings(is); try { is.close(); } catch (IOException e) { e.printStackTrace(); } return outgoing; } return null; } /** * ( begin auto-generated from loadStrings.xml ) * * Reads the contents of a file or url and creates a String array of its * individual lines. If a file is specified, it must be located in the * sketch's "data" directory/folder.<br /> * <br /> * The filename parameter can also be a URL to a file found online. For * security reasons, a Processing sketch found online can only download * files from the same server from which it came. Getting around this * restriction requires a <a * href="http://wiki.processing.org/w/Sign_an_Applet">signed applet</a>. * <br /> * If the file is not available or an error occurs, <b>null</b> will be * returned and an error message will be printed to the console. The error * message does not halt the program, however the null value may cause a * NullPointerException if your code does not check whether the value * returned is null. * <br/> <br/> * Starting with Processing release 0134, all files loaded and saved by the * Processing API use UTF-8 encoding. In previous releases, the default * encoding for your platform was used, which causes problems when files * are moved to other platforms. * * ( end auto-generated ) * * <h3>Advanced</h3> * Load data from a file and shove it into a String array. * <p> * Exceptions are handled internally, when an error, occurs, an * exception is printed to the console and 'null' is returned, * but the program continues running. This is a tradeoff between * 1) showing the user that there was a problem but 2) not requiring * that all i/o code is contained in try/catch blocks, for the sake * of new users (or people who are just trying to get things done * in a "scripting" fashion. If you want to handle exceptions, * use Java methods for I/O. * * @webref input:files * @param filename name of the file or url to load * @see PApplet#loadBytes(String) * @see PApplet#saveStrings(String, String[]) * @see PApplet#saveBytes(String, byte[]) */ public String[] loadStrings(String filename) { InputStream is = createInput(filename); if (is != null) return loadStrings(is); System.err.println("The file \"" + filename + "\" " + "is missing or inaccessible, make sure " + "the URL is valid or that the file has been " + "added to your sketch and is readable."); return null; } /** * @nowebref */ static public String[] loadStrings(InputStream input) { try { BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8")); return loadStrings(reader); } catch (IOException e) { e.printStackTrace(); } return null; } static public String[] loadStrings(BufferedReader reader) { try { String lines[] = new String[100]; int lineCount = 0; String line = null; while ((line = reader.readLine()) != null) { if (lineCount == lines.length) { String temp[] = new String[lineCount << 1]; System.arraycopy(lines, 0, temp, 0, lineCount); lines = temp; } lines[lineCount++] = line; } reader.close(); if (lineCount == lines.length) { return lines; } // resize array to appropriate amount for these lines String output[] = new String[lineCount]; System.arraycopy(lines, 0, output, 0, lineCount); return output; } catch (IOException e) { e.printStackTrace(); //throw new RuntimeException("Error inside loadStrings()"); } return null; } ////////////////////////////////////////////////////////////// // FILE OUTPUT /** * ( begin auto-generated from createOutput.xml ) * * Similar to <b>createInput()</b>, this creates a Java <b>OutputStream</b> * for a given filename or path. The file will be created in the sketch * folder, or in the same folder as an exported application. * <br /><br /> * If the path does not exist, intermediate folders will be created. If an * exception occurs, it will be printed to the console, and <b>null</b> * will be returned. * <br /><br /> * This function is a convenience over the Java approach that requires you * to 1) create a FileOutputStream object, 2) determine the exact file * location, and 3) handle exceptions. Exceptions are handled internally by * the function, which is more appropriate for "sketch" projects. * <br /><br /> * If the output filename ends with <b>.gz</b>, the output will be * automatically GZIP compressed as it is written. * * ( end auto-generated ) * @webref output:files * @param filename name of the file to open * @see PApplet#createInput(String) * @see PApplet#selectOutput() */ public OutputStream createOutput(String filename) { return createOutput(saveFile(filename)); } /** * @nowebref */ static public OutputStream createOutput(File file) { try { createPath(file); // make sure the path exists FileOutputStream fos = new FileOutputStream(file); if (file.getName().toLowerCase().endsWith(".gz")) { return new GZIPOutputStream(fos); } return fos; } catch (IOException e) { e.printStackTrace(); } return null; } /** * ( begin auto-generated from saveStream.xml ) * * Save the contents of a stream to a file in the sketch folder. This is * basically <b>saveBytes(blah, loadBytes())</b>, but done more efficiently * (and with less confusing syntax).<br /> * <br /> * When using the <b>targetFile</b> parameter, it writes to a <b>File</b> * object for greater control over the file location. (Note that unlike * some other functions, this will not automatically compress or uncompress * gzip files.) * * ( end auto-generated ) * * @webref output:files * @param target name of the file to write to * @param source location to read from (a filename, path, or URL) * @see PApplet#createOutput(String) */ public boolean saveStream(String target, String source) { return saveStream(saveFile(target), source); } /** * Identical to the other saveStream(), but writes to a File * object, for greater control over the file location. * <p/> * Note that unlike other api methods, this will not automatically * compress or uncompress gzip files. */ public boolean saveStream(File target, String source) { return saveStream(target, createInputRaw(source)); } /** * @nowebref */ public boolean saveStream(String target, InputStream source) { return saveStream(saveFile(target), source); } /** * @nowebref */ static public boolean saveStream(File target, InputStream source) { File tempFile = null; try { File parentDir = target.getParentFile(); // make sure that this path actually exists before writing createPath(target); tempFile = File.createTempFile(target.getName(), null, parentDir); FileOutputStream targetStream = new FileOutputStream(tempFile); saveStream(targetStream, source); targetStream.close(); targetStream = null; if (target.exists()) { if (!target.delete()) { System.err.println("Could not replace " + target.getAbsolutePath() + "."); } } if (!tempFile.renameTo(target)) { System.err.println("Could not rename temporary file " + tempFile.getAbsolutePath()); return false; } return true; } catch (IOException e) { if (tempFile != null) { tempFile.delete(); } e.printStackTrace(); return false; } } /** * @nowebref */ static public void saveStream(OutputStream target, InputStream source) throws IOException { BufferedInputStream bis = new BufferedInputStream(source, 16384); BufferedOutputStream bos = new BufferedOutputStream(target); byte[] buffer = new byte[8192]; int bytesRead; while ((bytesRead = bis.read(buffer)) != -1) { bos.write(buffer, 0, bytesRead); } bos.flush(); } /** * ( begin auto-generated from saveBytes.xml ) * * Opposite of <b>loadBytes()</b>, will write an entire array of bytes to a * file. The data is saved in binary format. This file is saved to the * sketch's folder, which is opened by selecting "Show sketch folder" from * the "Sketch" menu.<br /> * <br /> * It is not possible to use saveXxxxx() functions inside a web browser * unless the sketch is <a * href="http://wiki.processing.org/w/Sign_an_Applet">signed applet</A>. To * save a file back to a server, see the <a * href="http://wiki.processing.org/w/Saving_files_to_a_web-server">save to * web</A> code snippet on the Processing Wiki. * * ( end auto-generated ) * * @webref output:files * @param filename name of the file to write to * @param data array of bytes to be written * @see PApplet#loadStrings(String) * @see PApplet#loadBytes(String) * @see PApplet#saveStrings(String, String[]) */ public void saveBytes(String filename, byte[] data) { saveBytes(saveFile(filename), data); } /** * @nowebref * Saves bytes to a specific File location specified by the user. */ static public void saveBytes(File file, byte[] data) { File tempFile = null; try { File parentDir = file.getParentFile(); tempFile = File.createTempFile(file.getName(), null, parentDir); OutputStream output = createOutput(tempFile); saveBytes(output, data); output.close(); output = null; if (file.exists()) { if (!file.delete()) { System.err.println("Could not replace " + file.getAbsolutePath()); } } if (!tempFile.renameTo(file)) { System.err.println("Could not rename temporary file " + tempFile.getAbsolutePath()); } } catch (IOException e) { System.err.println("error saving bytes to " + file); if (tempFile != null) { tempFile.delete(); } e.printStackTrace(); } } /** * @nowebref * Spews a buffer of bytes to an OutputStream. */ static public void saveBytes(OutputStream output, byte[] data) { try { output.write(data); output.flush(); } catch (IOException e) { e.printStackTrace(); } } // /** * ( begin auto-generated from saveStrings.xml ) * * Writes an array of strings to a file, one line per string. This file is * saved to the sketch's folder, which is opened by selecting "Show sketch * folder" from the "Sketch" menu.<br /> * <br /> * It is not possible to use saveXxxxx() functions inside a web browser * unless the sketch is <a * href="http://wiki.processing.org/w/Sign_an_Applet">signed applet</A>. To * save a file back to a server, see the <a * href="http://wiki.processing.org/w/Saving_files_to_a_web-server">save to * web</A> code snippet on the Processing Wiki.<br/> * <br/ > * Starting with Processing 1.0, all files loaded and saved by the * Processing API use UTF-8 encoding. In previous releases, the default * encoding for your platform was used, which causes problems when files * are moved to other platforms. * * ( end auto-generated ) * @webref output:files * @param filename filename for output * @param data string array to be written * @see PApplet#loadStrings(String) * @see PApplet#loadBytes(String) * @see PApplet#saveBytes(String, byte[]) */ public void saveStrings(String filename, String data[]) { saveStrings(saveFile(filename), data); } /** * @nowebref */ static public void saveStrings(File file, String data[]) { saveStrings(createOutput(file), data); } /** * @nowebref */ static public void saveStrings(OutputStream output, String[] data) { PrintWriter writer = createWriter(output); for (int i = 0; i < data.length; i++) { writer.println(data[i]); } writer.flush(); writer.close(); } ////////////////////////////////////////////////////////////// /** * Prepend the sketch folder path to the filename (or path) that is * passed in. External libraries should use this function to save to * the sketch folder. * <p/> * Note that when running as an applet inside a web browser, * the sketchPath will be set to null, because security restrictions * prevent applets from accessing that information. * <p/> * This will also cause an error if the sketch is not inited properly, * meaning that init() was never called on the PApplet when hosted * my some other main() or by other code. For proper use of init(), * see the examples in the main description text for PApplet. */ public String sketchPath(String where) { if (sketchPath == null) { return where; // throw new RuntimeException("The applet was not inited properly, " + // "or security restrictions prevented " + // "it from determining its path."); } // isAbsolute() could throw an access exception, but so will writing // to the local disk using the sketch path, so this is safe here. // for 0120, added a try/catch anyways. try { if (new File(where).isAbsolute()) return where; } catch (Exception e) { } return sketchPath + File.separator + where; } public File sketchFile(String where) { return new File(sketchPath(where)); } /** * Returns a path inside the applet folder to save to. Like sketchPath(), * but creates any in-between folders so that things save properly. * <p/> * All saveXxxx() functions use the path to the sketch folder, rather than * its data folder. Once exported, the data folder will be found inside the * jar file of the exported application or applet. In this case, it's not * possible to save data into the jar file, because it will often be running * from a server, or marked in-use if running from a local file system. * With this in mind, saving to the data path doesn't make sense anyway. * If you know you're running locally, and want to save to the data folder, * use <TT>saveXxxx("data/blah.dat")</TT>. */ public String savePath(String where) { if (where == null) return null; String filename = sketchPath(where); createPath(filename); return filename; } /** * Identical to savePath(), but returns a File object. */ public File saveFile(String where) { return new File(savePath(where)); } /** * Return a full path to an item in the data folder. * <p> * This is only available with applications, not applets or Android. * On Windows and Linux, this is simply the data folder, which is located * in the same directory as the EXE file and lib folders. On Mac OS X, this * is a path to the data folder buried inside Contents/Resources/Java. * For the latter point, that also means that the data folder should not be * considered writable. Use sketchPath() for now, or inputPath() and * outputPath() once they're available in the 2.0 release. * <p> * dataPath() is not supported with applets because applets have their data * folder wrapped into the JAR file. To read data from the data folder that * works with an applet, you should use other methods such as createInput(), * createReader(), or loadStrings(). */ public String dataPath(String where) { return dataFile(where).getAbsolutePath(); } /** * Return a full path to an item in the data folder as a File object. * See the dataPath() method for more information. */ public File dataFile(String where) { // isAbsolute() could throw an access exception, but so will writing // to the local disk using the sketch path, so this is safe here. File why = new File(where); if (why.isAbsolute()) return why; String jarPath = getClass().getProtectionDomain().getCodeSource().getLocation().getPath(); if (jarPath.contains("Contents/Resources/Java/")) { // The path will be URL encoded (%20 for spaces) coming from above // http://code.google.com/p/processing/issues/detail?id=1073 File containingFolder = new File(urlDecode(jarPath)).getParentFile(); File dataFolder = new File(containingFolder, "data"); return new File(dataFolder, where); } // Windows, Linux, or when not using a Mac OS X .app file return new File(sketchPath + File.separator + "data" + File.separator + where); } /** * On Windows and Linux, this is simply the data folder. On Mac OS X, this is * the path to the data folder buried inside Contents/Resources/Java */ // public File inputFile(String where) { // } // public String inputPath(String where) { // } /** * Takes a path and creates any in-between folders if they don't * already exist. Useful when trying to save to a subfolder that * may not actually exist. */ static public void createPath(String path) { createPath(new File(path)); } static public void createPath(File file) { try { String parent = file.getParent(); if (parent != null) { File unit = new File(parent); if (!unit.exists()) unit.mkdirs(); } } catch (SecurityException se) { System.err.println("You don't have permissions to create " + file.getAbsolutePath()); } } static public String getExtension(String filename) { String extension; String lower = filename.toLowerCase(); int dot = filename.lastIndexOf('.'); if (dot == -1) { extension = "unknown"; // no extension found } extension = lower.substring(dot + 1); // check for, and strip any parameters on the url, i.e. // filename.jpg?blah=blah&something=that int question = extension.indexOf('?'); if (question != -1) { extension = extension.substring(0, question); } return extension; } ////////////////////////////////////////////////////////////// // URL ENCODING static public String urlEncode(String str) { try { return URLEncoder.encode(str, "UTF-8"); } catch (UnsupportedEncodingException e) { // oh c'mon return null; } } static public String urlDecode(String str) { try { return URLDecoder.decode(str, "UTF-8"); } catch (UnsupportedEncodingException e) { // safe per the JDK source return null; } } ////////////////////////////////////////////////////////////// // SORT /** * ( begin auto-generated from sort.xml ) * * Sorts an array of numbers from smallest to largest and puts an array of * words in alphabetical order. The original array is not modified, a * re-ordered array is returned. The <b>count</b> parameter states the * number of elements to sort. For example if there are 12 elements in an * array and if count is the value 5, only the first five elements on the * array will be sorted. <!--As of release 0126, the alphabetical ordering * is case insensitive.--> * * ( end auto-generated ) * @webref data:array_functions * @param list array to sort * @see PApplet#reverse(boolean[]) */ static public byte[] sort(byte list[]) { return sort(list, list.length); } /** * @param count number of elements to sort, starting from 0 */ static public byte[] sort(byte[] list, int count) { byte[] outgoing = new byte[list.length]; System.arraycopy(list, 0, outgoing, 0, list.length); Arrays.sort(outgoing, 0, count); return outgoing; } static public char[] sort(char list[]) { return sort(list, list.length); } static public char[] sort(char[] list, int count) { char[] outgoing = new char[list.length]; System.arraycopy(list, 0, outgoing, 0, list.length); Arrays.sort(outgoing, 0, count); return outgoing; } static public int[] sort(int list[]) { return sort(list, list.length); } static public int[] sort(int[] list, int count) { int[] outgoing = new int[list.length]; System.arraycopy(list, 0, outgoing, 0, list.length); Arrays.sort(outgoing, 0, count); return outgoing; } static public float[] sort(float list[]) { return sort(list, list.length); } static public float[] sort(float[] list, int count) { float[] outgoing = new float[list.length]; System.arraycopy(list, 0, outgoing, 0, list.length); Arrays.sort(outgoing, 0, count); return outgoing; } static public String[] sort(String list[]) { return sort(list, list.length); } static public String[] sort(String[] list, int count) { String[] outgoing = new String[list.length]; System.arraycopy(list, 0, outgoing, 0, list.length); Arrays.sort(outgoing, 0, count); return outgoing; } ////////////////////////////////////////////////////////////// // ARRAY UTILITIES /** * ( begin auto-generated from arrayCopy.xml ) * * Copies an array (or part of an array) to another array. The <b>src</b> * array is copied to the <b>dst</b> array, beginning at the position * specified by <b>srcPos</b> and into the position specified by * <b>dstPos</b>. The number of elements to copy is determined by * <b>length</b>. The simplified version with two arguments copies an * entire array to another of the same size. It is equivalent to * "arrayCopy(src, 0, dst, 0, src.length)". This function is far more * efficient for copying array data than iterating through a <b>for</b> and * copying each element. * * ( end auto-generated ) * @webref data:array_functions * @param src the source array * @param srcPosition starting position in the source array * @param dst the destination array of the same data type as the source array * @param dstPosition starting position in the destination array * @param length number of array elements to be copied * @see PApplet#concat(boolean[], boolean[]) */ static public void arrayCopy(Object src, int srcPosition, Object dst, int dstPosition, int length) { System.arraycopy(src, srcPosition, dst, dstPosition, length); } /** * Convenience method for arraycopy(). * Identical to <CODE>arraycopy(src, 0, dst, 0, length);</CODE> */ static public void arrayCopy(Object src, Object dst, int length) { System.arraycopy(src, 0, dst, 0, length); } /** * Shortcut to copy the entire contents of * the source into the destination array. * Identical to <CODE>arraycopy(src, 0, dst, 0, src.length);</CODE> */ static public void arrayCopy(Object src, Object dst) { System.arraycopy(src, 0, dst, 0, Array.getLength(src)); } // /** * @deprecated Use arrayCopy() instead. */ static public void arraycopy(Object src, int srcPosition, Object dst, int dstPosition, int length) { System.arraycopy(src, srcPosition, dst, dstPosition, length); } /** * @deprecated Use arrayCopy() instead. */ static public void arraycopy(Object src, Object dst, int length) { System.arraycopy(src, 0, dst, 0, length); } /** * @deprecated Use arrayCopy() instead. */ static public void arraycopy(Object src, Object dst) { System.arraycopy(src, 0, dst, 0, Array.getLength(src)); } /** * ( begin auto-generated from expand.xml ) * * Increases the size of an array. By default, this function doubles the * size of the array, but the optional <b>newSize</b> parameter provides * precise control over the increase in size. * <br/> <br/> * When using an array of objects, the data returned from the function must * be cast to the object array's data type. For example: <em>SomeClass[] * items = (SomeClass[]) expand(originalArray)</em>. * * ( end auto-generated ) * * @webref data:array_functions * @param list the array to expand * @see PApplet#shorten(boolean[]) */ static public boolean[] expand(boolean list[]) { return expand(list, list.length << 1); } /** * @param newSize new size for the array */ static public boolean[] expand(boolean list[], int newSize) { boolean temp[] = new boolean[newSize]; System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } static public byte[] expand(byte list[]) { return expand(list, list.length << 1); } static public byte[] expand(byte list[], int newSize) { byte temp[] = new byte[newSize]; System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } static public char[] expand(char list[]) { return expand(list, list.length << 1); } static public char[] expand(char list[], int newSize) { char temp[] = new char[newSize]; System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } static public int[] expand(int list[]) { return expand(list, list.length << 1); } static public int[] expand(int list[], int newSize) { int temp[] = new int[newSize]; System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } static public long[] expand(long list[]) { return expand(list, list.length << 1); } static public long[] expand(long list[], int newSize) { long temp[] = new long[newSize]; System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } static public float[] expand(float list[]) { return expand(list, list.length << 1); } static public float[] expand(float list[], int newSize) { float temp[] = new float[newSize]; System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } static public double[] expand(double list[]) { return expand(list, list.length << 1); } static public double[] expand(double list[], int newSize) { double temp[] = new double[newSize]; System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } static public String[] expand(String list[]) { return expand(list, list.length << 1); } static public String[] expand(String list[], int newSize) { String temp[] = new String[newSize]; // in case the new size is smaller than list.length System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } /** * @nowebref */ static public Object expand(Object array) { return expand(array, Array.getLength(array) << 1); } static public Object expand(Object list, int newSize) { Class<?> type = list.getClass().getComponentType(); Object temp = Array.newInstance(type, newSize); System.arraycopy(list, 0, temp, 0, Math.min(Array.getLength(list), newSize)); return temp; } // contract() has been removed in revision 0124, use subset() instead. // (expand() is also functionally equivalent) /** * ( begin auto-generated from append.xml ) * * Expands an array by one element and adds data to the new position. The * datatype of the <b>element</b> parameter must be the same as the * datatype of the array. * <br/> <br/> * When using an array of objects, the data returned from the function must * be cast to the object array's data type. For example: <em>SomeClass[] * items = (SomeClass[]) append(originalArray, element)</em>. * * ( end auto-generated ) * * @webref data:array_functions * @param array array to append * @param value new data for the array * @see PApplet#shorten(boolean[]) * @see PApplet#expand(boolean[]) */ static public byte[] append(byte array[], byte value) { array = expand(array, array.length + 1); array[array.length-1] = value; return array; } static public char[] append(char array[], char value) { array = expand(array, array.length + 1); array[array.length-1] = value; return array; } static public int[] append(int array[], int value) { array = expand(array, array.length + 1); array[array.length-1] = value; return array; } static public float[] append(float array[], float value) { array = expand(array, array.length + 1); array[array.length-1] = value; return array; } static public String[] append(String array[], String value) { array = expand(array, array.length + 1); array[array.length-1] = value; return array; } static public Object append(Object array, Object value) { int length = Array.getLength(array); array = expand(array, length + 1); Array.set(array, length, value); return array; } /** * ( begin auto-generated from shorten.xml ) * * Decreases an array by one element and returns the shortened array. * <br/> <br/> * When using an array of objects, the data returned from the function must * be cast to the object array's data type. For example: <em>SomeClass[] * items = (SomeClass[]) shorten(originalArray)</em>. * * ( end auto-generated ) * * @webref data:array_functions * @param list array to shorten * @see PApplet#append(byte[], byte) * @see PApplet#expand(boolean[]) */ static public boolean[] shorten(boolean list[]) { return subset(list, 0, list.length-1); } static public byte[] shorten(byte list[]) { return subset(list, 0, list.length-1); } static public char[] shorten(char list[]) { return subset(list, 0, list.length-1); } static public int[] shorten(int list[]) { return subset(list, 0, list.length-1); } static public float[] shorten(float list[]) { return subset(list, 0, list.length-1); } static public String[] shorten(String list[]) { return subset(list, 0, list.length-1); } static public Object shorten(Object list) { int length = Array.getLength(list); return subset(list, 0, length - 1); } /** * ( begin auto-generated from splice.xml ) * * Inserts a value or array of values into an existing array. The first two * parameters must be of the same datatype. The <b>array</b> parameter * defines the array which will be modified and the second parameter * defines the data which will be inserted. * <br/> <br/> * When using an array of objects, the data returned from the function must * be cast to the object array's data type. For example: <em>SomeClass[] * items = (SomeClass[]) splice(array1, array2, index)</em>. * * ( end auto-generated ) * @webref data:array_functions * @param list array to splice into * @param value value to be spliced in * @param index position in the array from which to insert data * @see PApplet#concat(boolean[], boolean[]) * @see PApplet#subset(boolean[], int, int) */ static final public boolean[] splice(boolean list[], boolean value, int index) { boolean outgoing[] = new boolean[list.length + 1]; System.arraycopy(list, 0, outgoing, 0, index); outgoing[index] = value; System.arraycopy(list, index, outgoing, index + 1, list.length - index); return outgoing; } static final public boolean[] splice(boolean list[], boolean value[], int index) { boolean outgoing[] = new boolean[list.length + value.length]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(value, 0, outgoing, index, value.length); System.arraycopy(list, index, outgoing, index + value.length, list.length - index); return outgoing; } static final public byte[] splice(byte list[], byte value, int index) { byte outgoing[] = new byte[list.length + 1]; System.arraycopy(list, 0, outgoing, 0, index); outgoing[index] = value; System.arraycopy(list, index, outgoing, index + 1, list.length - index); return outgoing; } static final public byte[] splice(byte list[], byte value[], int index) { byte outgoing[] = new byte[list.length + value.length]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(value, 0, outgoing, index, value.length); System.arraycopy(list, index, outgoing, index + value.length, list.length - index); return outgoing; } static final public char[] splice(char list[], char value, int index) { char outgoing[] = new char[list.length + 1]; System.arraycopy(list, 0, outgoing, 0, index); outgoing[index] = value; System.arraycopy(list, index, outgoing, index + 1, list.length - index); return outgoing; } static final public char[] splice(char list[], char value[], int index) { char outgoing[] = new char[list.length + value.length]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(value, 0, outgoing, index, value.length); System.arraycopy(list, index, outgoing, index + value.length, list.length - index); return outgoing; } static final public int[] splice(int list[], int value, int index) { int outgoing[] = new int[list.length + 1]; System.arraycopy(list, 0, outgoing, 0, index); outgoing[index] = value; System.arraycopy(list, index, outgoing, index + 1, list.length - index); return outgoing; } static final public int[] splice(int list[], int value[], int index) { int outgoing[] = new int[list.length + value.length]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(value, 0, outgoing, index, value.length); System.arraycopy(list, index, outgoing, index + value.length, list.length - index); return outgoing; } static final public float[] splice(float list[], float value, int index) { float outgoing[] = new float[list.length + 1]; System.arraycopy(list, 0, outgoing, 0, index); outgoing[index] = value; System.arraycopy(list, index, outgoing, index + 1, list.length - index); return outgoing; } static final public float[] splice(float list[], float value[], int index) { float outgoing[] = new float[list.length + value.length]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(value, 0, outgoing, index, value.length); System.arraycopy(list, index, outgoing, index + value.length, list.length - index); return outgoing; } static final public String[] splice(String list[], String value, int index) { String outgoing[] = new String[list.length + 1]; System.arraycopy(list, 0, outgoing, 0, index); outgoing[index] = value; System.arraycopy(list, index, outgoing, index + 1, list.length - index); return outgoing; } static final public String[] splice(String list[], String value[], int index) { String outgoing[] = new String[list.length + value.length]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(value, 0, outgoing, index, value.length); System.arraycopy(list, index, outgoing, index + value.length, list.length - index); return outgoing; } static final public Object splice(Object list, Object value, int index) { Object[] outgoing = null; int length = Array.getLength(list); // check whether item being spliced in is an array if (value.getClass().getName().charAt(0) == '[') { int vlength = Array.getLength(value); outgoing = new Object[length + vlength]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(value, 0, outgoing, index, vlength); System.arraycopy(list, index, outgoing, index + vlength, length - index); } else { outgoing = new Object[length + 1]; System.arraycopy(list, 0, outgoing, 0, index); Array.set(outgoing, index, value); System.arraycopy(list, index, outgoing, index + 1, length - index); } return outgoing; } static public boolean[] subset(boolean list[], int start) { return subset(list, start, list.length - start); } /** * ( begin auto-generated from subset.xml ) * * Extracts an array of elements from an existing array. The <b>array</b> * parameter defines the array from which the elements will be copied and * the <b>offset</b> and <b>length</b> parameters determine which elements * to extract. If no <b>length</b> is given, elements will be extracted * from the <b>offset</b> to the end of the array. When specifying the * <b>offset</b> remember the first array element is 0. This function does * not change the source array. * <br/> <br/> * When using an array of objects, the data returned from the function must * be cast to the object array's data type. For example: <em>SomeClass[] * items = (SomeClass[]) subset(originalArray, 0, 4)</em>. * * ( end auto-generated ) * @webref data:array_functions * @param list array to extract from * @param start position to begin * @param count number of values to extract * @see PApplet#splice(boolean[], boolean, int) */ static public boolean[] subset(boolean list[], int start, int count) { boolean output[] = new boolean[count]; System.arraycopy(list, start, output, 0, count); return output; } static public byte[] subset(byte list[], int start) { return subset(list, start, list.length - start); } static public byte[] subset(byte list[], int start, int count) { byte output[] = new byte[count]; System.arraycopy(list, start, output, 0, count); return output; } static public char[] subset(char list[], int start) { return subset(list, start, list.length - start); } static public char[] subset(char list[], int start, int count) { char output[] = new char[count]; System.arraycopy(list, start, output, 0, count); return output; } static public int[] subset(int list[], int start) { return subset(list, start, list.length - start); } static public int[] subset(int list[], int start, int count) { int output[] = new int[count]; System.arraycopy(list, start, output, 0, count); return output; } static public float[] subset(float list[], int start) { return subset(list, start, list.length - start); } static public float[] subset(float list[], int start, int count) { float output[] = new float[count]; System.arraycopy(list, start, output, 0, count); return output; } static public String[] subset(String list[], int start) { return subset(list, start, list.length - start); } static public String[] subset(String list[], int start, int count) { String output[] = new String[count]; System.arraycopy(list, start, output, 0, count); return output; } static public Object subset(Object list, int start) { int length = Array.getLength(list); return subset(list, start, length - start); } static public Object subset(Object list, int start, int count) { Class<?> type = list.getClass().getComponentType(); Object outgoing = Array.newInstance(type, count); System.arraycopy(list, start, outgoing, 0, count); return outgoing; } /** * ( begin auto-generated from concat.xml ) * * Concatenates two arrays. For example, concatenating the array { 1, 2, 3 * } and the array { 4, 5, 6 } yields { 1, 2, 3, 4, 5, 6 }. Both parameters * must be arrays of the same datatype. * <br/> <br/> * When using an array of objects, the data returned from the function must * be cast to the object array's data type. For example: <em>SomeClass[] * items = (SomeClass[]) concat(array1, array2)</em>. * * ( end auto-generated ) * @webref data:array_functions * @param a first array to concatenate * @param b second array to concatenate * @see PApplet#splice(boolean[], boolean, int) * @see PApplet#arrayCopy(Object, int, Object, int, int) */ static public boolean[] concat(boolean a[], boolean b[]) { boolean c[] = new boolean[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } static public byte[] concat(byte a[], byte b[]) { byte c[] = new byte[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } static public char[] concat(char a[], char b[]) { char c[] = new char[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } static public int[] concat(int a[], int b[]) { int c[] = new int[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } static public float[] concat(float a[], float b[]) { float c[] = new float[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } static public String[] concat(String a[], String b[]) { String c[] = new String[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } static public Object concat(Object a, Object b) { Class<?> type = a.getClass().getComponentType(); int alength = Array.getLength(a); int blength = Array.getLength(b); Object outgoing = Array.newInstance(type, alength + blength); System.arraycopy(a, 0, outgoing, 0, alength); System.arraycopy(b, 0, outgoing, alength, blength); return outgoing; } // /** * ( begin auto-generated from reverse.xml ) * * Reverses the order of an array. * * ( end auto-generated ) * @webref data:array_functions * @param list booleans[], bytes[], chars[], ints[], floats[], or Strings[] * @see PApplet#sort(String[], int) */ static public boolean[] reverse(boolean list[]) { boolean outgoing[] = new boolean[list.length]; int length1 = list.length - 1; for (int i = 0; i < list.length; i++) { outgoing[i] = list[length1 - i]; } return outgoing; } static public byte[] reverse(byte list[]) { byte outgoing[] = new byte[list.length]; int length1 = list.length - 1; for (int i = 0; i < list.length; i++) { outgoing[i] = list[length1 - i]; } return outgoing; } static public char[] reverse(char list[]) { char outgoing[] = new char[list.length]; int length1 = list.length - 1; for (int i = 0; i < list.length; i++) { outgoing[i] = list[length1 - i]; } return outgoing; } static public int[] reverse(int list[]) { int outgoing[] = new int[list.length]; int length1 = list.length - 1; for (int i = 0; i < list.length; i++) { outgoing[i] = list[length1 - i]; } return outgoing; } static public float[] reverse(float list[]) { float outgoing[] = new float[list.length]; int length1 = list.length - 1; for (int i = 0; i < list.length; i++) { outgoing[i] = list[length1 - i]; } return outgoing; } static public String[] reverse(String list[]) { String outgoing[] = new String[list.length]; int length1 = list.length - 1; for (int i = 0; i < list.length; i++) { outgoing[i] = list[length1 - i]; } return outgoing; } static public Object reverse(Object list) { Class<?> type = list.getClass().getComponentType(); int length = Array.getLength(list); Object outgoing = Array.newInstance(type, length); for (int i = 0; i < length; i++) { Array.set(outgoing, i, Array.get(list, (length - 1) - i)); } return outgoing; } ////////////////////////////////////////////////////////////// // STRINGS /** * ( begin auto-generated from trim.xml ) * * Removes whitespace characters from the beginning and end of a String. In * addition to standard whitespace characters such as space, carriage * return, and tab, this function also removes the Unicode "nbsp" character. * * ( end auto-generated ) * @webref data:string_functions * @param str any string * @see PApplet#split(String, String) * @see PApplet#join(String[], char) */ static public String trim(String str) { return str.replace('\u00A0', ' ').trim(); } /** * @param array a String array */ static public String[] trim(String[] array) { String[] outgoing = new String[array.length]; for (int i = 0; i < array.length; i++) { if (array[i] != null) { outgoing[i] = array[i].replace('\u00A0', ' ').trim(); } } return outgoing; } /** * ( begin auto-generated from join.xml ) * * Combines an array of Strings into one String, each separated by the * character(s) used for the <b>separator</b> parameter. To join arrays of * ints or floats, it's necessary to first convert them to strings using * <b>nf()</b> or <b>nfs()</b>. * * ( end auto-generated ) * @webref data:string_functions * @param list array of Strings * @param separator char or String to be placed between each item * @see PApplet#split(String, String) * @see PApplet#trim(String) * @see PApplet#nf(float, int, int) * @see PApplet#nfs(float, int, int) */ static public String join(String[] list, char separator) { return join(list, String.valueOf(separator)); } static public String join(String[] list, String separator) { StringBuffer buffer = new StringBuffer(); for (int i = 0; i < list.length; i++) { if (i != 0) buffer.append(separator); buffer.append(list[i]); } return buffer.toString(); } static public String[] splitTokens(String value) { return splitTokens(value, WHITESPACE); } /** * ( begin auto-generated from splitTokens.xml ) * * The splitTokens() function splits a String at one or many character * "tokens." The <b>tokens</b> parameter specifies the character or * characters to be used as a boundary. * <br/> <br/> * If no <b>tokens</b> character is specified, any whitespace character is * used to split. Whitespace characters include tab (\\t), line feed (\\n), * carriage return (\\r), form feed (\\f), and space. To convert a String * to an array of integers or floats, use the datatype conversion functions * <b>int()</b> and <b>float()</b> to convert the array of Strings. * * ( end auto-generated ) * @webref data:string_functions * @param value the String to be split * @param delim list of individual characters that will be used as separators * @see PApplet#split(String, String) * @see PApplet#join(String[], String) * @see PApplet#trim(String) */ static public String[] splitTokens(String value, String delim) { StringTokenizer toker = new StringTokenizer(value, delim); String pieces[] = new String[toker.countTokens()]; int index = 0; while (toker.hasMoreTokens()) { pieces[index++] = toker.nextToken(); } return pieces; } /** * ( begin auto-generated from split.xml ) * * The split() function breaks a string into pieces using a character or * string as the divider. The <b>delim</b> parameter specifies the * character or characters that mark the boundaries between each piece. A * String[] array is returned that contains each of the pieces. * <br/> <br/> * If the result is a set of numbers, you can convert the String[] array to * to a float[] or int[] array using the datatype conversion functions * <b>int()</b> and <b>float()</b> (see example above). * <br/> <br/> * The <b>splitTokens()</b> function works in a similar fashion, except * that it splits using a range of characters instead of a specific * character or sequence. * <!-- /><br /> * This function uses regular expressions to determine how the <b>delim</b> * parameter divides the <b>str</b> parameter. Therefore, if you use * characters such parentheses and brackets that are used with regular * expressions as a part of the <b>delim</b> parameter, you'll need to put * two blackslashes (\\\\) in front of the character (see example above). * You can read more about <a * href="http://en.wikipedia.org/wiki/Regular_expression">regular * expressions</a> and <a * href="http://en.wikipedia.org/wiki/Escape_character">escape * characters</a> on Wikipedia. * --> * * ( end auto-generated ) * @webref data:string_functions * @usage web_application * @param value the String to be split * @param delim the character or String used to separate the data */ static public String[] split(String value, char delim) { // do this so that the exception occurs inside the user's // program, rather than appearing to be a bug inside split() if (value == null) return null; //return split(what, String.valueOf(delim)); // huh char chars[] = value.toCharArray(); int splitCount = 0; //1; for (int i = 0; i < chars.length; i++) { if (chars[i] == delim) splitCount++; } // make sure that there is something in the input string //if (chars.length > 0) { // if the last char is a delimeter, get rid of it.. //if (chars[chars.length-1] == delim) splitCount--; // on second thought, i don't agree with this, will disable //} if (splitCount == 0) { String splits[] = new String[1]; splits[0] = new String(value); return splits; } //int pieceCount = splitCount + 1; String splits[] = new String[splitCount + 1]; int splitIndex = 0; int startIndex = 0; for (int i = 0; i < chars.length; i++) { if (chars[i] == delim) { splits[splitIndex++] = new String(chars, startIndex, i-startIndex); startIndex = i + 1; } } //if (startIndex != chars.length) { splits[splitIndex] = new String(chars, startIndex, chars.length-startIndex); //} return splits; } static public String[] split(String value, String delim) { ArrayList<String> items = new ArrayList<String>(); int index; int offset = 0; while ((index = value.indexOf(delim, offset)) != -1) { items.add(value.substring(offset, index)); offset = index + delim.length(); } items.add(value.substring(offset)); String[] outgoing = new String[items.size()]; items.toArray(outgoing); return outgoing; } static protected HashMap<String, Pattern> matchPatterns; static Pattern matchPattern(String regexp) { Pattern p = null; if (matchPatterns == null) { matchPatterns = new HashMap<String, Pattern>(); } else { p = matchPatterns.get(regexp); } if (p == null) { if (matchPatterns.size() == 10) { // Just clear out the match patterns here if more than 10 are being // used. It's not terribly efficient, but changes that you have >10 // different match patterns are very slim, unless you're doing // something really tricky (like custom match() methods), in which // case match() won't be efficient anyway. (And you should just be // using your own Java code.) The alternative is using a queue here, // but that's a silly amount of work for negligible benefit. matchPatterns.clear(); } p = Pattern.compile(regexp, Pattern.MULTILINE | Pattern.DOTALL); matchPatterns.put(regexp, p); } return p; } /** * ( begin auto-generated from match.xml ) * * The match() function is used to apply a regular expression to a piece of * text, and return matching groups (elements found inside parentheses) as * a String array. No match will return null. If no groups are specified in * the regexp, but the sequence matches, an array of length one (with the * matched text as the first element of the array) will be returned.<br /> * <br /> * To use the function, first check to see if the result is null. If the * result is null, then the sequence did not match. If the sequence did * match, an array is returned. * If there are groups (specified by sets of parentheses) in the regexp, * then the contents of each will be returned in the array. * Element [0] of a regexp match returns the entire matching string, and * the match groups start at element [1] (the first group is [1], the * second [2], and so on).<br /> * <br /> * The syntax can be found in the reference for Java's <a * href="http://download.oracle.com/javase/6/docs/api/">Pattern</a> class. * For regular expression syntax, read the <a * href="http://download.oracle.com/javase/tutorial/essential/regex/">Java * Tutorial</a> on the topic. * * ( end auto-generated ) * @webref data:string_functions * @param str the String to be searched * @param regexp the regexp to be used for matching * @see PApplet#matchAll(String, String) * @see PApplet#split(String, String) * @see PApplet#splitTokens(String, String) * @see PApplet#join(String[], String) * @see PApplet#trim(String) */ static public String[] match(String str, String regexp) { Pattern p = matchPattern(regexp); Matcher m = p.matcher(str); if (m.find()) { int count = m.groupCount() + 1; String[] groups = new String[count]; for (int i = 0; i < count; i++) { groups[i] = m.group(i); } return groups; } return null; } /** * ( begin auto-generated from matchAll.xml ) * * This function is used to apply a regular expression to a piece of text, * and return a list of matching groups (elements found inside parentheses) * as a two-dimensional String array. No matches will return null. If no * groups are specified in the regexp, but the sequence matches, a two * dimensional array is still returned, but the second dimension is only of * length one.<br /> * <br /> * To use the function, first check to see if the result is null. If the * result is null, then the sequence did not match at all. If the sequence * did match, a 2D array is returned. If there are groups (specified by * sets of parentheses) in the regexp, then the contents of each will be * returned in the array. * Assuming, a loop with counter variable i, element [i][0] of a regexp * match returns the entire matching string, and the match groups start at * element [i][1] (the first group is [i][1], the second [i][2], and so * on).<br /> * <br /> * The syntax can be found in the reference for Java's <a * href="http://download.oracle.com/javase/6/docs/api/">Pattern</a> class. * For regular expression syntax, read the <a * href="http://download.oracle.com/javase/tutorial/essential/regex/">Java * Tutorial</a> on the topic. * * ( end auto-generated ) * @webref data:string_functions * @param str the String to be searched * @param regexp the regexp to be used for matching * @see PApplet#match(String, String) * @see PApplet#split(String, String) * @see PApplet#splitTokens(String, String) * @see PApplet#join(String[], String) * @see PApplet#trim(String) */ static public String[][] matchAll(String str, String regexp) { Pattern p = matchPattern(regexp); Matcher m = p.matcher(str); ArrayList<String[]> results = new ArrayList<String[]>(); int count = m.groupCount() + 1; while (m.find()) { String[] groups = new String[count]; for (int i = 0; i < count; i++) { groups[i] = m.group(i); } results.add(groups); } if (results.isEmpty()) { return null; } String[][] matches = new String[results.size()][count]; for (int i = 0; i < matches.length; i++) { matches[i] = results.get(i); } return matches; } ////////////////////////////////////////////////////////////// // CASTING FUNCTIONS, INSERTED BY PREPROC /** * Convert a char to a boolean. 'T', 't', and '1' will become the * boolean value true, while 'F', 'f', or '0' will become false. */ /* static final public boolean parseBoolean(char what) { return ((what == 't') || (what == 'T') || (what == '1')); } */ /** * <p>Convert an integer to a boolean. Because of how Java handles upgrading * numbers, this will also cover byte and char (as they will upgrade to * an int without any sort of explicit cast).</p> * <p>The preprocessor will convert boolean(what) to parseBoolean(what).</p> * @return false if 0, true if any other number */ static final public boolean parseBoolean(int what) { return (what != 0); } /* // removed because this makes no useful sense static final public boolean parseBoolean(float what) { return (what != 0); } */ /** * Convert the string "true" or "false" to a boolean. * @return true if 'what' is "true" or "TRUE", false otherwise */ static final public boolean parseBoolean(String what) { return new Boolean(what).booleanValue(); } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /* // removed, no need to introduce strange syntax from other languages static final public boolean[] parseBoolean(char what[]) { boolean outgoing[] = new boolean[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = ((what[i] == 't') || (what[i] == 'T') || (what[i] == '1')); } return outgoing; } */ /** * Convert a byte array to a boolean array. Each element will be * evaluated identical to the integer case, where a byte equal * to zero will return false, and any other value will return true. * @return array of boolean elements */ /* static final public boolean[] parseBoolean(byte what[]) { boolean outgoing[] = new boolean[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (what[i] != 0); } return outgoing; } */ /** * Convert an int array to a boolean array. An int equal * to zero will return false, and any other value will return true. * @return array of boolean elements */ static final public boolean[] parseBoolean(int what[]) { boolean outgoing[] = new boolean[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (what[i] != 0); } return outgoing; } /* // removed, not necessary... if necessary, convert to int array first static final public boolean[] parseBoolean(float what[]) { boolean outgoing[] = new boolean[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (what[i] != 0); } return outgoing; } */ static final public boolean[] parseBoolean(String what[]) { boolean outgoing[] = new boolean[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = new Boolean(what[i]).booleanValue(); } return outgoing; } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static final public byte parseByte(boolean what) { return what ? (byte)1 : 0; } static final public byte parseByte(char what) { return (byte) what; } static final public byte parseByte(int what) { return (byte) what; } static final public byte parseByte(float what) { return (byte) what; } /* // nixed, no precedent static final public byte[] parseByte(String what) { // note: array[] return what.getBytes(); } */ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static final public byte[] parseByte(boolean what[]) { byte outgoing[] = new byte[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = what[i] ? (byte)1 : 0; } return outgoing; } static final public byte[] parseByte(char what[]) { byte outgoing[] = new byte[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (byte) what[i]; } return outgoing; } static final public byte[] parseByte(int what[]) { byte outgoing[] = new byte[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (byte) what[i]; } return outgoing; } static final public byte[] parseByte(float what[]) { byte outgoing[] = new byte[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (byte) what[i]; } return outgoing; } /* static final public byte[][] parseByte(String what[]) { // note: array[][] byte outgoing[][] = new byte[what.length][]; for (int i = 0; i < what.length; i++) { outgoing[i] = what[i].getBytes(); } return outgoing; } */ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /* static final public char parseChar(boolean what) { // 0/1 or T/F ? return what ? 't' : 'f'; } */ static final public char parseChar(byte what) { return (char) (what & 0xff); } static final public char parseChar(int what) { return (char) what; } /* static final public char parseChar(float what) { // nonsensical return (char) what; } static final public char[] parseChar(String what) { // note: array[] return what.toCharArray(); } */ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /* static final public char[] parseChar(boolean what[]) { // 0/1 or T/F ? char outgoing[] = new char[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = what[i] ? 't' : 'f'; } return outgoing; } */ static final public char[] parseChar(byte what[]) { char outgoing[] = new char[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (char) (what[i] & 0xff); } return outgoing; } static final public char[] parseChar(int what[]) { char outgoing[] = new char[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (char) what[i]; } return outgoing; } /* static final public char[] parseChar(float what[]) { // nonsensical char outgoing[] = new char[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (char) what[i]; } return outgoing; } static final public char[][] parseChar(String what[]) { // note: array[][] char outgoing[][] = new char[what.length][]; for (int i = 0; i < what.length; i++) { outgoing[i] = what[i].toCharArray(); } return outgoing; } */ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static final public int parseInt(boolean what) { return what ? 1 : 0; } /** * Note that parseInt() will un-sign a signed byte value. */ static final public int parseInt(byte what) { return what & 0xff; } /** * Note that parseInt('5') is unlike String in the sense that it * won't return 5, but the ascii value. This is because ((int) someChar) * returns the ascii value, and parseInt() is just longhand for the cast. */ static final public int parseInt(char what) { return what; } /** * Same as floor(), or an (int) cast. */ static final public int parseInt(float what) { return (int) what; } /** * Parse a String into an int value. Returns 0 if the value is bad. */ static final public int parseInt(String what) { return parseInt(what, 0); } /** * Parse a String to an int, and provide an alternate value that * should be used when the number is invalid. */ static final public int parseInt(String what, int otherwise) { try { int offset = what.indexOf('.'); if (offset == -1) { return Integer.parseInt(what); } else { return Integer.parseInt(what.substring(0, offset)); } } catch (NumberFormatException e) { } return otherwise; } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static final public int[] parseInt(boolean what[]) { int list[] = new int[what.length]; for (int i = 0; i < what.length; i++) { list[i] = what[i] ? 1 : 0; } return list; } static final public int[] parseInt(byte what[]) { // note this unsigns int list[] = new int[what.length]; for (int i = 0; i < what.length; i++) { list[i] = (what[i] & 0xff); } return list; } static final public int[] parseInt(char what[]) { int list[] = new int[what.length]; for (int i = 0; i < what.length; i++) { list[i] = what[i]; } return list; } static public int[] parseInt(float what[]) { int inties[] = new int[what.length]; for (int i = 0; i < what.length; i++) { inties[i] = (int)what[i]; } return inties; } /** * Make an array of int elements from an array of String objects. * If the String can't be parsed as a number, it will be set to zero. * * String s[] = { "1", "300", "44" }; * int numbers[] = parseInt(s); * * numbers will contain { 1, 300, 44 } */ static public int[] parseInt(String what[]) { return parseInt(what, 0); } /** * Make an array of int elements from an array of String objects. * If the String can't be parsed as a number, its entry in the * array will be set to the value of the "missing" parameter. * * String s[] = { "1", "300", "apple", "44" }; * int numbers[] = parseInt(s, 9999); * * numbers will contain { 1, 300, 9999, 44 } */ static public int[] parseInt(String what[], int missing) { int output[] = new int[what.length]; for (int i = 0; i < what.length; i++) { try { output[i] = Integer.parseInt(what[i]); } catch (NumberFormatException e) { output[i] = missing; } } return output; } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /* static final public float parseFloat(boolean what) { return what ? 1 : 0; } */ /** * Convert an int to a float value. Also handles bytes because of * Java's rules for upgrading values. */ static final public float parseFloat(int what) { // also handles byte return what; } static final public float parseFloat(String what) { return parseFloat(what, Float.NaN); } static final public float parseFloat(String what, float otherwise) { try { return new Float(what).floatValue(); } catch (NumberFormatException e) { } return otherwise; } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /* static final public float[] parseFloat(boolean what[]) { float floaties[] = new float[what.length]; for (int i = 0; i < what.length; i++) { floaties[i] = what[i] ? 1 : 0; } return floaties; } static final public float[] parseFloat(char what[]) { float floaties[] = new float[what.length]; for (int i = 0; i < what.length; i++) { floaties[i] = (char) what[i]; } return floaties; } */ static final public float[] parseByte(byte what[]) { float floaties[] = new float[what.length]; for (int i = 0; i < what.length; i++) { floaties[i] = what[i]; } return floaties; } static final public float[] parseFloat(int what[]) { float floaties[] = new float[what.length]; for (int i = 0; i < what.length; i++) { floaties[i] = what[i]; } return floaties; } static final public float[] parseFloat(String what[]) { return parseFloat(what, Float.NaN); } static final public float[] parseFloat(String what[], float missing) { float output[] = new float[what.length]; for (int i = 0; i < what.length; i++) { try { output[i] = new Float(what[i]).floatValue(); } catch (NumberFormatException e) { output[i] = missing; } } return output; } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static final public String str(boolean x) { return String.valueOf(x); } static final public String str(byte x) { return String.valueOf(x); } static final public String str(char x) { return String.valueOf(x); } static final public String str(int x) { return String.valueOf(x); } static final public String str(float x) { return String.valueOf(x); } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static final public String[] str(boolean x[]) { String s[] = new String[x.length]; for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]); return s; } static final public String[] str(byte x[]) { String s[] = new String[x.length]; for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]); return s; } static final public String[] str(char x[]) { String s[] = new String[x.length]; for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]); return s; } static final public String[] str(int x[]) { String s[] = new String[x.length]; for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]); return s; } static final public String[] str(float x[]) { String s[] = new String[x.length]; for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]); return s; } ////////////////////////////////////////////////////////////// // INT NUMBER FORMATTING /** * Integer number formatter. */ static private NumberFormat int_nf; static private int int_nf_digits; static private boolean int_nf_commas; static public String[] nf(int num[], int digits) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nf(num[i], digits); } return formatted; } /** * ( begin auto-generated from nf.xml ) * * Utility function for formatting numbers into strings. There are two * versions, one for formatting floats and one for formatting ints. The * values for the <b>digits</b>, <b>left</b>, and <b>right</b> parameters * should always be positive integers.<br /><br />As shown in the above * example, <b>nf()</b> is used to add zeros to the left and/or right of a * number. This is typically for aligning a list of numbers. To * <em>remove</em> digits from a floating-point number, use the * <b>int()</b>, <b>ceil()</b>, <b>floor()</b>, or <b>round()</b> * functions. * * ( end auto-generated ) * @webref data:string_functions * @param num the number(s) to format * @param digits number of digits to pad with zero * @see PApplet#nfs(float, int, int) * @see PApplet#nfp(float, int, int) * @see PApplet#nfc(float, int) * @see PApplet#int(float) */ static public String nf(int num, int digits) { if ((int_nf != null) && (int_nf_digits == digits) && !int_nf_commas) { return int_nf.format(num); } int_nf = NumberFormat.getInstance(); int_nf.setGroupingUsed(false); // no commas int_nf_commas = false; int_nf.setMinimumIntegerDigits(digits); int_nf_digits = digits; return int_nf.format(num); } /** * ( begin auto-generated from nfc.xml ) * * Utility function for formatting numbers into strings and placing * appropriate commas to mark units of 1000. There are two versions, one * for formatting ints and one for formatting an array of ints. The value * for the <b>digits</b> parameter should always be a positive integer. * <br/> <br/> * For a non-US locale, this will insert periods instead of commas, or * whatever is apprioriate for that region. * * ( end auto-generated ) * @webref data:string_functions * @param num the number(s) to format * @see PApplet#nf(float, int, int) * @see PApplet#nfp(float, int, int) * @see PApplet#nfc(float, int) */ static public String[] nfc(int num[]) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nfc(num[i]); } return formatted; } /** * nfc() or "number format with commas". This is an unfortunate misnomer * because in locales where a comma is not the separator for numbers, it * won't actually be outputting a comma, it'll use whatever makes sense for * the locale. */ static public String nfc(int num) { if ((int_nf != null) && (int_nf_digits == 0) && int_nf_commas) { return int_nf.format(num); } int_nf = NumberFormat.getInstance(); int_nf.setGroupingUsed(true); int_nf_commas = true; int_nf.setMinimumIntegerDigits(0); int_nf_digits = 0; return int_nf.format(num); } /** * number format signed (or space) * Formats a number but leaves a blank space in the front * when it's positive so that it can be properly aligned with * numbers that have a negative sign in front of them. */ /** * ( begin auto-generated from nfs.xml ) * * Utility function for formatting numbers into strings. Similar to * <b>nf()</b> but leaves a blank space in front of positive numbers so * they align with negative numbers in spite of the minus symbol. There are * two versions, one for formatting floats and one for formatting ints. The * values for the <b>digits</b>, <b>left</b>, and <b>right</b> parameters * should always be positive integers. * * ( end auto-generated ) * @webref data:string_functions * @param num the number(s) to format * @param digits number of digits to pad with zeroes * @see PApplet#nf(float, int, int) * @see PApplet#nfp(float, int, int) * @see PApplet#nfc(float, int) */ static public String nfs(int num, int digits) { return (num < 0) ? nf(num, digits) : (' ' + nf(num, digits)); } static public String[] nfs(int num[], int digits) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nfs(num[i], digits); } return formatted; } // /** * number format positive (or plus) * Formats a number, always placing a - or + sign * in the front when it's negative or positive. */ /** * ( begin auto-generated from nfp.xml ) * * Utility function for formatting numbers into strings. Similar to * <b>nf()</b> but puts a "+" in front of positive numbers and a "-" in * front of negative numbers. There are two versions, one for formatting * floats and one for formatting ints. The values for the <b>digits</b>, * <b>left</b>, and <b>right</b> parameters should always be positive integers. * * ( end auto-generated ) * @webref data:string_functions * @param num the number(s) to format * @param digits number of digits to pad with zeroes * @see PApplet#nf(float, int, int) * @see PApplet#nfs(float, int, int) * @see PApplet#nfc(float, int) */ static public String nfp(int num, int digits) { return (num < 0) ? nf(num, digits) : ('+' + nf(num, digits)); } static public String[] nfp(int num[], int digits) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nfp(num[i], digits); } return formatted; } ////////////////////////////////////////////////////////////// // FLOAT NUMBER FORMATTING static private NumberFormat float_nf; static private int float_nf_left, float_nf_right; static private boolean float_nf_commas; static public String[] nf(float num[], int left, int right) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nf(num[i], left, right); } return formatted; } /** * @param num[] the number(s) to format * @param left number of digits to the left of the decimal point * @param right number of digits to the right of the decimal point */ static public String nf(float num, int left, int right) { if ((float_nf != null) && (float_nf_left == left) && (float_nf_right == right) && !float_nf_commas) { return float_nf.format(num); } float_nf = NumberFormat.getInstance(); float_nf.setGroupingUsed(false); float_nf_commas = false; if (left != 0) float_nf.setMinimumIntegerDigits(left); if (right != 0) { float_nf.setMinimumFractionDigits(right); float_nf.setMaximumFractionDigits(right); } float_nf_left = left; float_nf_right = right; return float_nf.format(num); } /** * @param num[] the number(s) to format * @param right number of digits to the right of the decimal point */ static public String[] nfc(float num[], int right) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nfc(num[i], right); } return formatted; } static public String nfc(float num, int right) { if ((float_nf != null) && (float_nf_left == 0) && (float_nf_right == right) && float_nf_commas) { return float_nf.format(num); } float_nf = NumberFormat.getInstance(); float_nf.setGroupingUsed(true); float_nf_commas = true; if (right != 0) { float_nf.setMinimumFractionDigits(right); float_nf.setMaximumFractionDigits(right); } float_nf_left = 0; float_nf_right = right; return float_nf.format(num); } /** * @param num[] the number(s) to format * @param left the number of digits to the left of the decimal point * @param right the number of digits to the right of the decimal point */ static public String[] nfs(float num[], int left, int right) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nfs(num[i], left, right); } return formatted; } static public String nfs(float num, int left, int right) { return (num < 0) ? nf(num, left, right) : (' ' + nf(num, left, right)); } /** * @param left the number of digits to the left of the decimal point * @param right the number of digits to the right of the decimal point */ static public String[] nfp(float num[], int left, int right) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nfp(num[i], left, right); } return formatted; } static public String nfp(float num, int left, int right) { return (num < 0) ? nf(num, left, right) : ('+' + nf(num, left, right)); } ////////////////////////////////////////////////////////////// // HEX/BINARY CONVERSION /** * ( begin auto-generated from hex.xml ) * * Converts a byte, char, int, or color to a String containing the * equivalent hexadecimal notation. For example color(0, 102, 153) will * convert to the String "FF006699". This function can help make your geeky * debugging sessions much happier. * <br/> <br/> * Note that the maximum number of digits is 8, because an int value can * only represent up to 32 bits. Specifying more than eight digits will * simply shorten the string to eight anyway. * * ( end auto-generated ) * @webref data:conversion * @param value the value to convert * @see PApplet#unhex(String) * @see PApplet#binary(byte) * @see PApplet#unbinary(String) */ static final public String hex(byte value) { return hex(value, 2); } static final public String hex(char value) { return hex(value, 4); } static final public String hex(int value) { return hex(value, 8); } /** * @param digits the number of digits (maximum 8) */ static final public String hex(int value, int digits) { String stuff = Integer.toHexString(value).toUpperCase(); if (digits > 8) { digits = 8; } int length = stuff.length(); if (length > digits) { return stuff.substring(length - digits); } else if (length < digits) { return "00000000".substring(8 - (digits-length)) + stuff; } return stuff; } /** * ( begin auto-generated from unhex.xml ) * * Converts a String representation of a hexadecimal number to its * equivalent integer value. * * ( end auto-generated ) * * @webref data:conversion * @param value String to convert to an integer * @see PApplet#hex(int, int) * @see PApplet#binary(byte) * @see PApplet#unbinary(String) */ static final public int unhex(String value) { // has to parse as a Long so that it'll work for numbers bigger than 2^31 return (int) (Long.parseLong(value, 16)); } // /** * Returns a String that contains the binary value of a byte. * The returned value will always have 8 digits. */ static final public String binary(byte value) { return binary(value, 8); } /** * Returns a String that contains the binary value of a char. * The returned value will always have 16 digits because chars * are two bytes long. */ static final public String binary(char value) { return binary(value, 16); } /** * Returns a String that contains the binary value of an int. The length * depends on the size of the number itself. If you want a specific number * of digits use binary(int what, int digits) to specify how many. */ static final public String binary(int value) { return binary(value, 32); } /* * Returns a String that contains the binary value of an int. * The digits parameter determines how many digits will be used. */ /** * ( begin auto-generated from binary.xml ) * * Converts a byte, char, int, or color to a String containing the * equivalent binary notation. For example color(0, 102, 153, 255) will * convert to the String "11111111000000000110011010011001". This function * can help make your geeky debugging sessions much happier. * <br/> <br/> * Note that the maximum number of digits is 32, because an int value can * only represent up to 32 bits. Specifying more than 32 digits will simply * shorten the string to 32 anyway. * * ( end auto-generated ) * @webref data:conversion * @param value value to convert * @param digits number of digits to return * @see PApplet#unbinary(String) * @see PApplet#hex(int,int) * @see PApplet#unhex(String) */ static final public String binary(int value, int digits) { String stuff = Integer.toBinaryString(value); if (digits > 32) { digits = 32; } int length = stuff.length(); if (length > digits) { return stuff.substring(length - digits); } else if (length < digits) { int offset = 32 - (digits-length); return "00000000000000000000000000000000".substring(offset) + stuff; } return stuff; } /** * ( begin auto-generated from unbinary.xml ) * * Converts a String representation of a binary number to its equivalent * integer value. For example, unbinary("00001000") will return 8. * * ( end auto-generated ) * @webref data:conversion * @param value String to convert to an integer * @see PApplet#binary(byte) * @see PApplet#hex(int,int) * @see PApplet#unhex(String) */ static final public int unbinary(String value) { return Integer.parseInt(value, 2); } ////////////////////////////////////////////////////////////// // COLOR FUNCTIONS // moved here so that they can work without // the graphics actually being instantiated (outside setup) /** * ( begin auto-generated from color.xml ) * * Creates colors for storing in variables of the <b>color</b> datatype. * The parameters are interpreted as RGB or HSB values depending on the * current <b>colorMode()</b>. The default mode is RGB values from 0 to 255 * and therefore, the function call <b>color(255, 204, 0)</b> will return a * bright yellow color. More about how colors are stored can be found in * the reference for the <a href="color_datatype.html">color</a> datatype. * * ( end auto-generated ) * @webref color:creating_reading * @param gray number specifying value between white and black * @see PApplet#colorMode(int) */ public final int color(int gray) { if (g == null) { if (gray > 255) gray = 255; else if (gray < 0) gray = 0; return 0xff000000 | (gray << 16) | (gray << 8) | gray; } return g.color(gray); } /** * @nowebref * @param fgray number specifying value between white and black */ public final int color(float fgray) { if (g == null) { int gray = (int) fgray; if (gray > 255) gray = 255; else if (gray < 0) gray = 0; return 0xff000000 | (gray << 16) | (gray << 8) | gray; } return g.color(fgray); } /** * As of 0116 this also takes color(#FF8800, alpha) * @param alpha relative to current color range */ public final int color(int gray, int alpha) { if (g == null) { if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0; if (gray > 255) { // then assume this is actually a #FF8800 return (alpha << 24) | (gray & 0xFFFFFF); } else { //if (gray > 255) gray = 255; else if (gray < 0) gray = 0; return (alpha << 24) | (gray << 16) | (gray << 8) | gray; } } return g.color(gray, alpha); } /** * @nowebref */ public final int color(float fgray, float falpha) { if (g == null) { int gray = (int) fgray; int alpha = (int) falpha; if (gray > 255) gray = 255; else if (gray < 0) gray = 0; if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0; return 0xff000000 | (gray << 16) | (gray << 8) | gray; } return g.color(fgray, falpha); } /** * @param v1 red or hue values relative to the current color range * @param v2 green or saturation values relative to the current color range * @param v3 blue or brightness values relative to the current color range */ public final int color(int v1, int v2, int v3) { if (g == null) { if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0; if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0; if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0; return 0xff000000 | (v1 << 16) | (v2 << 8) | v3; } return g.color(v1, v2, v3); } public final int color(int v1, int v2, int v3, int alpha) { if (g == null) { if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0; if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0; if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0; if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0; return (alpha << 24) | (v1 << 16) | (v2 << 8) | v3; } return g.color(v1, v2, v3, alpha); } public final int color(float v1, float v2, float v3) { if (g == null) { if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0; if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0; if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0; return 0xff000000 | ((int)v1 << 16) | ((int)v2 << 8) | (int)v3; } return g.color(v1, v2, v3); } public final int color(float v1, float v2, float v3, float alpha) { if (g == null) { if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0; if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0; if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0; if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0; return ((int)alpha << 24) | ((int)v1 << 16) | ((int)v2 << 8) | (int)v3; } return g.color(v1, v2, v3, alpha); } static public int blendColor(int c1, int c2, int mode) { return PImage.blendColor(c1, c2, mode); } ////////////////////////////////////////////////////////////// // MAIN /** * Set this sketch to communicate its state back to the PDE. * <p/> * This uses the stderr stream to write positions of the window * (so that it will be saved by the PDE for the next run) and * notify on quit. See more notes in the Worker class. */ public void setupExternalMessages() { frame.addComponentListener(new ComponentAdapter() { @Override public void componentMoved(ComponentEvent e) { Point where = ((Frame) e.getSource()).getLocation(); System.err.println(PApplet.EXTERNAL_MOVE + " " + where.x + " " + where.y); System.err.flush(); // doesn't seem to help or hurt } }); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { // System.err.println(PApplet.EXTERNAL_QUIT); // System.err.flush(); // important // System.exit(0); exit(); // don't quit, need to just shut everything down (0133) } }); } /** * Set up a listener that will fire proper component resize events * in cases where frame.setResizable(true) is called. */ public void setupFrameResizeListener() { frame.addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { // Ignore bad resize events fired during setup to fix // http://dev.processing.org/bugs/show_bug.cgi?id=341 // This should also fix the blank screen on Linux bug // http://dev.processing.org/bugs/show_bug.cgi?id=282 if (frame.isResizable()) { // might be multiple resize calls before visible (i.e. first // when pack() is called, then when it's resized for use). // ignore them because it's not the user resizing things. Frame farm = (Frame) e.getComponent(); if (farm.isVisible()) { Insets insets = farm.getInsets(); Dimension windowSize = farm.getSize(); Rectangle newBounds = new Rectangle(insets.left, insets.top, windowSize.width - insets.left - insets.right, windowSize.height - insets.top - insets.bottom); Rectangle oldBounds = getBounds(); if (!newBounds.equals(oldBounds)) { // the ComponentListener in PApplet will handle calling size() setBounds(newBounds); } } } } }); } // /** // * GIF image of the Processing logo. // */ // static public final byte[] ICON_IMAGE = { // 71, 73, 70, 56, 57, 97, 16, 0, 16, 0, -77, 0, 0, 0, 0, 0, -1, -1, -1, 12, // 12, 13, -15, -15, -14, 45, 57, 74, 54, 80, 111, 47, 71, 97, 62, 88, 117, // 1, 14, 27, 7, 41, 73, 15, 52, 85, 2, 31, 55, 4, 54, 94, 18, 69, 109, 37, // 87, 126, -1, -1, -1, 33, -7, 4, 1, 0, 0, 15, 0, 44, 0, 0, 0, 0, 16, 0, 16, // 0, 0, 4, 122, -16, -107, 114, -86, -67, 83, 30, -42, 26, -17, -100, -45, // 56, -57, -108, 48, 40, 122, -90, 104, 67, -91, -51, 32, -53, 77, -78, -100, // 47, -86, 12, 76, -110, -20, -74, -101, 97, -93, 27, 40, 20, -65, 65, 48, // -111, 99, -20, -112, -117, -123, -47, -105, 24, 114, -112, 74, 69, 84, 25, // 93, 88, -75, 9, 46, 2, 49, 88, -116, -67, 7, -19, -83, 60, 38, 3, -34, 2, // 66, -95, 27, -98, 13, 4, -17, 55, 33, 109, 11, 11, -2, -128, 121, 123, 62, // 91, 120, -128, 127, 122, 115, 102, 2, 119, 0, -116, -113, -119, 6, 102, // 121, -108, -126, 5, 18, 6, 4, -102, -101, -100, 114, 15, 17, 0, 59 // }; static ArrayList<Image> iconImages; protected void setIconImage(Frame frame) { // On OS X, this only affects what shows up in the dock when minimized. // So this is actually a step backwards. Brilliant. if (platform != MACOSX) { //Image image = Toolkit.getDefaultToolkit().createImage(ICON_IMAGE); //frame.setIconImage(image); try { if (iconImages == null) { iconImages = new ArrayList<Image>(); final int[] sizes = { 16, 32, 48, 64 }; for (int sz : sizes) { URL url = getClass().getResource("/icon/icon-" + sz + ".png"); Image image = Toolkit.getDefaultToolkit().getImage(url); iconImages.add(image); //iconImages.add(Toolkit.getLibImage("icons/pde-" + sz + ".png", frame)); } } frame.setIconImages(iconImages); } catch (Exception e) { //e.printStackTrace(); // more or less harmless; don't spew errors } } } // Not gonna do this dynamically, only on startup. Too much headache. // public void fullscreen() { // if (frame != null) { // if (PApplet.platform == MACOSX) { // japplemenubar.JAppleMenuBar.hide(); // } // GraphicsConfiguration gc = frame.getGraphicsConfiguration(); // Rectangle rect = gc.getBounds(); //// GraphicsDevice device = gc.getDevice(); // frame.setBounds(rect.x, rect.y, rect.width, rect.height); // } // } /** * main() method for running this class from the command line. * <p> * <B>The options shown here are not yet finalized and will be * changing over the next several releases.</B> * <p> * The simplest way to turn and applet into an application is to * add the following code to your program: * <PRE>static public void main(String args[]) { * PApplet.main("YourSketchName", args); * }</PRE> * This will properly launch your applet from a double-clickable * .jar or from the command line. * <PRE> * Parameters useful for launching or also used by the PDE: * * --location=x,y upper-lefthand corner of where the applet * should appear on screen. if not used, * the default is to center on the main screen. * * --full-screen put the applet into full screen "present" mode. * * --hide-stop use to hide the stop button in situations where * you don't want to allow users to exit. also * see the FAQ on information for capturing the ESC * key when running in presentation mode. * * --stop-color=#xxxxxx color of the 'stop' text used to quit an * sketch when it's in present mode. * * --bgcolor=#xxxxxx background color of the window. * * --sketch-path location of where to save files from functions * like saveStrings() or saveFrame(). defaults to * the folder that the java application was * launched from, which means if this isn't set by * the pde, everything goes into the same folder * as processing.exe. * * --display=n set what display should be used by this sketch. * displays are numbered starting from 0. * * Parameters used by Processing when running via the PDE * * --external set when the applet is being used by the PDE * * --editor-location=x,y position of the upper-lefthand corner of the * editor window, for placement of applet window * </PRE> */ static public void main(final String[] args) { runSketch(args, null); } /** * Convenience method so that PApplet.main("YourSketch") launches a sketch, * rather than having to wrap it into a String array. * @param mainClass name of the class to load (with package if any) */ static public void main(final String mainClass) { main(mainClass, null); } /** * Convenience method so that PApplet.main("YourSketch", args) launches a * sketch, rather than having to wrap it into a String array, and appending * the 'args' array when not null. * @param mainClass name of the class to load (with package if any) * @param args command line arguments to pass to the sketch */ static public void main(final String mainClass, final String[] passedArgs) { String[] args = new String[] { mainClass }; if (passedArgs != null) { args = concat(args, passedArgs); } runSketch(args, null); } static public void runSketch(final String args[], final PApplet constructedApplet) { // Disable abyssmally slow Sun renderer on OS X 10.5. if (platform == MACOSX) { // Only run this on OS X otherwise it can cause a permissions error. // http://dev.processing.org/bugs/show_bug.cgi?id=976 System.setProperty("apple.awt.graphics.UseQuartz", String.valueOf(useQuartz)); } // Doesn't seem to do much to help avoid flicker System.setProperty("sun.awt.noerasebackground", "true"); // This doesn't do anything. // if (platform == WINDOWS) { // // For now, disable the D3D renderer on Java 6u10 because // // it causes problems with Present mode. // // http://dev.processing.org/bugs/show_bug.cgi?id=1009 // System.setProperty("sun.java2d.d3d", "false"); // } if (args.length < 1) { System.err.println("Usage: PApplet <appletname>"); System.err.println("For additional options, " + "see the Javadoc for PApplet"); System.exit(1); } // EventQueue.invokeLater(new Runnable() { // public void run() { // runSketchEDT(args, constructedApplet); // } // }); // } // // // static public void runSketchEDT(final String args[], final PApplet constructedApplet) { boolean external = false; int[] location = null; int[] editorLocation = null; String name = null; boolean present = false; // boolean exclusive = false; // Color backgroundColor = Color.BLACK; Color backgroundColor = null; //Color.BLACK; Color stopColor = Color.GRAY; GraphicsDevice displayDevice = null; boolean hideStop = false; String param = null, value = null; // try to get the user folder. if running under java web start, // this may cause a security exception if the code is not signed. // http://processing.org/discourse/yabb_beta/YaBB.cgi?board=Integrate;action=display;num=1159386274 String folder = null; try { folder = System.getProperty("user.dir"); } catch (Exception e) { } int argIndex = 0; while (argIndex < args.length) { int equals = args[argIndex].indexOf('='); if (equals != -1) { param = args[argIndex].substring(0, equals); value = args[argIndex].substring(equals + 1); if (param.equals(ARGS_EDITOR_LOCATION)) { external = true; editorLocation = parseInt(split(value, ',')); } else if (param.equals(ARGS_DISPLAY)) { int deviceIndex = Integer.parseInt(value); GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice devices[] = environment.getScreenDevices(); if ((deviceIndex >= 0) && (deviceIndex < devices.length)) { displayDevice = devices[deviceIndex]; } else { System.err.println("Display " + value + " does not exist, " + "using the default display instead."); for (int i = 0; i < devices.length; i++) { System.err.println(i + " is " + devices[i]); } } } else if (param.equals(ARGS_BGCOLOR)) { if (value.charAt(0) == '#') value = value.substring(1); backgroundColor = new Color(Integer.parseInt(value, 16)); } else if (param.equals(ARGS_STOP_COLOR)) { if (value.charAt(0) == '#') value = value.substring(1); stopColor = new Color(Integer.parseInt(value, 16)); } else if (param.equals(ARGS_SKETCH_FOLDER)) { folder = value; } else if (param.equals(ARGS_LOCATION)) { location = parseInt(split(value, ',')); } } else { if (args[argIndex].equals(ARGS_PRESENT)) { // keep for compatability present = true; } else if (args[argIndex].equals(ARGS_FULL_SCREEN)) { present = true; // } else if (args[argIndex].equals(ARGS_EXCLUSIVE)) { // exclusive = true; } else if (args[argIndex].equals(ARGS_HIDE_STOP)) { hideStop = true; } else if (args[argIndex].equals(ARGS_EXTERNAL)) { external = true; } else { name = args[argIndex]; break; // because of break, argIndex won't increment again } } argIndex++; } // Now that sketch path is passed in args after the sketch name // it's not set in the above loop(the above loop breaks after // finding sketch name). So setting sketch path here. for (int i = 0; i < args.length; i++) { if(args[i].startsWith(ARGS_SKETCH_FOLDER)){ folder = args[i].substring(args[i].indexOf('=') + 1); //System.err.println("SF set " + folder); } } // Set this property before getting into any GUI init code //System.setProperty("com.apple.mrj.application.apple.menu.about.name", name); // This )*)(*@#$ Apple crap don't work no matter where you put it // (static method of the class, at the top of main, wherever) if (displayDevice == null) { GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment(); displayDevice = environment.getDefaultScreenDevice(); } Frame frame = new Frame(displayDevice.getDefaultConfiguration()); frame.setBackground(new Color(0xCC, 0xCC, 0xCC)); // default Processing gray // JFrame frame = new JFrame(displayDevice.getDefaultConfiguration()); /* Frame frame = null; if (displayDevice != null) { frame = new Frame(displayDevice.getDefaultConfiguration()); } else { frame = new Frame(); } */ //Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); // remove the grow box by default // users who want it back can call frame.setResizable(true) // frame.setResizable(false); // moved later (issue #467) final PApplet applet; if (constructedApplet != null) { applet = constructedApplet; } else { try { Class<?> c = Thread.currentThread().getContextClassLoader().loadClass(name); applet = (PApplet) c.newInstance(); } catch (Exception e) { throw new RuntimeException(e); } } // Set the trimmings around the image applet.setIconImage(frame); frame.setTitle(name); // frame.setIgnoreRepaint(true); // does nothing // frame.addComponentListener(new ComponentAdapter() { // public void componentResized(ComponentEvent e) { // Component c = e.getComponent(); //// Rectangle bounds = c.getBounds(); // System.out.println(" " + c.getName() + " wants to be: " + c.getSize()); // } // }); // frame.addComponentListener(new ComponentListener() { // // public void componentShown(ComponentEvent e) { // debug("frame: " + e); // debug(" applet valid? " + applet.isValid()); //// ((PGraphicsJava2D) applet.g).redraw(); // } // // public void componentResized(ComponentEvent e) { // println("frame: " + e + " " + applet.frame.getInsets()); // Insets insets = applet.frame.getInsets(); // int wide = e.getComponent().getWidth() - (insets.left + insets.right); // int high = e.getComponent().getHeight() - (insets.top + insets.bottom); // if (applet.getWidth() != wide || applet.getHeight() != high) { // debug("Frame.componentResized() setting applet size " + wide + " " + high); // applet.setSize(wide, high); // } // } // // public void componentMoved(ComponentEvent e) { // //println("frame: " + e + " " + applet.frame.getInsets()); // Insets insets = applet.frame.getInsets(); // int wide = e.getComponent().getWidth() - (insets.left + insets.right); // int high = e.getComponent().getHeight() - (insets.top + insets.bottom); // //applet.g.setsi // if (applet.getWidth() != wide || applet.getHeight() != high) { // debug("Frame.componentMoved() setting applet size " + wide + " " + high); // applet.setSize(wide, high); // } // } // // public void componentHidden(ComponentEvent e) { // debug("frame: " + e); // } // }); // A handful of things that need to be set before init/start. applet.frame = frame; applet.sketchPath = folder; // If the applet doesn't call for full screen, but the command line does, // enable it. Conversely, if the command line does not, don't disable it. // applet.fullScreen |= present; // Query the applet to see if it wants to be full screen all the time. present |= applet.sketchFullScreen(); // pass everything after the class name in as args to the sketch itself // (fixed for 2.0a5, this was just subsetting by 1, which didn't skip opts) applet.args = PApplet.subset(args, argIndex + 1); applet.external = external; // Need to save the window bounds at full screen, // because pack() will cause the bounds to go to zero. // http://dev.processing.org/bugs/show_bug.cgi?id=923 Rectangle screenRect = displayDevice.getDefaultConfiguration().getBounds(); // DisplayMode doesn't work here, because we can't get the upper-left // corner of the display, which is important for multi-display setups. // Sketch has already requested to be the same as the screen's // width and height, so let's roll with full screen mode. if (screenRect.width == applet.sketchWidth() && screenRect.height == applet.sketchHeight()) { present = true; } // For 0149, moving this code (up to the pack() method) before init(). // For OpenGL (and perhaps other renderers in the future), a peer is // needed before a GLDrawable can be created. So pack() needs to be // called on the Frame before applet.init(), which itself calls size(), // and launches the Thread that will kick off setup(). // http://dev.processing.org/bugs/show_bug.cgi?id=891 // http://dev.processing.org/bugs/show_bug.cgi?id=908 if (present) { // if (platform == MACOSX) { // // Call some native code to remove the menu bar on OS X. Not necessary // // on Linux and Windows, who are happy to make full screen windows. // japplemenubar.JAppleMenuBar.hide(); // } frame.setUndecorated(true); if (backgroundColor != null) { frame.setBackground(backgroundColor); } // if (exclusive) { // displayDevice.setFullScreenWindow(frame); // // this trashes the location of the window on os x // //frame.setExtendedState(java.awt.Frame.MAXIMIZED_BOTH); // fullScreenRect = frame.getBounds(); // } else { frame.setBounds(screenRect); frame.setVisible(true); // } } frame.setLayout(null); frame.add(applet); if (present) { frame.invalidate(); } else { frame.pack(); } // insufficient, places the 100x100 sketches offset strangely //frame.validate(); // disabling resize has to happen after pack() to avoid apparent Apple bug // http://code.google.com/p/processing/issues/detail?id=467 frame.setResizable(false); applet.init(); // applet.start(); // Wait until the applet has figured out its width. // In a static mode app, this will be after setup() has completed, // and the empty draw() has set "finished" to true. // TODO make sure this won't hang if the applet has an exception. while (applet.defaultSize && !applet.finished) { //System.out.println("default size"); try { Thread.sleep(5); } catch (InterruptedException e) { //System.out.println("interrupt"); } } // // If 'present' wasn't already set, but the applet initializes // // to full screen, attempt to make things full screen anyway. // if (!present && // applet.width == screenRect.width && // applet.height == screenRect.height) { // // bounds will be set below, but can't change to setUndecorated() now // present = true; // } // // Opting not to do this, because we can't remove the decorations on the // // window at this point. And re-opening a new winodw is a lot of mess. // // Better all around to just encourage the use of sketchFullScreen() // // or cmd/ctrl-shift-R in the PDE. if (present) { if (platform == MACOSX) { // Call some native code to remove the menu bar on OS X. Not necessary // on Linux and Windows, who are happy to make full screen windows. japplemenubar.JAppleMenuBar.hide(); } // After the pack(), the screen bounds are gonna be 0s frame.setBounds(screenRect); applet.setBounds((screenRect.width - applet.width) / 2, (screenRect.height - applet.height) / 2, applet.width, applet.height); if (!hideStop) { Label label = new Label("stop"); label.setForeground(stopColor); label.addMouseListener(new MouseAdapter() { @Override public void mousePressed(java.awt.event.MouseEvent e) { System.exit(0); } }); frame.add(label); Dimension labelSize = label.getPreferredSize(); // sometimes shows up truncated on mac //System.out.println("label width is " + labelSize.width); labelSize = new Dimension(100, labelSize.height); label.setSize(labelSize); label.setLocation(20, screenRect.height - labelSize.height - 20); } // not always running externally when in present mode if (external) { applet.setupExternalMessages(); } } else { // if not presenting // can't do pack earlier cuz present mode don't like it // (can't go full screen with a frame after calling pack) // frame.pack(); // get insets. get more. Insets insets = frame.getInsets(); int windowW = Math.max(applet.width, MIN_WINDOW_WIDTH) + insets.left + insets.right; int windowH = Math.max(applet.height, MIN_WINDOW_HEIGHT) + insets.top + insets.bottom; frame.setSize(windowW, windowH); if (location != null) { // a specific location was received from the Runner // (applet has been run more than once, user placed window) frame.setLocation(location[0], location[1]); } else if (external && editorLocation != null) { int locationX = editorLocation[0] - 20; int locationY = editorLocation[1]; if (locationX - windowW > 10) { // if it fits to the left of the window frame.setLocation(locationX - windowW, locationY); } else { // doesn't fit // if it fits inside the editor window, // offset slightly from upper lefthand corner // so that it's plunked inside the text area locationX = editorLocation[0] + 66; locationY = editorLocation[1] + 66; if ((locationX + windowW > applet.displayWidth - 33) || (locationY + windowH > applet.displayHeight - 33)) { // otherwise center on screen locationX = (applet.displayWidth - windowW) / 2; locationY = (applet.displayHeight - windowH) / 2; } frame.setLocation(locationX, locationY); } } else { // just center on screen // Can't use frame.setLocationRelativeTo(null) because it sends the // frame to the main display, which undermines the --display setting. frame.setLocation(screenRect.x + (screenRect.width - applet.width) / 2, screenRect.y + (screenRect.height - applet.height) / 2); } Point frameLoc = frame.getLocation(); if (frameLoc.y < 0) { // Windows actually allows you to place frames where they can't be // closed. Awesome. http://dev.processing.org/bugs/show_bug.cgi?id=1508 frame.setLocation(frameLoc.x, 30); } if (backgroundColor != null) { // if (backgroundColor == Color.black) { //BLACK) { // // this means no bg color unless specified // backgroundColor = SystemColor.control; // } frame.setBackground(backgroundColor); } int usableWindowH = windowH - insets.top - insets.bottom; applet.setBounds((windowW - applet.width)/2, insets.top + (usableWindowH - applet.height)/2, applet.width, applet.height); if (external) { applet.setupExternalMessages(); } else { // !external frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); } // handle frame resizing events applet.setupFrameResizeListener(); // all set for rockin if (applet.displayable()) { frame.setVisible(true); } } // Disabling for 0185, because it causes an assertion failure on OS X // http://code.google.com/p/processing/issues/detail?id=258 // (Although this doesn't seem to be the one that was causing problems.) //applet.requestFocus(); // ask for keydowns } /** * These methods provide a means for running an already-constructed * sketch. In particular, it makes it easy to launch a sketch in * Jython: * * <pre>class MySketch(PApplet): * pass * *MySketch().runSketch();</pre> */ protected void runSketch(final String[] args) { final String[] argsWithSketchName = new String[args.length + 1]; System.arraycopy(args, 0, argsWithSketchName, 0, args.length); final String className = this.getClass().getSimpleName(); final String cleanedClass = className.replaceAll("__[^_]+__\\$", "").replaceAll("\\$\\d+", ""); argsWithSketchName[args.length] = cleanedClass; runSketch(argsWithSketchName, this); } protected void runSketch() { runSketch(new String[0]); } ////////////////////////////////////////////////////////////// /** * ( begin auto-generated from beginRecord.xml ) * * Opens a new file and all subsequent drawing functions are echoed to this * file as well as the display window. The <b>beginRecord()</b> function * requires two parameters, the first is the renderer and the second is the * file name. This function is always used with <b>endRecord()</b> to stop * the recording process and close the file. * <br /> <br /> * Note that beginRecord() will only pick up any settings that happen after * it has been called. For instance, if you call textFont() before * beginRecord(), then that font will not be set for the file that you're * recording to. * * ( end auto-generated ) * * @webref output:files * @param renderer for example, PDF * @param filename filename for output * @see PApplet#endRecord() */ public PGraphics beginRecord(String renderer, String filename) { filename = insertFrame(filename); PGraphics rec = createGraphics(width, height, renderer, filename); beginRecord(rec); return rec; } /** * @nowebref * Begin recording (echoing) commands to the specified PGraphics object. */ public void beginRecord(PGraphics recorder) { this.recorder = recorder; recorder.beginDraw(); } /** * ( begin auto-generated from endRecord.xml ) * * Stops the recording process started by <b>beginRecord()</b> and closes * the file. * * ( end auto-generated ) * @webref output:files * @see PApplet#beginRecord(String, String) */ public void endRecord() { if (recorder != null) { recorder.endDraw(); recorder.dispose(); recorder = null; } } /** * ( begin auto-generated from beginRaw.xml ) * * To create vectors from 3D data, use the <b>beginRaw()</b> and * <b>endRaw()</b> commands. These commands will grab the shape data just * before it is rendered to the screen. At this stage, your entire scene is * nothing but a long list of individual lines and triangles. This means * that a shape created with <b>sphere()</b> function will be made up of * hundreds of triangles, rather than a single object. Or that a * multi-segment line shape (such as a curve) will be rendered as * individual segments. * <br /><br /> * When using <b>beginRaw()</b> and <b>endRaw()</b>, it's possible to write * to either a 2D or 3D renderer. For instance, <b>beginRaw()</b> with the * PDF library will write the geometry as flattened triangles and lines, * even if recording from the <b>P3D</b> renderer. * <br /><br /> * If you want a background to show up in your files, use <b>rect(0, 0, * width, height)</b> after setting the <b>fill()</b> to the background * color. Otherwise the background will not be rendered to the file because * the background is not shape. * <br /><br /> * Using <b>hint(ENABLE_DEPTH_SORT)</b> can improve the appearance of 3D * geometry drawn to 2D file formats. See the <b>hint()</b> reference for * more details. * <br /><br /> * See examples in the reference for the <b>PDF</b> and <b>DXF</b> * libraries for more information. * * ( end auto-generated ) * * @webref output:files * @param renderer for example, PDF or DXF * @param filename filename for output * @see PApplet#endRaw() * @see PApplet#hint(int) */ public PGraphics beginRaw(String renderer, String filename) { filename = insertFrame(filename); PGraphics rec = createGraphics(width, height, renderer, filename); g.beginRaw(rec); return rec; } /** * @nowebref * Begin recording raw shape data to the specified renderer. * * This simply echoes to g.beginRaw(), but since is placed here (rather than * generated by preproc.pl) for clarity and so that it doesn't echo the * command should beginRecord() be in use. * * @param rawGraphics ??? */ public void beginRaw(PGraphics rawGraphics) { g.beginRaw(rawGraphics); } /** * ( begin auto-generated from endRaw.xml ) * * Complement to <b>beginRaw()</b>; they must always be used together. See * the <b>beginRaw()</b> reference for details. * * ( end auto-generated ) * * @webref output:files * @see PApplet#beginRaw(String, String) */ public void endRaw() { g.endRaw(); } /** * Starts shape recording and returns the PShape object that will * contain the geometry. */ /* public PShape beginRecord() { return g.beginRecord(); } */ ////////////////////////////////////////////////////////////// /** * ( begin auto-generated from loadPixels.xml ) * * Loads the pixel data for the display window into the <b>pixels[]</b> * array. This function must always be called before reading from or * writing to <b>pixels[]</b>. * <br/><br/> renderers may or may not seem to require <b>loadPixels()</b> * or <b>updatePixels()</b>. However, the rule is that any time you want to * manipulate the <b>pixels[]</b> array, you must first call * <b>loadPixels()</b>, and after changes have been made, call * <b>updatePixels()</b>. Even if the renderer may not seem to use this * function in the current Processing release, this will always be subject * to change. * * ( end auto-generated ) * <h3>Advanced</h3> * Override the g.pixels[] function to set the pixels[] array * that's part of the PApplet object. Allows the use of * pixels[] in the code, rather than g.pixels[]. * * @webref image:pixels * @see PApplet#pixels * @see PApplet#updatePixels() */ public void loadPixels() { g.loadPixels(); pixels = g.pixels; } /** * ( begin auto-generated from updatePixels.xml ) * * Updates the display window with the data in the <b>pixels[]</b> array. * Use in conjunction with <b>loadPixels()</b>. If you're only reading * pixels from the array, there's no need to call <b>updatePixels()</b> * unless there are changes. * <br/><br/> renderers may or may not seem to require <b>loadPixels()</b> * or <b>updatePixels()</b>. However, the rule is that any time you want to * manipulate the <b>pixels[]</b> array, you must first call * <b>loadPixels()</b>, and after changes have been made, call * <b>updatePixels()</b>. Even if the renderer may not seem to use this * function in the current Processing release, this will always be subject * to change. * <br/> <br/> * Currently, none of the renderers use the additional parameters to * <b>updatePixels()</b>, however this may be implemented in the future. * * ( end auto-generated ) * @webref image:pixels * @see PApplet#loadPixels() * @see PApplet#pixels */ public void updatePixels() { g.updatePixels(); } /** * @nowebref * @param x1 x-coordinate of the upper-left corner * @param y1 y-coordinate of the upper-left corner * @param x2 width of the region * @param y2 height of the region */ public void updatePixels(int x1, int y1, int x2, int y2) { g.updatePixels(x1, y1, x2, y2); } ////////////////////////////////////////////////////////////// // EVERYTHING BELOW THIS LINE IS AUTOMATICALLY GENERATED. DO NOT TOUCH! // This includes the Javadoc comments, which are automatically copied from // the PImage and PGraphics source code files. // public functions for processing.core /** * Store data of some kind for the renderer that requires extra metadata of * some kind. Usually this is a renderer-specific representation of the * image data, for instance a BufferedImage with tint() settings applied for * PGraphicsJava2D, or resized image data and OpenGL texture indices for * PGraphicsOpenGL. * @param renderer The PGraphics renderer associated to the image * @param storage The metadata required by the renderer */ public void setCache(PImage image, Object storage) { if (recorder != null) recorder.setCache(image, storage); g.setCache(image, storage); } /** * Get cache storage data for the specified renderer. Because each renderer * will cache data in different formats, it's necessary to store cache data * keyed by the renderer object. Otherwise, attempting to draw the same * image to both a PGraphicsJava2D and a PGraphicsOpenGL will cause errors. * @param renderer The PGraphics renderer associated to the image * @return metadata stored for the specified renderer */ public Object getCache(PImage image) { return g.getCache(image); } /** * Remove information associated with this renderer from the cache, if any. * @param renderer The PGraphics renderer whose cache data should be removed */ public void removeCache(PImage image) { if (recorder != null) recorder.removeCache(image); g.removeCache(image); } public PGL beginPGL() { return g.beginPGL(); } public void endPGL() { if (recorder != null) recorder.endPGL(); g.endPGL(); } public void flush() { if (recorder != null) recorder.flush(); g.flush(); } public void hint(int which) { if (recorder != null) recorder.hint(which); g.hint(which); } /** * Start a new shape of type POLYGON */ public void beginShape() { if (recorder != null) recorder.beginShape(); g.beginShape(); } /** * ( begin auto-generated from beginShape.xml ) * * Using the <b>beginShape()</b> and <b>endShape()</b> functions allow * creating more complex forms. <b>beginShape()</b> begins recording * vertices for a shape and <b>endShape()</b> stops recording. The value of * the <b>MODE</b> parameter tells it which types of shapes to create from * the provided vertices. With no mode specified, the shape can be any * irregular polygon. The parameters available for beginShape() are POINTS, * LINES, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, QUADS, and QUAD_STRIP. * After calling the <b>beginShape()</b> function, a series of * <b>vertex()</b> commands must follow. To stop drawing the shape, call * <b>endShape()</b>. The <b>vertex()</b> function with two parameters * specifies a position in 2D and the <b>vertex()</b> function with three * parameters specifies a position in 3D. Each shape will be outlined with * the current stroke color and filled with the fill color. * <br/> <br/> * Transformations such as <b>translate()</b>, <b>rotate()</b>, and * <b>scale()</b> do not work within <b>beginShape()</b>. It is also not * possible to use other shapes, such as <b>ellipse()</b> or <b>rect()</b> * within <b>beginShape()</b>. * <br/> <br/> * The P3D renderer settings allow <b>stroke()</b> and <b>fill()</b> * settings to be altered per-vertex, however the default P2D renderer does * not. Settings such as <b>strokeWeight()</b>, <b>strokeCap()</b>, and * <b>strokeJoin()</b> cannot be changed while inside a * <b>beginShape()</b>/<b>endShape()</b> block with any renderer. * * ( end auto-generated ) * @webref shape:vertex * @param kind Either POINTS, LINES, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, QUADS, or QUAD_STRIP * @see PShape * @see PGraphics#endShape() * @see PGraphics#vertex(float, float, float, float, float) * @see PGraphics#curveVertex(float, float, float) * @see PGraphics#bezierVertex(float, float, float, float, float, float, float, float, float) */ public void beginShape(int kind) { if (recorder != null) recorder.beginShape(kind); g.beginShape(kind); } /** * Sets whether the upcoming vertex is part of an edge. * Equivalent to glEdgeFlag(), for people familiar with OpenGL. */ public void edge(boolean edge) { if (recorder != null) recorder.edge(edge); g.edge(edge); } /** * ( begin auto-generated from normal.xml ) * * Sets the current normal vector. This is for drawing three dimensional * shapes and surfaces and specifies a vector perpendicular to the surface * of the shape which determines how lighting affects it. Processing * attempts to automatically assign normals to shapes, but since that's * imperfect, this is a better option when you want more control. This * function is identical to glNormal3f() in OpenGL. * * ( end auto-generated ) * @webref lights_camera:lights * @param nx x direction * @param ny y direction * @param nz z direction * @see PGraphics#beginShape(int) * @see PGraphics#endShape(int) * @see PGraphics#lights() */ public void normal(float nx, float ny, float nz) { if (recorder != null) recorder.normal(nx, ny, nz); g.normal(nx, ny, nz); } /** * ( begin auto-generated from textureMode.xml ) * * Sets the coordinate space for texture mapping. There are two options, * IMAGE, which refers to the actual coordinates of the image, and * NORMAL, which refers to a normalized space of values ranging from 0 * to 1. The default mode is IMAGE. In IMAGE, if an image is 100 x 200 * pixels, mapping the image onto the entire size of a quad would require * the points (0,0) (0,100) (100,200) (0,200). The same mapping in * NORMAL_SPACE is (0,0) (0,1) (1,1) (0,1). * * ( end auto-generated ) * @webref image:textures * @param mode either IMAGE or NORMAL * @see PGraphics#texture(PImage) * @see PGraphics#textureWrap(int) */ public void textureMode(int mode) { if (recorder != null) recorder.textureMode(mode); g.textureMode(mode); } /** * ( begin auto-generated from textureWrap.xml ) * * Description to come... * * ( end auto-generated from textureWrap.xml ) * * @webref image:textures * @param wrap Either CLAMP (default) or REPEAT * @see PGraphics#texture(PImage) * @see PGraphics#textureMode(int) */ public void textureWrap(int wrap) { if (recorder != null) recorder.textureWrap(wrap); g.textureWrap(wrap); } /** * ( begin auto-generated from texture.xml ) * * Sets a texture to be applied to vertex points. The <b>texture()</b> * function must be called between <b>beginShape()</b> and * <b>endShape()</b> and before any calls to <b>vertex()</b>. * <br/> <br/> * When textures are in use, the fill color is ignored. Instead, use tint() * to specify the color of the texture as it is applied to the shape. * * ( end auto-generated ) * @webref image:textures * @param image reference to a PImage object * @see PGraphics#textureMode(int) * @see PGraphics#textureWrap(int) * @see PGraphics#beginShape(int) * @see PGraphics#endShape(int) * @see PGraphics#vertex(float, float, float, float, float) */ public void texture(PImage image) { if (recorder != null) recorder.texture(image); g.texture(image); } /** * Removes texture image for current shape. * Needs to be called between beginShape and endShape * */ public void noTexture() { if (recorder != null) recorder.noTexture(); g.noTexture(); } public void vertex(float x, float y) { if (recorder != null) recorder.vertex(x, y); g.vertex(x, y); } public void vertex(float x, float y, float z) { if (recorder != null) recorder.vertex(x, y, z); g.vertex(x, y, z); } /** * Used by renderer subclasses or PShape to efficiently pass in already * formatted vertex information. * @param v vertex parameters, as a float array of length VERTEX_FIELD_COUNT */ public void vertex(float[] v) { if (recorder != null) recorder.vertex(v); g.vertex(v); } public void vertex(float x, float y, float u, float v) { if (recorder != null) recorder.vertex(x, y, u, v); g.vertex(x, y, u, v); } /** * ( begin auto-generated from vertex.xml ) * * All shapes are constructed by connecting a series of vertices. * <b>vertex()</b> is used to specify the vertex coordinates for points, * lines, triangles, quads, and polygons and is used exclusively within the * <b>beginShape()</b> and <b>endShape()</b> function.<br /> * <br /> * Drawing a vertex in 3D using the <b>z</b> parameter requires the P3D * parameter in combination with size as shown in the above example.<br /> * <br /> * This function is also used to map a texture onto the geometry. The * <b>texture()</b> function declares the texture to apply to the geometry * and the <b>u</b> and <b>v</b> coordinates set define the mapping of this * texture to the form. By default, the coordinates used for <b>u</b> and * <b>v</b> are specified in relation to the image's size in pixels, but * this relation can be changed with <b>textureMode()</b>. * * ( end auto-generated ) * @webref shape:vertex * @param x x-coordinate of the vertex * @param y y-coordinate of the vertex * @param z z-coordinate of the vertex * @param u horizontal coordinate for the texture mapping * @param v vertical coordinate for the texture mapping * @see PGraphics#beginShape(int) * @see PGraphics#endShape(int) * @see PGraphics#bezierVertex(float, float, float, float, float, float, float, float, float) * @see PGraphics#quadraticVertex(float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float, float) * @see PGraphics#texture(PImage) */ public void vertex(float x, float y, float z, float u, float v) { if (recorder != null) recorder.vertex(x, y, z, u, v); g.vertex(x, y, z, u, v); } /** * @webref shape:vertex */ public void beginContour() { if (recorder != null) recorder.beginContour(); g.beginContour(); } /** * @webref shape:vertex */ public void endContour() { if (recorder != null) recorder.endContour(); g.endContour(); } public void endShape() { if (recorder != null) recorder.endShape(); g.endShape(); } /** * ( begin auto-generated from endShape.xml ) * * The <b>endShape()</b> function is the companion to <b>beginShape()</b> * and may only be called after <b>beginShape()</b>. When <b>endshape()</b> * is called, all of image data defined since the previous call to * <b>beginShape()</b> is written into the image buffer. The constant CLOSE * as the value for the MODE parameter to close the shape (to connect the * beginning and the end). * * ( end auto-generated ) * @webref shape:vertex * @param mode use CLOSE to close the shape * @see PShape * @see PGraphics#beginShape(int) */ public void endShape(int mode) { if (recorder != null) recorder.endShape(mode); g.endShape(mode); } /** * @webref shape * @param filename name of file to load, can be .svg or .obj * @see PShape * @see PApplet#createShape() */ public PShape loadShape(String filename) { return g.loadShape(filename); } public PShape loadShape(String filename, String options) { return g.loadShape(filename, options); } /** * @webref shape * @see PShape * @see PShape#endShape() * @see PApplet#loadShape(String) */ public PShape createShape() { return g.createShape(); } public PShape createShape(PShape source) { return g.createShape(source); } /** * @param type either POINTS, LINES, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, QUADS, QUAD_STRIP */ public PShape createShape(int type) { return g.createShape(type); } /** * @param kind either LINE, TRIANGLE, RECT, ELLIPSE, ARC, SPHERE, BOX * @param p parameters that match the kind of shape */ public PShape createShape(int kind, float... p) { return g.createShape(kind, p); } /** * ( begin auto-generated from loadShader.xml ) * * This is a new reference entry for Processing 2.0. It will be updated shortly. * * ( end auto-generated ) * * @webref rendering:shaders * @param fragFilename name of fragment shader file */ public PShader loadShader(String fragFilename) { return g.loadShader(fragFilename); } /** * @param vertFilename name of vertex shader file */ public PShader loadShader(String fragFilename, String vertFilename) { return g.loadShader(fragFilename, vertFilename); } /** * ( begin auto-generated from shader.xml ) * * This is a new reference entry for Processing 2.0. It will be updated shortly. * * ( end auto-generated ) * * @webref rendering:shaders * @param shader name of shader file */ public void shader(PShader shader) { if (recorder != null) recorder.shader(shader); g.shader(shader); } /** * @param kind type of shader, either POINTS, LINES, or TRIANGLES */ public void shader(PShader shader, int kind) { if (recorder != null) recorder.shader(shader, kind); g.shader(shader, kind); } /** * ( begin auto-generated from resetShader.xml ) * * This is a new reference entry for Processing 2.0. It will be updated shortly. * * ( end auto-generated ) * * @webref rendering:shaders */ public void resetShader() { if (recorder != null) recorder.resetShader(); g.resetShader(); } /** * @param kind type of shader, either POINTS, LINES, or TRIANGLES */ public void resetShader(int kind) { if (recorder != null) recorder.resetShader(kind); g.resetShader(kind); } /** * @param shader the fragment shader to apply */ public void filter(PShader shader) { if (recorder != null) recorder.filter(shader); g.filter(shader); } /* * @webref rendering:shaders * @param a x-coordinate of the rectangle by default * @param b y-coordinate of the rectangle by default * @param c width of the rectangle by default * @param d height of the rectangle by default */ public void clip(float a, float b, float c, float d) { if (recorder != null) recorder.clip(a, b, c, d); g.clip(a, b, c, d); } /* * @webref rendering:shaders */ public void noClip() { if (recorder != null) recorder.noClip(); g.noClip(); } /** * ( begin auto-generated from blendMode.xml ) * * This is a new reference entry for Processing 2.0. It will be updated shortly. * * ( end auto-generated ) * * @webref Rendering * @param mode the blending mode to use */ public void blendMode(int mode) { if (recorder != null) recorder.blendMode(mode); g.blendMode(mode); } public void bezierVertex(float x2, float y2, float x3, float y3, float x4, float y4) { if (recorder != null) recorder.bezierVertex(x2, y2, x3, y3, x4, y4); g.bezierVertex(x2, y2, x3, y3, x4, y4); } /** * ( begin auto-generated from bezierVertex.xml ) * * Specifies vertex coordinates for Bezier curves. Each call to * <b>bezierVertex()</b> defines the position of two control points and one * anchor point of a Bezier curve, adding a new segment to a line or shape. * The first time <b>bezierVertex()</b> is used within a * <b>beginShape()</b> call, it must be prefaced with a call to * <b>vertex()</b> to set the first anchor point. This function must be * used between <b>beginShape()</b> and <b>endShape()</b> and only when * there is no MODE parameter specified to <b>beginShape()</b>. Using the * 3D version requires rendering with P3D (see the Environment reference * for more information). * * ( end auto-generated ) * @webref shape:vertex * @param x2 the x-coordinate of the 1st control point * @param y2 the y-coordinate of the 1st control point * @param z2 the z-coordinate of the 1st control point * @param x3 the x-coordinate of the 2nd control point * @param y3 the y-coordinate of the 2nd control point * @param z3 the z-coordinate of the 2nd control point * @param x4 the x-coordinate of the anchor point * @param y4 the y-coordinate of the anchor point * @param z4 the z-coordinate of the anchor point * @see PGraphics#curveVertex(float, float, float) * @see PGraphics#vertex(float, float, float, float, float) * @see PGraphics#quadraticVertex(float, float, float, float, float, float) * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) */ public void bezierVertex(float x2, float y2, float z2, float x3, float y3, float z3, float x4, float y4, float z4) { if (recorder != null) recorder.bezierVertex(x2, y2, z2, x3, y3, z3, x4, y4, z4); g.bezierVertex(x2, y2, z2, x3, y3, z3, x4, y4, z4); } /** * @webref shape:vertex * @param cx the x-coordinate of the control point * @param cy the y-coordinate of the control point * @param x3 the x-coordinate of the anchor point * @param y3 the y-coordinate of the anchor point * @see PGraphics#curveVertex(float, float, float) * @see PGraphics#vertex(float, float, float, float, float) * @see PGraphics#bezierVertex(float, float, float, float, float, float) * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) */ public void quadraticVertex(float cx, float cy, float x3, float y3) { if (recorder != null) recorder.quadraticVertex(cx, cy, x3, y3); g.quadraticVertex(cx, cy, x3, y3); } /** * @param cz the z-coordinate of the control point * @param z3 the z-coordinate of the anchor point */ public void quadraticVertex(float cx, float cy, float cz, float x3, float y3, float z3) { if (recorder != null) recorder.quadraticVertex(cx, cy, cz, x3, y3, z3); g.quadraticVertex(cx, cy, cz, x3, y3, z3); } /** * ( begin auto-generated from curveVertex.xml ) * * Specifies vertex coordinates for curves. This function may only be used * between <b>beginShape()</b> and <b>endShape()</b> and only when there is * no MODE parameter specified to <b>beginShape()</b>. The first and last * points in a series of <b>curveVertex()</b> lines will be used to guide * the beginning and end of a the curve. A minimum of four points is * required to draw a tiny curve between the second and third points. * Adding a fifth point with <b>curveVertex()</b> will draw the curve * between the second, third, and fourth points. The <b>curveVertex()</b> * function is an implementation of Catmull-Rom splines. Using the 3D * version requires rendering with P3D (see the Environment reference for * more information). * * ( end auto-generated ) * * @webref shape:vertex * @param x the x-coordinate of the vertex * @param y the y-coordinate of the vertex * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#beginShape(int) * @see PGraphics#endShape(int) * @see PGraphics#vertex(float, float, float, float, float) * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#quadraticVertex(float, float, float, float, float, float) */ public void curveVertex(float x, float y) { if (recorder != null) recorder.curveVertex(x, y); g.curveVertex(x, y); } /** * @param z the z-coordinate of the vertex */ public void curveVertex(float x, float y, float z) { if (recorder != null) recorder.curveVertex(x, y, z); g.curveVertex(x, y, z); } /** * ( begin auto-generated from point.xml ) * * Draws a point, a coordinate in space at the dimension of one pixel. The * first parameter is the horizontal value for the point, the second value * is the vertical value for the point, and the optional third value is the * depth value. Drawing this shape in 3D with the <b>z</b> parameter * requires the P3D parameter in combination with <b>size()</b> as shown in * the above example. * * ( end auto-generated ) * * @webref shape:2d_primitives * @param x x-coordinate of the point * @param y y-coordinate of the point */ public void point(float x, float y) { if (recorder != null) recorder.point(x, y); g.point(x, y); } /** * @param z z-coordinate of the point */ public void point(float x, float y, float z) { if (recorder != null) recorder.point(x, y, z); g.point(x, y, z); } /** * ( begin auto-generated from line.xml ) * * Draws a line (a direct path between two points) to the screen. The * version of <b>line()</b> with four parameters draws the line in 2D. To * color a line, use the <b>stroke()</b> function. A line cannot be filled, * therefore the <b>fill()</b> function will not affect the color of a * line. 2D lines are drawn with a width of one pixel by default, but this * can be changed with the <b>strokeWeight()</b> function. The version with * six parameters allows the line to be placed anywhere within XYZ space. * Drawing this shape in 3D with the <b>z</b> parameter requires the P3D * parameter in combination with <b>size()</b> as shown in the above example. * * ( end auto-generated ) * @webref shape:2d_primitives * @param x1 x-coordinate of the first point * @param y1 y-coordinate of the first point * @param x2 x-coordinate of the second point * @param y2 y-coordinate of the second point * @see PGraphics#strokeWeight(float) * @see PGraphics#strokeJoin(int) * @see PGraphics#strokeCap(int) * @see PGraphics#beginShape() */ public void line(float x1, float y1, float x2, float y2) { if (recorder != null) recorder.line(x1, y1, x2, y2); g.line(x1, y1, x2, y2); } /** * @param z1 z-coordinate of the first point * @param z2 z-coordinate of the second point */ public void line(float x1, float y1, float z1, float x2, float y2, float z2) { if (recorder != null) recorder.line(x1, y1, z1, x2, y2, z2); g.line(x1, y1, z1, x2, y2, z2); } /** * ( begin auto-generated from triangle.xml ) * * A triangle is a plane created by connecting three points. The first two * arguments specify the first point, the middle two arguments specify the * second point, and the last two arguments specify the third point. * * ( end auto-generated ) * @webref shape:2d_primitives * @param x1 x-coordinate of the first point * @param y1 y-coordinate of the first point * @param x2 x-coordinate of the second point * @param y2 y-coordinate of the second point * @param x3 x-coordinate of the third point * @param y3 y-coordinate of the third point * @see PApplet#beginShape() */ public void triangle(float x1, float y1, float x2, float y2, float x3, float y3) { if (recorder != null) recorder.triangle(x1, y1, x2, y2, x3, y3); g.triangle(x1, y1, x2, y2, x3, y3); } /** * ( begin auto-generated from quad.xml ) * * A quad is a quadrilateral, a four sided polygon. It is similar to a * rectangle, but the angles between its edges are not constrained to * ninety degrees. The first pair of parameters (x1,y1) sets the first * vertex and the subsequent pairs should proceed clockwise or * counter-clockwise around the defined shape. * * ( end auto-generated ) * @webref shape:2d_primitives * @param x1 x-coordinate of the first corner * @param y1 y-coordinate of the first corner * @param x2 x-coordinate of the second corner * @param y2 y-coordinate of the second corner * @param x3 x-coordinate of the third corner * @param y3 y-coordinate of the third corner * @param x4 x-coordinate of the fourth corner * @param y4 y-coordinate of the fourth corner */ public void quad(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) { if (recorder != null) recorder.quad(x1, y1, x2, y2, x3, y3, x4, y4); g.quad(x1, y1, x2, y2, x3, y3, x4, y4); } /** * ( begin auto-generated from rectMode.xml ) * * Modifies the location from which rectangles draw. The default mode is * <b>rectMode(CORNER)</b>, which specifies the location to be the upper * left corner of the shape and uses the third and fourth parameters of * <b>rect()</b> to specify the width and height. The syntax * <b>rectMode(CORNERS)</b> uses the first and second parameters of * <b>rect()</b> to set the location of one corner and uses the third and * fourth parameters to set the opposite corner. The syntax * <b>rectMode(CENTER)</b> draws the image from its center point and uses * the third and forth parameters of <b>rect()</b> to specify the image's * width and height. The syntax <b>rectMode(RADIUS)</b> draws the image * from its center point and uses the third and forth parameters of * <b>rect()</b> to specify half of the image's width and height. The * parameter must be written in ALL CAPS because Processing is a case * sensitive language. Note: In version 125, the mode named CENTER_RADIUS * was shortened to RADIUS. * * ( end auto-generated ) * @webref shape:attributes * @param mode either CORNER, CORNERS, CENTER, or RADIUS * @see PGraphics#rect(float, float, float, float) */ public void rectMode(int mode) { if (recorder != null) recorder.rectMode(mode); g.rectMode(mode); } /** * ( begin auto-generated from rect.xml ) * * Draws a rectangle to the screen. A rectangle is a four-sided shape with * every angle at ninety degrees. By default, the first two parameters set * the location of the upper-left corner, the third sets the width, and the * fourth sets the height. These parameters may be changed with the * <b>rectMode()</b> function. * * ( end auto-generated ) * * @webref shape:2d_primitives * @param a x-coordinate of the rectangle by default * @param b y-coordinate of the rectangle by default * @param c width of the rectangle by default * @param d height of the rectangle by default * @see PGraphics#rectMode(int) * @see PGraphics#quad(float, float, float, float, float, float, float, float) */ public void rect(float a, float b, float c, float d) { if (recorder != null) recorder.rect(a, b, c, d); g.rect(a, b, c, d); } /** * @param r radii for all four corners */ public void rect(float a, float b, float c, float d, float r) { if (recorder != null) recorder.rect(a, b, c, d, r); g.rect(a, b, c, d, r); } /** * @param tl radius for top-left corner * @param tr radius for top-right corner * @param br radius for bottom-right corner * @param bl radius for bottom-left corner */ public void rect(float a, float b, float c, float d, float tl, float tr, float br, float bl) { if (recorder != null) recorder.rect(a, b, c, d, tl, tr, br, bl); g.rect(a, b, c, d, tl, tr, br, bl); } /** * ( begin auto-generated from ellipseMode.xml ) * * The origin of the ellipse is modified by the <b>ellipseMode()</b> * function. The default configuration is <b>ellipseMode(CENTER)</b>, which * specifies the location of the ellipse as the center of the shape. The * <b>RADIUS</b> mode is the same, but the width and height parameters to * <b>ellipse()</b> specify the radius of the ellipse, rather than the * diameter. The <b>CORNER</b> mode draws the shape from the upper-left * corner of its bounding box. The <b>CORNERS</b> mode uses the four * parameters to <b>ellipse()</b> to set two opposing corners of the * ellipse's bounding box. The parameter must be written in ALL CAPS * because Processing is a case-sensitive language. * * ( end auto-generated ) * @webref shape:attributes * @param mode either CENTER, RADIUS, CORNER, or CORNERS * @see PApplet#ellipse(float, float, float, float) * @see PApplet#arc(float, float, float, float, float, float) */ public void ellipseMode(int mode) { if (recorder != null) recorder.ellipseMode(mode); g.ellipseMode(mode); } /** * ( begin auto-generated from ellipse.xml ) * * Draws an ellipse (oval) in the display window. An ellipse with an equal * <b>width</b> and <b>height</b> is a circle. The first two parameters set * the location, the third sets the width, and the fourth sets the height. * The origin may be changed with the <b>ellipseMode()</b> function. * * ( end auto-generated ) * @webref shape:2d_primitives * @param a x-coordinate of the ellipse * @param b y-coordinate of the ellipse * @param c width of the ellipse by default * @param d height of the ellipse by default * @see PApplet#ellipseMode(int) * @see PApplet#arc(float, float, float, float, float, float) */ public void ellipse(float a, float b, float c, float d) { if (recorder != null) recorder.ellipse(a, b, c, d); g.ellipse(a, b, c, d); } /** * ( begin auto-generated from arc.xml ) * * Draws an arc in the display window. Arcs are drawn along the outer edge * of an ellipse defined by the <b>x</b>, <b>y</b>, <b>width</b> and * <b>height</b> parameters. The origin or the arc's ellipse may be changed * with the <b>ellipseMode()</b> function. The <b>start</b> and <b>stop</b> * parameters specify the angles at which to draw the arc. * * ( end auto-generated ) * @webref shape:2d_primitives * @param a x-coordinate of the arc's ellipse * @param b y-coordinate of the arc's ellipse * @param c width of the arc's ellipse by default * @param d height of the arc's ellipse by default * @param start angle to start the arc, specified in radians * @param stop angle to stop the arc, specified in radians * @see PApplet#ellipse(float, float, float, float) * @see PApplet#ellipseMode(int) * @see PApplet#radians(float) * @see PApplet#degrees(float) */ public void arc(float a, float b, float c, float d, float start, float stop) { if (recorder != null) recorder.arc(a, b, c, d, start, stop); g.arc(a, b, c, d, start, stop); } /* * @param mode either OPEN, CHORD, or PIE */ public void arc(float a, float b, float c, float d, float start, float stop, int mode) { if (recorder != null) recorder.arc(a, b, c, d, start, stop, mode); g.arc(a, b, c, d, start, stop, mode); } /** * ( begin auto-generated from box.xml ) * * A box is an extruded rectangle. A box with equal dimension on all sides * is a cube. * * ( end auto-generated ) * * @webref shape:3d_primitives * @param size dimension of the box in all dimensions (creates a cube) * @see PGraphics#sphere(float) */ public void box(float size) { if (recorder != null) recorder.box(size); g.box(size); } /** * @param w dimension of the box in the x-dimension * @param h dimension of the box in the y-dimension * @param d dimension of the box in the z-dimension */ public void box(float w, float h, float d) { if (recorder != null) recorder.box(w, h, d); g.box(w, h, d); } /** * ( begin auto-generated from sphereDetail.xml ) * * Controls the detail used to render a sphere by adjusting the number of * vertices of the sphere mesh. The default resolution is 30, which creates * a fairly detailed sphere definition with vertices every 360/30 = 12 * degrees. If you're going to render a great number of spheres per frame, * it is advised to reduce the level of detail using this function. The * setting stays active until <b>sphereDetail()</b> is called again with a * new parameter and so should <i>not</i> be called prior to every * <b>sphere()</b> statement, unless you wish to render spheres with * different settings, e.g. using less detail for smaller spheres or ones * further away from the camera. To control the detail of the horizontal * and vertical resolution independently, use the version of the functions * with two parameters. * * ( end auto-generated ) * * <h3>Advanced</h3> * Code for sphereDetail() submitted by toxi [031031]. * Code for enhanced u/v version from davbol [080801]. * * @param res number of segments (minimum 3) used per full circle revolution * @webref shape:3d_primitives * @see PGraphics#sphere(float) */ public void sphereDetail(int res) { if (recorder != null) recorder.sphereDetail(res); g.sphereDetail(res); } /** * @param ures number of segments used longitudinally per full circle revolutoin * @param vres number of segments used latitudinally from top to bottom */ public void sphereDetail(int ures, int vres) { if (recorder != null) recorder.sphereDetail(ures, vres); g.sphereDetail(ures, vres); } /** * ( begin auto-generated from sphere.xml ) * * A sphere is a hollow ball made from tessellated triangles. * * ( end auto-generated ) * * <h3>Advanced</h3> * <P> * Implementation notes: * <P> * cache all the points of the sphere in a static array * top and bottom are just a bunch of triangles that land * in the center point * <P> * sphere is a series of concentric circles who radii vary * along the shape, based on, er.. cos or something * <PRE> * [toxi 031031] new sphere code. removed all multiplies with * radius, as scale() will take care of that anyway * * [toxi 031223] updated sphere code (removed modulos) * and introduced sphereAt(x,y,z,r) * to avoid additional translate()'s on the user/sketch side * * [davbol 080801] now using separate sphereDetailU/V * </PRE> * * @webref shape:3d_primitives * @param r the radius of the sphere * @see PGraphics#sphereDetail(int) */ public void sphere(float r) { if (recorder != null) recorder.sphere(r); g.sphere(r); } /** * ( begin auto-generated from bezierPoint.xml ) * * Evaluates the Bezier at point t for points a, b, c, d. The parameter t * varies between 0 and 1, a and d are points on the curve, and b and c are * the control points. This can be done once with the x coordinates and a * second time with the y coordinates to get the location of a bezier curve * at t. * * ( end auto-generated ) * * <h3>Advanced</h3> * For instance, to convert the following example:<PRE> * stroke(255, 102, 0); * line(85, 20, 10, 10); * line(90, 90, 15, 80); * stroke(0, 0, 0); * bezier(85, 20, 10, 10, 90, 90, 15, 80); * * // draw it in gray, using 10 steps instead of the default 20 * // this is a slower way to do it, but useful if you need * // to do things with the coordinates at each step * stroke(128); * beginShape(LINE_STRIP); * for (int i = 0; i <= 10; i++) { * float t = i / 10.0f; * float x = bezierPoint(85, 10, 90, 15, t); * float y = bezierPoint(20, 10, 90, 80, t); * vertex(x, y); * } * endShape();</PRE> * * @webref shape:curves * @param a coordinate of first point on the curve * @param b coordinate of first control point * @param c coordinate of second control point * @param d coordinate of second point on the curve * @param t value between 0 and 1 * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#bezierVertex(float, float, float, float, float, float) * @see PGraphics#curvePoint(float, float, float, float, float) */ public float bezierPoint(float a, float b, float c, float d, float t) { return g.bezierPoint(a, b, c, d, t); } /** * ( begin auto-generated from bezierTangent.xml ) * * Calculates the tangent of a point on a Bezier curve. There is a good * definition of <a href="http://en.wikipedia.org/wiki/Tangent" * target="new"><em>tangent</em> on Wikipedia</a>. * * ( end auto-generated ) * * <h3>Advanced</h3> * Code submitted by Dave Bollinger (davol) for release 0136. * * @webref shape:curves * @param a coordinate of first point on the curve * @param b coordinate of first control point * @param c coordinate of second control point * @param d coordinate of second point on the curve * @param t value between 0 and 1 * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#bezierVertex(float, float, float, float, float, float) * @see PGraphics#curvePoint(float, float, float, float, float) */ public float bezierTangent(float a, float b, float c, float d, float t) { return g.bezierTangent(a, b, c, d, t); } /** * ( begin auto-generated from bezierDetail.xml ) * * Sets the resolution at which Beziers display. The default value is 20. * This function is only useful when using the P3D renderer as the default * P2D renderer does not use this information. * * ( end auto-generated ) * * @webref shape:curves * @param detail resolution of the curves * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float, float) * @see PGraphics#curveTightness(float) */ public void bezierDetail(int detail) { if (recorder != null) recorder.bezierDetail(detail); g.bezierDetail(detail); } public void bezier(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) { if (recorder != null) recorder.bezier(x1, y1, x2, y2, x3, y3, x4, y4); g.bezier(x1, y1, x2, y2, x3, y3, x4, y4); } /** * ( begin auto-generated from bezier.xml ) * * Draws a Bezier curve on the screen. These curves are defined by a series * of anchor and control points. The first two parameters specify the first * anchor point and the last two parameters specify the other anchor point. * The middle parameters specify the control points which define the shape * of the curve. Bezier curves were developed by French engineer Pierre * Bezier. Using the 3D version requires rendering with P3D (see the * Environment reference for more information). * * ( end auto-generated ) * * <h3>Advanced</h3> * Draw a cubic bezier curve. The first and last points are * the on-curve points. The middle two are the 'control' points, * or 'handles' in an application like Illustrator. * <P> * Identical to typing: * <PRE>beginShape(); * vertex(x1, y1); * bezierVertex(x2, y2, x3, y3, x4, y4); * endShape(); * </PRE> * In Postscript-speak, this would be: * <PRE>moveto(x1, y1); * curveto(x2, y2, x3, y3, x4, y4);</PRE> * If you were to try and continue that curve like so: * <PRE>curveto(x5, y5, x6, y6, x7, y7);</PRE> * This would be done in processing by adding these statements: * <PRE>bezierVertex(x5, y5, x6, y6, x7, y7) * </PRE> * To draw a quadratic (instead of cubic) curve, * use the control point twice by doubling it: * <PRE>bezier(x1, y1, cx, cy, cx, cy, x2, y2);</PRE> * * @webref shape:curves * @param x1 coordinates for the first anchor point * @param y1 coordinates for the first anchor point * @param z1 coordinates for the first anchor point * @param x2 coordinates for the first control point * @param y2 coordinates for the first control point * @param z2 coordinates for the first control point * @param x3 coordinates for the second control point * @param y3 coordinates for the second control point * @param z3 coordinates for the second control point * @param x4 coordinates for the second anchor point * @param y4 coordinates for the second anchor point * @param z4 coordinates for the second anchor point * * @see PGraphics#bezierVertex(float, float, float, float, float, float) * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) */ public void bezier(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, float x4, float y4, float z4) { if (recorder != null) recorder.bezier(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4); g.bezier(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4); } /** * ( begin auto-generated from curvePoint.xml ) * * Evalutes the curve at point t for points a, b, c, d. The parameter t * varies between 0 and 1, a and d are points on the curve, and b and c are * the control points. This can be done once with the x coordinates and a * second time with the y coordinates to get the location of a curve at t. * * ( end auto-generated ) * * @webref shape:curves * @param a coordinate of first point on the curve * @param b coordinate of second point on the curve * @param c coordinate of third point on the curve * @param d coordinate of fourth point on the curve * @param t value between 0 and 1 * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float) * @see PGraphics#bezierPoint(float, float, float, float, float) */ public float curvePoint(float a, float b, float c, float d, float t) { return g.curvePoint(a, b, c, d, t); } /** * ( begin auto-generated from curveTangent.xml ) * * Calculates the tangent of a point on a curve. There's a good definition * of <em><a href="http://en.wikipedia.org/wiki/Tangent" * target="new">tangent</em> on Wikipedia</a>. * * ( end auto-generated ) * * <h3>Advanced</h3> * Code thanks to Dave Bollinger (Bug #715) * * @webref shape:curves * @param a coordinate of first point on the curve * @param b coordinate of first control point * @param c coordinate of second control point * @param d coordinate of second point on the curve * @param t value between 0 and 1 * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float) * @see PGraphics#curvePoint(float, float, float, float, float) * @see PGraphics#bezierTangent(float, float, float, float, float) */ public float curveTangent(float a, float b, float c, float d, float t) { return g.curveTangent(a, b, c, d, t); } /** * ( begin auto-generated from curveDetail.xml ) * * Sets the resolution at which curves display. The default value is 20. * This function is only useful when using the P3D renderer as the default * P2D renderer does not use this information. * * ( end auto-generated ) * * @webref shape:curves * @param detail resolution of the curves * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float) * @see PGraphics#curveTightness(float) */ public void curveDetail(int detail) { if (recorder != null) recorder.curveDetail(detail); g.curveDetail(detail); } /** * ( begin auto-generated from curveTightness.xml ) * * Modifies the quality of forms created with <b>curve()</b> and * <b>curveVertex()</b>. The parameter <b>squishy</b> determines how the * curve fits to the vertex points. The value 0.0 is the default value for * <b>squishy</b> (this value defines the curves to be Catmull-Rom splines) * and the value 1.0 connects all the points with straight lines. Values * within the range -5.0 and 5.0 will deform the curves but will leave them * recognizable and as values increase in magnitude, they will continue to deform. * * ( end auto-generated ) * * @webref shape:curves * @param tightness amount of deformation from the original vertices * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float) */ public void curveTightness(float tightness) { if (recorder != null) recorder.curveTightness(tightness); g.curveTightness(tightness); } /** * ( begin auto-generated from curve.xml ) * * Draws a curved line on the screen. The first and second parameters * specify the beginning control point and the last two parameters specify * the ending control point. The middle parameters specify the start and * stop of the curve. Longer curves can be created by putting a series of * <b>curve()</b> functions together or using <b>curveVertex()</b>. An * additional function called <b>curveTightness()</b> provides control for * the visual quality of the curve. The <b>curve()</b> function is an * implementation of Catmull-Rom splines. Using the 3D version requires * rendering with P3D (see the Environment reference for more information). * * ( end auto-generated ) * * <h3>Advanced</h3> * As of revision 0070, this function no longer doubles the first * and last points. The curves are a bit more boring, but it's more * mathematically correct, and properly mirrored in curvePoint(). * <P> * Identical to typing out:<PRE> * beginShape(); * curveVertex(x1, y1); * curveVertex(x2, y2); * curveVertex(x3, y3); * curveVertex(x4, y4); * endShape(); * </PRE> * * @webref shape:curves * @param x1 coordinates for the beginning control point * @param y1 coordinates for the beginning control point * @param x2 coordinates for the first point * @param y2 coordinates for the first point * @param x3 coordinates for the second point * @param y3 coordinates for the second point * @param x4 coordinates for the ending control point * @param y4 coordinates for the ending control point * @see PGraphics#curveVertex(float, float) * @see PGraphics#curveTightness(float) * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) */ public void curve(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) { if (recorder != null) recorder.curve(x1, y1, x2, y2, x3, y3, x4, y4); g.curve(x1, y1, x2, y2, x3, y3, x4, y4); } /** * @param z1 coordinates for the beginning control point * @param z2 coordinates for the first point * @param z3 coordinates for the second point * @param z4 coordinates for the ending control point */ public void curve(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, float x4, float y4, float z4) { if (recorder != null) recorder.curve(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4); g.curve(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4); } /** * ( begin auto-generated from smooth.xml ) * * Draws all geometry with smooth (anti-aliased) edges. This will sometimes * slow down the frame rate of the application, but will enhance the visual * refinement. Note that <b>smooth()</b> will also improve image quality of * resized images, and <b>noSmooth()</b> will disable image (and font) * smoothing altogether. * * ( end auto-generated ) * * @webref shape:attributes * @see PGraphics#noSmooth() * @see PGraphics#hint(int) * @see PApplet#size(int, int, String) */ public void smooth() { if (recorder != null) recorder.smooth(); g.smooth(); } /** * * @param level either 2, 4, or 8 */ public void smooth(int level) { if (recorder != null) recorder.smooth(level); g.smooth(level); } /** * ( begin auto-generated from noSmooth.xml ) * * Draws all geometry with jagged (aliased) edges. * * ( end auto-generated ) * @webref shape:attributes * @see PGraphics#smooth() */ public void noSmooth() { if (recorder != null) recorder.noSmooth(); g.noSmooth(); } /** * ( begin auto-generated from imageMode.xml ) * * Modifies the location from which images draw. The default mode is * <b>imageMode(CORNER)</b>, which specifies the location to be the upper * left corner and uses the fourth and fifth parameters of <b>image()</b> * to set the image's width and height. The syntax * <b>imageMode(CORNERS)</b> uses the second and third parameters of * <b>image()</b> to set the location of one corner of the image and uses * the fourth and fifth parameters to set the opposite corner. Use * <b>imageMode(CENTER)</b> to draw images centered at the given x and y * position.<br /> * <br /> * The parameter to <b>imageMode()</b> must be written in ALL CAPS because * Processing is a case-sensitive language. * * ( end auto-generated ) * * @webref image:loading_displaying * @param mode either CORNER, CORNERS, or CENTER * @see PApplet#loadImage(String, String) * @see PImage * @see PGraphics#image(PImage, float, float, float, float) * @see PGraphics#background(float, float, float, float) */ public void imageMode(int mode) { if (recorder != null) recorder.imageMode(mode); g.imageMode(mode); } /** * ( begin auto-generated from image.xml ) * * Displays images to the screen. The images must be in the sketch's "data" * directory to load correctly. Select "Add file..." from the "Sketch" menu * to add the image. Processing currently works with GIF, JPEG, and Targa * images. The <b>img</b> parameter specifies the image to display and the * <b>x</b> and <b>y</b> parameters define the location of the image from * its upper-left corner. The image is displayed at its original size * unless the <b>width</b> and <b>height</b> parameters specify a different * size.<br /> * <br /> * The <b>imageMode()</b> function changes the way the parameters work. For * example, a call to <b>imageMode(CORNERS)</b> will change the * <b>width</b> and <b>height</b> parameters to define the x and y values * of the opposite corner of the image.<br /> * <br /> * The color of an image may be modified with the <b>tint()</b> function. * This function will maintain transparency for GIF and PNG images. * * ( end auto-generated ) * * <h3>Advanced</h3> * Starting with release 0124, when using the default (JAVA2D) renderer, * smooth() will also improve image quality of resized images. * * @webref image:loading_displaying * @param img the image to display * @param a x-coordinate of the image * @param b y-coordinate of the image * @see PApplet#loadImage(String, String) * @see PImage * @see PGraphics#imageMode(int) * @see PGraphics#tint(float) * @see PGraphics#background(float, float, float, float) * @see PGraphics#alpha(int) */ public void image(PImage img, float a, float b) { if (recorder != null) recorder.image(img, a, b); g.image(img, a, b); } /** * @param c width to display the image * @param d height to display the image */ public void image(PImage img, float a, float b, float c, float d) { if (recorder != null) recorder.image(img, a, b, c, d); g.image(img, a, b, c, d); } /** * Draw an image(), also specifying u/v coordinates. * In this method, the u, v coordinates are always based on image space * location, regardless of the current textureMode(). * * @nowebref */ public void image(PImage img, float a, float b, float c, float d, int u1, int v1, int u2, int v2) { if (recorder != null) recorder.image(img, a, b, c, d, u1, v1, u2, v2); g.image(img, a, b, c, d, u1, v1, u2, v2); } /** * ( begin auto-generated from shapeMode.xml ) * * Modifies the location from which shapes draw. The default mode is * <b>shapeMode(CORNER)</b>, which specifies the location to be the upper * left corner of the shape and uses the third and fourth parameters of * <b>shape()</b> to specify the width and height. The syntax * <b>shapeMode(CORNERS)</b> uses the first and second parameters of * <b>shape()</b> to set the location of one corner and uses the third and * fourth parameters to set the opposite corner. The syntax * <b>shapeMode(CENTER)</b> draws the shape from its center point and uses * the third and forth parameters of <b>shape()</b> to specify the width * and height. The parameter must be written in "ALL CAPS" because * Processing is a case sensitive language. * * ( end auto-generated ) * * @webref shape:loading_displaying * @param mode either CORNER, CORNERS, CENTER * @see PShape * @see PGraphics#shape(PShape) * @see PGraphics#rectMode(int) */ public void shapeMode(int mode) { if (recorder != null) recorder.shapeMode(mode); g.shapeMode(mode); } public void shape(PShape shape) { if (recorder != null) recorder.shape(shape); g.shape(shape); } /** * ( begin auto-generated from shape.xml ) * * Displays shapes to the screen. The shapes must be in the sketch's "data" * directory to load correctly. Select "Add file..." from the "Sketch" menu * to add the shape. Processing currently works with SVG shapes only. The * <b>sh</b> parameter specifies the shape to display and the <b>x</b> and * <b>y</b> parameters define the location of the shape from its upper-left * corner. The shape is displayed at its original size unless the * <b>width</b> and <b>height</b> parameters specify a different size. The * <b>shapeMode()</b> function changes the way the parameters work. A call * to <b>shapeMode(CORNERS)</b>, for example, will change the width and * height parameters to define the x and y values of the opposite corner of * the shape. * <br /><br /> * Note complex shapes may draw awkwardly with P3D. This renderer does not * yet support shapes that have holes or complicated breaks. * * ( end auto-generated ) * * @webref shape:loading_displaying * @param shape the shape to display * @param x x-coordinate of the shape * @param y y-coordinate of the shape * @see PShape * @see PApplet#loadShape(String) * @see PGraphics#shapeMode(int) * * Convenience method to draw at a particular location. */ public void shape(PShape shape, float x, float y) { if (recorder != null) recorder.shape(shape, x, y); g.shape(shape, x, y); } /** * @param a x-coordinate of the shape * @param b y-coordinate of the shape * @param c width to display the shape * @param d height to display the shape */ public void shape(PShape shape, float a, float b, float c, float d) { if (recorder != null) recorder.shape(shape, a, b, c, d); g.shape(shape, a, b, c, d); } public void textAlign(int alignX) { if (recorder != null) recorder.textAlign(alignX); g.textAlign(alignX); } /** * ( begin auto-generated from textAlign.xml ) * * Sets the current alignment for drawing text. The parameters LEFT, * CENTER, and RIGHT set the display characteristics of the letters in * relation to the values for the <b>x</b> and <b>y</b> parameters of the * <b>text()</b> function. * <br/> <br/> * In Processing 0125 and later, an optional second parameter can be used * to vertically align the text. BASELINE is the default, and the vertical * alignment will be reset to BASELINE if the second parameter is not used. * The TOP and CENTER parameters are straightforward. The BOTTOM parameter * offsets the line based on the current <b>textDescent()</b>. For multiple * lines, the final line will be aligned to the bottom, with the previous * lines appearing above it. * <br/> <br/> * When using <b>text()</b> with width and height parameters, BASELINE is * ignored, and treated as TOP. (Otherwise, text would by default draw * outside the box, since BASELINE is the default setting. BASELINE is not * a useful drawing mode for text drawn in a rectangle.) * <br/> <br/> * The vertical alignment is based on the value of <b>textAscent()</b>, * which many fonts do not specify correctly. It may be necessary to use a * hack and offset by a few pixels by hand so that the offset looks * correct. To do this as less of a hack, use some percentage of * <b>textAscent()</b> or <b>textDescent()</b> so that the hack works even * if you change the size of the font. * * ( end auto-generated ) * * @webref typography:attributes * @param alignX horizontal alignment, either LEFT, CENTER, or RIGHT * @param alignY vertical alignment, either TOP, BOTTOM, CENTER, or BASELINE * @see PApplet#loadFont(String) * @see PFont * @see PGraphics#text(String, float, float) */ public void textAlign(int alignX, int alignY) { if (recorder != null) recorder.textAlign(alignX, alignY); g.textAlign(alignX, alignY); } /** * ( begin auto-generated from textAscent.xml ) * * Returns ascent of the current font at its current size. This information * is useful for determining the height of the font above the baseline. For * example, adding the <b>textAscent()</b> and <b>textDescent()</b> values * will give you the total height of the line. * * ( end auto-generated ) * * @webref typography:metrics * @see PGraphics#textDescent() */ public float textAscent() { return g.textAscent(); } /** * ( begin auto-generated from textDescent.xml ) * * Returns descent of the current font at its current size. This * information is useful for determining the height of the font below the * baseline. For example, adding the <b>textAscent()</b> and * <b>textDescent()</b> values will give you the total height of the line. * * ( end auto-generated ) * * @webref typography:metrics * @see PGraphics#textAscent() */ public float textDescent() { return g.textDescent(); } /** * ( begin auto-generated from textFont.xml ) * * Sets the current font that will be drawn with the <b>text()</b> * function. Fonts must be loaded with <b>loadFont()</b> before it can be * used. This font will be used in all subsequent calls to the * <b>text()</b> function. If no <b>size</b> parameter is input, the font * will appear at its original size (the size it was created at with the * "Create Font..." tool) until it is changed with <b>textSize()</b>. <br * /> <br /> Because fonts are usually bitmaped, you should create fonts at * the sizes that will be used most commonly. Using <b>textFont()</b> * without the size parameter will result in the cleanest-looking text. <br * /><br /> With the default (JAVA2D) and PDF renderers, it's also possible * to enable the use of native fonts via the command * <b>hint(ENABLE_NATIVE_FONTS)</b>. This will produce vector text in * JAVA2D sketches and PDF output in cases where the vector data is * available: when the font is still installed, or the font is created via * the <b>createFont()</b> function (rather than the Create Font tool). * * ( end auto-generated ) * * @webref typography:loading_displaying * @param which any variable of the type PFont * @see PApplet#createFont(String, float, boolean) * @see PApplet#loadFont(String) * @see PFont * @see PGraphics#text(String, float, float) */ public void textFont(PFont which) { if (recorder != null) recorder.textFont(which); g.textFont(which); } /** * @param size the size of the letters in units of pixels */ public void textFont(PFont which, float size) { if (recorder != null) recorder.textFont(which, size); g.textFont(which, size); } /** * ( begin auto-generated from textLeading.xml ) * * Sets the spacing between lines of text in units of pixels. This setting * will be used in all subsequent calls to the <b>text()</b> function. * * ( end auto-generated ) * * @webref typography:attributes * @param leading the size in pixels for spacing between lines * @see PApplet#loadFont(String) * @see PFont#PFont * @see PGraphics#text(String, float, float) * @see PGraphics#textFont(PFont) */ public void textLeading(float leading) { if (recorder != null) recorder.textLeading(leading); g.textLeading(leading); } /** * ( begin auto-generated from textMode.xml ) * * Sets the way text draws to the screen. In the default configuration, the * <b>MODEL</b> mode, it's possible to rotate, scale, and place letters in * two and three dimensional space.<br /> * <br /> * The <b>SHAPE</b> mode draws text using the the glyph outlines of * individual characters rather than as textures. This mode is only * supported with the <b>PDF</b> and <b>P3D</b> renderer settings. With the * <b>PDF</b> renderer, you must call <b>textMode(SHAPE)</b> before any * other drawing occurs. If the outlines are not available, then * <b>textMode(SHAPE)</b> will be ignored and <b>textMode(MODEL)</b> will * be used instead.<br /> * <br /> * The <b>textMode(SHAPE)</b> option in <b>P3D</b> can be combined with * <b>beginRaw()</b> to write vector-accurate text to 2D and 3D output * files, for instance <b>DXF</b> or <b>PDF</b>. The <b>SHAPE</b> mode is * not currently optimized for <b>P3D</b>, so if recording shape data, use * <b>textMode(MODEL)</b> until you're ready to capture the geometry with <b>beginRaw()</b>. * * ( end auto-generated ) * * @webref typography:attributes * @param mode either MODEL or SHAPE * @see PApplet#loadFont(String) * @see PFont#PFont * @see PGraphics#text(String, float, float) * @see PGraphics#textFont(PFont) * @see PGraphics#beginRaw(PGraphics) * @see PApplet#createFont(String, float, boolean) */ public void textMode(int mode) { if (recorder != null) recorder.textMode(mode); g.textMode(mode); } /** * ( begin auto-generated from textSize.xml ) * * Sets the current font size. This size will be used in all subsequent * calls to the <b>text()</b> function. Font size is measured in units of pixels. * * ( end auto-generated ) * * @webref typography:attributes * @param size the size of the letters in units of pixels * @see PApplet#loadFont(String) * @see PFont#PFont * @see PGraphics#text(String, float, float) * @see PGraphics#textFont(PFont) */ public void textSize(float size) { if (recorder != null) recorder.textSize(size); g.textSize(size); } /** * @param c the character to measure */ public float textWidth(char c) { return g.textWidth(c); } /** * ( begin auto-generated from textWidth.xml ) * * Calculates and returns the width of any character or text string. * * ( end auto-generated ) * * @webref typography:attributes * @param str the String of characters to measure * @see PApplet#loadFont(String) * @see PFont#PFont * @see PGraphics#text(String, float, float) * @see PGraphics#textFont(PFont) */ public float textWidth(String str) { return g.textWidth(str); } /** * @nowebref */ public float textWidth(char[] chars, int start, int length) { return g.textWidth(chars, start, length); } /** * ( begin auto-generated from text.xml ) * * Draws text to the screen. Displays the information specified in the * <b>data</b> or <b>stringdata</b> parameters on the screen in the * position specified by the <b>x</b> and <b>y</b> parameters and the * optional <b>z</b> parameter. A default font will be used unless a font * is set with the <b>textFont()</b> function. Change the color of the text * with the <b>fill()</b> function. The text displays in relation to the * <b>textAlign()</b> function, which gives the option to draw to the left, * right, and center of the coordinates. * <br /><br /> * The <b>x2</b> and <b>y2</b> parameters define a rectangular area to * display within and may only be used with string data. For text drawn * inside a rectangle, the coordinates are interpreted based on the current * <b>rectMode()</b> setting. * * ( end auto-generated ) * * @webref typography:loading_displaying * @param c the alphanumeric character to be displayed * @param x x-coordinate of text * @param y y-coordinate of text * @see PGraphics#textAlign(int, int) * @see PGraphics#textMode(int) * @see PApplet#loadFont(String) * @see PGraphics#textFont(PFont) * @see PGraphics#rectMode(int) * @see PGraphics#fill(int, float) * @see_external String */ public void text(char c, float x, float y) { if (recorder != null) recorder.text(c, x, y); g.text(c, x, y); } /** * @param z z-coordinate of text */ public void text(char c, float x, float y, float z) { if (recorder != null) recorder.text(c, x, y, z); g.text(c, x, y, z); } /** * <h3>Advanced</h3> * Draw a chunk of text. * Newlines that are \n (Unix newline or linefeed char, ascii 10) * are honored, but \r (carriage return, Windows and Mac OS) are * ignored. */ public void text(String str, float x, float y) { if (recorder != null) recorder.text(str, x, y); g.text(str, x, y); } /** * <h3>Advanced</h3> * Method to draw text from an array of chars. This method will usually be * more efficient than drawing from a String object, because the String will * not be converted to a char array before drawing. * @param chars the alphanumberic symbols to be displayed * @param start array index at which to start writing characters * @param stop array index at which to stop writing characters */ public void text(char[] chars, int start, int stop, float x, float y) { if (recorder != null) recorder.text(chars, start, stop, x, y); g.text(chars, start, stop, x, y); } /** * Same as above but with a z coordinate. */ public void text(String str, float x, float y, float z) { if (recorder != null) recorder.text(str, x, y, z); g.text(str, x, y, z); } public void text(char[] chars, int start, int stop, float x, float y, float z) { if (recorder != null) recorder.text(chars, start, stop, x, y, z); g.text(chars, start, stop, x, y, z); } /** * <h3>Advanced</h3> * Draw text in a box that is constrained to a particular size. * The current rectMode() determines what the coordinates mean * (whether x1/y1/x2/y2 or x/y/w/h). * <P/> * Note that the x,y coords of the start of the box * will align with the *ascent* of the text, not the baseline, * as is the case for the other text() functions. * <P/> * Newlines that are \n (Unix newline or linefeed char, ascii 10) * are honored, and \r (carriage return, Windows and Mac OS) are * ignored. * * @param x1 by default, the x-coordinate of text, see rectMode() for more info * @param y1 by default, the x-coordinate of text, see rectMode() for more info * @param x2 by default, the width of the text box, see rectMode() for more info * @param y2 by default, the height of the text box, see rectMode() for more info */ public void text(String str, float x1, float y1, float x2, float y2) { if (recorder != null) recorder.text(str, x1, y1, x2, y2); g.text(str, x1, y1, x2, y2); } public void text(int num, float x, float y) { if (recorder != null) recorder.text(num, x, y); g.text(num, x, y); } public void text(int num, float x, float y, float z) { if (recorder != null) recorder.text(num, x, y, z); g.text(num, x, y, z); } /** * This does a basic number formatting, to avoid the * generally ugly appearance of printing floats. * Users who want more control should use their own nf() cmmand, * or if they want the long, ugly version of float, * use String.valueOf() to convert the float to a String first. * * @param num the numeric value to be displayed */ public void text(float num, float x, float y) { if (recorder != null) recorder.text(num, x, y); g.text(num, x, y); } public void text(float num, float x, float y, float z) { if (recorder != null) recorder.text(num, x, y, z); g.text(num, x, y, z); } /** * ( begin auto-generated from pushMatrix.xml ) * * Pushes the current transformation matrix onto the matrix stack. * Understanding <b>pushMatrix()</b> and <b>popMatrix()</b> requires * understanding the concept of a matrix stack. The <b>pushMatrix()</b> * function saves the current coordinate system to the stack and * <b>popMatrix()</b> restores the prior coordinate system. * <b>pushMatrix()</b> and <b>popMatrix()</b> are used in conjuction with * the other transformation functions and may be embedded to control the * scope of the transformations. * * ( end auto-generated ) * * @webref transform * @see PGraphics#popMatrix() * @see PGraphics#translate(float, float, float) * @see PGraphics#rotate(float) * @see PGraphics#rotateX(float) * @see PGraphics#rotateY(float) * @see PGraphics#rotateZ(float) */ public void pushMatrix() { if (recorder != null) recorder.pushMatrix(); g.pushMatrix(); } /** * ( begin auto-generated from popMatrix.xml ) * * Pops the current transformation matrix off the matrix stack. * Understanding pushing and popping requires understanding the concept of * a matrix stack. The <b>pushMatrix()</b> function saves the current * coordinate system to the stack and <b>popMatrix()</b> restores the prior * coordinate system. <b>pushMatrix()</b> and <b>popMatrix()</b> are used * in conjuction with the other transformation functions and may be * embedded to control the scope of the transformations. * * ( end auto-generated ) * * @webref transform * @see PGraphics#pushMatrix() */ public void popMatrix() { if (recorder != null) recorder.popMatrix(); g.popMatrix(); } /** * ( begin auto-generated from translate.xml ) * * Specifies an amount to displace objects within the display window. The * <b>x</b> parameter specifies left/right translation, the <b>y</b> * parameter specifies up/down translation, and the <b>z</b> parameter * specifies translations toward/away from the screen. Using this function * with the <b>z</b> parameter requires using P3D as a parameter in * combination with size as shown in the above example. Transformations * apply to everything that happens after and subsequent calls to the * function accumulates the effect. For example, calling <b>translate(50, * 0)</b> and then <b>translate(20, 0)</b> is the same as <b>translate(70, * 0)</b>. If <b>translate()</b> is called within <b>draw()</b>, the * transformation is reset when the loop begins again. This function can be * further controlled by the <b>pushMatrix()</b> and <b>popMatrix()</b>. * * ( end auto-generated ) * * @webref transform * @param x left/right translation * @param y up/down translation * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#rotate(float) * @see PGraphics#rotateX(float) * @see PGraphics#rotateY(float) * @see PGraphics#rotateZ(float) * @see PGraphics#scale(float, float, float) */ public void translate(float x, float y) { if (recorder != null) recorder.translate(x, y); g.translate(x, y); } /** * @param z forward/backward translation */ public void translate(float x, float y, float z) { if (recorder != null) recorder.translate(x, y, z); g.translate(x, y, z); } /** * ( begin auto-generated from rotate.xml ) * * Rotates a shape the amount specified by the <b>angle</b> parameter. * Angles should be specified in radians (values from 0 to TWO_PI) or * converted to radians with the <b>radians()</b> function. * <br/> <br/> * Objects are always rotated around their relative position to the origin * and positive numbers rotate objects in a clockwise direction. * Transformations apply to everything that happens after and subsequent * calls to the function accumulates the effect. For example, calling * <b>rotate(HALF_PI)</b> and then <b>rotate(HALF_PI)</b> is the same as * <b>rotate(PI)</b>. All tranformations are reset when <b>draw()</b> * begins again. * <br/> <br/> * Technically, <b>rotate()</b> multiplies the current transformation * matrix by a rotation matrix. This function can be further controlled by * the <b>pushMatrix()</b> and <b>popMatrix()</b>. * * ( end auto-generated ) * * @webref transform * @param angle angle of rotation specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#rotateX(float) * @see PGraphics#rotateY(float) * @see PGraphics#rotateZ(float) * @see PGraphics#scale(float, float, float) * @see PApplet#radians(float) */ public void rotate(float angle) { if (recorder != null) recorder.rotate(angle); g.rotate(angle); } /** * ( begin auto-generated from rotateX.xml ) * * Rotates a shape around the x-axis the amount specified by the * <b>angle</b> parameter. Angles should be specified in radians (values * from 0 to PI*2) or converted to radians with the <b>radians()</b> * function. Objects are always rotated around their relative position to * the origin and positive numbers rotate objects in a counterclockwise * direction. Transformations apply to everything that happens after and * subsequent calls to the function accumulates the effect. For example, * calling <b>rotateX(PI/2)</b> and then <b>rotateX(PI/2)</b> is the same * as <b>rotateX(PI)</b>. If <b>rotateX()</b> is called within the * <b>draw()</b>, the transformation is reset when the loop begins again. * This function requires using P3D as a third parameter to <b>size()</b> * as shown in the example above. * * ( end auto-generated ) * * @webref transform * @param angle angle of rotation specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#rotate(float) * @see PGraphics#rotateY(float) * @see PGraphics#rotateZ(float) * @see PGraphics#scale(float, float, float) * @see PGraphics#translate(float, float, float) */ public void rotateX(float angle) { if (recorder != null) recorder.rotateX(angle); g.rotateX(angle); } /** * ( begin auto-generated from rotateY.xml ) * * Rotates a shape around the y-axis the amount specified by the * <b>angle</b> parameter. Angles should be specified in radians (values * from 0 to PI*2) or converted to radians with the <b>radians()</b> * function. Objects are always rotated around their relative position to * the origin and positive numbers rotate objects in a counterclockwise * direction. Transformations apply to everything that happens after and * subsequent calls to the function accumulates the effect. For example, * calling <b>rotateY(PI/2)</b> and then <b>rotateY(PI/2)</b> is the same * as <b>rotateY(PI)</b>. If <b>rotateY()</b> is called within the * <b>draw()</b>, the transformation is reset when the loop begins again. * This function requires using P3D as a third parameter to <b>size()</b> * as shown in the examples above. * * ( end auto-generated ) * * @webref transform * @param angle angle of rotation specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#rotate(float) * @see PGraphics#rotateX(float) * @see PGraphics#rotateZ(float) * @see PGraphics#scale(float, float, float) * @see PGraphics#translate(float, float, float) */ public void rotateY(float angle) { if (recorder != null) recorder.rotateY(angle); g.rotateY(angle); } /** * ( begin auto-generated from rotateZ.xml ) * * Rotates a shape around the z-axis the amount specified by the * <b>angle</b> parameter. Angles should be specified in radians (values * from 0 to PI*2) or converted to radians with the <b>radians()</b> * function. Objects are always rotated around their relative position to * the origin and positive numbers rotate objects in a counterclockwise * direction. Transformations apply to everything that happens after and * subsequent calls to the function accumulates the effect. For example, * calling <b>rotateZ(PI/2)</b> and then <b>rotateZ(PI/2)</b> is the same * as <b>rotateZ(PI)</b>. If <b>rotateZ()</b> is called within the * <b>draw()</b>, the transformation is reset when the loop begins again. * This function requires using P3D as a third parameter to <b>size()</b> * as shown in the examples above. * * ( end auto-generated ) * * @webref transform * @param angle angle of rotation specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#rotate(float) * @see PGraphics#rotateX(float) * @see PGraphics#rotateY(float) * @see PGraphics#scale(float, float, float) * @see PGraphics#translate(float, float, float) */ public void rotateZ(float angle) { if (recorder != null) recorder.rotateZ(angle); g.rotateZ(angle); } /** * <h3>Advanced</h3> * Rotate about a vector in space. Same as the glRotatef() function. * @param x * @param y * @param z */ public void rotate(float angle, float x, float y, float z) { if (recorder != null) recorder.rotate(angle, x, y, z); g.rotate(angle, x, y, z); } /** * ( begin auto-generated from scale.xml ) * * Increases or decreases the size of a shape by expanding and contracting * vertices. Objects always scale from their relative origin to the * coordinate system. Scale values are specified as decimal percentages. * For example, the function call <b>scale(2.0)</b> increases the dimension * of a shape by 200%. Transformations apply to everything that happens * after and subsequent calls to the function multiply the effect. For * example, calling <b>scale(2.0)</b> and then <b>scale(1.5)</b> is the * same as <b>scale(3.0)</b>. If <b>scale()</b> is called within * <b>draw()</b>, the transformation is reset when the loop begins again. * Using this fuction with the <b>z</b> parameter requires using P3D as a * parameter for <b>size()</b> as shown in the example above. This function * can be further controlled by <b>pushMatrix()</b> and <b>popMatrix()</b>. * * ( end auto-generated ) * * @webref transform * @param s percentage to scale the object * @see PGraphics#pushMatrix() * @see PGraphics#popMatrix() * @see PGraphics#translate(float, float, float) * @see PGraphics#rotate(float) * @see PGraphics#rotateX(float) * @see PGraphics#rotateY(float) * @see PGraphics#rotateZ(float) */ public void scale(float s) { if (recorder != null) recorder.scale(s); g.scale(s); } /** * <h3>Advanced</h3> * Scale in X and Y. Equivalent to scale(sx, sy, 1). * * Not recommended for use in 3D, because the z-dimension is just * scaled by 1, since there's no way to know what else to scale it by. * * @param x percentage to scale the object in the x-axis * @param y percentage to scale the object in the y-axis */ public void scale(float x, float y) { if (recorder != null) recorder.scale(x, y); g.scale(x, y); } /** * @param z percentage to scale the object in the z-axis */ public void scale(float x, float y, float z) { if (recorder != null) recorder.scale(x, y, z); g.scale(x, y, z); } /** * ( begin auto-generated from shearX.xml ) * * Shears a shape around the x-axis the amount specified by the * <b>angle</b> parameter. Angles should be specified in radians (values * from 0 to PI*2) or converted to radians with the <b>radians()</b> * function. Objects are always sheared around their relative position to * the origin and positive numbers shear objects in a clockwise direction. * Transformations apply to everything that happens after and subsequent * calls to the function accumulates the effect. For example, calling * <b>shearX(PI/2)</b> and then <b>shearX(PI/2)</b> is the same as * <b>shearX(PI)</b>. If <b>shearX()</b> is called within the * <b>draw()</b>, the transformation is reset when the loop begins again. * <br/> <br/> * Technically, <b>shearX()</b> multiplies the current transformation * matrix by a rotation matrix. This function can be further controlled by * the <b>pushMatrix()</b> and <b>popMatrix()</b> functions. * * ( end auto-generated ) * * @webref transform * @param angle angle of shear specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#shearY(float) * @see PGraphics#scale(float, float, float) * @see PGraphics#translate(float, float, float) * @see PApplet#radians(float) */ public void shearX(float angle) { if (recorder != null) recorder.shearX(angle); g.shearX(angle); } /** * ( begin auto-generated from shearY.xml ) * * Shears a shape around the y-axis the amount specified by the * <b>angle</b> parameter. Angles should be specified in radians (values * from 0 to PI*2) or converted to radians with the <b>radians()</b> * function. Objects are always sheared around their relative position to * the origin and positive numbers shear objects in a clockwise direction. * Transformations apply to everything that happens after and subsequent * calls to the function accumulates the effect. For example, calling * <b>shearY(PI/2)</b> and then <b>shearY(PI/2)</b> is the same as * <b>shearY(PI)</b>. If <b>shearY()</b> is called within the * <b>draw()</b>, the transformation is reset when the loop begins again. * <br/> <br/> * Technically, <b>shearY()</b> multiplies the current transformation * matrix by a rotation matrix. This function can be further controlled by * the <b>pushMatrix()</b> and <b>popMatrix()</b> functions. * * ( end auto-generated ) * * @webref transform * @param angle angle of shear specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#shearX(float) * @see PGraphics#scale(float, float, float) * @see PGraphics#translate(float, float, float) * @see PApplet#radians(float) */ public void shearY(float angle) { if (recorder != null) recorder.shearY(angle); g.shearY(angle); } /** * ( begin auto-generated from resetMatrix.xml ) * * Replaces the current matrix with the identity matrix. The equivalent * function in OpenGL is glLoadIdentity(). * * ( end auto-generated ) * * @webref transform * @see PGraphics#pushMatrix() * @see PGraphics#popMatrix() * @see PGraphics#applyMatrix(PMatrix) * @see PGraphics#printMatrix() */ public void resetMatrix() { if (recorder != null) recorder.resetMatrix(); g.resetMatrix(); } /** * ( begin auto-generated from applyMatrix.xml ) * * Multiplies the current matrix by the one specified through the * parameters. This is very slow because it will try to calculate the * inverse of the transform, so avoid it whenever possible. The equivalent * function in OpenGL is glMultMatrix(). * * ( end auto-generated ) * * @webref transform * @source * @see PGraphics#pushMatrix() * @see PGraphics#popMatrix() * @see PGraphics#resetMatrix() * @see PGraphics#printMatrix() */ public void applyMatrix(PMatrix source) { if (recorder != null) recorder.applyMatrix(source); g.applyMatrix(source); } public void applyMatrix(PMatrix2D source) { if (recorder != null) recorder.applyMatrix(source); g.applyMatrix(source); } /** * @param n00 numbers which define the 4x4 matrix to be multiplied * @param n01 numbers which define the 4x4 matrix to be multiplied * @param n02 numbers which define the 4x4 matrix to be multiplied * @param n10 numbers which define the 4x4 matrix to be multiplied * @param n11 numbers which define the 4x4 matrix to be multiplied * @param n12 numbers which define the 4x4 matrix to be multiplied */ public void applyMatrix(float n00, float n01, float n02, float n10, float n11, float n12) { if (recorder != null) recorder.applyMatrix(n00, n01, n02, n10, n11, n12); g.applyMatrix(n00, n01, n02, n10, n11, n12); } public void applyMatrix(PMatrix3D source) { if (recorder != null) recorder.applyMatrix(source); g.applyMatrix(source); } /** * @param n03 numbers which define the 4x4 matrix to be multiplied * @param n13 numbers which define the 4x4 matrix to be multiplied * @param n20 numbers which define the 4x4 matrix to be multiplied * @param n21 numbers which define the 4x4 matrix to be multiplied * @param n22 numbers which define the 4x4 matrix to be multiplied * @param n23 numbers which define the 4x4 matrix to be multiplied * @param n30 numbers which define the 4x4 matrix to be multiplied * @param n31 numbers which define the 4x4 matrix to be multiplied * @param n32 numbers which define the 4x4 matrix to be multiplied * @param n33 numbers which define the 4x4 matrix to be multiplied */ public void applyMatrix(float n00, float n01, float n02, float n03, float n10, float n11, float n12, float n13, float n20, float n21, float n22, float n23, float n30, float n31, float n32, float n33) { if (recorder != null) recorder.applyMatrix(n00, n01, n02, n03, n10, n11, n12, n13, n20, n21, n22, n23, n30, n31, n32, n33); g.applyMatrix(n00, n01, n02, n03, n10, n11, n12, n13, n20, n21, n22, n23, n30, n31, n32, n33); } public PMatrix getMatrix() { return g.getMatrix(); } /** * Copy the current transformation matrix into the specified target. * Pass in null to create a new matrix. */ public PMatrix2D getMatrix(PMatrix2D target) { return g.getMatrix(target); } /** * Copy the current transformation matrix into the specified target. * Pass in null to create a new matrix. */ public PMatrix3D getMatrix(PMatrix3D target) { return g.getMatrix(target); } /** * Set the current transformation matrix to the contents of another. */ public void setMatrix(PMatrix source) { if (recorder != null) recorder.setMatrix(source); g.setMatrix(source); } /** * Set the current transformation to the contents of the specified source. */ public void setMatrix(PMatrix2D source) { if (recorder != null) recorder.setMatrix(source); g.setMatrix(source); } /** * Set the current transformation to the contents of the specified source. */ public void setMatrix(PMatrix3D source) { if (recorder != null) recorder.setMatrix(source); g.setMatrix(source); } /** * ( begin auto-generated from printMatrix.xml ) * * Prints the current matrix to the Console (the text window at the bottom * of Processing). * * ( end auto-generated ) * * @webref transform * @see PGraphics#pushMatrix() * @see PGraphics#popMatrix() * @see PGraphics#resetMatrix() * @see PGraphics#applyMatrix(PMatrix) */ public void printMatrix() { if (recorder != null) recorder.printMatrix(); g.printMatrix(); } /** * ( begin auto-generated from beginCamera.xml ) * * The <b>beginCamera()</b> and <b>endCamera()</b> functions enable * advanced customization of the camera space. The functions are useful if * you want to more control over camera movement, however for most users, * the <b>camera()</b> function will be sufficient.<br /><br />The camera * functions will replace any transformations (such as <b>rotate()</b> or * <b>translate()</b>) that occur before them in <b>draw()</b>, but they * will not automatically replace the camera transform itself. For this * reason, camera functions should be placed at the beginning of * <b>draw()</b> (so that transformations happen afterwards), and the * <b>camera()</b> function can be used after <b>beginCamera()</b> if you * want to reset the camera before applying transformations.<br /><br * />This function sets the matrix mode to the camera matrix so calls such * as <b>translate()</b>, <b>rotate()</b>, applyMatrix() and resetMatrix() * affect the camera. <b>beginCamera()</b> should always be used with a * following <b>endCamera()</b> and pairs of <b>beginCamera()</b> and * <b>endCamera()</b> cannot be nested. * * ( end auto-generated ) * * @webref lights_camera:camera * @see PGraphics#camera() * @see PGraphics#endCamera() * @see PGraphics#applyMatrix(PMatrix) * @see PGraphics#resetMatrix() * @see PGraphics#translate(float, float, float) * @see PGraphics#scale(float, float, float) */ public void beginCamera() { if (recorder != null) recorder.beginCamera(); g.beginCamera(); } /** * ( begin auto-generated from endCamera.xml ) * * The <b>beginCamera()</b> and <b>endCamera()</b> functions enable * advanced customization of the camera space. Please see the reference for * <b>beginCamera()</b> for a description of how the functions are used. * * ( end auto-generated ) * * @webref lights_camera:camera * @see PGraphics#camera(float, float, float, float, float, float, float, float, float) */ public void endCamera() { if (recorder != null) recorder.endCamera(); g.endCamera(); } /** * ( begin auto-generated from camera.xml ) * * Sets the position of the camera through setting the eye position, the * center of the scene, and which axis is facing upward. Moving the eye * position and the direction it is pointing (the center of the scene) * allows the images to be seen from different angles. The version without * any parameters sets the camera to the default position, pointing to the * center of the display window with the Y axis as up. The default values * are <b>camera(width/2.0, height/2.0, (height/2.0) / tan(PI*30.0 / * 180.0), width/2.0, height/2.0, 0, 0, 1, 0)</b>. This function is similar * to <b>gluLookAt()</b> in OpenGL, but it first clears the current camera settings. * * ( end auto-generated ) * * @webref lights_camera:camera * @see PGraphics#endCamera() * @see PGraphics#frustum(float, float, float, float, float, float) */ public void camera() { if (recorder != null) recorder.camera(); g.camera(); } /** * @param eyeX x-coordinate for the eye * @param eyeY y-coordinate for the eye * @param eyeZ z-coordinate for the eye * @param centerX x-coordinate for the center of the scene * @param centerY y-coordinate for the center of the scene * @param centerZ z-coordinate for the center of the scene * @param upX usually 0.0, 1.0, or -1.0 * @param upY usually 0.0, 1.0, or -1.0 * @param upZ usually 0.0, 1.0, or -1.0 */ public void camera(float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ) { if (recorder != null) recorder.camera(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ); g.camera(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ); } /** * ( begin auto-generated from printCamera.xml ) * * Prints the current camera matrix to the Console (the text window at the * bottom of Processing). * * ( end auto-generated ) * @webref lights_camera:camera * @see PGraphics#camera(float, float, float, float, float, float, float, float, float) */ public void printCamera() { if (recorder != null) recorder.printCamera(); g.printCamera(); } /** * ( begin auto-generated from ortho.xml ) * * Sets an orthographic projection and defines a parallel clipping volume. * All objects with the same dimension appear the same size, regardless of * whether they are near or far from the camera. The parameters to this * function specify the clipping volume where left and right are the * minimum and maximum x values, top and bottom are the minimum and maximum * y values, and near and far are the minimum and maximum z values. If no * parameters are given, the default is used: ortho(0, width, 0, height, * -10, 10). * * ( end auto-generated ) * * @webref lights_camera:camera */ public void ortho() { if (recorder != null) recorder.ortho(); g.ortho(); } /** * @param left left plane of the clipping volume * @param right right plane of the clipping volume * @param bottom bottom plane of the clipping volume * @param top top plane of the clipping volume */ public void ortho(float left, float right, float bottom, float top) { if (recorder != null) recorder.ortho(left, right, bottom, top); g.ortho(left, right, bottom, top); } /** * @param near maximum distance from the origin to the viewer * @param far maximum distance from the origin away from the viewer */ public void ortho(float left, float right, float bottom, float top, float near, float far) { if (recorder != null) recorder.ortho(left, right, bottom, top, near, far); g.ortho(left, right, bottom, top, near, far); } /** * ( begin auto-generated from perspective.xml ) * * Sets a perspective projection applying foreshortening, making distant * objects appear smaller than closer ones. The parameters define a viewing * volume with the shape of truncated pyramid. Objects near to the front of * the volume appear their actual size, while farther objects appear * smaller. This projection simulates the perspective of the world more * accurately than orthographic projection. The version of perspective * without parameters sets the default perspective and the version with * four parameters allows the programmer to set the area precisely. The * default values are: perspective(PI/3.0, width/height, cameraZ/10.0, * cameraZ*10.0) where cameraZ is ((height/2.0) / tan(PI*60.0/360.0)); * * ( end auto-generated ) * * @webref lights_camera:camera */ public void perspective() { if (recorder != null) recorder.perspective(); g.perspective(); } /** * @param fovy field-of-view angle (in radians) for vertical direction * @param aspect ratio of width to height * @param zNear z-position of nearest clipping plane * @param zFar z-position of farthest clipping plane */ public void perspective(float fovy, float aspect, float zNear, float zFar) { if (recorder != null) recorder.perspective(fovy, aspect, zNear, zFar); g.perspective(fovy, aspect, zNear, zFar); } /** * ( begin auto-generated from frustum.xml ) * * Sets a perspective matrix defined through the parameters. Works like * glFrustum, except it wipes out the current perspective matrix rather * than muliplying itself with it. * * ( end auto-generated ) * * @webref lights_camera:camera * @param left left coordinate of the clipping plane * @param right right coordinate of the clipping plane * @param bottom bottom coordinate of the clipping plane * @param top top coordinate of the clipping plane * @param near near component of the clipping plane; must be greater than zero * @param far far component of the clipping plane; must be greater than the near value * @see PGraphics#camera(float, float, float, float, float, float, float, float, float) * @see PGraphics#endCamera() * @see PGraphics#perspective(float, float, float, float) */ public void frustum(float left, float right, float bottom, float top, float near, float far) { if (recorder != null) recorder.frustum(left, right, bottom, top, near, far); g.frustum(left, right, bottom, top, near, far); } /** * ( begin auto-generated from printProjection.xml ) * * Prints the current projection matrix to the Console (the text window at * the bottom of Processing). * * ( end auto-generated ) * * @webref lights_camera:camera * @see PGraphics#camera(float, float, float, float, float, float, float, float, float) */ public void printProjection() { if (recorder != null) recorder.printProjection(); g.printProjection(); } /** * ( begin auto-generated from screenX.xml ) * * Takes a three-dimensional X, Y, Z position and returns the X value for * where it will appear on a (two-dimensional) screen. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @see PGraphics#screenY(float, float, float) * @see PGraphics#screenZ(float, float, float) */ public float screenX(float x, float y) { return g.screenX(x, y); } /** * ( begin auto-generated from screenY.xml ) * * Takes a three-dimensional X, Y, Z position and returns the Y value for * where it will appear on a (two-dimensional) screen. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @see PGraphics#screenX(float, float, float) * @see PGraphics#screenZ(float, float, float) */ public float screenY(float x, float y) { return g.screenY(x, y); } /** * @param z 3D z-coordinate to be mapped */ public float screenX(float x, float y, float z) { return g.screenX(x, y, z); } /** * @param z 3D z-coordinate to be mapped */ public float screenY(float x, float y, float z) { return g.screenY(x, y, z); } /** * ( begin auto-generated from screenZ.xml ) * * Takes a three-dimensional X, Y, Z position and returns the Z value for * where it will appear on a (two-dimensional) screen. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @param z 3D z-coordinate to be mapped * @see PGraphics#screenX(float, float, float) * @see PGraphics#screenY(float, float, float) */ public float screenZ(float x, float y, float z) { return g.screenZ(x, y, z); } /** * ( begin auto-generated from modelX.xml ) * * Returns the three-dimensional X, Y, Z position in model space. This * returns the X value for a given coordinate based on the current set of * transformations (scale, rotate, translate, etc.) The X value can be used * to place an object in space relative to the location of the original * point once the transformations are no longer in use. * <br/> <br/> * In the example, the <b>modelX()</b>, <b>modelY()</b>, and * <b>modelZ()</b> functions record the location of a box in space after * being placed using a series of translate and rotate commands. After * popMatrix() is called, those transformations no longer apply, but the * (x, y, z) coordinate returned by the model functions is used to place * another box in the same location. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @param z 3D z-coordinate to be mapped * @see PGraphics#modelY(float, float, float) * @see PGraphics#modelZ(float, float, float) */ public float modelX(float x, float y, float z) { return g.modelX(x, y, z); } /** * ( begin auto-generated from modelY.xml ) * * Returns the three-dimensional X, Y, Z position in model space. This * returns the Y value for a given coordinate based on the current set of * transformations (scale, rotate, translate, etc.) The Y value can be used * to place an object in space relative to the location of the original * point once the transformations are no longer in use.<br /> * <br /> * In the example, the <b>modelX()</b>, <b>modelY()</b>, and * <b>modelZ()</b> functions record the location of a box in space after * being placed using a series of translate and rotate commands. After * popMatrix() is called, those transformations no longer apply, but the * (x, y, z) coordinate returned by the model functions is used to place * another box in the same location. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @param z 3D z-coordinate to be mapped * @see PGraphics#modelX(float, float, float) * @see PGraphics#modelZ(float, float, float) */ public float modelY(float x, float y, float z) { return g.modelY(x, y, z); } /** * ( begin auto-generated from modelZ.xml ) * * Returns the three-dimensional X, Y, Z position in model space. This * returns the Z value for a given coordinate based on the current set of * transformations (scale, rotate, translate, etc.) The Z value can be used * to place an object in space relative to the location of the original * point once the transformations are no longer in use.<br /> * <br /> * In the example, the <b>modelX()</b>, <b>modelY()</b>, and * <b>modelZ()</b> functions record the location of a box in space after * being placed using a series of translate and rotate commands. After * popMatrix() is called, those transformations no longer apply, but the * (x, y, z) coordinate returned by the model functions is used to place * another box in the same location. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @param z 3D z-coordinate to be mapped * @see PGraphics#modelX(float, float, float) * @see PGraphics#modelY(float, float, float) */ public float modelZ(float x, float y, float z) { return g.modelZ(x, y, z); } /** * ( begin auto-generated from pushStyle.xml ) * * The <b>pushStyle()</b> function saves the current style settings and * <b>popStyle()</b> restores the prior settings. Note that these functions * are always used together. They allow you to change the style settings * and later return to what you had. When a new style is started with * <b>pushStyle()</b>, it builds on the current style information. The * <b>pushStyle()</b> and <b>popStyle()</b> functions can be embedded to * provide more control (see the second example above for a demonstration.) * <br /><br /> * The style information controlled by the following functions are included * in the style: * fill(), stroke(), tint(), strokeWeight(), strokeCap(), strokeJoin(), * imageMode(), rectMode(), ellipseMode(), shapeMode(), colorMode(), * textAlign(), textFont(), textMode(), textSize(), textLeading(), * emissive(), specular(), shininess(), ambient() * * ( end auto-generated ) * * @webref structure * @see PGraphics#popStyle() */ public void pushStyle() { if (recorder != null) recorder.pushStyle(); g.pushStyle(); } /** * ( begin auto-generated from popStyle.xml ) * * The <b>pushStyle()</b> function saves the current style settings and * <b>popStyle()</b> restores the prior settings; these functions are * always used together. They allow you to change the style settings and * later return to what you had. When a new style is started with * <b>pushStyle()</b>, it builds on the current style information. The * <b>pushStyle()</b> and <b>popStyle()</b> functions can be embedded to * provide more control (see the second example above for a demonstration.) * * ( end auto-generated ) * * @webref structure * @see PGraphics#pushStyle() */ public void popStyle() { if (recorder != null) recorder.popStyle(); g.popStyle(); } public void style(PStyle s) { if (recorder != null) recorder.style(s); g.style(s); } /** * ( begin auto-generated from strokeWeight.xml ) * * Sets the width of the stroke used for lines, points, and the border * around shapes. All widths are set in units of pixels. * <br/> <br/> * When drawing with P3D, series of connected lines (such as the stroke * around a polygon, triangle, or ellipse) produce unattractive results * when a thick stroke weight is set (<a * href="http://code.google.com/p/processing/issues/detail?id=123">see * Issue 123</a>). With P3D, the minimum and maximum values for * <b>strokeWeight()</b> are controlled by the graphics card and the * operating system's OpenGL implementation. For instance, the thickness * may not go higher than 10 pixels. * * ( end auto-generated ) * * @webref shape:attributes * @param weight the weight (in pixels) of the stroke * @see PGraphics#stroke(int, float) * @see PGraphics#strokeJoin(int) * @see PGraphics#strokeCap(int) */ public void strokeWeight(float weight) { if (recorder != null) recorder.strokeWeight(weight); g.strokeWeight(weight); } /** * ( begin auto-generated from strokeJoin.xml ) * * Sets the style of the joints which connect line segments. These joints * are either mitered, beveled, or rounded and specified with the * corresponding parameters MITER, BEVEL, and ROUND. The default joint is * MITER. * <br/> <br/> * This function is not available with the P3D renderer, (<a * href="http://code.google.com/p/processing/issues/detail?id=123">see * Issue 123</a>). More information about the renderers can be found in the * <b>size()</b> reference. * * ( end auto-generated ) * * @webref shape:attributes * @param join either MITER, BEVEL, ROUND * @see PGraphics#stroke(int, float) * @see PGraphics#strokeWeight(float) * @see PGraphics#strokeCap(int) */ public void strokeJoin(int join) { if (recorder != null) recorder.strokeJoin(join); g.strokeJoin(join); } /** * ( begin auto-generated from strokeCap.xml ) * * Sets the style for rendering line endings. These ends are either * squared, extended, or rounded and specified with the corresponding * parameters SQUARE, PROJECT, and ROUND. The default cap is ROUND. * <br/> <br/> * This function is not available with the P3D renderer (<a * href="http://code.google.com/p/processing/issues/detail?id=123">see * Issue 123</a>). More information about the renderers can be found in the * <b>size()</b> reference. * * ( end auto-generated ) * * @webref shape:attributes * @param cap either SQUARE, PROJECT, or ROUND * @see PGraphics#stroke(int, float) * @see PGraphics#strokeWeight(float) * @see PGraphics#strokeJoin(int) * @see PApplet#size(int, int, String, String) */ public void strokeCap(int cap) { if (recorder != null) recorder.strokeCap(cap); g.strokeCap(cap); } /** * ( begin auto-generated from noStroke.xml ) * * Disables drawing the stroke (outline). If both <b>noStroke()</b> and * <b>noFill()</b> are called, nothing will be drawn to the screen. * * ( end auto-generated ) * * @webref color:setting * @see PGraphics#stroke(float, float, float, float) */ public void noStroke() { if (recorder != null) recorder.noStroke(); g.noStroke(); } /** * ( begin auto-generated from stroke.xml ) * * Sets the color used to draw lines and borders around shapes. This color * is either specified in terms of the RGB or HSB color depending on the * current <b>colorMode()</b> (the default color space is RGB, with each * value in the range from 0 to 255). * <br/> <br/> * When using hexadecimal notation to specify a color, use "#" or "0x" * before the values (e.g. #CCFFAA, 0xFFCCFFAA). The # syntax uses six * digits to specify a color (the way colors are specified in HTML and * CSS). When using the hexadecimal notation starting with "0x", the * hexadecimal value must be specified with eight characters; the first two * characters define the alpha component and the remainder the red, green, * and blue components. * <br/> <br/> * The value for the parameter "gray" must be less than or equal to the * current maximum value as specified by <b>colorMode()</b>. The default * maximum value is 255. * * ( end auto-generated ) * * @param rgb color value in hexadecimal notation * @see PGraphics#noStroke() * @see PGraphics#fill(int, float) * @see PGraphics#tint(int, float) * @see PGraphics#background(float, float, float, float) * @see PGraphics#colorMode(int, float, float, float, float) */ public void stroke(int rgb) { if (recorder != null) recorder.stroke(rgb); g.stroke(rgb); } /** * @param alpha opacity of the stroke */ public void stroke(int rgb, float alpha) { if (recorder != null) recorder.stroke(rgb, alpha); g.stroke(rgb, alpha); } /** * @param gray specifies a value between white and black */ public void stroke(float gray) { if (recorder != null) recorder.stroke(gray); g.stroke(gray); } public void stroke(float gray, float alpha) { if (recorder != null) recorder.stroke(gray, alpha); g.stroke(gray, alpha); } /** * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) * @webref color:setting */ public void stroke(float v1, float v2, float v3) { if (recorder != null) recorder.stroke(v1, v2, v3); g.stroke(v1, v2, v3); } public void stroke(float v1, float v2, float v3, float alpha) { if (recorder != null) recorder.stroke(v1, v2, v3, alpha); g.stroke(v1, v2, v3, alpha); } /** * ( begin auto-generated from noTint.xml ) * * Removes the current fill value for displaying images and reverts to * displaying images with their original hues. * * ( end auto-generated ) * * @webref image:loading_displaying * @usage web_application * @see PGraphics#tint(float, float, float, float) * @see PGraphics#image(PImage, float, float, float, float) */ public void noTint() { if (recorder != null) recorder.noTint(); g.noTint(); } /** * ( begin auto-generated from tint.xml ) * * Sets the fill value for displaying images. Images can be tinted to * specified colors or made transparent by setting the alpha.<br /> * <br /> * To make an image transparent, but not change it's color, use white as * the tint color and specify an alpha value. For instance, tint(255, 128) * will make an image 50% transparent (unless <b>colorMode()</b> has been * used).<br /> * <br /> * When using hexadecimal notation to specify a color, use "#" or "0x" * before the values (e.g. #CCFFAA, 0xFFCCFFAA). The # syntax uses six * digits to specify a color (the way colors are specified in HTML and * CSS). When using the hexadecimal notation starting with "0x", the * hexadecimal value must be specified with eight characters; the first two * characters define the alpha component and the remainder the red, green, * and blue components.<br /> * <br /> * The value for the parameter "gray" must be less than or equal to the * current maximum value as specified by <b>colorMode()</b>. The default * maximum value is 255.<br /> * <br /> * The <b>tint()</b> function is also used to control the coloring of * textures in 3D. * * ( end auto-generated ) * * @webref image:loading_displaying * @usage web_application * @param rgb color value in hexadecimal notation * @see PGraphics#noTint() * @see PGraphics#image(PImage, float, float, float, float) */ public void tint(int rgb) { if (recorder != null) recorder.tint(rgb); g.tint(rgb); } /** * @param alpha opacity of the image */ public void tint(int rgb, float alpha) { if (recorder != null) recorder.tint(rgb, alpha); g.tint(rgb, alpha); } /** * @param gray specifies a value between white and black */ public void tint(float gray) { if (recorder != null) recorder.tint(gray); g.tint(gray); } public void tint(float gray, float alpha) { if (recorder != null) recorder.tint(gray, alpha); g.tint(gray, alpha); } /** * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) */ public void tint(float v1, float v2, float v3) { if (recorder != null) recorder.tint(v1, v2, v3); g.tint(v1, v2, v3); } public void tint(float v1, float v2, float v3, float alpha) { if (recorder != null) recorder.tint(v1, v2, v3, alpha); g.tint(v1, v2, v3, alpha); } /** * ( begin auto-generated from noFill.xml ) * * Disables filling geometry. If both <b>noStroke()</b> and <b>noFill()</b> * are called, nothing will be drawn to the screen. * * ( end auto-generated ) * * @webref color:setting * @usage web_application * @see PGraphics#fill(float, float, float, float) */ public void noFill() { if (recorder != null) recorder.noFill(); g.noFill(); } /** * ( begin auto-generated from fill.xml ) * * Sets the color used to fill shapes. For example, if you run <b>fill(204, * 102, 0)</b>, all subsequent shapes will be filled with orange. This * color is either specified in terms of the RGB or HSB color depending on * the current <b>colorMode()</b> (the default color space is RGB, with * each value in the range from 0 to 255). * <br/> <br/> * When using hexadecimal notation to specify a color, use "#" or "0x" * before the values (e.g. #CCFFAA, 0xFFCCFFAA). The # syntax uses six * digits to specify a color (the way colors are specified in HTML and * CSS). When using the hexadecimal notation starting with "0x", the * hexadecimal value must be specified with eight characters; the first two * characters define the alpha component and the remainder the red, green, * and blue components. * <br/> <br/> * The value for the parameter "gray" must be less than or equal to the * current maximum value as specified by <b>colorMode()</b>. The default * maximum value is 255. * <br/> <br/> * To change the color of an image (or a texture), use tint(). * * ( end auto-generated ) * * @webref color:setting * @usage web_application * @param rgb color variable or hex value * @see PGraphics#noFill() * @see PGraphics#stroke(int, float) * @see PGraphics#tint(int, float) * @see PGraphics#background(float, float, float, float) * @see PGraphics#colorMode(int, float, float, float, float) */ public void fill(int rgb) { if (recorder != null) recorder.fill(rgb); g.fill(rgb); } /** * @param alpha opacity of the fill */ public void fill(int rgb, float alpha) { if (recorder != null) recorder.fill(rgb, alpha); g.fill(rgb, alpha); } /** * @param gray number specifying value between white and black */ public void fill(float gray) { if (recorder != null) recorder.fill(gray); g.fill(gray); } public void fill(float gray, float alpha) { if (recorder != null) recorder.fill(gray, alpha); g.fill(gray, alpha); } /** * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) */ public void fill(float v1, float v2, float v3) { if (recorder != null) recorder.fill(v1, v2, v3); g.fill(v1, v2, v3); } public void fill(float v1, float v2, float v3, float alpha) { if (recorder != null) recorder.fill(v1, v2, v3, alpha); g.fill(v1, v2, v3, alpha); } /** * ( begin auto-generated from ambient.xml ) * * Sets the ambient reflectance for shapes drawn to the screen. This is * combined with the ambient light component of environment. The color * components set through the parameters define the reflectance. For * example in the default color mode, setting v1=255, v2=126, v3=0, would * cause all the red light to reflect and half of the green light to * reflect. Used in combination with <b>emissive()</b>, <b>specular()</b>, * and <b>shininess()</b> in setting the material properties of shapes. * * ( end auto-generated ) * * @webref lights_camera:material_properties * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#emissive(float, float, float) * @see PGraphics#specular(float, float, float) * @see PGraphics#shininess(float) */ public void ambient(int rgb) { if (recorder != null) recorder.ambient(rgb); g.ambient(rgb); } /** * @param gray number specifying value between white and black */ public void ambient(float gray) { if (recorder != null) recorder.ambient(gray); g.ambient(gray); } /** * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) */ public void ambient(float v1, float v2, float v3) { if (recorder != null) recorder.ambient(v1, v2, v3); g.ambient(v1, v2, v3); } /** * ( begin auto-generated from specular.xml ) * * Sets the specular color of the materials used for shapes drawn to the * screen, which sets the color of hightlights. Specular refers to light * which bounces off a surface in a perferred direction (rather than * bouncing in all directions like a diffuse light). Used in combination * with <b>emissive()</b>, <b>ambient()</b>, and <b>shininess()</b> in * setting the material properties of shapes. * * ( end auto-generated ) * * @webref lights_camera:material_properties * @usage web_application * @param rgb color to set * @see PGraphics#lightSpecular(float, float, float) * @see PGraphics#ambient(float, float, float) * @see PGraphics#emissive(float, float, float) * @see PGraphics#shininess(float) */ public void specular(int rgb) { if (recorder != null) recorder.specular(rgb); g.specular(rgb); } /** * gray number specifying value between white and black */ public void specular(float gray) { if (recorder != null) recorder.specular(gray); g.specular(gray); } /** * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) */ public void specular(float v1, float v2, float v3) { if (recorder != null) recorder.specular(v1, v2, v3); g.specular(v1, v2, v3); } /** * ( begin auto-generated from shininess.xml ) * * Sets the amount of gloss in the surface of shapes. Used in combination * with <b>ambient()</b>, <b>specular()</b>, and <b>emissive()</b> in * setting the material properties of shapes. * * ( end auto-generated ) * * @webref lights_camera:material_properties * @usage web_application * @param shine degree of shininess * @see PGraphics#emissive(float, float, float) * @see PGraphics#ambient(float, float, float) * @see PGraphics#specular(float, float, float) */ public void shininess(float shine) { if (recorder != null) recorder.shininess(shine); g.shininess(shine); } /** * ( begin auto-generated from emissive.xml ) * * Sets the emissive color of the material used for drawing shapes drawn to * the screen. Used in combination with <b>ambient()</b>, * <b>specular()</b>, and <b>shininess()</b> in setting the material * properties of shapes. * * ( end auto-generated ) * * @webref lights_camera:material_properties * @usage web_application * @param rgb color to set * @see PGraphics#ambient(float, float, float) * @see PGraphics#specular(float, float, float) * @see PGraphics#shininess(float) */ public void emissive(int rgb) { if (recorder != null) recorder.emissive(rgb); g.emissive(rgb); } /** * gray number specifying value between white and black */ public void emissive(float gray) { if (recorder != null) recorder.emissive(gray); g.emissive(gray); } /** * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) */ public void emissive(float v1, float v2, float v3) { if (recorder != null) recorder.emissive(v1, v2, v3); g.emissive(v1, v2, v3); } /** * ( begin auto-generated from lights.xml ) * * Sets the default ambient light, directional light, falloff, and specular * values. The defaults are ambientLight(128, 128, 128) and * directionalLight(128, 128, 128, 0, 0, -1), lightFalloff(1, 0, 0), and * lightSpecular(0, 0, 0). Lights need to be included in the draw() to * remain persistent in a looping program. Placing them in the setup() of a * looping program will cause them to only have an effect the first time * through the loop. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @see PGraphics#ambientLight(float, float, float, float, float, float) * @see PGraphics#directionalLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#noLights() */ public void lights() { if (recorder != null) recorder.lights(); g.lights(); } /** * ( begin auto-generated from noLights.xml ) * * Disable all lighting. Lighting is turned off by default and enabled with * the <b>lights()</b> function. This function can be used to disable * lighting so that 2D geometry (which does not require lighting) can be * drawn after a set of lighted 3D geometry. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @see PGraphics#lights() */ public void noLights() { if (recorder != null) recorder.noLights(); g.noLights(); } /** * ( begin auto-generated from ambientLight.xml ) * * Adds an ambient light. Ambient light doesn't come from a specific * direction, the rays have light have bounced around so much that objects * are evenly lit from all sides. Ambient lights are almost always used in * combination with other types of lights. Lights need to be included in * the <b>draw()</b> to remain persistent in a looping program. Placing * them in the <b>setup()</b> of a looping program will cause them to only * have an effect the first time through the loop. The effect of the * parameters is determined by the current color mode. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) * @see PGraphics#lights() * @see PGraphics#directionalLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) */ public void ambientLight(float v1, float v2, float v3) { if (recorder != null) recorder.ambientLight(v1, v2, v3); g.ambientLight(v1, v2, v3); } /** * @param x x-coordinate of the light * @param y y-coordinate of the light * @param z z-coordinate of the light */ public void ambientLight(float v1, float v2, float v3, float x, float y, float z) { if (recorder != null) recorder.ambientLight(v1, v2, v3, x, y, z); g.ambientLight(v1, v2, v3, x, y, z); } /** * ( begin auto-generated from directionalLight.xml ) * * Adds a directional light. Directional light comes from one direction and * is stronger when hitting a surface squarely and weaker if it hits at a a * gentle angle. After hitting a surface, a directional lights scatters in * all directions. Lights need to be included in the <b>draw()</b> to * remain persistent in a looping program. Placing them in the * <b>setup()</b> of a looping program will cause them to only have an * effect the first time through the loop. The affect of the <b>v1</b>, * <b>v2</b>, and <b>v3</b> parameters is determined by the current color * mode. The <b>nx</b>, <b>ny</b>, and <b>nz</b> parameters specify the * direction the light is facing. For example, setting <b>ny</b> to -1 will * cause the geometry to be lit from below (the light is facing directly upward). * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) * @param nx direction along the x-axis * @param ny direction along the y-axis * @param nz direction along the z-axis * @see PGraphics#lights() * @see PGraphics#ambientLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) */ public void directionalLight(float v1, float v2, float v3, float nx, float ny, float nz) { if (recorder != null) recorder.directionalLight(v1, v2, v3, nx, ny, nz); g.directionalLight(v1, v2, v3, nx, ny, nz); } /** * ( begin auto-generated from pointLight.xml ) * * Adds a point light. Lights need to be included in the <b>draw()</b> to * remain persistent in a looping program. Placing them in the * <b>setup()</b> of a looping program will cause them to only have an * effect the first time through the loop. The affect of the <b>v1</b>, * <b>v2</b>, and <b>v3</b> parameters is determined by the current color * mode. The <b>x</b>, <b>y</b>, and <b>z</b> parameters set the position * of the light. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) * @param x x-coordinate of the light * @param y y-coordinate of the light * @param z z-coordinate of the light * @see PGraphics#lights() * @see PGraphics#directionalLight(float, float, float, float, float, float) * @see PGraphics#ambientLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) */ public void pointLight(float v1, float v2, float v3, float x, float y, float z) { if (recorder != null) recorder.pointLight(v1, v2, v3, x, y, z); g.pointLight(v1, v2, v3, x, y, z); } /** * ( begin auto-generated from spotLight.xml ) * * Adds a spot light. Lights need to be included in the <b>draw()</b> to * remain persistent in a looping program. Placing them in the * <b>setup()</b> of a looping program will cause them to only have an * effect the first time through the loop. The affect of the <b>v1</b>, * <b>v2</b>, and <b>v3</b> parameters is determined by the current color * mode. The <b>x</b>, <b>y</b>, and <b>z</b> parameters specify the * position of the light and <b>nx</b>, <b>ny</b>, <b>nz</b> specify the * direction or light. The <b>angle</b> parameter affects angle of the * spotlight cone. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) * @param x x-coordinate of the light * @param y y-coordinate of the light * @param z z-coordinate of the light * @param nx direction along the x axis * @param ny direction along the y axis * @param nz direction along the z axis * @param angle angle of the spotlight cone * @param concentration exponent determining the center bias of the cone * @see PGraphics#lights() * @see PGraphics#directionalLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#ambientLight(float, float, float, float, float, float) */ public void spotLight(float v1, float v2, float v3, float x, float y, float z, float nx, float ny, float nz, float angle, float concentration) { if (recorder != null) recorder.spotLight(v1, v2, v3, x, y, z, nx, ny, nz, angle, concentration); g.spotLight(v1, v2, v3, x, y, z, nx, ny, nz, angle, concentration); } /** * ( begin auto-generated from lightFalloff.xml ) * * Sets the falloff rates for point lights, spot lights, and ambient * lights. The parameters are used to determine the falloff with the * following equation:<br /><br />d = distance from light position to * vertex position<br />falloff = 1 / (CONSTANT + d * LINEAR + (d*d) * * QUADRATIC)<br /><br />Like <b>fill()</b>, it affects only the elements * which are created after it in the code. The default value if * <b>LightFalloff(1.0, 0.0, 0.0)</b>. Thinking about an ambient light with * a falloff can be tricky. It is used, for example, if you wanted a region * of your scene to be lit ambiently one color and another region to be lit * ambiently by another color, you would use an ambient light with location * and falloff. You can think of it as a point light that doesn't care * which direction a surface is facing. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param constant constant value or determining falloff * @param linear linear value for determining falloff * @param quadratic quadratic value for determining falloff * @see PGraphics#lights() * @see PGraphics#ambientLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#lightSpecular(float, float, float) */ public void lightFalloff(float constant, float linear, float quadratic) { if (recorder != null) recorder.lightFalloff(constant, linear, quadratic); g.lightFalloff(constant, linear, quadratic); } /** * ( begin auto-generated from lightSpecular.xml ) * * Sets the specular color for lights. Like <b>fill()</b>, it affects only * the elements which are created after it in the code. Specular refers to * light which bounces off a surface in a perferred direction (rather than * bouncing in all directions like a diffuse light) and is used for * creating highlights. The specular quality of a light interacts with the * specular material qualities set through the <b>specular()</b> and * <b>shininess()</b> functions. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) * @see PGraphics#specular(float, float, float) * @see PGraphics#lights() * @see PGraphics#ambientLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) */ public void lightSpecular(float v1, float v2, float v3) { if (recorder != null) recorder.lightSpecular(v1, v2, v3); g.lightSpecular(v1, v2, v3); } /** * ( begin auto-generated from background.xml ) * * The <b>background()</b> function sets the color used for the background * of the Processing window. The default background is light gray. In the * <b>draw()</b> function, the background color is used to clear the * display window at the beginning of each frame. * <br/> <br/> * An image can also be used as the background for a sketch, however its * width and height must be the same size as the sketch window. To resize * an image 'b' to the size of the sketch window, use b.resize(width, height). * <br/> <br/> * Images used as background will ignore the current <b>tint()</b> setting. * <br/> <br/> * It is not possible to use transparency (alpha) in background colors with * the main drawing surface, however they will work properly with <b>createGraphics()</b>. * * ( end auto-generated ) * * <h3>Advanced</h3> * <p>Clear the background with a color that includes an alpha value. This can * only be used with objects created by createGraphics(), because the main * drawing surface cannot be set transparent.</p> * <p>It might be tempting to use this function to partially clear the screen * on each frame, however that's not how this function works. When calling * background(), the pixels will be replaced with pixels that have that level * of transparency. To do a semi-transparent overlay, use fill() with alpha * and draw a rectangle.</p> * * @webref color:setting * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#stroke(float) * @see PGraphics#fill(float) * @see PGraphics#tint(float) * @see PGraphics#colorMode(int) */ public void background(int rgb) { if (recorder != null) recorder.background(rgb); g.background(rgb); } /** * @param alpha opacity of the background */ public void background(int rgb, float alpha) { if (recorder != null) recorder.background(rgb, alpha); g.background(rgb, alpha); } /** * @param gray specifies a value between white and black */ public void background(float gray) { if (recorder != null) recorder.background(gray); g.background(gray); } public void background(float gray, float alpha) { if (recorder != null) recorder.background(gray, alpha); g.background(gray, alpha); } /** * @param v1 red or hue value (depending on the current color mode) * @param v2 green or saturation value (depending on the current color mode) * @param v3 blue or brightness value (depending on the current color mode) */ public void background(float v1, float v2, float v3) { if (recorder != null) recorder.background(v1, v2, v3); g.background(v1, v2, v3); } public void background(float v1, float v2, float v3, float alpha) { if (recorder != null) recorder.background(v1, v2, v3, alpha); g.background(v1, v2, v3, alpha); } /** * @webref color:setting */ public void clear() { if (recorder != null) recorder.clear(); g.clear(); } /** * Takes an RGB or ARGB image and sets it as the background. * The width and height of the image must be the same size as the sketch. * Use image.resize(width, height) to make short work of such a task.<br/> * <br/> * Note that even if the image is set as RGB, the high 8 bits of each pixel * should be set opaque (0xFF000000) because the image data will be copied * directly to the screen, and non-opaque background images may have strange * behavior. Use image.filter(OPAQUE) to handle this easily.<br/> * <br/> * When using 3D, this will also clear the zbuffer (if it exists). * * @param image PImage to set as background (must be same size as the sketch window) */ public void background(PImage image) { if (recorder != null) recorder.background(image); g.background(image); } /** * ( begin auto-generated from colorMode.xml ) * * Changes the way Processing interprets color data. By default, the * parameters for <b>fill()</b>, <b>stroke()</b>, <b>background()</b>, and * <b>color()</b> are defined by values between 0 and 255 using the RGB * color model. The <b>colorMode()</b> function is used to change the * numerical range used for specifying colors and to switch color systems. * For example, calling <b>colorMode(RGB, 1.0)</b> will specify that values * are specified between 0 and 1. The limits for defining colors are * altered by setting the parameters range1, range2, range3, and range 4. * * ( end auto-generated ) * * @webref color:setting * @usage web_application * @param mode Either RGB or HSB, corresponding to Red/Green/Blue and Hue/Saturation/Brightness * @see PGraphics#background(float) * @see PGraphics#fill(float) * @see PGraphics#stroke(float) */ public void colorMode(int mode) { if (recorder != null) recorder.colorMode(mode); g.colorMode(mode); } /** * @param max range for all color elements */ public void colorMode(int mode, float max) { if (recorder != null) recorder.colorMode(mode, max); g.colorMode(mode, max); } /** * @param max1 range for the red or hue depending on the current color mode * @param max2 range for the green or saturation depending on the current color mode * @param max3 range for the blue or brightness depending on the current color mode */ public void colorMode(int mode, float max1, float max2, float max3) { if (recorder != null) recorder.colorMode(mode, max1, max2, max3); g.colorMode(mode, max1, max2, max3); } /** * @param maxA range for the alpha */ public void colorMode(int mode, float max1, float max2, float max3, float maxA) { if (recorder != null) recorder.colorMode(mode, max1, max2, max3, maxA); g.colorMode(mode, max1, max2, max3, maxA); } /** * ( begin auto-generated from alpha.xml ) * * Extracts the alpha value from a color. * * ( end auto-generated ) * @webref color:creating_reading * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#green(int) * @see PGraphics#blue(int) * @see PGraphics#hue(int) * @see PGraphics#saturation(int) * @see PGraphics#brightness(int) */ public final float alpha(int rgb) { return g.alpha(rgb); } /** * ( begin auto-generated from red.xml ) * * Extracts the red value from a color, scaled to match current * <b>colorMode()</b>. This value is always returned as a float so be * careful not to assign it to an int value.<br /><br />The red() function * is easy to use and undestand, but is slower than another technique. To * achieve the same results when working in <b>colorMode(RGB, 255)</b>, but * with greater speed, use the &gt;&gt; (right shift) operator with a bit * mask. For example, the following two lines of code are equivalent:<br * /><pre>float r1 = red(myColor);<br />float r2 = myColor &gt;&gt; 16 * &amp; 0xFF;</pre> * * ( end auto-generated ) * * @webref color:creating_reading * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#green(int) * @see PGraphics#blue(int) * @see PGraphics#alpha(int) * @see PGraphics#hue(int) * @see PGraphics#saturation(int) * @see PGraphics#brightness(int) * @see_external rightshift */ public final float red(int rgb) { return g.red(rgb); } /** * ( begin auto-generated from green.xml ) * * Extracts the green value from a color, scaled to match current * <b>colorMode()</b>. This value is always returned as a float so be * careful not to assign it to an int value.<br /><br />The <b>green()</b> * function is easy to use and undestand, but is slower than another * technique. To achieve the same results when working in <b>colorMode(RGB, * 255)</b>, but with greater speed, use the &gt;&gt; (right shift) * operator with a bit mask. For example, the following two lines of code * are equivalent:<br /><pre>float r1 = green(myColor);<br />float r2 = * myColor &gt;&gt; 8 &amp; 0xFF;</pre> * * ( end auto-generated ) * * @webref color:creating_reading * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#blue(int) * @see PGraphics#alpha(int) * @see PGraphics#hue(int) * @see PGraphics#saturation(int) * @see PGraphics#brightness(int) * @see_external rightshift */ public final float green(int rgb) { return g.green(rgb); } /** * ( begin auto-generated from blue.xml ) * * Extracts the blue value from a color, scaled to match current * <b>colorMode()</b>. This value is always returned as a float so be * careful not to assign it to an int value.<br /><br />The <b>blue()</b> * function is easy to use and undestand, but is slower than another * technique. To achieve the same results when working in <b>colorMode(RGB, * 255)</b>, but with greater speed, use a bit mask to remove the other * color components. For example, the following two lines of code are * equivalent:<br /><pre>float r1 = blue(myColor);<br />float r2 = myColor * &amp; 0xFF;</pre> * * ( end auto-generated ) * * @webref color:creating_reading * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#green(int) * @see PGraphics#alpha(int) * @see PGraphics#hue(int) * @see PGraphics#saturation(int) * @see PGraphics#brightness(int) * @see_external rightshift */ public final float blue(int rgb) { return g.blue(rgb); } /** * ( begin auto-generated from hue.xml ) * * Extracts the hue value from a color. * * ( end auto-generated ) * @webref color:creating_reading * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#green(int) * @see PGraphics#blue(int) * @see PGraphics#alpha(int) * @see PGraphics#saturation(int) * @see PGraphics#brightness(int) */ public final float hue(int rgb) { return g.hue(rgb); } /** * ( begin auto-generated from saturation.xml ) * * Extracts the saturation value from a color. * * ( end auto-generated ) * @webref color:creating_reading * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#green(int) * @see PGraphics#blue(int) * @see PGraphics#alpha(int) * @see PGraphics#hue(int) * @see PGraphics#brightness(int) */ public final float saturation(int rgb) { return g.saturation(rgb); } /** * ( begin auto-generated from brightness.xml ) * * Extracts the brightness value from a color. * * ( end auto-generated ) * * @webref color:creating_reading * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#green(int) * @see PGraphics#blue(int) * @see PGraphics#alpha(int) * @see PGraphics#hue(int) * @see PGraphics#saturation(int) */ public final float brightness(int rgb) { return g.brightness(rgb); } /** * ( begin auto-generated from lerpColor.xml ) * * Calculates a color or colors between two color at a specific increment. * The <b>amt</b> parameter is the amount to interpolate between the two * values where 0.0 equal to the first point, 0.1 is very near the first * point, 0.5 is half-way in between, etc. * * ( end auto-generated ) * * @webref color:creating_reading * @usage web_application * @param c1 interpolate from this color * @param c2 interpolate to this color * @param amt between 0.0 and 1.0 * @see PImage#blendColor(int, int, int) * @see PGraphics#color(float, float, float, float) */ public int lerpColor(int c1, int c2, float amt) { return g.lerpColor(c1, c2, amt); } /** * @nowebref * Interpolate between two colors. Like lerp(), but for the * individual color components of a color supplied as an int value. */ static public int lerpColor(int c1, int c2, float amt, int mode) { return PGraphics.lerpColor(c1, c2, amt, mode); } /** * Display a warning that the specified method is only available with 3D. * @param method The method name (no parentheses) */ static public void showDepthWarning(String method) { PGraphics.showDepthWarning(method); } /** * Display a warning that the specified method that takes x, y, z parameters * can only be used with x and y parameters in this renderer. * @param method The method name (no parentheses) */ static public void showDepthWarningXYZ(String method) { PGraphics.showDepthWarningXYZ(method); } /** * Display a warning that the specified method is simply unavailable. */ static public void showMethodWarning(String method) { PGraphics.showMethodWarning(method); } /** * Error that a particular variation of a method is unavailable (even though * other variations are). For instance, if vertex(x, y, u, v) is not * available, but vertex(x, y) is just fine. */ static public void showVariationWarning(String str) { PGraphics.showVariationWarning(str); } /** * Display a warning that the specified method is not implemented, meaning * that it could be either a completely missing function, although other * variations of it may still work properly. */ static public void showMissingWarning(String method) { PGraphics.showMissingWarning(method); } /** * Return true if this renderer should be drawn to the screen. Defaults to * returning true, since nearly all renderers are on-screen beasts. But can * be overridden for subclasses like PDF so that a window doesn't open up. * <br/> <br/> * A better name? showFrame, displayable, isVisible, visible, shouldDisplay, * what to call this? */ public boolean displayable() { return g.displayable(); } /** * Return true if this renderer does rendering through OpenGL. Defaults to false. */ public boolean isGL() { return g.isGL(); } /** * ( begin auto-generated from PImage_get.xml ) * * Reads the color of any pixel or grabs a section of an image. If no * parameters are specified, the entire image is returned. Use the <b>x</b> * and <b>y</b> parameters to get the value of one pixel. Get a section of * the display window by specifying an additional <b>width</b> and * <b>height</b> parameter. When getting an image, the <b>x</b> and * <b>y</b> parameters define the coordinates for the upper-left corner of * the image, regardless of the current <b>imageMode()</b>.<br /> * <br /> * If the pixel requested is outside of the image window, black is * returned. The numbers returned are scaled according to the current color * ranges, but only RGB values are returned by this function. For example, * even though you may have drawn a shape with <b>colorMode(HSB)</b>, the * numbers returned will be in RGB format.<br /> * <br /> * Getting the color of a single pixel with <b>get(x, y)</b> is easy, but * not as fast as grabbing the data directly from <b>pixels[]</b>. The * equivalent statement to <b>get(x, y)</b> using <b>pixels[]</b> is * <b>pixels[y*width+x]</b>. See the reference for <b>pixels[]</b> for more information. * * ( end auto-generated ) * * <h3>Advanced</h3> * Returns an ARGB "color" type (a packed 32 bit int with the color. * If the coordinate is outside the image, zero is returned * (black, but completely transparent). * <P> * If the image is in RGB format (i.e. on a PVideo object), * the value will get its high bits set, just to avoid cases where * they haven't been set already. * <P> * If the image is in ALPHA format, this returns a white with its * alpha value set. * <P> * This function is included primarily for beginners. It is quite * slow because it has to check to see if the x, y that was provided * is inside the bounds, and then has to check to see what image * type it is. If you want things to be more efficient, access the * pixels[] array directly. * * @webref image:pixels * @brief Reads the color of any pixel or grabs a rectangle of pixels * @usage web_application * @param x x-coordinate of the pixel * @param y y-coordinate of the pixel * @see PApplet#set(int, int, int) * @see PApplet#pixels * @see PApplet#copy(PImage, int, int, int, int, int, int, int, int) */ public int get(int x, int y) { return g.get(x, y); } /** * @param w width of pixel rectangle to get * @param h height of pixel rectangle to get */ public PImage get(int x, int y, int w, int h) { return g.get(x, y, w, h); } /** * Returns a copy of this PImage. Equivalent to get(0, 0, width, height). */ public PImage get() { return g.get(); } /** * ( begin auto-generated from PImage_set.xml ) * * Changes the color of any pixel or writes an image directly into the * display window.<br /> * <br /> * The <b>x</b> and <b>y</b> parameters specify the pixel to change and the * <b>color</b> parameter specifies the color value. The color parameter is * affected by the current color mode (the default is RGB values from 0 to * 255). When setting an image, the <b>x</b> and <b>y</b> parameters define * the coordinates for the upper-left corner of the image, regardless of * the current <b>imageMode()</b>. * <br /><br /> * Setting the color of a single pixel with <b>set(x, y)</b> is easy, but * not as fast as putting the data directly into <b>pixels[]</b>. The * equivalent statement to <b>set(x, y, #000000)</b> using <b>pixels[]</b> * is <b>pixels[y*width+x] = #000000</b>. See the reference for * <b>pixels[]</b> for more information. * * ( end auto-generated ) * * @webref image:pixels * @brief writes a color to any pixel or writes an image into another * @usage web_application * @param x x-coordinate of the pixel * @param y y-coordinate of the pixel * @param c any value of the color datatype * @see PImage#get(int, int, int, int) * @see PImage#pixels * @see PImage#copy(PImage, int, int, int, int, int, int, int, int) */ public void set(int x, int y, int c) { if (recorder != null) recorder.set(x, y, c); g.set(x, y, c); } /** * <h3>Advanced</h3> * Efficient method of drawing an image's pixels directly to this surface. * No variations are employed, meaning that any scale, tint, or imageMode * settings will be ignored. * * @param img image to copy into the original image */ public void set(int x, int y, PImage img) { if (recorder != null) recorder.set(x, y, img); g.set(x, y, img); } /** * ( begin auto-generated from PImage_mask.xml ) * * Masks part of an image from displaying by loading another image and * using it as an alpha channel. This mask image should only contain * grayscale data, but only the blue color channel is used. The mask image * needs to be the same size as the image to which it is applied.<br /> * <br /> * In addition to using a mask image, an integer array containing the alpha * channel data can be specified directly. This method is useful for * creating dynamically generated alpha masks. This array must be of the * same length as the target image's pixels array and should contain only * grayscale data of values between 0-255. * * ( end auto-generated ) * * <h3>Advanced</h3> * * Set alpha channel for an image. Black colors in the source * image will make the destination image completely transparent, * and white will make things fully opaque. Gray values will * be in-between steps. * <P> * Strictly speaking the "blue" value from the source image is * used as the alpha color. For a fully grayscale image, this * is correct, but for a color image it's not 100% accurate. * For a more accurate conversion, first use filter(GRAY) * which will make the image into a "correct" grayscale by * performing a proper luminance-based conversion. * * @webref pimage:method * @usage web_application * @brief Masks part of an image with another image as an alpha channel * @param maskArray array of integers used as the alpha channel, needs to be the same length as the image's pixel array */ public void mask(PImage img) { if (recorder != null) recorder.mask(img); g.mask(img); } public void filter(int kind) { if (recorder != null) recorder.filter(kind); g.filter(kind); } /** * ( begin auto-generated from PImage_filter.xml ) * * Filters an image as defined by one of the following modes:<br /><br * />THRESHOLD - converts the image to black and white pixels depending if * they are above or below the threshold defined by the level parameter. * The level must be between 0.0 (black) and 1.0(white). If no level is * specified, 0.5 is used.<br /> * <br /> * GRAY - converts any colors in the image to grayscale equivalents<br /> * <br /> * INVERT - sets each pixel to its inverse value<br /> * <br /> * POSTERIZE - limits each channel of the image to the number of colors * specified as the level parameter<br /> * <br /> * BLUR - executes a Guassian blur with the level parameter specifying the * extent of the blurring. If no level parameter is used, the blur is * equivalent to Guassian blur of radius 1<br /> * <br /> * OPAQUE - sets the alpha channel to entirely opaque<br /> * <br /> * ERODE - reduces the light areas with the amount defined by the level * parameter<br /> * <br /> * DILATE - increases the light areas with the amount defined by the level parameter * * ( end auto-generated ) * * <h3>Advanced</h3> * Method to apply a variety of basic filters to this image. * <P> * <UL> * <LI>filter(BLUR) provides a basic blur. * <LI>filter(GRAY) converts the image to grayscale based on luminance. * <LI>filter(INVERT) will invert the color components in the image. * <LI>filter(OPAQUE) set all the high bits in the image to opaque * <LI>filter(THRESHOLD) converts the image to black and white. * <LI>filter(DILATE) grow white/light areas * <LI>filter(ERODE) shrink white/light areas * </UL> * Luminance conversion code contributed by * <A HREF="http://www.toxi.co.uk">toxi</A> * <P/> * Gaussian blur code contributed by * <A HREF="http://incubator.quasimondo.com">Mario Klingemann</A> * * @webref image:pixels * @brief Converts the image to grayscale or black and white * @usage web_application * @param kind Either THRESHOLD, GRAY, OPAQUE, INVERT, POSTERIZE, BLUR, ERODE, or DILATE * @param param unique for each, see above */ public void filter(int kind, float param) { if (recorder != null) recorder.filter(kind, param); g.filter(kind, param); } /** * ( begin auto-generated from PImage_copy.xml ) * * Copies a region of pixels from one image into another. If the source and * destination regions aren't the same size, it will automatically resize * source pixels to fit the specified target region. No alpha information * is used in the process, however if the source image has an alpha channel * set, it will be copied as well. * <br /><br /> * As of release 0149, this function ignores <b>imageMode()</b>. * * ( end auto-generated ) * * @webref image:pixels * @brief Copies the entire image * @usage web_application * @param sx X coordinate of the source's upper left corner * @param sy Y coordinate of the source's upper left corner * @param sw source image width * @param sh source image height * @param dx X coordinate of the destination's upper left corner * @param dy Y coordinate of the destination's upper left corner * @param dw destination image width * @param dh destination image height * @see PGraphics#alpha(int) * @see PImage#blend(PImage, int, int, int, int, int, int, int, int, int) */ public void copy(int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh) { if (recorder != null) recorder.copy(sx, sy, sw, sh, dx, dy, dw, dh); g.copy(sx, sy, sw, sh, dx, dy, dw, dh); } /** * @param src an image variable referring to the source image. */ public void copy(PImage src, int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh) { if (recorder != null) recorder.copy(src, sx, sy, sw, sh, dx, dy, dw, dh); g.copy(src, sx, sy, sw, sh, dx, dy, dw, dh); } public void blend(int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh, int mode) { if (recorder != null) recorder.blend(sx, sy, sw, sh, dx, dy, dw, dh, mode); g.blend(sx, sy, sw, sh, dx, dy, dw, dh, mode); } /** * ( begin auto-generated from PImage_blend.xml ) * * Blends a region of pixels into the image specified by the <b>img</b> * parameter. These copies utilize full alpha channel support and a choice * of the following modes to blend the colors of source pixels (A) with the * ones of pixels in the destination image (B):<br /> * <br /> * BLEND - linear interpolation of colours: C = A*factor + B<br /> * <br /> * ADD - additive blending with white clip: C = min(A*factor + B, 255)<br /> * <br /> * SUBTRACT - subtractive blending with black clip: C = max(B - A*factor, * 0)<br /> * <br /> * DARKEST - only the darkest colour succeeds: C = min(A*factor, B)<br /> * <br /> * LIGHTEST - only the lightest colour succeeds: C = max(A*factor, B)<br /> * <br /> * DIFFERENCE - subtract colors from underlying image.<br /> * <br /> * EXCLUSION - similar to DIFFERENCE, but less extreme.<br /> * <br /> * MULTIPLY - Multiply the colors, result will always be darker.<br /> * <br /> * SCREEN - Opposite multiply, uses inverse values of the colors.<br /> * <br /> * OVERLAY - A mix of MULTIPLY and SCREEN. Multiplies dark values, * and screens light values.<br /> * <br /> * HARD_LIGHT - SCREEN when greater than 50% gray, MULTIPLY when lower.<br /> * <br /> * SOFT_LIGHT - Mix of DARKEST and LIGHTEST. * Works like OVERLAY, but not as harsh.<br /> * <br /> * DODGE - Lightens light tones and increases contrast, ignores darks. * Called "Color Dodge" in Illustrator and Photoshop.<br /> * <br /> * BURN - Darker areas are applied, increasing contrast, ignores lights. * Called "Color Burn" in Illustrator and Photoshop.<br /> * <br /> * All modes use the alpha information (highest byte) of source image * pixels as the blending factor. If the source and destination regions are * different sizes, the image will be automatically resized to match the * destination size. If the <b>srcImg</b> parameter is not used, the * display window is used as the source image.<br /> * <br /> * As of release 0149, this function ignores <b>imageMode()</b>. * * ( end auto-generated ) * * @webref image:pixels * @brief Copies a pixel or rectangle of pixels using different blending modes * @param src an image variable referring to the source image * @param sx X coordinate of the source's upper left corner * @param sy Y coordinate of the source's upper left corner * @param sw source image width * @param sh source image height * @param dx X coordinate of the destinations's upper left corner * @param dy Y coordinate of the destinations's upper left corner * @param dw destination image width * @param dh destination image height * @param mode Either BLEND, ADD, SUBTRACT, LIGHTEST, DARKEST, DIFFERENCE, EXCLUSION, MULTIPLY, SCREEN, OVERLAY, HARD_LIGHT, SOFT_LIGHT, DODGE, BURN * * @see PApplet#alpha(int) * @see PImage#copy(PImage, int, int, int, int, int, int, int, int) * @see PImage#blendColor(int,int,int) */ public void blend(PImage src, int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh, int mode) { if (recorder != null) recorder.blend(src, sx, sy, sw, sh, dx, dy, dw, dh, mode); g.blend(src, sx, sy, sw, sh, dx, dy, dw, dh, mode); } }
true
true
public PImage loadImage(String filename, String extension) { //, Object params) { if (extension == null) { String lower = filename.toLowerCase(); int dot = filename.lastIndexOf('.'); if (dot == -1) { extension = "unknown"; // no extension found } extension = lower.substring(dot + 1); // check for, and strip any parameters on the url, i.e. // filename.jpg?blah=blah&something=that int question = extension.indexOf('?'); if (question != -1) { extension = extension.substring(0, question); } } // just in case. them users will try anything! extension = extension.toLowerCase(); if (extension.equals("tga")) { try { PImage image = loadImageTGA(filename); // if (params != null) { // image.setParams(g, params); // } return image; } catch (IOException e) { e.printStackTrace(); return null; } } if (extension.equals("tif") || extension.equals("tiff")) { byte bytes[] = loadBytes(filename); PImage image = (bytes == null) ? null : PImage.loadTIFF(bytes); // if (params != null) { // image.setParams(g, params); // } return image; } // For jpeg, gif, and png, load them using createImage(), // because the javax.imageio code was found to be much slower. // http://dev.processing.org/bugs/show_bug.cgi?id=392 try { if (extension.equals("jpg") || extension.equals("jpeg") || extension.equals("gif") || extension.equals("png") || extension.equals("unknown")) { byte bytes[] = loadBytes(filename); if (bytes == null) { return null; } else { Image awtImage = Toolkit.getDefaultToolkit().createImage(bytes); PImage image = loadImageMT(awtImage); if (image.width == -1) { System.err.println("The file " + filename + " contains bad image data, or may not be an image."); } // if it's a .gif image, test to see if it has transparency if (extension.equals("gif") || extension.equals("png")) { image.checkAlpha(); } // if (params != null) { // image.setParams(g, params); // } return image; } } } catch (Exception e) { // show error, but move on to the stuff below, see if it'll work e.printStackTrace(); } if (loadImageFormats == null) { loadImageFormats = ImageIO.getReaderFormatNames(); } if (loadImageFormats != null) { for (int i = 0; i < loadImageFormats.length; i++) { if (extension.equals(loadImageFormats[i])) { return loadImageIO(filename); // PImage image = loadImageIO(filename); // if (params != null) { // image.setParams(g, params); // } // return image; } } } // failed, could not load image after all those attempts System.err.println("Could not find a method to load " + filename); return null; } public PImage requestImage(String filename) { // return requestImage(filename, null, null); return requestImage(filename, null); } /** * ( begin auto-generated from requestImage.xml ) * * This function load images on a separate thread so that your sketch does * not freeze while images load during <b>setup()</b>. While the image is * loading, its width and height will be 0. If an error occurs while * loading the image, its width and height will be set to -1. You'll know * when the image has loaded properly because its width and height will be * greater than 0. Asynchronous image loading (particularly when * downloading from a server) can dramatically improve performance.<br /> * <br/> <b>extension</b> parameter is used to determine the image type in * cases where the image filename does not end with a proper extension. * Specify the extension as the second parameter to <b>requestImage()</b>. * * ( end auto-generated ) * * @webref image:loading_displaying * @param filename name of the file to load, can be .gif, .jpg, .tga, or a handful of other image types depending on your platform * @param extension the type of image to load, for example "png", "gif", "jpg" * @see PImage * @see PApplet#loadImage(String, String) */ public PImage requestImage(String filename, String extension) { PImage vessel = createImage(0, 0, ARGB); AsyncImageLoader ail = new AsyncImageLoader(filename, extension, vessel); ail.start(); return vessel; } // /** // * @nowebref // */ // public PImage requestImage(String filename, String extension, Object params) { // PImage vessel = createImage(0, 0, ARGB, params); // AsyncImageLoader ail = // new AsyncImageLoader(filename, extension, vessel); // ail.start(); // return vessel; // } /** * By trial and error, four image loading threads seem to work best when * loading images from online. This is consistent with the number of open * connections that web browsers will maintain. The variable is made public * (however no accessor has been added since it's esoteric) if you really * want to have control over the value used. For instance, when loading local * files, it might be better to only have a single thread (or two) loading * images so that you're disk isn't simply jumping around. */ public int requestImageMax = 4; volatile int requestImageCount; class AsyncImageLoader extends Thread { String filename; String extension; PImage vessel; public AsyncImageLoader(String filename, String extension, PImage vessel) { this.filename = filename; this.extension = extension; this.vessel = vessel; } @Override public void run() { while (requestImageCount == requestImageMax) { try { Thread.sleep(10); } catch (InterruptedException e) { } } requestImageCount++; PImage actual = loadImage(filename, extension); // An error message should have already printed if (actual == null) { vessel.width = -1; vessel.height = -1; } else { vessel.width = actual.width; vessel.height = actual.height; vessel.format = actual.format; vessel.pixels = actual.pixels; } requestImageCount--; } } /** * Load an AWT image synchronously by setting up a MediaTracker for * a single image, and blocking until it has loaded. */ protected PImage loadImageMT(Image awtImage) { MediaTracker tracker = new MediaTracker(this); tracker.addImage(awtImage, 0); try { tracker.waitForAll(); } catch (InterruptedException e) { //e.printStackTrace(); // non-fatal, right? } PImage image = new PImage(awtImage); image.parent = this; return image; } /** * Use Java 1.4 ImageIO methods to load an image. */ protected PImage loadImageIO(String filename) { InputStream stream = createInput(filename); if (stream == null) { System.err.println("The image " + filename + " could not be found."); return null; } try { BufferedImage bi = ImageIO.read(stream); PImage outgoing = new PImage(bi.getWidth(), bi.getHeight()); outgoing.parent = this; bi.getRGB(0, 0, outgoing.width, outgoing.height, outgoing.pixels, 0, outgoing.width); // check the alpha for this image // was gonna call getType() on the image to see if RGB or ARGB, // but it's not actually useful, since gif images will come through // as TYPE_BYTE_INDEXED, which means it'll still have to check for // the transparency. also, would have to iterate through all the other // types and guess whether alpha was in there, so.. just gonna stick // with the old method. outgoing.checkAlpha(); // return the image return outgoing; } catch (Exception e) { e.printStackTrace(); return null; } } /** * Targa image loader for RLE-compressed TGA files. * <p> * Rewritten for 0115 to read/write RLE-encoded targa images. * For 0125, non-RLE encoded images are now supported, along with * images whose y-order is reversed (which is standard for TGA files). */ protected PImage loadImageTGA(String filename) throws IOException { InputStream is = createInput(filename); if (is == null) return null; byte header[] = new byte[18]; int offset = 0; do { int count = is.read(header, offset, header.length - offset); if (count == -1) return null; offset += count; } while (offset < 18); /* header[2] image type code 2 (0x02) - Uncompressed, RGB images. 3 (0x03) - Uncompressed, black and white images. 10 (0x0A) - Runlength encoded RGB images. 11 (0x0B) - Compressed, black and white images. (grayscale?) header[16] is the bit depth (8, 24, 32) header[17] image descriptor (packed bits) 0x20 is 32 = origin upper-left 0x28 is 32 + 8 = origin upper-left + 32 bits 7 6 5 4 3 2 1 0 128 64 32 16 8 4 2 1 */ int format = 0; if (((header[2] == 3) || (header[2] == 11)) && // B&W, plus RLE or not (header[16] == 8) && // 8 bits ((header[17] == 0x8) || (header[17] == 0x28))) { // origin, 32 bit format = ALPHA; } else if (((header[2] == 2) || (header[2] == 10)) && // RGB, RLE or not (header[16] == 24) && // 24 bits ((header[17] == 0x20) || (header[17] == 0))) { // origin format = RGB; } else if (((header[2] == 2) || (header[2] == 10)) && (header[16] == 32) && ((header[17] == 0x8) || (header[17] == 0x28))) { // origin, 32 format = ARGB; } if (format == 0) { System.err.println("Unknown .tga file format for " + filename); //" (" + header[2] + " " + //(header[16] & 0xff) + " " + //hex(header[17], 2) + ")"); return null; } int w = ((header[13] & 0xff) << 8) + (header[12] & 0xff); int h = ((header[15] & 0xff) << 8) + (header[14] & 0xff); PImage outgoing = createImage(w, h, format); // where "reversed" means upper-left corner (normal for most of // the modernized world, but "reversed" for the tga spec) //boolean reversed = (header[17] & 0x20) != 0; // https://github.com/processing/processing/issues/1682 boolean reversed = (header[17] & 0x20) == 0; if ((header[2] == 2) || (header[2] == 3)) { // not RLE encoded if (reversed) { int index = (h-1) * w; switch (format) { case ALPHA: for (int y = h-1; y >= 0; y--) { for (int x = 0; x < w; x++) { outgoing.pixels[index + x] = is.read(); } index -= w; } break; case RGB: for (int y = h-1; y >= 0; y--) { for (int x = 0; x < w; x++) { outgoing.pixels[index + x] = is.read() | (is.read() << 8) | (is.read() << 16) | 0xff000000; } index -= w; } break; case ARGB: for (int y = h-1; y >= 0; y--) { for (int x = 0; x < w; x++) { outgoing.pixels[index + x] = is.read() | (is.read() << 8) | (is.read() << 16) | (is.read() << 24); } index -= w; } } } else { // not reversed int count = w * h; switch (format) { case ALPHA: for (int i = 0; i < count; i++) { outgoing.pixels[i] = is.read(); } break; case RGB: for (int i = 0; i < count; i++) { outgoing.pixels[i] = is.read() | (is.read() << 8) | (is.read() << 16) | 0xff000000; } break; case ARGB: for (int i = 0; i < count; i++) { outgoing.pixels[i] = is.read() | (is.read() << 8) | (is.read() << 16) | (is.read() << 24); } break; } } } else { // header[2] is 10 or 11 int index = 0; int px[] = outgoing.pixels; while (index < px.length) { int num = is.read(); boolean isRLE = (num & 0x80) != 0; if (isRLE) { num -= 127; // (num & 0x7F) + 1 int pixel = 0; switch (format) { case ALPHA: pixel = is.read(); break; case RGB: pixel = 0xFF000000 | is.read() | (is.read() << 8) | (is.read() << 16); //(is.read() << 16) | (is.read() << 8) | is.read(); break; case ARGB: pixel = is.read() | (is.read() << 8) | (is.read() << 16) | (is.read() << 24); break; } for (int i = 0; i < num; i++) { px[index++] = pixel; if (index == px.length) break; } } else { // write up to 127 bytes as uncompressed num += 1; switch (format) { case ALPHA: for (int i = 0; i < num; i++) { px[index++] = is.read(); } break; case RGB: for (int i = 0; i < num; i++) { px[index++] = 0xFF000000 | is.read() | (is.read() << 8) | (is.read() << 16); //(is.read() << 16) | (is.read() << 8) | is.read(); } break; case ARGB: for (int i = 0; i < num; i++) { px[index++] = is.read() | //(is.read() << 24) | (is.read() << 8) | (is.read() << 16) | (is.read() << 24); //(is.read() << 16) | (is.read() << 8) | is.read(); } break; } } } if (!reversed) { int[] temp = new int[w]; for (int y = 0; y < h/2; y++) { int z = (h-1) - y; System.arraycopy(px, y*w, temp, 0, w); System.arraycopy(px, z*w, px, y*w, w); System.arraycopy(temp, 0, px, z*w, w); } } } return outgoing; } ////////////////////////////////////////////////////////////// // DATA I/O // /** // * @webref input:files // * @brief Creates a new XML object // * @param name the name to be given to the root element of the new XML object // * @return an XML object, or null // * @see XML // * @see PApplet#loadXML(String) // * @see PApplet#parseXML(String) // * @see PApplet#saveXML(XML, String) // */ // public XML createXML(String name) { // try { // return new XML(name); // } catch (Exception e) { // e.printStackTrace(); // return null; // } // } /** * @webref input:files * @param filename name of a file in the data folder or a URL. * @see XML * @see PApplet#parseXML(String) * @see PApplet#saveXML(XML, String) * @see PApplet#loadBytes(String) * @see PApplet#loadStrings(String) * @see PApplet#loadTable(String) */ public XML loadXML(String filename) { return loadXML(filename, null); } // version that uses 'options' though there are currently no supported options /** * @nowebref */ public XML loadXML(String filename, String options) { try { return new XML(createReader(filename), options); } catch (Exception e) { e.printStackTrace(); return null; } } /** * @webref input:files * @brief Converts String content to an XML object * @param data the content to be parsed as XML * @return an XML object, or null * @see XML * @see PApplet#loadXML(String) * @see PApplet#saveXML(XML, String) */ public XML parseXML(String xmlString) { return parseXML(xmlString, null); } public XML parseXML(String xmlString, String options) { try { return XML.parse(xmlString, options); } catch (Exception e) { e.printStackTrace(); return null; } } /** * @webref output:files * @param xml the XML object to save to disk * @param filename name of the file to write to * @see XML * @see PApplet#loadXML(String) * @see PApplet#parseXML(String) */ public boolean saveXML(XML xml, String filename) { return saveXML(xml, filename, null); } public boolean saveXML(XML xml, String filename, String options) { return xml.save(saveFile(filename), options); } public JSONObject parseJSONObject(String input) { return new JSONObject(new StringReader(input)); } /** * @webref output:files * @param filename name of a file in the data folder or a URL * @see JSONObject * @see JSONArray * @see PApplet#loadJSONArray(String) * @see PApplet#saveJSONObject(JSONObject, String) * @see PApplet#saveJSONArray(JSONArray, String) */ public JSONObject loadJSONObject(String filename) { return new JSONObject(createReader(filename)); } /** * @webref output:files * @see JSONObject * @see JSONArray * @see PApplet#loadJSONObject(String) * @see PApplet#loadJSONArray(String) * @see PApplet#saveJSONArray(JSONArray, String) */ public boolean saveJSONObject(JSONObject json, String filename) { return saveJSONObject(json, filename, null); } public boolean saveJSONObject(JSONObject json, String filename, String options) { return json.save(saveFile(filename), options); } public JSONArray parseJSONArray(String input) { return new JSONArray(new StringReader(input)); } /** * @webref output:files * @param filename name of a file in the data folder or a URL * @see JSONObject * @see JSONArray * @see PApplet#loadJSONObject(String) * @see PApplet#saveJSONObject(JSONObject, String) * @see PApplet#saveJSONArray(JSONArray, String) */ public JSONArray loadJSONArray(String filename) { return new JSONArray(createReader(filename)); } /** * @webref output:files * @see JSONObject * @see JSONArray * @see PApplet#loadJSONObject(String) * @see PApplet#loadJSONArray(String) * @see PApplet#saveJSONObject(JSONObject, String) */ public boolean saveJSONArray(JSONArray json, String filename) { return saveJSONArray(json, filename); } public boolean saveJSONArray(JSONArray json, String filename, String options) { return json.save(saveFile(filename), options); } // /** // * @webref input:files // * @see Table // * @see PApplet#loadTable(String) // * @see PApplet#saveTable(Table, String) // */ // public Table createTable() { // return new Table(); // } /** * @webref input:files * @param filename name of a file in the data folder or a URL. * @see Table * @see PApplet#saveTable(Table, String) * @see PApplet#loadBytes(String) * @see PApplet#loadStrings(String) * @see PApplet#loadXML(String) */ public Table loadTable(String filename) { return loadTable(filename, null); } /** * @param options may contain "header", "tsv", "csv", or "bin" separated by commas */ public Table loadTable(String filename, String options) { try { // String ext = checkExtension(filename); // if (ext != null) { // if (ext.equals("csv") || ext.equals("tsv") || ext.equals("bin")) { // if (options == null) { // options = ext; // } else { // options = ext + "," + options; // } // } // } return new Table(createInput(filename), Table.extensionOptions(true, filename, options)); } catch (IOException e) { e.printStackTrace(); return null; } } /** * @webref input:files * @param table the Table object to save to a file * @param filename the filename to which the Table should be saved * @see Table * @see PApplet#loadTable(String) */ public boolean saveTable(Table table, String filename) { return saveTable(table, filename, null); } /** * @param options can be one of "tsv", "csv", "bin", or "html" */ public boolean saveTable(Table table, String filename, String options) { // String ext = checkExtension(filename); // if (ext != null) { // if (ext.equals("csv") || ext.equals("tsv") || ext.equals("bin") || ext.equals("html")) { // if (options == null) { // options = ext; // } else { // options = ext + "," + options; // } // } // } try { // Figure out location and make sure the target path exists File outputFile = saveFile(filename); // Open a stream and take care of .gz if necessary return table.save(outputFile, options); } catch (IOException e) { e.printStackTrace(); return false; } } ////////////////////////////////////////////////////////////// // FONT I/O /** * ( begin auto-generated from loadFont.xml ) * * Loads a font into a variable of type <b>PFont</b>. To load correctly, * fonts must be located in the data directory of the current sketch. To * create a font to use with Processing, select "Create Font..." from the * Tools menu. This will create a font in the format Processing requires * and also adds it to the current sketch's data directory.<br /> * <br /> * Like <b>loadImage()</b> and other functions that load data, the * <b>loadFont()</b> function should not be used inside <b>draw()</b>, * because it will slow down the sketch considerably, as the font will be * re-loaded from the disk (or network) on each frame.<br /> * <br /> * For most renderers, Processing displays fonts using the .vlw font * format, which uses images for each letter, rather than defining them * through vector data. When <b>hint(ENABLE_NATIVE_FONTS)</b> is used with * the JAVA2D renderer, the native version of a font will be used if it is * installed on the user's machine.<br /> * <br /> * Using <b>createFont()</b> (instead of loadFont) enables vector data to * be used with the JAVA2D (default) renderer setting. This can be helpful * when many font sizes are needed, or when using any renderer based on * JAVA2D, such as the PDF library. * * ( end auto-generated ) * @webref typography:loading_displaying * @param filename name of the font to load * @see PFont * @see PGraphics#textFont(PFont, float) * @see PApplet#createFont(String, float, boolean, char[]) */ public PFont loadFont(String filename) { try { InputStream input = createInput(filename); return new PFont(input); } catch (Exception e) { die("Could not load font " + filename + ". " + "Make sure that the font has been copied " + "to the data folder of your sketch.", e); } return null; } /** * Used by PGraphics to remove the requirement for loading a font! */ protected PFont createDefaultFont(float size) { // Font f = new Font("SansSerif", Font.PLAIN, 12); // println("n: " + f.getName()); // println("fn: " + f.getFontName()); // println("ps: " + f.getPSName()); return createFont("Lucida Sans", size, true, null); } public PFont createFont(String name, float size) { return createFont(name, size, true, null); } public PFont createFont(String name, float size, boolean smooth) { return createFont(name, size, smooth, null); } /** * ( begin auto-generated from createFont.xml ) * * Dynamically converts a font to the format used by Processing from either * a font name that's installed on the computer, or from a .ttf or .otf * file inside the sketches "data" folder. This function is an advanced * feature for precise control. On most occasions you should create fonts * through selecting "Create Font..." from the Tools menu. * <br /><br /> * Use the <b>PFont.list()</b> method to first determine the names for the * fonts recognized by the computer and are compatible with this function. * Because of limitations in Java, not all fonts can be used and some might * work with one operating system and not others. When sharing a sketch * with other people or posting it on the web, you may need to include a * .ttf or .otf version of your font in the data directory of the sketch * because other people might not have the font installed on their * computer. Only fonts that can legally be distributed should be included * with a sketch. * <br /><br /> * The <b>size</b> parameter states the font size you want to generate. The * <b>smooth</b> parameter specifies if the font should be antialiased or * not, and the <b>charset</b> parameter is an array of chars that * specifies the characters to generate. * <br /><br /> * This function creates a bitmapped version of a font in the same manner * as the Create Font tool. It loads a font by name, and converts it to a * series of images based on the size of the font. When possible, the * <b>text()</b> function will use a native font rather than the bitmapped * version created behind the scenes with <b>createFont()</b>. For * instance, when using P2D, the actual native version of the font will be * employed by the sketch, improving drawing quality and performance. With * the P3D renderer, the bitmapped version will be used. While this can * drastically improve speed and appearance, results are poor when * exporting if the sketch does not include the .otf or .ttf file, and the * requested font is not available on the machine running the sketch. * * ( end auto-generated ) * @webref typography:loading_displaying * @param name name of the font to load * @param size point size of the font * @param smooth true for an antialiased font, false for aliased * @param charset array containing characters to be generated * @see PFont * @see PGraphics#textFont(PFont, float) * @see PGraphics#text(String, float, float, float, float, float) * @see PApplet#loadFont(String) */ public PFont createFont(String name, float size, boolean smooth, char charset[]) { String lowerName = name.toLowerCase(); Font baseFont = null; try { InputStream stream = null; if (lowerName.endsWith(".otf") || lowerName.endsWith(".ttf")) { stream = createInput(name); if (stream == null) { System.err.println("The font \"" + name + "\" " + "is missing or inaccessible, make sure " + "the URL is valid or that the file has been " + "added to your sketch and is readable."); return null; } baseFont = Font.createFont(Font.TRUETYPE_FONT, createInput(name)); } else { baseFont = PFont.findFont(name); } return new PFont(baseFont.deriveFont(size), smooth, charset, stream != null); } catch (Exception e) { System.err.println("Problem createFont(" + name + ")"); e.printStackTrace(); return null; } } ////////////////////////////////////////////////////////////// // FILE/FOLDER SELECTION private Frame selectFrame; private Frame selectFrame() { if (frame != null) { selectFrame = frame; } else if (selectFrame == null) { Component comp = getParent(); while (comp != null) { if (comp instanceof Frame) { selectFrame = (Frame) comp; break; } comp = comp.getParent(); } // Who you callin' a hack? if (selectFrame == null) { selectFrame = new Frame(); } } return selectFrame; } /** * Open a platform-specific file chooser dialog to select a file for input. * After the selection is made, the selected File will be passed to the * 'callback' function. If the dialog is closed or canceled, null will be * sent to the function, so that the program is not waiting for additional * input. The callback is necessary because of how threading works. * * <pre> * void setup() { * selectInput("Select a file to process:", "fileSelected"); * } * * void fileSelected(File selection) { * if (selection == null) { * println("Window was closed or the user hit cancel."); * } else { * println("User selected " + fileSeleted.getAbsolutePath()); * } * } * </pre> * * For advanced users, the method must be 'public', which is true for all * methods inside a sketch when run from the PDE, but must explicitly be * set when using Eclipse or other development environments. * * @webref input:files * @param prompt message to the user * @param callback name of the method to be called when the selection is made */ public void selectInput(String prompt, String callback) { selectInput(prompt, callback, null); } public void selectInput(String prompt, String callback, File file) { selectInput(prompt, callback, file, this); } public void selectInput(String prompt, String callback, File file, Object callbackObject) { selectInput(prompt, callback, file, callbackObject, selectFrame()); } static public void selectInput(String prompt, String callbackMethod, File file, Object callbackObject, Frame parent) { selectImpl(prompt, callbackMethod, file, callbackObject, parent, FileDialog.LOAD); } /** * See selectInput() for details. * * @webref output:files * @param prompt message to the user * @param callback name of the method to be called when the selection is made */ public void selectOutput(String prompt, String callback) { selectOutput(prompt, callback, null); } public void selectOutput(String prompt, String callback, File file) { selectOutput(prompt, callback, file, this); } public void selectOutput(String prompt, String callback, File file, Object callbackObject) { selectOutput(prompt, callback, file, callbackObject, selectFrame()); } static public void selectOutput(String prompt, String callbackMethod, File file, Object callbackObject, Frame parent) { selectImpl(prompt, callbackMethod, file, callbackObject, parent, FileDialog.SAVE); } static protected void selectImpl(final String prompt, final String callbackMethod, final File defaultSelection, final Object callbackObject, final Frame parentFrame, final int mode) { EventQueue.invokeLater(new Runnable() { public void run() { File selectedFile = null; if (useNativeSelect) { FileDialog dialog = new FileDialog(parentFrame, prompt, mode); if (defaultSelection != null) { dialog.setDirectory(defaultSelection.getParent()); dialog.setFile(defaultSelection.getName()); } dialog.setVisible(true); String directory = dialog.getDirectory(); String filename = dialog.getFile(); if (filename != null) { selectedFile = new File(directory, filename); } } else { JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle(prompt); if (defaultSelection != null) { chooser.setSelectedFile(defaultSelection); } int result = -1; if (mode == FileDialog.SAVE) { result = chooser.showSaveDialog(parentFrame); } else if (mode == FileDialog.LOAD) { result = chooser.showOpenDialog(parentFrame); } if (result == JFileChooser.APPROVE_OPTION) { selectedFile = chooser.getSelectedFile(); } } selectCallback(selectedFile, callbackMethod, callbackObject); } }); } /** * See selectInput() for details. * * @webref input:files * @param prompt message to the user * @param callback name of the method to be called when the selection is made */ public void selectFolder(String prompt, String callback) { selectFolder(prompt, callback, null); } public void selectFolder(String prompt, String callback, File file) { selectFolder(prompt, callback, file, this); } public void selectFolder(String prompt, String callback, File file, Object callbackObject) { selectFolder(prompt, callback, file, callbackObject, selectFrame()); } static public void selectFolder(final String prompt, final String callbackMethod, final File defaultSelection, final Object callbackObject, final Frame parentFrame) { EventQueue.invokeLater(new Runnable() { public void run() { File selectedFile = null; if (platform == MACOSX && useNativeSelect != false) { FileDialog fileDialog = new FileDialog(parentFrame, prompt, FileDialog.LOAD); System.setProperty("apple.awt.fileDialogForDirectories", "true"); fileDialog.setVisible(true); System.setProperty("apple.awt.fileDialogForDirectories", "false"); String filename = fileDialog.getFile(); if (filename != null) { selectedFile = new File(fileDialog.getDirectory(), fileDialog.getFile()); } } else { JFileChooser fileChooser = new JFileChooser(); fileChooser.setDialogTitle(prompt); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); if (defaultSelection != null) { fileChooser.setSelectedFile(defaultSelection); } int result = fileChooser.showOpenDialog(parentFrame); if (result == JFileChooser.APPROVE_OPTION) { selectedFile = fileChooser.getSelectedFile(); } } selectCallback(selectedFile, callbackMethod, callbackObject); } }); } static private void selectCallback(File selectedFile, String callbackMethod, Object callbackObject) { try { Class<?> callbackClass = callbackObject.getClass(); Method selectMethod = callbackClass.getMethod(callbackMethod, new Class[] { File.class }); selectMethod.invoke(callbackObject, new Object[] { selectedFile }); } catch (IllegalAccessException iae) { System.err.println(callbackMethod + "() must be public"); } catch (InvocationTargetException ite) { ite.printStackTrace(); } catch (NoSuchMethodException nsme) { System.err.println(callbackMethod + "() could not be found"); } } ////////////////////////////////////////////////////////////// // EXTENSIONS /** * Get the compression-free extension for this filename. * @param filename The filename to check * @return an extension, skipping past .gz if it's present */ static public String checkExtension(String filename) { // Don't consider the .gz as part of the name, createInput() // and createOuput() will take care of fixing that up. if (filename.toLowerCase().endsWith(".gz")) { filename = filename.substring(0, filename.length() - 3); } int dotIndex = filename.lastIndexOf('.'); if (dotIndex != -1) { return filename.substring(dotIndex + 1).toLowerCase(); } return null; } ////////////////////////////////////////////////////////////// // READERS AND WRITERS /** * ( begin auto-generated from createReader.xml ) * * Creates a <b>BufferedReader</b> object that can be used to read files * line-by-line as individual <b>String</b> objects. This is the complement * to the <b>createWriter()</b> function. * <br/> <br/> * Starting with Processing release 0134, all files loaded and saved by the * Processing API use UTF-8 encoding. In previous releases, the default * encoding for your platform was used, which causes problems when files * are moved to other platforms. * * ( end auto-generated ) * @webref input:files * @param filename name of the file to be opened * @see BufferedReader * @see PApplet#createWriter(String) * @see PrintWriter */ public BufferedReader createReader(String filename) { try { InputStream is = createInput(filename); if (is == null) { System.err.println(filename + " does not exist or could not be read"); return null; } return createReader(is); } catch (Exception e) { if (filename == null) { System.err.println("Filename passed to reader() was null"); } else { System.err.println("Couldn't create a reader for " + filename); } } return null; } /** * @nowebref */ static public BufferedReader createReader(File file) { try { InputStream is = new FileInputStream(file); if (file.getName().toLowerCase().endsWith(".gz")) { is = new GZIPInputStream(is); } return createReader(is); } catch (Exception e) { if (file == null) { throw new RuntimeException("File passed to createReader() was null"); } else { e.printStackTrace(); throw new RuntimeException("Couldn't create a reader for " + file.getAbsolutePath()); } } //return null; } /** * @nowebref * I want to read lines from a stream. If I have to type the * following lines any more I'm gonna send Sun my medical bills. */ static public BufferedReader createReader(InputStream input) { InputStreamReader isr = null; try { isr = new InputStreamReader(input, "UTF-8"); } catch (UnsupportedEncodingException e) { } // not gonna happen return new BufferedReader(isr); } /** * ( begin auto-generated from createWriter.xml ) * * Creates a new file in the sketch folder, and a <b>PrintWriter</b> object * to write to it. For the file to be made correctly, it should be flushed * and must be closed with its <b>flush()</b> and <b>close()</b> methods * (see above example). * <br/> <br/> * Starting with Processing release 0134, all files loaded and saved by the * Processing API use UTF-8 encoding. In previous releases, the default * encoding for your platform was used, which causes problems when files * are moved to other platforms. * * ( end auto-generated ) * * @webref output:files * @param filename name of the file to be created * @see PrintWriter * @see PApplet#createReader * @see BufferedReader */ public PrintWriter createWriter(String filename) { return createWriter(saveFile(filename)); } /** * @nowebref * I want to print lines to a file. I have RSI from typing these * eight lines of code so many times. */ static public PrintWriter createWriter(File file) { try { createPath(file); // make sure in-between folders exist OutputStream output = new FileOutputStream(file); if (file.getName().toLowerCase().endsWith(".gz")) { output = new GZIPOutputStream(output); } return createWriter(output); } catch (Exception e) { if (file == null) { throw new RuntimeException("File passed to createWriter() was null"); } else { e.printStackTrace(); throw new RuntimeException("Couldn't create a writer for " + file.getAbsolutePath()); } } //return null; } /** * @nowebref * I want to print lines to a file. Why am I always explaining myself? * It's the JavaSoft API engineers who need to explain themselves. */ static public PrintWriter createWriter(OutputStream output) { try { BufferedOutputStream bos = new BufferedOutputStream(output, 8192); OutputStreamWriter osw = new OutputStreamWriter(bos, "UTF-8"); return new PrintWriter(osw); } catch (UnsupportedEncodingException e) { } // not gonna happen return null; } ////////////////////////////////////////////////////////////// // FILE INPUT /** * @deprecated As of release 0136, use createInput() instead. */ public InputStream openStream(String filename) { return createInput(filename); } /** * ( begin auto-generated from createInput.xml ) * * This is a function for advanced programmers to open a Java InputStream. * It's useful if you want to use the facilities provided by PApplet to * easily open files from the data folder or from a URL, but want an * InputStream object so that you can use other parts of Java to take more * control of how the stream is read.<br /> * <br /> * The filename passed in can be:<br /> * - A URL, for instance <b>openStream("http://processing.org/")</b><br /> * - A file in the sketch's <b>data</b> folder<br /> * - The full path to a file to be opened locally (when running as an * application)<br /> * <br /> * If the requested item doesn't exist, null is returned. If not online, * this will also check to see if the user is asking for a file whose name * isn't properly capitalized. If capitalization is different, an error * will be printed to the console. This helps prevent issues that appear * when a sketch is exported to the web, where case sensitivity matters, as * opposed to running from inside the Processing Development Environment on * Windows or Mac OS, where case sensitivity is preserved but ignored.<br /> * <br /> * If the file ends with <b>.gz</b>, the stream will automatically be gzip * decompressed. If you don't want the automatic decompression, use the * related function <b>createInputRaw()</b>. * <br /> * In earlier releases, this function was called <b>openStream()</b>.<br /> * <br /> * * ( end auto-generated ) * * <h3>Advanced</h3> * Simplified method to open a Java InputStream. * <p> * This method is useful if you want to use the facilities provided * by PApplet to easily open things from the data folder or from a URL, * but want an InputStream object so that you can use other Java * methods to take more control of how the stream is read. * <p> * If the requested item doesn't exist, null is returned. * (Prior to 0096, die() would be called, killing the applet) * <p> * For 0096+, the "data" folder is exported intact with subfolders, * and openStream() properly handles subdirectories from the data folder * <p> * If not online, this will also check to see if the user is asking * for a file whose name isn't properly capitalized. This helps prevent * issues when a sketch is exported to the web, where case sensitivity * matters, as opposed to Windows and the Mac OS default where * case sensitivity is preserved but ignored. * <p> * It is strongly recommended that libraries use this method to open * data files, so that the loading sequence is handled in the same way * as functions like loadBytes(), loadImage(), etc. * <p> * The filename passed in can be: * <UL> * <LI>A URL, for instance openStream("http://processing.org/"); * <LI>A file in the sketch's data folder * <LI>Another file to be opened locally (when running as an application) * </UL> * * @webref input:files * @param filename the name of the file to use as input * @see PApplet#createOutput(String) * @see PApplet#selectOutput(String) * @see PApplet#selectInput(String) * */ public InputStream createInput(String filename) { InputStream input = createInputRaw(filename); if ((input != null) && filename.toLowerCase().endsWith(".gz")) { try { return new GZIPInputStream(input); } catch (IOException e) { e.printStackTrace(); return null; } } return input; } /** * Call openStream() without automatic gzip decompression. */ public InputStream createInputRaw(String filename) { InputStream stream = null; if (filename == null) return null; if (filename.length() == 0) { // an error will be called by the parent function //System.err.println("The filename passed to openStream() was empty."); return null; } // safe to check for this as a url first. this will prevent online // access logs from being spammed with GET /sketchfolder/http://blahblah if (filename.contains(":")) { // at least smells like URL try { URL url = new URL(filename); stream = url.openStream(); return stream; } catch (MalformedURLException mfue) { // not a url, that's fine } catch (FileNotFoundException fnfe) { // Java 1.5 likes to throw this when URL not available. (fix for 0119) // http://dev.processing.org/bugs/show_bug.cgi?id=403 } catch (IOException e) { // changed for 0117, shouldn't be throwing exception e.printStackTrace(); //System.err.println("Error downloading from URL " + filename); return null; //throw new RuntimeException("Error downloading from URL " + filename); } } // Moved this earlier than the getResourceAsStream() checks, because // calling getResourceAsStream() on a directory lists its contents. // http://dev.processing.org/bugs/show_bug.cgi?id=716 try { // First see if it's in a data folder. This may fail by throwing // a SecurityException. If so, this whole block will be skipped. File file = new File(dataPath(filename)); if (!file.exists()) { // next see if it's just in the sketch folder file = sketchFile(filename); } if (file.isDirectory()) { return null; } if (file.exists()) { try { // handle case sensitivity check String filePath = file.getCanonicalPath(); String filenameActual = new File(filePath).getName(); // make sure there isn't a subfolder prepended to the name String filenameShort = new File(filename).getName(); // if the actual filename is the same, but capitalized // differently, warn the user. //if (filenameActual.equalsIgnoreCase(filenameShort) && //!filenameActual.equals(filenameShort)) { if (!filenameActual.equals(filenameShort)) { throw new RuntimeException("This file is named " + filenameActual + " not " + filename + ". Rename the file " + "or change your code."); } } catch (IOException e) { } } // if this file is ok, may as well just load it stream = new FileInputStream(file); if (stream != null) return stream; // have to break these out because a general Exception might // catch the RuntimeException being thrown above } catch (IOException ioe) { } catch (SecurityException se) { } // Using getClassLoader() prevents java from converting dots // to slashes or requiring a slash at the beginning. // (a slash as a prefix means that it'll load from the root of // the jar, rather than trying to dig into the package location) ClassLoader cl = getClass().getClassLoader(); // by default, data files are exported to the root path of the jar. // (not the data folder) so check there first. stream = cl.getResourceAsStream("data/" + filename); if (stream != null) { String cn = stream.getClass().getName(); // this is an irritation of sun's java plug-in, which will return // a non-null stream for an object that doesn't exist. like all good // things, this is probably introduced in java 1.5. awesome! // http://dev.processing.org/bugs/show_bug.cgi?id=359 if (!cn.equals("sun.plugin.cache.EmptyInputStream")) { return stream; } } // When used with an online script, also need to check without the // data folder, in case it's not in a subfolder called 'data'. // http://dev.processing.org/bugs/show_bug.cgi?id=389 stream = cl.getResourceAsStream(filename); if (stream != null) { String cn = stream.getClass().getName(); if (!cn.equals("sun.plugin.cache.EmptyInputStream")) { return stream; } } // Finally, something special for the Internet Explorer users. Turns out // that we can't get files that are part of the same folder using the // methods above when using IE, so we have to resort to the old skool // getDocumentBase() from teh applet dayz. 1996, my brotha. try { URL base = getDocumentBase(); if (base != null) { URL url = new URL(base, filename); URLConnection conn = url.openConnection(); return conn.getInputStream(); // if (conn instanceof HttpURLConnection) { // HttpURLConnection httpConnection = (HttpURLConnection) conn; // // test for 401 result (HTTP only) // int responseCode = httpConnection.getResponseCode(); // } } } catch (Exception e) { } // IO or NPE or... // Now try it with a 'data' subfolder. getting kinda desperate for data... try { URL base = getDocumentBase(); if (base != null) { URL url = new URL(base, "data/" + filename); URLConnection conn = url.openConnection(); return conn.getInputStream(); } } catch (Exception e) { } try { // attempt to load from a local file, used when running as // an application, or as a signed applet try { // first try to catch any security exceptions try { stream = new FileInputStream(dataPath(filename)); if (stream != null) return stream; } catch (IOException e2) { } try { stream = new FileInputStream(sketchPath(filename)); if (stream != null) return stream; } catch (Exception e) { } // ignored try { stream = new FileInputStream(filename); if (stream != null) return stream; } catch (IOException e1) { } } catch (SecurityException se) { } // online, whups } catch (Exception e) { //die(e.getMessage(), e); e.printStackTrace(); } return null; } /** * @nowebref */ static public InputStream createInput(File file) { if (file == null) { throw new IllegalArgumentException("File passed to createInput() was null"); } try { InputStream input = new FileInputStream(file); if (file.getName().toLowerCase().endsWith(".gz")) { return new GZIPInputStream(input); } return input; } catch (IOException e) { System.err.println("Could not createInput() for " + file); e.printStackTrace(); return null; } } /** * ( begin auto-generated from loadBytes.xml ) * * Reads the contents of a file or url and places it in a byte array. If a * file is specified, it must be located in the sketch's "data" * directory/folder.<br /> * <br /> * The filename parameter can also be a URL to a file found online. For * security reasons, a Processing sketch found online can only download * files from the same server from which it came. Getting around this * restriction requires a <a * href="http://wiki.processing.org/w/Sign_an_Applet">signed applet</a>. * * ( end auto-generated ) * @webref input:files * @param filename name of a file in the data folder or a URL. * @see PApplet#loadStrings(String) * @see PApplet#saveStrings(String, String[]) * @see PApplet#saveBytes(String, byte[]) * */ public byte[] loadBytes(String filename) { InputStream is = createInput(filename); if (is != null) { byte[] outgoing = loadBytes(is); try { is.close(); } catch (IOException e) { e.printStackTrace(); // shouldn't happen } return outgoing; } System.err.println("The file \"" + filename + "\" " + "is missing or inaccessible, make sure " + "the URL is valid or that the file has been " + "added to your sketch and is readable."); return null; } /** * @nowebref */ static public byte[] loadBytes(InputStream input) { try { BufferedInputStream bis = new BufferedInputStream(input); ByteArrayOutputStream out = new ByteArrayOutputStream(); int c = bis.read(); while (c != -1) { out.write(c); c = bis.read(); } return out.toByteArray(); } catch (IOException e) { e.printStackTrace(); //throw new RuntimeException("Couldn't load bytes from stream"); } return null; } /** * @nowebref */ static public byte[] loadBytes(File file) { InputStream is = createInput(file); return loadBytes(is); } /** * @nowebref */ static public String[] loadStrings(File file) { InputStream is = createInput(file); if (is != null) { String[] outgoing = loadStrings(is); try { is.close(); } catch (IOException e) { e.printStackTrace(); } return outgoing; } return null; } /** * ( begin auto-generated from loadStrings.xml ) * * Reads the contents of a file or url and creates a String array of its * individual lines. If a file is specified, it must be located in the * sketch's "data" directory/folder.<br /> * <br /> * The filename parameter can also be a URL to a file found online. For * security reasons, a Processing sketch found online can only download * files from the same server from which it came. Getting around this * restriction requires a <a * href="http://wiki.processing.org/w/Sign_an_Applet">signed applet</a>. * <br /> * If the file is not available or an error occurs, <b>null</b> will be * returned and an error message will be printed to the console. The error * message does not halt the program, however the null value may cause a * NullPointerException if your code does not check whether the value * returned is null. * <br/> <br/> * Starting with Processing release 0134, all files loaded and saved by the * Processing API use UTF-8 encoding. In previous releases, the default * encoding for your platform was used, which causes problems when files * are moved to other platforms. * * ( end auto-generated ) * * <h3>Advanced</h3> * Load data from a file and shove it into a String array. * <p> * Exceptions are handled internally, when an error, occurs, an * exception is printed to the console and 'null' is returned, * but the program continues running. This is a tradeoff between * 1) showing the user that there was a problem but 2) not requiring * that all i/o code is contained in try/catch blocks, for the sake * of new users (or people who are just trying to get things done * in a "scripting" fashion. If you want to handle exceptions, * use Java methods for I/O. * * @webref input:files * @param filename name of the file or url to load * @see PApplet#loadBytes(String) * @see PApplet#saveStrings(String, String[]) * @see PApplet#saveBytes(String, byte[]) */ public String[] loadStrings(String filename) { InputStream is = createInput(filename); if (is != null) return loadStrings(is); System.err.println("The file \"" + filename + "\" " + "is missing or inaccessible, make sure " + "the URL is valid or that the file has been " + "added to your sketch and is readable."); return null; } /** * @nowebref */ static public String[] loadStrings(InputStream input) { try { BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8")); return loadStrings(reader); } catch (IOException e) { e.printStackTrace(); } return null; } static public String[] loadStrings(BufferedReader reader) { try { String lines[] = new String[100]; int lineCount = 0; String line = null; while ((line = reader.readLine()) != null) { if (lineCount == lines.length) { String temp[] = new String[lineCount << 1]; System.arraycopy(lines, 0, temp, 0, lineCount); lines = temp; } lines[lineCount++] = line; } reader.close(); if (lineCount == lines.length) { return lines; } // resize array to appropriate amount for these lines String output[] = new String[lineCount]; System.arraycopy(lines, 0, output, 0, lineCount); return output; } catch (IOException e) { e.printStackTrace(); //throw new RuntimeException("Error inside loadStrings()"); } return null; } ////////////////////////////////////////////////////////////// // FILE OUTPUT /** * ( begin auto-generated from createOutput.xml ) * * Similar to <b>createInput()</b>, this creates a Java <b>OutputStream</b> * for a given filename or path. The file will be created in the sketch * folder, or in the same folder as an exported application. * <br /><br /> * If the path does not exist, intermediate folders will be created. If an * exception occurs, it will be printed to the console, and <b>null</b> * will be returned. * <br /><br /> * This function is a convenience over the Java approach that requires you * to 1) create a FileOutputStream object, 2) determine the exact file * location, and 3) handle exceptions. Exceptions are handled internally by * the function, which is more appropriate for "sketch" projects. * <br /><br /> * If the output filename ends with <b>.gz</b>, the output will be * automatically GZIP compressed as it is written. * * ( end auto-generated ) * @webref output:files * @param filename name of the file to open * @see PApplet#createInput(String) * @see PApplet#selectOutput() */ public OutputStream createOutput(String filename) { return createOutput(saveFile(filename)); } /** * @nowebref */ static public OutputStream createOutput(File file) { try { createPath(file); // make sure the path exists FileOutputStream fos = new FileOutputStream(file); if (file.getName().toLowerCase().endsWith(".gz")) { return new GZIPOutputStream(fos); } return fos; } catch (IOException e) { e.printStackTrace(); } return null; } /** * ( begin auto-generated from saveStream.xml ) * * Save the contents of a stream to a file in the sketch folder. This is * basically <b>saveBytes(blah, loadBytes())</b>, but done more efficiently * (and with less confusing syntax).<br /> * <br /> * When using the <b>targetFile</b> parameter, it writes to a <b>File</b> * object for greater control over the file location. (Note that unlike * some other functions, this will not automatically compress or uncompress * gzip files.) * * ( end auto-generated ) * * @webref output:files * @param target name of the file to write to * @param source location to read from (a filename, path, or URL) * @see PApplet#createOutput(String) */ public boolean saveStream(String target, String source) { return saveStream(saveFile(target), source); } /** * Identical to the other saveStream(), but writes to a File * object, for greater control over the file location. * <p/> * Note that unlike other api methods, this will not automatically * compress or uncompress gzip files. */ public boolean saveStream(File target, String source) { return saveStream(target, createInputRaw(source)); } /** * @nowebref */ public boolean saveStream(String target, InputStream source) { return saveStream(saveFile(target), source); } /** * @nowebref */ static public boolean saveStream(File target, InputStream source) { File tempFile = null; try { File parentDir = target.getParentFile(); // make sure that this path actually exists before writing createPath(target); tempFile = File.createTempFile(target.getName(), null, parentDir); FileOutputStream targetStream = new FileOutputStream(tempFile); saveStream(targetStream, source); targetStream.close(); targetStream = null; if (target.exists()) { if (!target.delete()) { System.err.println("Could not replace " + target.getAbsolutePath() + "."); } } if (!tempFile.renameTo(target)) { System.err.println("Could not rename temporary file " + tempFile.getAbsolutePath()); return false; } return true; } catch (IOException e) { if (tempFile != null) { tempFile.delete(); } e.printStackTrace(); return false; } } /** * @nowebref */ static public void saveStream(OutputStream target, InputStream source) throws IOException { BufferedInputStream bis = new BufferedInputStream(source, 16384); BufferedOutputStream bos = new BufferedOutputStream(target); byte[] buffer = new byte[8192]; int bytesRead; while ((bytesRead = bis.read(buffer)) != -1) { bos.write(buffer, 0, bytesRead); } bos.flush(); } /** * ( begin auto-generated from saveBytes.xml ) * * Opposite of <b>loadBytes()</b>, will write an entire array of bytes to a * file. The data is saved in binary format. This file is saved to the * sketch's folder, which is opened by selecting "Show sketch folder" from * the "Sketch" menu.<br /> * <br /> * It is not possible to use saveXxxxx() functions inside a web browser * unless the sketch is <a * href="http://wiki.processing.org/w/Sign_an_Applet">signed applet</A>. To * save a file back to a server, see the <a * href="http://wiki.processing.org/w/Saving_files_to_a_web-server">save to * web</A> code snippet on the Processing Wiki. * * ( end auto-generated ) * * @webref output:files * @param filename name of the file to write to * @param data array of bytes to be written * @see PApplet#loadStrings(String) * @see PApplet#loadBytes(String) * @see PApplet#saveStrings(String, String[]) */ public void saveBytes(String filename, byte[] data) { saveBytes(saveFile(filename), data); } /** * @nowebref * Saves bytes to a specific File location specified by the user. */ static public void saveBytes(File file, byte[] data) { File tempFile = null; try { File parentDir = file.getParentFile(); tempFile = File.createTempFile(file.getName(), null, parentDir); OutputStream output = createOutput(tempFile); saveBytes(output, data); output.close(); output = null; if (file.exists()) { if (!file.delete()) { System.err.println("Could not replace " + file.getAbsolutePath()); } } if (!tempFile.renameTo(file)) { System.err.println("Could not rename temporary file " + tempFile.getAbsolutePath()); } } catch (IOException e) { System.err.println("error saving bytes to " + file); if (tempFile != null) { tempFile.delete(); } e.printStackTrace(); } } /** * @nowebref * Spews a buffer of bytes to an OutputStream. */ static public void saveBytes(OutputStream output, byte[] data) { try { output.write(data); output.flush(); } catch (IOException e) { e.printStackTrace(); } } // /** * ( begin auto-generated from saveStrings.xml ) * * Writes an array of strings to a file, one line per string. This file is * saved to the sketch's folder, which is opened by selecting "Show sketch * folder" from the "Sketch" menu.<br /> * <br /> * It is not possible to use saveXxxxx() functions inside a web browser * unless the sketch is <a * href="http://wiki.processing.org/w/Sign_an_Applet">signed applet</A>. To * save a file back to a server, see the <a * href="http://wiki.processing.org/w/Saving_files_to_a_web-server">save to * web</A> code snippet on the Processing Wiki.<br/> * <br/ > * Starting with Processing 1.0, all files loaded and saved by the * Processing API use UTF-8 encoding. In previous releases, the default * encoding for your platform was used, which causes problems when files * are moved to other platforms. * * ( end auto-generated ) * @webref output:files * @param filename filename for output * @param data string array to be written * @see PApplet#loadStrings(String) * @see PApplet#loadBytes(String) * @see PApplet#saveBytes(String, byte[]) */ public void saveStrings(String filename, String data[]) { saveStrings(saveFile(filename), data); } /** * @nowebref */ static public void saveStrings(File file, String data[]) { saveStrings(createOutput(file), data); } /** * @nowebref */ static public void saveStrings(OutputStream output, String[] data) { PrintWriter writer = createWriter(output); for (int i = 0; i < data.length; i++) { writer.println(data[i]); } writer.flush(); writer.close(); } ////////////////////////////////////////////////////////////// /** * Prepend the sketch folder path to the filename (or path) that is * passed in. External libraries should use this function to save to * the sketch folder. * <p/> * Note that when running as an applet inside a web browser, * the sketchPath will be set to null, because security restrictions * prevent applets from accessing that information. * <p/> * This will also cause an error if the sketch is not inited properly, * meaning that init() was never called on the PApplet when hosted * my some other main() or by other code. For proper use of init(), * see the examples in the main description text for PApplet. */ public String sketchPath(String where) { if (sketchPath == null) { return where; // throw new RuntimeException("The applet was not inited properly, " + // "or security restrictions prevented " + // "it from determining its path."); } // isAbsolute() could throw an access exception, but so will writing // to the local disk using the sketch path, so this is safe here. // for 0120, added a try/catch anyways. try { if (new File(where).isAbsolute()) return where; } catch (Exception e) { } return sketchPath + File.separator + where; } public File sketchFile(String where) { return new File(sketchPath(where)); } /** * Returns a path inside the applet folder to save to. Like sketchPath(), * but creates any in-between folders so that things save properly. * <p/> * All saveXxxx() functions use the path to the sketch folder, rather than * its data folder. Once exported, the data folder will be found inside the * jar file of the exported application or applet. In this case, it's not * possible to save data into the jar file, because it will often be running * from a server, or marked in-use if running from a local file system. * With this in mind, saving to the data path doesn't make sense anyway. * If you know you're running locally, and want to save to the data folder, * use <TT>saveXxxx("data/blah.dat")</TT>. */ public String savePath(String where) { if (where == null) return null; String filename = sketchPath(where); createPath(filename); return filename; } /** * Identical to savePath(), but returns a File object. */ public File saveFile(String where) { return new File(savePath(where)); } /** * Return a full path to an item in the data folder. * <p> * This is only available with applications, not applets or Android. * On Windows and Linux, this is simply the data folder, which is located * in the same directory as the EXE file and lib folders. On Mac OS X, this * is a path to the data folder buried inside Contents/Resources/Java. * For the latter point, that also means that the data folder should not be * considered writable. Use sketchPath() for now, or inputPath() and * outputPath() once they're available in the 2.0 release. * <p> * dataPath() is not supported with applets because applets have their data * folder wrapped into the JAR file. To read data from the data folder that * works with an applet, you should use other methods such as createInput(), * createReader(), or loadStrings(). */ public String dataPath(String where) { return dataFile(where).getAbsolutePath(); } /** * Return a full path to an item in the data folder as a File object. * See the dataPath() method for more information. */ public File dataFile(String where) { // isAbsolute() could throw an access exception, but so will writing // to the local disk using the sketch path, so this is safe here. File why = new File(where); if (why.isAbsolute()) return why; String jarPath = getClass().getProtectionDomain().getCodeSource().getLocation().getPath(); if (jarPath.contains("Contents/Resources/Java/")) { // The path will be URL encoded (%20 for spaces) coming from above // http://code.google.com/p/processing/issues/detail?id=1073 File containingFolder = new File(urlDecode(jarPath)).getParentFile(); File dataFolder = new File(containingFolder, "data"); return new File(dataFolder, where); } // Windows, Linux, or when not using a Mac OS X .app file return new File(sketchPath + File.separator + "data" + File.separator + where); } /** * On Windows and Linux, this is simply the data folder. On Mac OS X, this is * the path to the data folder buried inside Contents/Resources/Java */ // public File inputFile(String where) { // } // public String inputPath(String where) { // } /** * Takes a path and creates any in-between folders if they don't * already exist. Useful when trying to save to a subfolder that * may not actually exist. */ static public void createPath(String path) { createPath(new File(path)); } static public void createPath(File file) { try { String parent = file.getParent(); if (parent != null) { File unit = new File(parent); if (!unit.exists()) unit.mkdirs(); } } catch (SecurityException se) { System.err.println("You don't have permissions to create " + file.getAbsolutePath()); } } static public String getExtension(String filename) { String extension; String lower = filename.toLowerCase(); int dot = filename.lastIndexOf('.'); if (dot == -1) { extension = "unknown"; // no extension found } extension = lower.substring(dot + 1); // check for, and strip any parameters on the url, i.e. // filename.jpg?blah=blah&something=that int question = extension.indexOf('?'); if (question != -1) { extension = extension.substring(0, question); } return extension; } ////////////////////////////////////////////////////////////// // URL ENCODING static public String urlEncode(String str) { try { return URLEncoder.encode(str, "UTF-8"); } catch (UnsupportedEncodingException e) { // oh c'mon return null; } } static public String urlDecode(String str) { try { return URLDecoder.decode(str, "UTF-8"); } catch (UnsupportedEncodingException e) { // safe per the JDK source return null; } } ////////////////////////////////////////////////////////////// // SORT /** * ( begin auto-generated from sort.xml ) * * Sorts an array of numbers from smallest to largest and puts an array of * words in alphabetical order. The original array is not modified, a * re-ordered array is returned. The <b>count</b> parameter states the * number of elements to sort. For example if there are 12 elements in an * array and if count is the value 5, only the first five elements on the * array will be sorted. <!--As of release 0126, the alphabetical ordering * is case insensitive.--> * * ( end auto-generated ) * @webref data:array_functions * @param list array to sort * @see PApplet#reverse(boolean[]) */ static public byte[] sort(byte list[]) { return sort(list, list.length); } /** * @param count number of elements to sort, starting from 0 */ static public byte[] sort(byte[] list, int count) { byte[] outgoing = new byte[list.length]; System.arraycopy(list, 0, outgoing, 0, list.length); Arrays.sort(outgoing, 0, count); return outgoing; } static public char[] sort(char list[]) { return sort(list, list.length); } static public char[] sort(char[] list, int count) { char[] outgoing = new char[list.length]; System.arraycopy(list, 0, outgoing, 0, list.length); Arrays.sort(outgoing, 0, count); return outgoing; } static public int[] sort(int list[]) { return sort(list, list.length); } static public int[] sort(int[] list, int count) { int[] outgoing = new int[list.length]; System.arraycopy(list, 0, outgoing, 0, list.length); Arrays.sort(outgoing, 0, count); return outgoing; } static public float[] sort(float list[]) { return sort(list, list.length); } static public float[] sort(float[] list, int count) { float[] outgoing = new float[list.length]; System.arraycopy(list, 0, outgoing, 0, list.length); Arrays.sort(outgoing, 0, count); return outgoing; } static public String[] sort(String list[]) { return sort(list, list.length); } static public String[] sort(String[] list, int count) { String[] outgoing = new String[list.length]; System.arraycopy(list, 0, outgoing, 0, list.length); Arrays.sort(outgoing, 0, count); return outgoing; } ////////////////////////////////////////////////////////////// // ARRAY UTILITIES /** * ( begin auto-generated from arrayCopy.xml ) * * Copies an array (or part of an array) to another array. The <b>src</b> * array is copied to the <b>dst</b> array, beginning at the position * specified by <b>srcPos</b> and into the position specified by * <b>dstPos</b>. The number of elements to copy is determined by * <b>length</b>. The simplified version with two arguments copies an * entire array to another of the same size. It is equivalent to * "arrayCopy(src, 0, dst, 0, src.length)". This function is far more * efficient for copying array data than iterating through a <b>for</b> and * copying each element. * * ( end auto-generated ) * @webref data:array_functions * @param src the source array * @param srcPosition starting position in the source array * @param dst the destination array of the same data type as the source array * @param dstPosition starting position in the destination array * @param length number of array elements to be copied * @see PApplet#concat(boolean[], boolean[]) */ static public void arrayCopy(Object src, int srcPosition, Object dst, int dstPosition, int length) { System.arraycopy(src, srcPosition, dst, dstPosition, length); } /** * Convenience method for arraycopy(). * Identical to <CODE>arraycopy(src, 0, dst, 0, length);</CODE> */ static public void arrayCopy(Object src, Object dst, int length) { System.arraycopy(src, 0, dst, 0, length); } /** * Shortcut to copy the entire contents of * the source into the destination array. * Identical to <CODE>arraycopy(src, 0, dst, 0, src.length);</CODE> */ static public void arrayCopy(Object src, Object dst) { System.arraycopy(src, 0, dst, 0, Array.getLength(src)); } // /** * @deprecated Use arrayCopy() instead. */ static public void arraycopy(Object src, int srcPosition, Object dst, int dstPosition, int length) { System.arraycopy(src, srcPosition, dst, dstPosition, length); } /** * @deprecated Use arrayCopy() instead. */ static public void arraycopy(Object src, Object dst, int length) { System.arraycopy(src, 0, dst, 0, length); } /** * @deprecated Use arrayCopy() instead. */ static public void arraycopy(Object src, Object dst) { System.arraycopy(src, 0, dst, 0, Array.getLength(src)); } /** * ( begin auto-generated from expand.xml ) * * Increases the size of an array. By default, this function doubles the * size of the array, but the optional <b>newSize</b> parameter provides * precise control over the increase in size. * <br/> <br/> * When using an array of objects, the data returned from the function must * be cast to the object array's data type. For example: <em>SomeClass[] * items = (SomeClass[]) expand(originalArray)</em>. * * ( end auto-generated ) * * @webref data:array_functions * @param list the array to expand * @see PApplet#shorten(boolean[]) */ static public boolean[] expand(boolean list[]) { return expand(list, list.length << 1); } /** * @param newSize new size for the array */ static public boolean[] expand(boolean list[], int newSize) { boolean temp[] = new boolean[newSize]; System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } static public byte[] expand(byte list[]) { return expand(list, list.length << 1); } static public byte[] expand(byte list[], int newSize) { byte temp[] = new byte[newSize]; System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } static public char[] expand(char list[]) { return expand(list, list.length << 1); } static public char[] expand(char list[], int newSize) { char temp[] = new char[newSize]; System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } static public int[] expand(int list[]) { return expand(list, list.length << 1); } static public int[] expand(int list[], int newSize) { int temp[] = new int[newSize]; System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } static public long[] expand(long list[]) { return expand(list, list.length << 1); } static public long[] expand(long list[], int newSize) { long temp[] = new long[newSize]; System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } static public float[] expand(float list[]) { return expand(list, list.length << 1); } static public float[] expand(float list[], int newSize) { float temp[] = new float[newSize]; System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } static public double[] expand(double list[]) { return expand(list, list.length << 1); } static public double[] expand(double list[], int newSize) { double temp[] = new double[newSize]; System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } static public String[] expand(String list[]) { return expand(list, list.length << 1); } static public String[] expand(String list[], int newSize) { String temp[] = new String[newSize]; // in case the new size is smaller than list.length System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } /** * @nowebref */ static public Object expand(Object array) { return expand(array, Array.getLength(array) << 1); } static public Object expand(Object list, int newSize) { Class<?> type = list.getClass().getComponentType(); Object temp = Array.newInstance(type, newSize); System.arraycopy(list, 0, temp, 0, Math.min(Array.getLength(list), newSize)); return temp; } // contract() has been removed in revision 0124, use subset() instead. // (expand() is also functionally equivalent) /** * ( begin auto-generated from append.xml ) * * Expands an array by one element and adds data to the new position. The * datatype of the <b>element</b> parameter must be the same as the * datatype of the array. * <br/> <br/> * When using an array of objects, the data returned from the function must * be cast to the object array's data type. For example: <em>SomeClass[] * items = (SomeClass[]) append(originalArray, element)</em>. * * ( end auto-generated ) * * @webref data:array_functions * @param array array to append * @param value new data for the array * @see PApplet#shorten(boolean[]) * @see PApplet#expand(boolean[]) */ static public byte[] append(byte array[], byte value) { array = expand(array, array.length + 1); array[array.length-1] = value; return array; } static public char[] append(char array[], char value) { array = expand(array, array.length + 1); array[array.length-1] = value; return array; } static public int[] append(int array[], int value) { array = expand(array, array.length + 1); array[array.length-1] = value; return array; } static public float[] append(float array[], float value) { array = expand(array, array.length + 1); array[array.length-1] = value; return array; } static public String[] append(String array[], String value) { array = expand(array, array.length + 1); array[array.length-1] = value; return array; } static public Object append(Object array, Object value) { int length = Array.getLength(array); array = expand(array, length + 1); Array.set(array, length, value); return array; } /** * ( begin auto-generated from shorten.xml ) * * Decreases an array by one element and returns the shortened array. * <br/> <br/> * When using an array of objects, the data returned from the function must * be cast to the object array's data type. For example: <em>SomeClass[] * items = (SomeClass[]) shorten(originalArray)</em>. * * ( end auto-generated ) * * @webref data:array_functions * @param list array to shorten * @see PApplet#append(byte[], byte) * @see PApplet#expand(boolean[]) */ static public boolean[] shorten(boolean list[]) { return subset(list, 0, list.length-1); } static public byte[] shorten(byte list[]) { return subset(list, 0, list.length-1); } static public char[] shorten(char list[]) { return subset(list, 0, list.length-1); } static public int[] shorten(int list[]) { return subset(list, 0, list.length-1); } static public float[] shorten(float list[]) { return subset(list, 0, list.length-1); } static public String[] shorten(String list[]) { return subset(list, 0, list.length-1); } static public Object shorten(Object list) { int length = Array.getLength(list); return subset(list, 0, length - 1); } /** * ( begin auto-generated from splice.xml ) * * Inserts a value or array of values into an existing array. The first two * parameters must be of the same datatype. The <b>array</b> parameter * defines the array which will be modified and the second parameter * defines the data which will be inserted. * <br/> <br/> * When using an array of objects, the data returned from the function must * be cast to the object array's data type. For example: <em>SomeClass[] * items = (SomeClass[]) splice(array1, array2, index)</em>. * * ( end auto-generated ) * @webref data:array_functions * @param list array to splice into * @param value value to be spliced in * @param index position in the array from which to insert data * @see PApplet#concat(boolean[], boolean[]) * @see PApplet#subset(boolean[], int, int) */ static final public boolean[] splice(boolean list[], boolean value, int index) { boolean outgoing[] = new boolean[list.length + 1]; System.arraycopy(list, 0, outgoing, 0, index); outgoing[index] = value; System.arraycopy(list, index, outgoing, index + 1, list.length - index); return outgoing; } static final public boolean[] splice(boolean list[], boolean value[], int index) { boolean outgoing[] = new boolean[list.length + value.length]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(value, 0, outgoing, index, value.length); System.arraycopy(list, index, outgoing, index + value.length, list.length - index); return outgoing; } static final public byte[] splice(byte list[], byte value, int index) { byte outgoing[] = new byte[list.length + 1]; System.arraycopy(list, 0, outgoing, 0, index); outgoing[index] = value; System.arraycopy(list, index, outgoing, index + 1, list.length - index); return outgoing; } static final public byte[] splice(byte list[], byte value[], int index) { byte outgoing[] = new byte[list.length + value.length]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(value, 0, outgoing, index, value.length); System.arraycopy(list, index, outgoing, index + value.length, list.length - index); return outgoing; } static final public char[] splice(char list[], char value, int index) { char outgoing[] = new char[list.length + 1]; System.arraycopy(list, 0, outgoing, 0, index); outgoing[index] = value; System.arraycopy(list, index, outgoing, index + 1, list.length - index); return outgoing; } static final public char[] splice(char list[], char value[], int index) { char outgoing[] = new char[list.length + value.length]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(value, 0, outgoing, index, value.length); System.arraycopy(list, index, outgoing, index + value.length, list.length - index); return outgoing; } static final public int[] splice(int list[], int value, int index) { int outgoing[] = new int[list.length + 1]; System.arraycopy(list, 0, outgoing, 0, index); outgoing[index] = value; System.arraycopy(list, index, outgoing, index + 1, list.length - index); return outgoing; } static final public int[] splice(int list[], int value[], int index) { int outgoing[] = new int[list.length + value.length]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(value, 0, outgoing, index, value.length); System.arraycopy(list, index, outgoing, index + value.length, list.length - index); return outgoing; } static final public float[] splice(float list[], float value, int index) { float outgoing[] = new float[list.length + 1]; System.arraycopy(list, 0, outgoing, 0, index); outgoing[index] = value; System.arraycopy(list, index, outgoing, index + 1, list.length - index); return outgoing; } static final public float[] splice(float list[], float value[], int index) { float outgoing[] = new float[list.length + value.length]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(value, 0, outgoing, index, value.length); System.arraycopy(list, index, outgoing, index + value.length, list.length - index); return outgoing; } static final public String[] splice(String list[], String value, int index) { String outgoing[] = new String[list.length + 1]; System.arraycopy(list, 0, outgoing, 0, index); outgoing[index] = value; System.arraycopy(list, index, outgoing, index + 1, list.length - index); return outgoing; } static final public String[] splice(String list[], String value[], int index) { String outgoing[] = new String[list.length + value.length]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(value, 0, outgoing, index, value.length); System.arraycopy(list, index, outgoing, index + value.length, list.length - index); return outgoing; } static final public Object splice(Object list, Object value, int index) { Object[] outgoing = null; int length = Array.getLength(list); // check whether item being spliced in is an array if (value.getClass().getName().charAt(0) == '[') { int vlength = Array.getLength(value); outgoing = new Object[length + vlength]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(value, 0, outgoing, index, vlength); System.arraycopy(list, index, outgoing, index + vlength, length - index); } else { outgoing = new Object[length + 1]; System.arraycopy(list, 0, outgoing, 0, index); Array.set(outgoing, index, value); System.arraycopy(list, index, outgoing, index + 1, length - index); } return outgoing; } static public boolean[] subset(boolean list[], int start) { return subset(list, start, list.length - start); } /** * ( begin auto-generated from subset.xml ) * * Extracts an array of elements from an existing array. The <b>array</b> * parameter defines the array from which the elements will be copied and * the <b>offset</b> and <b>length</b> parameters determine which elements * to extract. If no <b>length</b> is given, elements will be extracted * from the <b>offset</b> to the end of the array. When specifying the * <b>offset</b> remember the first array element is 0. This function does * not change the source array. * <br/> <br/> * When using an array of objects, the data returned from the function must * be cast to the object array's data type. For example: <em>SomeClass[] * items = (SomeClass[]) subset(originalArray, 0, 4)</em>. * * ( end auto-generated ) * @webref data:array_functions * @param list array to extract from * @param start position to begin * @param count number of values to extract * @see PApplet#splice(boolean[], boolean, int) */ static public boolean[] subset(boolean list[], int start, int count) { boolean output[] = new boolean[count]; System.arraycopy(list, start, output, 0, count); return output; } static public byte[] subset(byte list[], int start) { return subset(list, start, list.length - start); } static public byte[] subset(byte list[], int start, int count) { byte output[] = new byte[count]; System.arraycopy(list, start, output, 0, count); return output; } static public char[] subset(char list[], int start) { return subset(list, start, list.length - start); } static public char[] subset(char list[], int start, int count) { char output[] = new char[count]; System.arraycopy(list, start, output, 0, count); return output; } static public int[] subset(int list[], int start) { return subset(list, start, list.length - start); } static public int[] subset(int list[], int start, int count) { int output[] = new int[count]; System.arraycopy(list, start, output, 0, count); return output; } static public float[] subset(float list[], int start) { return subset(list, start, list.length - start); } static public float[] subset(float list[], int start, int count) { float output[] = new float[count]; System.arraycopy(list, start, output, 0, count); return output; } static public String[] subset(String list[], int start) { return subset(list, start, list.length - start); } static public String[] subset(String list[], int start, int count) { String output[] = new String[count]; System.arraycopy(list, start, output, 0, count); return output; } static public Object subset(Object list, int start) { int length = Array.getLength(list); return subset(list, start, length - start); } static public Object subset(Object list, int start, int count) { Class<?> type = list.getClass().getComponentType(); Object outgoing = Array.newInstance(type, count); System.arraycopy(list, start, outgoing, 0, count); return outgoing; } /** * ( begin auto-generated from concat.xml ) * * Concatenates two arrays. For example, concatenating the array { 1, 2, 3 * } and the array { 4, 5, 6 } yields { 1, 2, 3, 4, 5, 6 }. Both parameters * must be arrays of the same datatype. * <br/> <br/> * When using an array of objects, the data returned from the function must * be cast to the object array's data type. For example: <em>SomeClass[] * items = (SomeClass[]) concat(array1, array2)</em>. * * ( end auto-generated ) * @webref data:array_functions * @param a first array to concatenate * @param b second array to concatenate * @see PApplet#splice(boolean[], boolean, int) * @see PApplet#arrayCopy(Object, int, Object, int, int) */ static public boolean[] concat(boolean a[], boolean b[]) { boolean c[] = new boolean[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } static public byte[] concat(byte a[], byte b[]) { byte c[] = new byte[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } static public char[] concat(char a[], char b[]) { char c[] = new char[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } static public int[] concat(int a[], int b[]) { int c[] = new int[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } static public float[] concat(float a[], float b[]) { float c[] = new float[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } static public String[] concat(String a[], String b[]) { String c[] = new String[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } static public Object concat(Object a, Object b) { Class<?> type = a.getClass().getComponentType(); int alength = Array.getLength(a); int blength = Array.getLength(b); Object outgoing = Array.newInstance(type, alength + blength); System.arraycopy(a, 0, outgoing, 0, alength); System.arraycopy(b, 0, outgoing, alength, blength); return outgoing; } // /** * ( begin auto-generated from reverse.xml ) * * Reverses the order of an array. * * ( end auto-generated ) * @webref data:array_functions * @param list booleans[], bytes[], chars[], ints[], floats[], or Strings[] * @see PApplet#sort(String[], int) */ static public boolean[] reverse(boolean list[]) { boolean outgoing[] = new boolean[list.length]; int length1 = list.length - 1; for (int i = 0; i < list.length; i++) { outgoing[i] = list[length1 - i]; } return outgoing; } static public byte[] reverse(byte list[]) { byte outgoing[] = new byte[list.length]; int length1 = list.length - 1; for (int i = 0; i < list.length; i++) { outgoing[i] = list[length1 - i]; } return outgoing; } static public char[] reverse(char list[]) { char outgoing[] = new char[list.length]; int length1 = list.length - 1; for (int i = 0; i < list.length; i++) { outgoing[i] = list[length1 - i]; } return outgoing; } static public int[] reverse(int list[]) { int outgoing[] = new int[list.length]; int length1 = list.length - 1; for (int i = 0; i < list.length; i++) { outgoing[i] = list[length1 - i]; } return outgoing; } static public float[] reverse(float list[]) { float outgoing[] = new float[list.length]; int length1 = list.length - 1; for (int i = 0; i < list.length; i++) { outgoing[i] = list[length1 - i]; } return outgoing; } static public String[] reverse(String list[]) { String outgoing[] = new String[list.length]; int length1 = list.length - 1; for (int i = 0; i < list.length; i++) { outgoing[i] = list[length1 - i]; } return outgoing; } static public Object reverse(Object list) { Class<?> type = list.getClass().getComponentType(); int length = Array.getLength(list); Object outgoing = Array.newInstance(type, length); for (int i = 0; i < length; i++) { Array.set(outgoing, i, Array.get(list, (length - 1) - i)); } return outgoing; } ////////////////////////////////////////////////////////////// // STRINGS /** * ( begin auto-generated from trim.xml ) * * Removes whitespace characters from the beginning and end of a String. In * addition to standard whitespace characters such as space, carriage * return, and tab, this function also removes the Unicode "nbsp" character. * * ( end auto-generated ) * @webref data:string_functions * @param str any string * @see PApplet#split(String, String) * @see PApplet#join(String[], char) */ static public String trim(String str) { return str.replace('\u00A0', ' ').trim(); } /** * @param array a String array */ static public String[] trim(String[] array) { String[] outgoing = new String[array.length]; for (int i = 0; i < array.length; i++) { if (array[i] != null) { outgoing[i] = array[i].replace('\u00A0', ' ').trim(); } } return outgoing; } /** * ( begin auto-generated from join.xml ) * * Combines an array of Strings into one String, each separated by the * character(s) used for the <b>separator</b> parameter. To join arrays of * ints or floats, it's necessary to first convert them to strings using * <b>nf()</b> or <b>nfs()</b>. * * ( end auto-generated ) * @webref data:string_functions * @param list array of Strings * @param separator char or String to be placed between each item * @see PApplet#split(String, String) * @see PApplet#trim(String) * @see PApplet#nf(float, int, int) * @see PApplet#nfs(float, int, int) */ static public String join(String[] list, char separator) { return join(list, String.valueOf(separator)); } static public String join(String[] list, String separator) { StringBuffer buffer = new StringBuffer(); for (int i = 0; i < list.length; i++) { if (i != 0) buffer.append(separator); buffer.append(list[i]); } return buffer.toString(); } static public String[] splitTokens(String value) { return splitTokens(value, WHITESPACE); } /** * ( begin auto-generated from splitTokens.xml ) * * The splitTokens() function splits a String at one or many character * "tokens." The <b>tokens</b> parameter specifies the character or * characters to be used as a boundary. * <br/> <br/> * If no <b>tokens</b> character is specified, any whitespace character is * used to split. Whitespace characters include tab (\\t), line feed (\\n), * carriage return (\\r), form feed (\\f), and space. To convert a String * to an array of integers or floats, use the datatype conversion functions * <b>int()</b> and <b>float()</b> to convert the array of Strings. * * ( end auto-generated ) * @webref data:string_functions * @param value the String to be split * @param delim list of individual characters that will be used as separators * @see PApplet#split(String, String) * @see PApplet#join(String[], String) * @see PApplet#trim(String) */ static public String[] splitTokens(String value, String delim) { StringTokenizer toker = new StringTokenizer(value, delim); String pieces[] = new String[toker.countTokens()]; int index = 0; while (toker.hasMoreTokens()) { pieces[index++] = toker.nextToken(); } return pieces; } /** * ( begin auto-generated from split.xml ) * * The split() function breaks a string into pieces using a character or * string as the divider. The <b>delim</b> parameter specifies the * character or characters that mark the boundaries between each piece. A * String[] array is returned that contains each of the pieces. * <br/> <br/> * If the result is a set of numbers, you can convert the String[] array to * to a float[] or int[] array using the datatype conversion functions * <b>int()</b> and <b>float()</b> (see example above). * <br/> <br/> * The <b>splitTokens()</b> function works in a similar fashion, except * that it splits using a range of characters instead of a specific * character or sequence. * <!-- /><br /> * This function uses regular expressions to determine how the <b>delim</b> * parameter divides the <b>str</b> parameter. Therefore, if you use * characters such parentheses and brackets that are used with regular * expressions as a part of the <b>delim</b> parameter, you'll need to put * two blackslashes (\\\\) in front of the character (see example above). * You can read more about <a * href="http://en.wikipedia.org/wiki/Regular_expression">regular * expressions</a> and <a * href="http://en.wikipedia.org/wiki/Escape_character">escape * characters</a> on Wikipedia. * --> * * ( end auto-generated ) * @webref data:string_functions * @usage web_application * @param value the String to be split * @param delim the character or String used to separate the data */ static public String[] split(String value, char delim) { // do this so that the exception occurs inside the user's // program, rather than appearing to be a bug inside split() if (value == null) return null; //return split(what, String.valueOf(delim)); // huh char chars[] = value.toCharArray(); int splitCount = 0; //1; for (int i = 0; i < chars.length; i++) { if (chars[i] == delim) splitCount++; } // make sure that there is something in the input string //if (chars.length > 0) { // if the last char is a delimeter, get rid of it.. //if (chars[chars.length-1] == delim) splitCount--; // on second thought, i don't agree with this, will disable //} if (splitCount == 0) { String splits[] = new String[1]; splits[0] = new String(value); return splits; } //int pieceCount = splitCount + 1; String splits[] = new String[splitCount + 1]; int splitIndex = 0; int startIndex = 0; for (int i = 0; i < chars.length; i++) { if (chars[i] == delim) { splits[splitIndex++] = new String(chars, startIndex, i-startIndex); startIndex = i + 1; } } //if (startIndex != chars.length) { splits[splitIndex] = new String(chars, startIndex, chars.length-startIndex); //} return splits; } static public String[] split(String value, String delim) { ArrayList<String> items = new ArrayList<String>(); int index; int offset = 0; while ((index = value.indexOf(delim, offset)) != -1) { items.add(value.substring(offset, index)); offset = index + delim.length(); } items.add(value.substring(offset)); String[] outgoing = new String[items.size()]; items.toArray(outgoing); return outgoing; } static protected HashMap<String, Pattern> matchPatterns; static Pattern matchPattern(String regexp) { Pattern p = null; if (matchPatterns == null) { matchPatterns = new HashMap<String, Pattern>(); } else { p = matchPatterns.get(regexp); } if (p == null) { if (matchPatterns.size() == 10) { // Just clear out the match patterns here if more than 10 are being // used. It's not terribly efficient, but changes that you have >10 // different match patterns are very slim, unless you're doing // something really tricky (like custom match() methods), in which // case match() won't be efficient anyway. (And you should just be // using your own Java code.) The alternative is using a queue here, // but that's a silly amount of work for negligible benefit. matchPatterns.clear(); } p = Pattern.compile(regexp, Pattern.MULTILINE | Pattern.DOTALL); matchPatterns.put(regexp, p); } return p; } /** * ( begin auto-generated from match.xml ) * * The match() function is used to apply a regular expression to a piece of * text, and return matching groups (elements found inside parentheses) as * a String array. No match will return null. If no groups are specified in * the regexp, but the sequence matches, an array of length one (with the * matched text as the first element of the array) will be returned.<br /> * <br /> * To use the function, first check to see if the result is null. If the * result is null, then the sequence did not match. If the sequence did * match, an array is returned. * If there are groups (specified by sets of parentheses) in the regexp, * then the contents of each will be returned in the array. * Element [0] of a regexp match returns the entire matching string, and * the match groups start at element [1] (the first group is [1], the * second [2], and so on).<br /> * <br /> * The syntax can be found in the reference for Java's <a * href="http://download.oracle.com/javase/6/docs/api/">Pattern</a> class. * For regular expression syntax, read the <a * href="http://download.oracle.com/javase/tutorial/essential/regex/">Java * Tutorial</a> on the topic. * * ( end auto-generated ) * @webref data:string_functions * @param str the String to be searched * @param regexp the regexp to be used for matching * @see PApplet#matchAll(String, String) * @see PApplet#split(String, String) * @see PApplet#splitTokens(String, String) * @see PApplet#join(String[], String) * @see PApplet#trim(String) */ static public String[] match(String str, String regexp) { Pattern p = matchPattern(regexp); Matcher m = p.matcher(str); if (m.find()) { int count = m.groupCount() + 1; String[] groups = new String[count]; for (int i = 0; i < count; i++) { groups[i] = m.group(i); } return groups; } return null; } /** * ( begin auto-generated from matchAll.xml ) * * This function is used to apply a regular expression to a piece of text, * and return a list of matching groups (elements found inside parentheses) * as a two-dimensional String array. No matches will return null. If no * groups are specified in the regexp, but the sequence matches, a two * dimensional array is still returned, but the second dimension is only of * length one.<br /> * <br /> * To use the function, first check to see if the result is null. If the * result is null, then the sequence did not match at all. If the sequence * did match, a 2D array is returned. If there are groups (specified by * sets of parentheses) in the regexp, then the contents of each will be * returned in the array. * Assuming, a loop with counter variable i, element [i][0] of a regexp * match returns the entire matching string, and the match groups start at * element [i][1] (the first group is [i][1], the second [i][2], and so * on).<br /> * <br /> * The syntax can be found in the reference for Java's <a * href="http://download.oracle.com/javase/6/docs/api/">Pattern</a> class. * For regular expression syntax, read the <a * href="http://download.oracle.com/javase/tutorial/essential/regex/">Java * Tutorial</a> on the topic. * * ( end auto-generated ) * @webref data:string_functions * @param str the String to be searched * @param regexp the regexp to be used for matching * @see PApplet#match(String, String) * @see PApplet#split(String, String) * @see PApplet#splitTokens(String, String) * @see PApplet#join(String[], String) * @see PApplet#trim(String) */ static public String[][] matchAll(String str, String regexp) { Pattern p = matchPattern(regexp); Matcher m = p.matcher(str); ArrayList<String[]> results = new ArrayList<String[]>(); int count = m.groupCount() + 1; while (m.find()) { String[] groups = new String[count]; for (int i = 0; i < count; i++) { groups[i] = m.group(i); } results.add(groups); } if (results.isEmpty()) { return null; } String[][] matches = new String[results.size()][count]; for (int i = 0; i < matches.length; i++) { matches[i] = results.get(i); } return matches; } ////////////////////////////////////////////////////////////// // CASTING FUNCTIONS, INSERTED BY PREPROC /** * Convert a char to a boolean. 'T', 't', and '1' will become the * boolean value true, while 'F', 'f', or '0' will become false. */ /* static final public boolean parseBoolean(char what) { return ((what == 't') || (what == 'T') || (what == '1')); } */ /** * <p>Convert an integer to a boolean. Because of how Java handles upgrading * numbers, this will also cover byte and char (as they will upgrade to * an int without any sort of explicit cast).</p> * <p>The preprocessor will convert boolean(what) to parseBoolean(what).</p> * @return false if 0, true if any other number */ static final public boolean parseBoolean(int what) { return (what != 0); } /* // removed because this makes no useful sense static final public boolean parseBoolean(float what) { return (what != 0); } */ /** * Convert the string "true" or "false" to a boolean. * @return true if 'what' is "true" or "TRUE", false otherwise */ static final public boolean parseBoolean(String what) { return new Boolean(what).booleanValue(); } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /* // removed, no need to introduce strange syntax from other languages static final public boolean[] parseBoolean(char what[]) { boolean outgoing[] = new boolean[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = ((what[i] == 't') || (what[i] == 'T') || (what[i] == '1')); } return outgoing; } */ /** * Convert a byte array to a boolean array. Each element will be * evaluated identical to the integer case, where a byte equal * to zero will return false, and any other value will return true. * @return array of boolean elements */ /* static final public boolean[] parseBoolean(byte what[]) { boolean outgoing[] = new boolean[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (what[i] != 0); } return outgoing; } */ /** * Convert an int array to a boolean array. An int equal * to zero will return false, and any other value will return true. * @return array of boolean elements */ static final public boolean[] parseBoolean(int what[]) { boolean outgoing[] = new boolean[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (what[i] != 0); } return outgoing; } /* // removed, not necessary... if necessary, convert to int array first static final public boolean[] parseBoolean(float what[]) { boolean outgoing[] = new boolean[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (what[i] != 0); } return outgoing; } */ static final public boolean[] parseBoolean(String what[]) { boolean outgoing[] = new boolean[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = new Boolean(what[i]).booleanValue(); } return outgoing; } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static final public byte parseByte(boolean what) { return what ? (byte)1 : 0; } static final public byte parseByte(char what) { return (byte) what; } static final public byte parseByte(int what) { return (byte) what; } static final public byte parseByte(float what) { return (byte) what; } /* // nixed, no precedent static final public byte[] parseByte(String what) { // note: array[] return what.getBytes(); } */ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static final public byte[] parseByte(boolean what[]) { byte outgoing[] = new byte[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = what[i] ? (byte)1 : 0; } return outgoing; } static final public byte[] parseByte(char what[]) { byte outgoing[] = new byte[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (byte) what[i]; } return outgoing; } static final public byte[] parseByte(int what[]) { byte outgoing[] = new byte[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (byte) what[i]; } return outgoing; } static final public byte[] parseByte(float what[]) { byte outgoing[] = new byte[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (byte) what[i]; } return outgoing; } /* static final public byte[][] parseByte(String what[]) { // note: array[][] byte outgoing[][] = new byte[what.length][]; for (int i = 0; i < what.length; i++) { outgoing[i] = what[i].getBytes(); } return outgoing; } */ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /* static final public char parseChar(boolean what) { // 0/1 or T/F ? return what ? 't' : 'f'; } */ static final public char parseChar(byte what) { return (char) (what & 0xff); } static final public char parseChar(int what) { return (char) what; } /* static final public char parseChar(float what) { // nonsensical return (char) what; } static final public char[] parseChar(String what) { // note: array[] return what.toCharArray(); } */ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /* static final public char[] parseChar(boolean what[]) { // 0/1 or T/F ? char outgoing[] = new char[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = what[i] ? 't' : 'f'; } return outgoing; } */ static final public char[] parseChar(byte what[]) { char outgoing[] = new char[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (char) (what[i] & 0xff); } return outgoing; } static final public char[] parseChar(int what[]) { char outgoing[] = new char[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (char) what[i]; } return outgoing; } /* static final public char[] parseChar(float what[]) { // nonsensical char outgoing[] = new char[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (char) what[i]; } return outgoing; } static final public char[][] parseChar(String what[]) { // note: array[][] char outgoing[][] = new char[what.length][]; for (int i = 0; i < what.length; i++) { outgoing[i] = what[i].toCharArray(); } return outgoing; } */ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static final public int parseInt(boolean what) { return what ? 1 : 0; } /** * Note that parseInt() will un-sign a signed byte value. */ static final public int parseInt(byte what) { return what & 0xff; } /** * Note that parseInt('5') is unlike String in the sense that it * won't return 5, but the ascii value. This is because ((int) someChar) * returns the ascii value, and parseInt() is just longhand for the cast. */ static final public int parseInt(char what) { return what; } /** * Same as floor(), or an (int) cast. */ static final public int parseInt(float what) { return (int) what; } /** * Parse a String into an int value. Returns 0 if the value is bad. */ static final public int parseInt(String what) { return parseInt(what, 0); } /** * Parse a String to an int, and provide an alternate value that * should be used when the number is invalid. */ static final public int parseInt(String what, int otherwise) { try { int offset = what.indexOf('.'); if (offset == -1) { return Integer.parseInt(what); } else { return Integer.parseInt(what.substring(0, offset)); } } catch (NumberFormatException e) { } return otherwise; } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static final public int[] parseInt(boolean what[]) { int list[] = new int[what.length]; for (int i = 0; i < what.length; i++) { list[i] = what[i] ? 1 : 0; } return list; } static final public int[] parseInt(byte what[]) { // note this unsigns int list[] = new int[what.length]; for (int i = 0; i < what.length; i++) { list[i] = (what[i] & 0xff); } return list; } static final public int[] parseInt(char what[]) { int list[] = new int[what.length]; for (int i = 0; i < what.length; i++) { list[i] = what[i]; } return list; } static public int[] parseInt(float what[]) { int inties[] = new int[what.length]; for (int i = 0; i < what.length; i++) { inties[i] = (int)what[i]; } return inties; } /** * Make an array of int elements from an array of String objects. * If the String can't be parsed as a number, it will be set to zero. * * String s[] = { "1", "300", "44" }; * int numbers[] = parseInt(s); * * numbers will contain { 1, 300, 44 } */ static public int[] parseInt(String what[]) { return parseInt(what, 0); } /** * Make an array of int elements from an array of String objects. * If the String can't be parsed as a number, its entry in the * array will be set to the value of the "missing" parameter. * * String s[] = { "1", "300", "apple", "44" }; * int numbers[] = parseInt(s, 9999); * * numbers will contain { 1, 300, 9999, 44 } */ static public int[] parseInt(String what[], int missing) { int output[] = new int[what.length]; for (int i = 0; i < what.length; i++) { try { output[i] = Integer.parseInt(what[i]); } catch (NumberFormatException e) { output[i] = missing; } } return output; } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /* static final public float parseFloat(boolean what) { return what ? 1 : 0; } */ /** * Convert an int to a float value. Also handles bytes because of * Java's rules for upgrading values. */ static final public float parseFloat(int what) { // also handles byte return what; } static final public float parseFloat(String what) { return parseFloat(what, Float.NaN); } static final public float parseFloat(String what, float otherwise) { try { return new Float(what).floatValue(); } catch (NumberFormatException e) { } return otherwise; } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /* static final public float[] parseFloat(boolean what[]) { float floaties[] = new float[what.length]; for (int i = 0; i < what.length; i++) { floaties[i] = what[i] ? 1 : 0; } return floaties; } static final public float[] parseFloat(char what[]) { float floaties[] = new float[what.length]; for (int i = 0; i < what.length; i++) { floaties[i] = (char) what[i]; } return floaties; } */ static final public float[] parseByte(byte what[]) { float floaties[] = new float[what.length]; for (int i = 0; i < what.length; i++) { floaties[i] = what[i]; } return floaties; } static final public float[] parseFloat(int what[]) { float floaties[] = new float[what.length]; for (int i = 0; i < what.length; i++) { floaties[i] = what[i]; } return floaties; } static final public float[] parseFloat(String what[]) { return parseFloat(what, Float.NaN); } static final public float[] parseFloat(String what[], float missing) { float output[] = new float[what.length]; for (int i = 0; i < what.length; i++) { try { output[i] = new Float(what[i]).floatValue(); } catch (NumberFormatException e) { output[i] = missing; } } return output; } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static final public String str(boolean x) { return String.valueOf(x); } static final public String str(byte x) { return String.valueOf(x); } static final public String str(char x) { return String.valueOf(x); } static final public String str(int x) { return String.valueOf(x); } static final public String str(float x) { return String.valueOf(x); } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static final public String[] str(boolean x[]) { String s[] = new String[x.length]; for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]); return s; } static final public String[] str(byte x[]) { String s[] = new String[x.length]; for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]); return s; } static final public String[] str(char x[]) { String s[] = new String[x.length]; for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]); return s; } static final public String[] str(int x[]) { String s[] = new String[x.length]; for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]); return s; } static final public String[] str(float x[]) { String s[] = new String[x.length]; for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]); return s; } ////////////////////////////////////////////////////////////// // INT NUMBER FORMATTING /** * Integer number formatter. */ static private NumberFormat int_nf; static private int int_nf_digits; static private boolean int_nf_commas; static public String[] nf(int num[], int digits) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nf(num[i], digits); } return formatted; } /** * ( begin auto-generated from nf.xml ) * * Utility function for formatting numbers into strings. There are two * versions, one for formatting floats and one for formatting ints. The * values for the <b>digits</b>, <b>left</b>, and <b>right</b> parameters * should always be positive integers.<br /><br />As shown in the above * example, <b>nf()</b> is used to add zeros to the left and/or right of a * number. This is typically for aligning a list of numbers. To * <em>remove</em> digits from a floating-point number, use the * <b>int()</b>, <b>ceil()</b>, <b>floor()</b>, or <b>round()</b> * functions. * * ( end auto-generated ) * @webref data:string_functions * @param num the number(s) to format * @param digits number of digits to pad with zero * @see PApplet#nfs(float, int, int) * @see PApplet#nfp(float, int, int) * @see PApplet#nfc(float, int) * @see PApplet#int(float) */ static public String nf(int num, int digits) { if ((int_nf != null) && (int_nf_digits == digits) && !int_nf_commas) { return int_nf.format(num); } int_nf = NumberFormat.getInstance(); int_nf.setGroupingUsed(false); // no commas int_nf_commas = false; int_nf.setMinimumIntegerDigits(digits); int_nf_digits = digits; return int_nf.format(num); } /** * ( begin auto-generated from nfc.xml ) * * Utility function for formatting numbers into strings and placing * appropriate commas to mark units of 1000. There are two versions, one * for formatting ints and one for formatting an array of ints. The value * for the <b>digits</b> parameter should always be a positive integer. * <br/> <br/> * For a non-US locale, this will insert periods instead of commas, or * whatever is apprioriate for that region. * * ( end auto-generated ) * @webref data:string_functions * @param num the number(s) to format * @see PApplet#nf(float, int, int) * @see PApplet#nfp(float, int, int) * @see PApplet#nfc(float, int) */ static public String[] nfc(int num[]) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nfc(num[i]); } return formatted; } /** * nfc() or "number format with commas". This is an unfortunate misnomer * because in locales where a comma is not the separator for numbers, it * won't actually be outputting a comma, it'll use whatever makes sense for * the locale. */ static public String nfc(int num) { if ((int_nf != null) && (int_nf_digits == 0) && int_nf_commas) { return int_nf.format(num); } int_nf = NumberFormat.getInstance(); int_nf.setGroupingUsed(true); int_nf_commas = true; int_nf.setMinimumIntegerDigits(0); int_nf_digits = 0; return int_nf.format(num); } /** * number format signed (or space) * Formats a number but leaves a blank space in the front * when it's positive so that it can be properly aligned with * numbers that have a negative sign in front of them. */ /** * ( begin auto-generated from nfs.xml ) * * Utility function for formatting numbers into strings. Similar to * <b>nf()</b> but leaves a blank space in front of positive numbers so * they align with negative numbers in spite of the minus symbol. There are * two versions, one for formatting floats and one for formatting ints. The * values for the <b>digits</b>, <b>left</b>, and <b>right</b> parameters * should always be positive integers. * * ( end auto-generated ) * @webref data:string_functions * @param num the number(s) to format * @param digits number of digits to pad with zeroes * @see PApplet#nf(float, int, int) * @see PApplet#nfp(float, int, int) * @see PApplet#nfc(float, int) */ static public String nfs(int num, int digits) { return (num < 0) ? nf(num, digits) : (' ' + nf(num, digits)); } static public String[] nfs(int num[], int digits) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nfs(num[i], digits); } return formatted; } // /** * number format positive (or plus) * Formats a number, always placing a - or + sign * in the front when it's negative or positive. */ /** * ( begin auto-generated from nfp.xml ) * * Utility function for formatting numbers into strings. Similar to * <b>nf()</b> but puts a "+" in front of positive numbers and a "-" in * front of negative numbers. There are two versions, one for formatting * floats and one for formatting ints. The values for the <b>digits</b>, * <b>left</b>, and <b>right</b> parameters should always be positive integers. * * ( end auto-generated ) * @webref data:string_functions * @param num the number(s) to format * @param digits number of digits to pad with zeroes * @see PApplet#nf(float, int, int) * @see PApplet#nfs(float, int, int) * @see PApplet#nfc(float, int) */ static public String nfp(int num, int digits) { return (num < 0) ? nf(num, digits) : ('+' + nf(num, digits)); } static public String[] nfp(int num[], int digits) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nfp(num[i], digits); } return formatted; } ////////////////////////////////////////////////////////////// // FLOAT NUMBER FORMATTING static private NumberFormat float_nf; static private int float_nf_left, float_nf_right; static private boolean float_nf_commas; static public String[] nf(float num[], int left, int right) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nf(num[i], left, right); } return formatted; } /** * @param num[] the number(s) to format * @param left number of digits to the left of the decimal point * @param right number of digits to the right of the decimal point */ static public String nf(float num, int left, int right) { if ((float_nf != null) && (float_nf_left == left) && (float_nf_right == right) && !float_nf_commas) { return float_nf.format(num); } float_nf = NumberFormat.getInstance(); float_nf.setGroupingUsed(false); float_nf_commas = false; if (left != 0) float_nf.setMinimumIntegerDigits(left); if (right != 0) { float_nf.setMinimumFractionDigits(right); float_nf.setMaximumFractionDigits(right); } float_nf_left = left; float_nf_right = right; return float_nf.format(num); } /** * @param num[] the number(s) to format * @param right number of digits to the right of the decimal point */ static public String[] nfc(float num[], int right) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nfc(num[i], right); } return formatted; } static public String nfc(float num, int right) { if ((float_nf != null) && (float_nf_left == 0) && (float_nf_right == right) && float_nf_commas) { return float_nf.format(num); } float_nf = NumberFormat.getInstance(); float_nf.setGroupingUsed(true); float_nf_commas = true; if (right != 0) { float_nf.setMinimumFractionDigits(right); float_nf.setMaximumFractionDigits(right); } float_nf_left = 0; float_nf_right = right; return float_nf.format(num); } /** * @param num[] the number(s) to format * @param left the number of digits to the left of the decimal point * @param right the number of digits to the right of the decimal point */ static public String[] nfs(float num[], int left, int right) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nfs(num[i], left, right); } return formatted; } static public String nfs(float num, int left, int right) { return (num < 0) ? nf(num, left, right) : (' ' + nf(num, left, right)); } /** * @param left the number of digits to the left of the decimal point * @param right the number of digits to the right of the decimal point */ static public String[] nfp(float num[], int left, int right) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nfp(num[i], left, right); } return formatted; } static public String nfp(float num, int left, int right) { return (num < 0) ? nf(num, left, right) : ('+' + nf(num, left, right)); } ////////////////////////////////////////////////////////////// // HEX/BINARY CONVERSION /** * ( begin auto-generated from hex.xml ) * * Converts a byte, char, int, or color to a String containing the * equivalent hexadecimal notation. For example color(0, 102, 153) will * convert to the String "FF006699". This function can help make your geeky * debugging sessions much happier. * <br/> <br/> * Note that the maximum number of digits is 8, because an int value can * only represent up to 32 bits. Specifying more than eight digits will * simply shorten the string to eight anyway. * * ( end auto-generated ) * @webref data:conversion * @param value the value to convert * @see PApplet#unhex(String) * @see PApplet#binary(byte) * @see PApplet#unbinary(String) */ static final public String hex(byte value) { return hex(value, 2); } static final public String hex(char value) { return hex(value, 4); } static final public String hex(int value) { return hex(value, 8); } /** * @param digits the number of digits (maximum 8) */ static final public String hex(int value, int digits) { String stuff = Integer.toHexString(value).toUpperCase(); if (digits > 8) { digits = 8; } int length = stuff.length(); if (length > digits) { return stuff.substring(length - digits); } else if (length < digits) { return "00000000".substring(8 - (digits-length)) + stuff; } return stuff; } /** * ( begin auto-generated from unhex.xml ) * * Converts a String representation of a hexadecimal number to its * equivalent integer value. * * ( end auto-generated ) * * @webref data:conversion * @param value String to convert to an integer * @see PApplet#hex(int, int) * @see PApplet#binary(byte) * @see PApplet#unbinary(String) */ static final public int unhex(String value) { // has to parse as a Long so that it'll work for numbers bigger than 2^31 return (int) (Long.parseLong(value, 16)); } // /** * Returns a String that contains the binary value of a byte. * The returned value will always have 8 digits. */ static final public String binary(byte value) { return binary(value, 8); } /** * Returns a String that contains the binary value of a char. * The returned value will always have 16 digits because chars * are two bytes long. */ static final public String binary(char value) { return binary(value, 16); } /** * Returns a String that contains the binary value of an int. The length * depends on the size of the number itself. If you want a specific number * of digits use binary(int what, int digits) to specify how many. */ static final public String binary(int value) { return binary(value, 32); } /* * Returns a String that contains the binary value of an int. * The digits parameter determines how many digits will be used. */ /** * ( begin auto-generated from binary.xml ) * * Converts a byte, char, int, or color to a String containing the * equivalent binary notation. For example color(0, 102, 153, 255) will * convert to the String "11111111000000000110011010011001". This function * can help make your geeky debugging sessions much happier. * <br/> <br/> * Note that the maximum number of digits is 32, because an int value can * only represent up to 32 bits. Specifying more than 32 digits will simply * shorten the string to 32 anyway. * * ( end auto-generated ) * @webref data:conversion * @param value value to convert * @param digits number of digits to return * @see PApplet#unbinary(String) * @see PApplet#hex(int,int) * @see PApplet#unhex(String) */ static final public String binary(int value, int digits) { String stuff = Integer.toBinaryString(value); if (digits > 32) { digits = 32; } int length = stuff.length(); if (length > digits) { return stuff.substring(length - digits); } else if (length < digits) { int offset = 32 - (digits-length); return "00000000000000000000000000000000".substring(offset) + stuff; } return stuff; } /** * ( begin auto-generated from unbinary.xml ) * * Converts a String representation of a binary number to its equivalent * integer value. For example, unbinary("00001000") will return 8. * * ( end auto-generated ) * @webref data:conversion * @param value String to convert to an integer * @see PApplet#binary(byte) * @see PApplet#hex(int,int) * @see PApplet#unhex(String) */ static final public int unbinary(String value) { return Integer.parseInt(value, 2); } ////////////////////////////////////////////////////////////// // COLOR FUNCTIONS // moved here so that they can work without // the graphics actually being instantiated (outside setup) /** * ( begin auto-generated from color.xml ) * * Creates colors for storing in variables of the <b>color</b> datatype. * The parameters are interpreted as RGB or HSB values depending on the * current <b>colorMode()</b>. The default mode is RGB values from 0 to 255 * and therefore, the function call <b>color(255, 204, 0)</b> will return a * bright yellow color. More about how colors are stored can be found in * the reference for the <a href="color_datatype.html">color</a> datatype. * * ( end auto-generated ) * @webref color:creating_reading * @param gray number specifying value between white and black * @see PApplet#colorMode(int) */ public final int color(int gray) { if (g == null) { if (gray > 255) gray = 255; else if (gray < 0) gray = 0; return 0xff000000 | (gray << 16) | (gray << 8) | gray; } return g.color(gray); } /** * @nowebref * @param fgray number specifying value between white and black */ public final int color(float fgray) { if (g == null) { int gray = (int) fgray; if (gray > 255) gray = 255; else if (gray < 0) gray = 0; return 0xff000000 | (gray << 16) | (gray << 8) | gray; } return g.color(fgray); } /** * As of 0116 this also takes color(#FF8800, alpha) * @param alpha relative to current color range */ public final int color(int gray, int alpha) { if (g == null) { if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0; if (gray > 255) { // then assume this is actually a #FF8800 return (alpha << 24) | (gray & 0xFFFFFF); } else { //if (gray > 255) gray = 255; else if (gray < 0) gray = 0; return (alpha << 24) | (gray << 16) | (gray << 8) | gray; } } return g.color(gray, alpha); } /** * @nowebref */ public final int color(float fgray, float falpha) { if (g == null) { int gray = (int) fgray; int alpha = (int) falpha; if (gray > 255) gray = 255; else if (gray < 0) gray = 0; if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0; return 0xff000000 | (gray << 16) | (gray << 8) | gray; } return g.color(fgray, falpha); } /** * @param v1 red or hue values relative to the current color range * @param v2 green or saturation values relative to the current color range * @param v3 blue or brightness values relative to the current color range */ public final int color(int v1, int v2, int v3) { if (g == null) { if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0; if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0; if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0; return 0xff000000 | (v1 << 16) | (v2 << 8) | v3; } return g.color(v1, v2, v3); } public final int color(int v1, int v2, int v3, int alpha) { if (g == null) { if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0; if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0; if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0; if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0; return (alpha << 24) | (v1 << 16) | (v2 << 8) | v3; } return g.color(v1, v2, v3, alpha); } public final int color(float v1, float v2, float v3) { if (g == null) { if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0; if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0; if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0; return 0xff000000 | ((int)v1 << 16) | ((int)v2 << 8) | (int)v3; } return g.color(v1, v2, v3); } public final int color(float v1, float v2, float v3, float alpha) { if (g == null) { if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0; if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0; if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0; if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0; return ((int)alpha << 24) | ((int)v1 << 16) | ((int)v2 << 8) | (int)v3; } return g.color(v1, v2, v3, alpha); } static public int blendColor(int c1, int c2, int mode) { return PImage.blendColor(c1, c2, mode); } ////////////////////////////////////////////////////////////// // MAIN /** * Set this sketch to communicate its state back to the PDE. * <p/> * This uses the stderr stream to write positions of the window * (so that it will be saved by the PDE for the next run) and * notify on quit. See more notes in the Worker class. */ public void setupExternalMessages() { frame.addComponentListener(new ComponentAdapter() { @Override public void componentMoved(ComponentEvent e) { Point where = ((Frame) e.getSource()).getLocation(); System.err.println(PApplet.EXTERNAL_MOVE + " " + where.x + " " + where.y); System.err.flush(); // doesn't seem to help or hurt } }); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { // System.err.println(PApplet.EXTERNAL_QUIT); // System.err.flush(); // important // System.exit(0); exit(); // don't quit, need to just shut everything down (0133) } }); } /** * Set up a listener that will fire proper component resize events * in cases where frame.setResizable(true) is called. */ public void setupFrameResizeListener() { frame.addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { // Ignore bad resize events fired during setup to fix // http://dev.processing.org/bugs/show_bug.cgi?id=341 // This should also fix the blank screen on Linux bug // http://dev.processing.org/bugs/show_bug.cgi?id=282 if (frame.isResizable()) { // might be multiple resize calls before visible (i.e. first // when pack() is called, then when it's resized for use). // ignore them because it's not the user resizing things. Frame farm = (Frame) e.getComponent(); if (farm.isVisible()) { Insets insets = farm.getInsets(); Dimension windowSize = farm.getSize(); Rectangle newBounds = new Rectangle(insets.left, insets.top, windowSize.width - insets.left - insets.right, windowSize.height - insets.top - insets.bottom); Rectangle oldBounds = getBounds(); if (!newBounds.equals(oldBounds)) { // the ComponentListener in PApplet will handle calling size() setBounds(newBounds); } } } } }); } // /** // * GIF image of the Processing logo. // */ // static public final byte[] ICON_IMAGE = { // 71, 73, 70, 56, 57, 97, 16, 0, 16, 0, -77, 0, 0, 0, 0, 0, -1, -1, -1, 12, // 12, 13, -15, -15, -14, 45, 57, 74, 54, 80, 111, 47, 71, 97, 62, 88, 117, // 1, 14, 27, 7, 41, 73, 15, 52, 85, 2, 31, 55, 4, 54, 94, 18, 69, 109, 37, // 87, 126, -1, -1, -1, 33, -7, 4, 1, 0, 0, 15, 0, 44, 0, 0, 0, 0, 16, 0, 16, // 0, 0, 4, 122, -16, -107, 114, -86, -67, 83, 30, -42, 26, -17, -100, -45, // 56, -57, -108, 48, 40, 122, -90, 104, 67, -91, -51, 32, -53, 77, -78, -100, // 47, -86, 12, 76, -110, -20, -74, -101, 97, -93, 27, 40, 20, -65, 65, 48, // -111, 99, -20, -112, -117, -123, -47, -105, 24, 114, -112, 74, 69, 84, 25, // 93, 88, -75, 9, 46, 2, 49, 88, -116, -67, 7, -19, -83, 60, 38, 3, -34, 2, // 66, -95, 27, -98, 13, 4, -17, 55, 33, 109, 11, 11, -2, -128, 121, 123, 62, // 91, 120, -128, 127, 122, 115, 102, 2, 119, 0, -116, -113, -119, 6, 102, // 121, -108, -126, 5, 18, 6, 4, -102, -101, -100, 114, 15, 17, 0, 59 // }; static ArrayList<Image> iconImages; protected void setIconImage(Frame frame) { // On OS X, this only affects what shows up in the dock when minimized. // So this is actually a step backwards. Brilliant. if (platform != MACOSX) { //Image image = Toolkit.getDefaultToolkit().createImage(ICON_IMAGE); //frame.setIconImage(image); try { if (iconImages == null) { iconImages = new ArrayList<Image>(); final int[] sizes = { 16, 32, 48, 64 }; for (int sz : sizes) { URL url = getClass().getResource("/icon/icon-" + sz + ".png"); Image image = Toolkit.getDefaultToolkit().getImage(url); iconImages.add(image); //iconImages.add(Toolkit.getLibImage("icons/pde-" + sz + ".png", frame)); } } frame.setIconImages(iconImages); } catch (Exception e) { //e.printStackTrace(); // more or less harmless; don't spew errors } } } // Not gonna do this dynamically, only on startup. Too much headache. // public void fullscreen() { // if (frame != null) { // if (PApplet.platform == MACOSX) { // japplemenubar.JAppleMenuBar.hide(); // } // GraphicsConfiguration gc = frame.getGraphicsConfiguration(); // Rectangle rect = gc.getBounds(); //// GraphicsDevice device = gc.getDevice(); // frame.setBounds(rect.x, rect.y, rect.width, rect.height); // } // } /** * main() method for running this class from the command line. * <p> * <B>The options shown here are not yet finalized and will be * changing over the next several releases.</B> * <p> * The simplest way to turn and applet into an application is to * add the following code to your program: * <PRE>static public void main(String args[]) { * PApplet.main("YourSketchName", args); * }</PRE> * This will properly launch your applet from a double-clickable * .jar or from the command line. * <PRE> * Parameters useful for launching or also used by the PDE: * * --location=x,y upper-lefthand corner of where the applet * should appear on screen. if not used, * the default is to center on the main screen. * * --full-screen put the applet into full screen "present" mode. * * --hide-stop use to hide the stop button in situations where * you don't want to allow users to exit. also * see the FAQ on information for capturing the ESC * key when running in presentation mode. * * --stop-color=#xxxxxx color of the 'stop' text used to quit an * sketch when it's in present mode. * * --bgcolor=#xxxxxx background color of the window. * * --sketch-path location of where to save files from functions * like saveStrings() or saveFrame(). defaults to * the folder that the java application was * launched from, which means if this isn't set by * the pde, everything goes into the same folder * as processing.exe. * * --display=n set what display should be used by this sketch. * displays are numbered starting from 0. * * Parameters used by Processing when running via the PDE * * --external set when the applet is being used by the PDE * * --editor-location=x,y position of the upper-lefthand corner of the * editor window, for placement of applet window * </PRE> */ static public void main(final String[] args) { runSketch(args, null); } /** * Convenience method so that PApplet.main("YourSketch") launches a sketch, * rather than having to wrap it into a String array. * @param mainClass name of the class to load (with package if any) */ static public void main(final String mainClass) { main(mainClass, null); } /** * Convenience method so that PApplet.main("YourSketch", args) launches a * sketch, rather than having to wrap it into a String array, and appending * the 'args' array when not null. * @param mainClass name of the class to load (with package if any) * @param args command line arguments to pass to the sketch */ static public void main(final String mainClass, final String[] passedArgs) { String[] args = new String[] { mainClass }; if (passedArgs != null) { args = concat(args, passedArgs); } runSketch(args, null); } static public void runSketch(final String args[], final PApplet constructedApplet) { // Disable abyssmally slow Sun renderer on OS X 10.5. if (platform == MACOSX) { // Only run this on OS X otherwise it can cause a permissions error. // http://dev.processing.org/bugs/show_bug.cgi?id=976 System.setProperty("apple.awt.graphics.UseQuartz", String.valueOf(useQuartz)); } // Doesn't seem to do much to help avoid flicker System.setProperty("sun.awt.noerasebackground", "true"); // This doesn't do anything. // if (platform == WINDOWS) { // // For now, disable the D3D renderer on Java 6u10 because // // it causes problems with Present mode. // // http://dev.processing.org/bugs/show_bug.cgi?id=1009 // System.setProperty("sun.java2d.d3d", "false"); // } if (args.length < 1) { System.err.println("Usage: PApplet <appletname>"); System.err.println("For additional options, " + "see the Javadoc for PApplet"); System.exit(1); } // EventQueue.invokeLater(new Runnable() { // public void run() { // runSketchEDT(args, constructedApplet); // } // }); // } // // // static public void runSketchEDT(final String args[], final PApplet constructedApplet) { boolean external = false; int[] location = null; int[] editorLocation = null; String name = null; boolean present = false; // boolean exclusive = false; // Color backgroundColor = Color.BLACK; Color backgroundColor = null; //Color.BLACK; Color stopColor = Color.GRAY; GraphicsDevice displayDevice = null; boolean hideStop = false; String param = null, value = null; // try to get the user folder. if running under java web start, // this may cause a security exception if the code is not signed. // http://processing.org/discourse/yabb_beta/YaBB.cgi?board=Integrate;action=display;num=1159386274 String folder = null; try { folder = System.getProperty("user.dir"); } catch (Exception e) { } int argIndex = 0; while (argIndex < args.length) { int equals = args[argIndex].indexOf('='); if (equals != -1) { param = args[argIndex].substring(0, equals); value = args[argIndex].substring(equals + 1); if (param.equals(ARGS_EDITOR_LOCATION)) { external = true; editorLocation = parseInt(split(value, ',')); } else if (param.equals(ARGS_DISPLAY)) { int deviceIndex = Integer.parseInt(value); GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice devices[] = environment.getScreenDevices(); if ((deviceIndex >= 0) && (deviceIndex < devices.length)) { displayDevice = devices[deviceIndex]; } else { System.err.println("Display " + value + " does not exist, " + "using the default display instead."); for (int i = 0; i < devices.length; i++) { System.err.println(i + " is " + devices[i]); } } } else if (param.equals(ARGS_BGCOLOR)) { if (value.charAt(0) == '#') value = value.substring(1); backgroundColor = new Color(Integer.parseInt(value, 16)); } else if (param.equals(ARGS_STOP_COLOR)) { if (value.charAt(0) == '#') value = value.substring(1); stopColor = new Color(Integer.parseInt(value, 16)); } else if (param.equals(ARGS_SKETCH_FOLDER)) { folder = value; } else if (param.equals(ARGS_LOCATION)) { location = parseInt(split(value, ',')); } } else { if (args[argIndex].equals(ARGS_PRESENT)) { // keep for compatability present = true; } else if (args[argIndex].equals(ARGS_FULL_SCREEN)) { present = true; // } else if (args[argIndex].equals(ARGS_EXCLUSIVE)) { // exclusive = true; } else if (args[argIndex].equals(ARGS_HIDE_STOP)) { hideStop = true; } else if (args[argIndex].equals(ARGS_EXTERNAL)) { external = true; } else { name = args[argIndex]; break; // because of break, argIndex won't increment again } } argIndex++; } // Now that sketch path is passed in args after the sketch name // it's not set in the above loop(the above loop breaks after // finding sketch name). So setting sketch path here. for (int i = 0; i < args.length; i++) { if(args[i].startsWith(ARGS_SKETCH_FOLDER)){ folder = args[i].substring(args[i].indexOf('=') + 1); //System.err.println("SF set " + folder); } } // Set this property before getting into any GUI init code //System.setProperty("com.apple.mrj.application.apple.menu.about.name", name); // This )*)(*@#$ Apple crap don't work no matter where you put it // (static method of the class, at the top of main, wherever) if (displayDevice == null) { GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment(); displayDevice = environment.getDefaultScreenDevice(); } Frame frame = new Frame(displayDevice.getDefaultConfiguration()); frame.setBackground(new Color(0xCC, 0xCC, 0xCC)); // default Processing gray // JFrame frame = new JFrame(displayDevice.getDefaultConfiguration()); /* Frame frame = null; if (displayDevice != null) { frame = new Frame(displayDevice.getDefaultConfiguration()); } else { frame = new Frame(); } */ //Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); // remove the grow box by default // users who want it back can call frame.setResizable(true) // frame.setResizable(false); // moved later (issue #467) final PApplet applet; if (constructedApplet != null) { applet = constructedApplet; } else { try { Class<?> c = Thread.currentThread().getContextClassLoader().loadClass(name); applet = (PApplet) c.newInstance(); } catch (Exception e) { throw new RuntimeException(e); } } // Set the trimmings around the image applet.setIconImage(frame); frame.setTitle(name); // frame.setIgnoreRepaint(true); // does nothing // frame.addComponentListener(new ComponentAdapter() { // public void componentResized(ComponentEvent e) { // Component c = e.getComponent(); //// Rectangle bounds = c.getBounds(); // System.out.println(" " + c.getName() + " wants to be: " + c.getSize()); // } // }); // frame.addComponentListener(new ComponentListener() { // // public void componentShown(ComponentEvent e) { // debug("frame: " + e); // debug(" applet valid? " + applet.isValid()); //// ((PGraphicsJava2D) applet.g).redraw(); // } // // public void componentResized(ComponentEvent e) { // println("frame: " + e + " " + applet.frame.getInsets()); // Insets insets = applet.frame.getInsets(); // int wide = e.getComponent().getWidth() - (insets.left + insets.right); // int high = e.getComponent().getHeight() - (insets.top + insets.bottom); // if (applet.getWidth() != wide || applet.getHeight() != high) { // debug("Frame.componentResized() setting applet size " + wide + " " + high); // applet.setSize(wide, high); // } // } // // public void componentMoved(ComponentEvent e) { // //println("frame: " + e + " " + applet.frame.getInsets()); // Insets insets = applet.frame.getInsets(); // int wide = e.getComponent().getWidth() - (insets.left + insets.right); // int high = e.getComponent().getHeight() - (insets.top + insets.bottom); // //applet.g.setsi // if (applet.getWidth() != wide || applet.getHeight() != high) { // debug("Frame.componentMoved() setting applet size " + wide + " " + high); // applet.setSize(wide, high); // } // } // // public void componentHidden(ComponentEvent e) { // debug("frame: " + e); // } // }); // A handful of things that need to be set before init/start. applet.frame = frame; applet.sketchPath = folder; // If the applet doesn't call for full screen, but the command line does, // enable it. Conversely, if the command line does not, don't disable it. // applet.fullScreen |= present; // Query the applet to see if it wants to be full screen all the time. present |= applet.sketchFullScreen(); // pass everything after the class name in as args to the sketch itself // (fixed for 2.0a5, this was just subsetting by 1, which didn't skip opts) applet.args = PApplet.subset(args, argIndex + 1); applet.external = external; // Need to save the window bounds at full screen, // because pack() will cause the bounds to go to zero. // http://dev.processing.org/bugs/show_bug.cgi?id=923 Rectangle screenRect = displayDevice.getDefaultConfiguration().getBounds(); // DisplayMode doesn't work here, because we can't get the upper-left // corner of the display, which is important for multi-display setups. // Sketch has already requested to be the same as the screen's // width and height, so let's roll with full screen mode. if (screenRect.width == applet.sketchWidth() && screenRect.height == applet.sketchHeight()) { present = true; } // For 0149, moving this code (up to the pack() method) before init(). // For OpenGL (and perhaps other renderers in the future), a peer is // needed before a GLDrawable can be created. So pack() needs to be // called on the Frame before applet.init(), which itself calls size(), // and launches the Thread that will kick off setup(). // http://dev.processing.org/bugs/show_bug.cgi?id=891 // http://dev.processing.org/bugs/show_bug.cgi?id=908 if (present) { // if (platform == MACOSX) { // // Call some native code to remove the menu bar on OS X. Not necessary // // on Linux and Windows, who are happy to make full screen windows. // japplemenubar.JAppleMenuBar.hide(); // } frame.setUndecorated(true); if (backgroundColor != null) { frame.setBackground(backgroundColor); } // if (exclusive) { // displayDevice.setFullScreenWindow(frame); // // this trashes the location of the window on os x // //frame.setExtendedState(java.awt.Frame.MAXIMIZED_BOTH); // fullScreenRect = frame.getBounds(); // } else { frame.setBounds(screenRect); frame.setVisible(true); // } } frame.setLayout(null); frame.add(applet); if (present) { frame.invalidate(); } else { frame.pack(); } // insufficient, places the 100x100 sketches offset strangely //frame.validate(); // disabling resize has to happen after pack() to avoid apparent Apple bug // http://code.google.com/p/processing/issues/detail?id=467 frame.setResizable(false); applet.init(); // applet.start(); // Wait until the applet has figured out its width. // In a static mode app, this will be after setup() has completed, // and the empty draw() has set "finished" to true. // TODO make sure this won't hang if the applet has an exception. while (applet.defaultSize && !applet.finished) { //System.out.println("default size"); try { Thread.sleep(5); } catch (InterruptedException e) { //System.out.println("interrupt"); } } // // If 'present' wasn't already set, but the applet initializes // // to full screen, attempt to make things full screen anyway. // if (!present && // applet.width == screenRect.width && // applet.height == screenRect.height) { // // bounds will be set below, but can't change to setUndecorated() now // present = true; // } // // Opting not to do this, because we can't remove the decorations on the // // window at this point. And re-opening a new winodw is a lot of mess. // // Better all around to just encourage the use of sketchFullScreen() // // or cmd/ctrl-shift-R in the PDE. if (present) { if (platform == MACOSX) { // Call some native code to remove the menu bar on OS X. Not necessary // on Linux and Windows, who are happy to make full screen windows. japplemenubar.JAppleMenuBar.hide(); } // After the pack(), the screen bounds are gonna be 0s frame.setBounds(screenRect); applet.setBounds((screenRect.width - applet.width) / 2, (screenRect.height - applet.height) / 2, applet.width, applet.height); if (!hideStop) { Label label = new Label("stop"); label.setForeground(stopColor); label.addMouseListener(new MouseAdapter() { @Override public void mousePressed(java.awt.event.MouseEvent e) { System.exit(0); } }); frame.add(label); Dimension labelSize = label.getPreferredSize(); // sometimes shows up truncated on mac //System.out.println("label width is " + labelSize.width); labelSize = new Dimension(100, labelSize.height); label.setSize(labelSize); label.setLocation(20, screenRect.height - labelSize.height - 20); } // not always running externally when in present mode if (external) { applet.setupExternalMessages(); } } else { // if not presenting // can't do pack earlier cuz present mode don't like it // (can't go full screen with a frame after calling pack) // frame.pack(); // get insets. get more. Insets insets = frame.getInsets(); int windowW = Math.max(applet.width, MIN_WINDOW_WIDTH) + insets.left + insets.right; int windowH = Math.max(applet.height, MIN_WINDOW_HEIGHT) + insets.top + insets.bottom; frame.setSize(windowW, windowH); if (location != null) { // a specific location was received from the Runner // (applet has been run more than once, user placed window) frame.setLocation(location[0], location[1]); } else if (external && editorLocation != null) { int locationX = editorLocation[0] - 20; int locationY = editorLocation[1]; if (locationX - windowW > 10) { // if it fits to the left of the window frame.setLocation(locationX - windowW, locationY); } else { // doesn't fit // if it fits inside the editor window, // offset slightly from upper lefthand corner // so that it's plunked inside the text area locationX = editorLocation[0] + 66; locationY = editorLocation[1] + 66; if ((locationX + windowW > applet.displayWidth - 33) || (locationY + windowH > applet.displayHeight - 33)) { // otherwise center on screen locationX = (applet.displayWidth - windowW) / 2; locationY = (applet.displayHeight - windowH) / 2; } frame.setLocation(locationX, locationY); } } else { // just center on screen // Can't use frame.setLocationRelativeTo(null) because it sends the // frame to the main display, which undermines the --display setting. frame.setLocation(screenRect.x + (screenRect.width - applet.width) / 2, screenRect.y + (screenRect.height - applet.height) / 2); } Point frameLoc = frame.getLocation(); if (frameLoc.y < 0) { // Windows actually allows you to place frames where they can't be // closed. Awesome. http://dev.processing.org/bugs/show_bug.cgi?id=1508 frame.setLocation(frameLoc.x, 30); } if (backgroundColor != null) { // if (backgroundColor == Color.black) { //BLACK) { // // this means no bg color unless specified // backgroundColor = SystemColor.control; // } frame.setBackground(backgroundColor); } int usableWindowH = windowH - insets.top - insets.bottom; applet.setBounds((windowW - applet.width)/2, insets.top + (usableWindowH - applet.height)/2, applet.width, applet.height); if (external) { applet.setupExternalMessages(); } else { // !external frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); } // handle frame resizing events applet.setupFrameResizeListener(); // all set for rockin if (applet.displayable()) { frame.setVisible(true); } } // Disabling for 0185, because it causes an assertion failure on OS X // http://code.google.com/p/processing/issues/detail?id=258 // (Although this doesn't seem to be the one that was causing problems.) //applet.requestFocus(); // ask for keydowns } /** * These methods provide a means for running an already-constructed * sketch. In particular, it makes it easy to launch a sketch in * Jython: * * <pre>class MySketch(PApplet): * pass * *MySketch().runSketch();</pre> */ protected void runSketch(final String[] args) { final String[] argsWithSketchName = new String[args.length + 1]; System.arraycopy(args, 0, argsWithSketchName, 0, args.length); final String className = this.getClass().getSimpleName(); final String cleanedClass = className.replaceAll("__[^_]+__\\$", "").replaceAll("\\$\\d+", ""); argsWithSketchName[args.length] = cleanedClass; runSketch(argsWithSketchName, this); } protected void runSketch() { runSketch(new String[0]); } ////////////////////////////////////////////////////////////// /** * ( begin auto-generated from beginRecord.xml ) * * Opens a new file and all subsequent drawing functions are echoed to this * file as well as the display window. The <b>beginRecord()</b> function * requires two parameters, the first is the renderer and the second is the * file name. This function is always used with <b>endRecord()</b> to stop * the recording process and close the file. * <br /> <br /> * Note that beginRecord() will only pick up any settings that happen after * it has been called. For instance, if you call textFont() before * beginRecord(), then that font will not be set for the file that you're * recording to. * * ( end auto-generated ) * * @webref output:files * @param renderer for example, PDF * @param filename filename for output * @see PApplet#endRecord() */ public PGraphics beginRecord(String renderer, String filename) { filename = insertFrame(filename); PGraphics rec = createGraphics(width, height, renderer, filename); beginRecord(rec); return rec; } /** * @nowebref * Begin recording (echoing) commands to the specified PGraphics object. */ public void beginRecord(PGraphics recorder) { this.recorder = recorder; recorder.beginDraw(); } /** * ( begin auto-generated from endRecord.xml ) * * Stops the recording process started by <b>beginRecord()</b> and closes * the file. * * ( end auto-generated ) * @webref output:files * @see PApplet#beginRecord(String, String) */ public void endRecord() { if (recorder != null) { recorder.endDraw(); recorder.dispose(); recorder = null; } } /** * ( begin auto-generated from beginRaw.xml ) * * To create vectors from 3D data, use the <b>beginRaw()</b> and * <b>endRaw()</b> commands. These commands will grab the shape data just * before it is rendered to the screen. At this stage, your entire scene is * nothing but a long list of individual lines and triangles. This means * that a shape created with <b>sphere()</b> function will be made up of * hundreds of triangles, rather than a single object. Or that a * multi-segment line shape (such as a curve) will be rendered as * individual segments. * <br /><br /> * When using <b>beginRaw()</b> and <b>endRaw()</b>, it's possible to write * to either a 2D or 3D renderer. For instance, <b>beginRaw()</b> with the * PDF library will write the geometry as flattened triangles and lines, * even if recording from the <b>P3D</b> renderer. * <br /><br /> * If you want a background to show up in your files, use <b>rect(0, 0, * width, height)</b> after setting the <b>fill()</b> to the background * color. Otherwise the background will not be rendered to the file because * the background is not shape. * <br /><br /> * Using <b>hint(ENABLE_DEPTH_SORT)</b> can improve the appearance of 3D * geometry drawn to 2D file formats. See the <b>hint()</b> reference for * more details. * <br /><br /> * See examples in the reference for the <b>PDF</b> and <b>DXF</b> * libraries for more information. * * ( end auto-generated ) * * @webref output:files * @param renderer for example, PDF or DXF * @param filename filename for output * @see PApplet#endRaw() * @see PApplet#hint(int) */ public PGraphics beginRaw(String renderer, String filename) { filename = insertFrame(filename); PGraphics rec = createGraphics(width, height, renderer, filename); g.beginRaw(rec); return rec; } /** * @nowebref * Begin recording raw shape data to the specified renderer. * * This simply echoes to g.beginRaw(), but since is placed here (rather than * generated by preproc.pl) for clarity and so that it doesn't echo the * command should beginRecord() be in use. * * @param rawGraphics ??? */ public void beginRaw(PGraphics rawGraphics) { g.beginRaw(rawGraphics); } /** * ( begin auto-generated from endRaw.xml ) * * Complement to <b>beginRaw()</b>; they must always be used together. See * the <b>beginRaw()</b> reference for details. * * ( end auto-generated ) * * @webref output:files * @see PApplet#beginRaw(String, String) */ public void endRaw() { g.endRaw(); } /** * Starts shape recording and returns the PShape object that will * contain the geometry. */ /* public PShape beginRecord() { return g.beginRecord(); } */ ////////////////////////////////////////////////////////////// /** * ( begin auto-generated from loadPixels.xml ) * * Loads the pixel data for the display window into the <b>pixels[]</b> * array. This function must always be called before reading from or * writing to <b>pixels[]</b>. * <br/><br/> renderers may or may not seem to require <b>loadPixels()</b> * or <b>updatePixels()</b>. However, the rule is that any time you want to * manipulate the <b>pixels[]</b> array, you must first call * <b>loadPixels()</b>, and after changes have been made, call * <b>updatePixels()</b>. Even if the renderer may not seem to use this * function in the current Processing release, this will always be subject * to change. * * ( end auto-generated ) * <h3>Advanced</h3> * Override the g.pixels[] function to set the pixels[] array * that's part of the PApplet object. Allows the use of * pixels[] in the code, rather than g.pixels[]. * * @webref image:pixels * @see PApplet#pixels * @see PApplet#updatePixels() */ public void loadPixels() { g.loadPixels(); pixels = g.pixels; } /** * ( begin auto-generated from updatePixels.xml ) * * Updates the display window with the data in the <b>pixels[]</b> array. * Use in conjunction with <b>loadPixels()</b>. If you're only reading * pixels from the array, there's no need to call <b>updatePixels()</b> * unless there are changes. * <br/><br/> renderers may or may not seem to require <b>loadPixels()</b> * or <b>updatePixels()</b>. However, the rule is that any time you want to * manipulate the <b>pixels[]</b> array, you must first call * <b>loadPixels()</b>, and after changes have been made, call * <b>updatePixels()</b>. Even if the renderer may not seem to use this * function in the current Processing release, this will always be subject * to change. * <br/> <br/> * Currently, none of the renderers use the additional parameters to * <b>updatePixels()</b>, however this may be implemented in the future. * * ( end auto-generated ) * @webref image:pixels * @see PApplet#loadPixels() * @see PApplet#pixels */ public void updatePixels() { g.updatePixels(); } /** * @nowebref * @param x1 x-coordinate of the upper-left corner * @param y1 y-coordinate of the upper-left corner * @param x2 width of the region * @param y2 height of the region */ public void updatePixels(int x1, int y1, int x2, int y2) { g.updatePixels(x1, y1, x2, y2); } ////////////////////////////////////////////////////////////// // EVERYTHING BELOW THIS LINE IS AUTOMATICALLY GENERATED. DO NOT TOUCH! // This includes the Javadoc comments, which are automatically copied from // the PImage and PGraphics source code files. // public functions for processing.core /** * Store data of some kind for the renderer that requires extra metadata of * some kind. Usually this is a renderer-specific representation of the * image data, for instance a BufferedImage with tint() settings applied for * PGraphicsJava2D, or resized image data and OpenGL texture indices for * PGraphicsOpenGL. * @param renderer The PGraphics renderer associated to the image * @param storage The metadata required by the renderer */ public void setCache(PImage image, Object storage) { if (recorder != null) recorder.setCache(image, storage); g.setCache(image, storage); } /** * Get cache storage data for the specified renderer. Because each renderer * will cache data in different formats, it's necessary to store cache data * keyed by the renderer object. Otherwise, attempting to draw the same * image to both a PGraphicsJava2D and a PGraphicsOpenGL will cause errors. * @param renderer The PGraphics renderer associated to the image * @return metadata stored for the specified renderer */ public Object getCache(PImage image) { return g.getCache(image); } /** * Remove information associated with this renderer from the cache, if any. * @param renderer The PGraphics renderer whose cache data should be removed */ public void removeCache(PImage image) { if (recorder != null) recorder.removeCache(image); g.removeCache(image); } public PGL beginPGL() { return g.beginPGL(); } public void endPGL() { if (recorder != null) recorder.endPGL(); g.endPGL(); } public void flush() { if (recorder != null) recorder.flush(); g.flush(); } public void hint(int which) { if (recorder != null) recorder.hint(which); g.hint(which); } /** * Start a new shape of type POLYGON */ public void beginShape() { if (recorder != null) recorder.beginShape(); g.beginShape(); } /** * ( begin auto-generated from beginShape.xml ) * * Using the <b>beginShape()</b> and <b>endShape()</b> functions allow * creating more complex forms. <b>beginShape()</b> begins recording * vertices for a shape and <b>endShape()</b> stops recording. The value of * the <b>MODE</b> parameter tells it which types of shapes to create from * the provided vertices. With no mode specified, the shape can be any * irregular polygon. The parameters available for beginShape() are POINTS, * LINES, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, QUADS, and QUAD_STRIP. * After calling the <b>beginShape()</b> function, a series of * <b>vertex()</b> commands must follow. To stop drawing the shape, call * <b>endShape()</b>. The <b>vertex()</b> function with two parameters * specifies a position in 2D and the <b>vertex()</b> function with three * parameters specifies a position in 3D. Each shape will be outlined with * the current stroke color and filled with the fill color. * <br/> <br/> * Transformations such as <b>translate()</b>, <b>rotate()</b>, and * <b>scale()</b> do not work within <b>beginShape()</b>. It is also not * possible to use other shapes, such as <b>ellipse()</b> or <b>rect()</b> * within <b>beginShape()</b>. * <br/> <br/> * The P3D renderer settings allow <b>stroke()</b> and <b>fill()</b> * settings to be altered per-vertex, however the default P2D renderer does * not. Settings such as <b>strokeWeight()</b>, <b>strokeCap()</b>, and * <b>strokeJoin()</b> cannot be changed while inside a * <b>beginShape()</b>/<b>endShape()</b> block with any renderer. * * ( end auto-generated ) * @webref shape:vertex * @param kind Either POINTS, LINES, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, QUADS, or QUAD_STRIP * @see PShape * @see PGraphics#endShape() * @see PGraphics#vertex(float, float, float, float, float) * @see PGraphics#curveVertex(float, float, float) * @see PGraphics#bezierVertex(float, float, float, float, float, float, float, float, float) */ public void beginShape(int kind) { if (recorder != null) recorder.beginShape(kind); g.beginShape(kind); } /** * Sets whether the upcoming vertex is part of an edge. * Equivalent to glEdgeFlag(), for people familiar with OpenGL. */ public void edge(boolean edge) { if (recorder != null) recorder.edge(edge); g.edge(edge); } /** * ( begin auto-generated from normal.xml ) * * Sets the current normal vector. This is for drawing three dimensional * shapes and surfaces and specifies a vector perpendicular to the surface * of the shape which determines how lighting affects it. Processing * attempts to automatically assign normals to shapes, but since that's * imperfect, this is a better option when you want more control. This * function is identical to glNormal3f() in OpenGL. * * ( end auto-generated ) * @webref lights_camera:lights * @param nx x direction * @param ny y direction * @param nz z direction * @see PGraphics#beginShape(int) * @see PGraphics#endShape(int) * @see PGraphics#lights() */ public void normal(float nx, float ny, float nz) { if (recorder != null) recorder.normal(nx, ny, nz); g.normal(nx, ny, nz); } /** * ( begin auto-generated from textureMode.xml ) * * Sets the coordinate space for texture mapping. There are two options, * IMAGE, which refers to the actual coordinates of the image, and * NORMAL, which refers to a normalized space of values ranging from 0 * to 1. The default mode is IMAGE. In IMAGE, if an image is 100 x 200 * pixels, mapping the image onto the entire size of a quad would require * the points (0,0) (0,100) (100,200) (0,200). The same mapping in * NORMAL_SPACE is (0,0) (0,1) (1,1) (0,1). * * ( end auto-generated ) * @webref image:textures * @param mode either IMAGE or NORMAL * @see PGraphics#texture(PImage) * @see PGraphics#textureWrap(int) */ public void textureMode(int mode) { if (recorder != null) recorder.textureMode(mode); g.textureMode(mode); } /** * ( begin auto-generated from textureWrap.xml ) * * Description to come... * * ( end auto-generated from textureWrap.xml ) * * @webref image:textures * @param wrap Either CLAMP (default) or REPEAT * @see PGraphics#texture(PImage) * @see PGraphics#textureMode(int) */ public void textureWrap(int wrap) { if (recorder != null) recorder.textureWrap(wrap); g.textureWrap(wrap); } /** * ( begin auto-generated from texture.xml ) * * Sets a texture to be applied to vertex points. The <b>texture()</b> * function must be called between <b>beginShape()</b> and * <b>endShape()</b> and before any calls to <b>vertex()</b>. * <br/> <br/> * When textures are in use, the fill color is ignored. Instead, use tint() * to specify the color of the texture as it is applied to the shape. * * ( end auto-generated ) * @webref image:textures * @param image reference to a PImage object * @see PGraphics#textureMode(int) * @see PGraphics#textureWrap(int) * @see PGraphics#beginShape(int) * @see PGraphics#endShape(int) * @see PGraphics#vertex(float, float, float, float, float) */ public void texture(PImage image) { if (recorder != null) recorder.texture(image); g.texture(image); } /** * Removes texture image for current shape. * Needs to be called between beginShape and endShape * */ public void noTexture() { if (recorder != null) recorder.noTexture(); g.noTexture(); } public void vertex(float x, float y) { if (recorder != null) recorder.vertex(x, y); g.vertex(x, y); } public void vertex(float x, float y, float z) { if (recorder != null) recorder.vertex(x, y, z); g.vertex(x, y, z); } /** * Used by renderer subclasses or PShape to efficiently pass in already * formatted vertex information. * @param v vertex parameters, as a float array of length VERTEX_FIELD_COUNT */ public void vertex(float[] v) { if (recorder != null) recorder.vertex(v); g.vertex(v); } public void vertex(float x, float y, float u, float v) { if (recorder != null) recorder.vertex(x, y, u, v); g.vertex(x, y, u, v); } /** * ( begin auto-generated from vertex.xml ) * * All shapes are constructed by connecting a series of vertices. * <b>vertex()</b> is used to specify the vertex coordinates for points, * lines, triangles, quads, and polygons and is used exclusively within the * <b>beginShape()</b> and <b>endShape()</b> function.<br /> * <br /> * Drawing a vertex in 3D using the <b>z</b> parameter requires the P3D * parameter in combination with size as shown in the above example.<br /> * <br /> * This function is also used to map a texture onto the geometry. The * <b>texture()</b> function declares the texture to apply to the geometry * and the <b>u</b> and <b>v</b> coordinates set define the mapping of this * texture to the form. By default, the coordinates used for <b>u</b> and * <b>v</b> are specified in relation to the image's size in pixels, but * this relation can be changed with <b>textureMode()</b>. * * ( end auto-generated ) * @webref shape:vertex * @param x x-coordinate of the vertex * @param y y-coordinate of the vertex * @param z z-coordinate of the vertex * @param u horizontal coordinate for the texture mapping * @param v vertical coordinate for the texture mapping * @see PGraphics#beginShape(int) * @see PGraphics#endShape(int) * @see PGraphics#bezierVertex(float, float, float, float, float, float, float, float, float) * @see PGraphics#quadraticVertex(float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float, float) * @see PGraphics#texture(PImage) */ public void vertex(float x, float y, float z, float u, float v) { if (recorder != null) recorder.vertex(x, y, z, u, v); g.vertex(x, y, z, u, v); } /** * @webref shape:vertex */ public void beginContour() { if (recorder != null) recorder.beginContour(); g.beginContour(); } /** * @webref shape:vertex */ public void endContour() { if (recorder != null) recorder.endContour(); g.endContour(); } public void endShape() { if (recorder != null) recorder.endShape(); g.endShape(); } /** * ( begin auto-generated from endShape.xml ) * * The <b>endShape()</b> function is the companion to <b>beginShape()</b> * and may only be called after <b>beginShape()</b>. When <b>endshape()</b> * is called, all of image data defined since the previous call to * <b>beginShape()</b> is written into the image buffer. The constant CLOSE * as the value for the MODE parameter to close the shape (to connect the * beginning and the end). * * ( end auto-generated ) * @webref shape:vertex * @param mode use CLOSE to close the shape * @see PShape * @see PGraphics#beginShape(int) */ public void endShape(int mode) { if (recorder != null) recorder.endShape(mode); g.endShape(mode); } /** * @webref shape * @param filename name of file to load, can be .svg or .obj * @see PShape * @see PApplet#createShape() */ public PShape loadShape(String filename) { return g.loadShape(filename); } public PShape loadShape(String filename, String options) { return g.loadShape(filename, options); } /** * @webref shape * @see PShape * @see PShape#endShape() * @see PApplet#loadShape(String) */ public PShape createShape() { return g.createShape(); } public PShape createShape(PShape source) { return g.createShape(source); } /** * @param type either POINTS, LINES, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, QUADS, QUAD_STRIP */ public PShape createShape(int type) { return g.createShape(type); } /** * @param kind either LINE, TRIANGLE, RECT, ELLIPSE, ARC, SPHERE, BOX * @param p parameters that match the kind of shape */ public PShape createShape(int kind, float... p) { return g.createShape(kind, p); } /** * ( begin auto-generated from loadShader.xml ) * * This is a new reference entry for Processing 2.0. It will be updated shortly. * * ( end auto-generated ) * * @webref rendering:shaders * @param fragFilename name of fragment shader file */ public PShader loadShader(String fragFilename) { return g.loadShader(fragFilename); } /** * @param vertFilename name of vertex shader file */ public PShader loadShader(String fragFilename, String vertFilename) { return g.loadShader(fragFilename, vertFilename); } /** * ( begin auto-generated from shader.xml ) * * This is a new reference entry for Processing 2.0. It will be updated shortly. * * ( end auto-generated ) * * @webref rendering:shaders * @param shader name of shader file */ public void shader(PShader shader) { if (recorder != null) recorder.shader(shader); g.shader(shader); } /** * @param kind type of shader, either POINTS, LINES, or TRIANGLES */ public void shader(PShader shader, int kind) { if (recorder != null) recorder.shader(shader, kind); g.shader(shader, kind); } /** * ( begin auto-generated from resetShader.xml ) * * This is a new reference entry for Processing 2.0. It will be updated shortly. * * ( end auto-generated ) * * @webref rendering:shaders */ public void resetShader() { if (recorder != null) recorder.resetShader(); g.resetShader(); } /** * @param kind type of shader, either POINTS, LINES, or TRIANGLES */ public void resetShader(int kind) { if (recorder != null) recorder.resetShader(kind); g.resetShader(kind); } /** * @param shader the fragment shader to apply */ public void filter(PShader shader) { if (recorder != null) recorder.filter(shader); g.filter(shader); } /* * @webref rendering:shaders * @param a x-coordinate of the rectangle by default * @param b y-coordinate of the rectangle by default * @param c width of the rectangle by default * @param d height of the rectangle by default */ public void clip(float a, float b, float c, float d) { if (recorder != null) recorder.clip(a, b, c, d); g.clip(a, b, c, d); } /* * @webref rendering:shaders */ public void noClip() { if (recorder != null) recorder.noClip(); g.noClip(); } /** * ( begin auto-generated from blendMode.xml ) * * This is a new reference entry for Processing 2.0. It will be updated shortly. * * ( end auto-generated ) * * @webref Rendering * @param mode the blending mode to use */ public void blendMode(int mode) { if (recorder != null) recorder.blendMode(mode); g.blendMode(mode); } public void bezierVertex(float x2, float y2, float x3, float y3, float x4, float y4) { if (recorder != null) recorder.bezierVertex(x2, y2, x3, y3, x4, y4); g.bezierVertex(x2, y2, x3, y3, x4, y4); } /** * ( begin auto-generated from bezierVertex.xml ) * * Specifies vertex coordinates for Bezier curves. Each call to * <b>bezierVertex()</b> defines the position of two control points and one * anchor point of a Bezier curve, adding a new segment to a line or shape. * The first time <b>bezierVertex()</b> is used within a * <b>beginShape()</b> call, it must be prefaced with a call to * <b>vertex()</b> to set the first anchor point. This function must be * used between <b>beginShape()</b> and <b>endShape()</b> and only when * there is no MODE parameter specified to <b>beginShape()</b>. Using the * 3D version requires rendering with P3D (see the Environment reference * for more information). * * ( end auto-generated ) * @webref shape:vertex * @param x2 the x-coordinate of the 1st control point * @param y2 the y-coordinate of the 1st control point * @param z2 the z-coordinate of the 1st control point * @param x3 the x-coordinate of the 2nd control point * @param y3 the y-coordinate of the 2nd control point * @param z3 the z-coordinate of the 2nd control point * @param x4 the x-coordinate of the anchor point * @param y4 the y-coordinate of the anchor point * @param z4 the z-coordinate of the anchor point * @see PGraphics#curveVertex(float, float, float) * @see PGraphics#vertex(float, float, float, float, float) * @see PGraphics#quadraticVertex(float, float, float, float, float, float) * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) */ public void bezierVertex(float x2, float y2, float z2, float x3, float y3, float z3, float x4, float y4, float z4) { if (recorder != null) recorder.bezierVertex(x2, y2, z2, x3, y3, z3, x4, y4, z4); g.bezierVertex(x2, y2, z2, x3, y3, z3, x4, y4, z4); } /** * @webref shape:vertex * @param cx the x-coordinate of the control point * @param cy the y-coordinate of the control point * @param x3 the x-coordinate of the anchor point * @param y3 the y-coordinate of the anchor point * @see PGraphics#curveVertex(float, float, float) * @see PGraphics#vertex(float, float, float, float, float) * @see PGraphics#bezierVertex(float, float, float, float, float, float) * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) */ public void quadraticVertex(float cx, float cy, float x3, float y3) { if (recorder != null) recorder.quadraticVertex(cx, cy, x3, y3); g.quadraticVertex(cx, cy, x3, y3); } /** * @param cz the z-coordinate of the control point * @param z3 the z-coordinate of the anchor point */ public void quadraticVertex(float cx, float cy, float cz, float x3, float y3, float z3) { if (recorder != null) recorder.quadraticVertex(cx, cy, cz, x3, y3, z3); g.quadraticVertex(cx, cy, cz, x3, y3, z3); } /** * ( begin auto-generated from curveVertex.xml ) * * Specifies vertex coordinates for curves. This function may only be used * between <b>beginShape()</b> and <b>endShape()</b> and only when there is * no MODE parameter specified to <b>beginShape()</b>. The first and last * points in a series of <b>curveVertex()</b> lines will be used to guide * the beginning and end of a the curve. A minimum of four points is * required to draw a tiny curve between the second and third points. * Adding a fifth point with <b>curveVertex()</b> will draw the curve * between the second, third, and fourth points. The <b>curveVertex()</b> * function is an implementation of Catmull-Rom splines. Using the 3D * version requires rendering with P3D (see the Environment reference for * more information). * * ( end auto-generated ) * * @webref shape:vertex * @param x the x-coordinate of the vertex * @param y the y-coordinate of the vertex * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#beginShape(int) * @see PGraphics#endShape(int) * @see PGraphics#vertex(float, float, float, float, float) * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#quadraticVertex(float, float, float, float, float, float) */ public void curveVertex(float x, float y) { if (recorder != null) recorder.curveVertex(x, y); g.curveVertex(x, y); } /** * @param z the z-coordinate of the vertex */ public void curveVertex(float x, float y, float z) { if (recorder != null) recorder.curveVertex(x, y, z); g.curveVertex(x, y, z); } /** * ( begin auto-generated from point.xml ) * * Draws a point, a coordinate in space at the dimension of one pixel. The * first parameter is the horizontal value for the point, the second value * is the vertical value for the point, and the optional third value is the * depth value. Drawing this shape in 3D with the <b>z</b> parameter * requires the P3D parameter in combination with <b>size()</b> as shown in * the above example. * * ( end auto-generated ) * * @webref shape:2d_primitives * @param x x-coordinate of the point * @param y y-coordinate of the point */ public void point(float x, float y) { if (recorder != null) recorder.point(x, y); g.point(x, y); } /** * @param z z-coordinate of the point */ public void point(float x, float y, float z) { if (recorder != null) recorder.point(x, y, z); g.point(x, y, z); } /** * ( begin auto-generated from line.xml ) * * Draws a line (a direct path between two points) to the screen. The * version of <b>line()</b> with four parameters draws the line in 2D. To * color a line, use the <b>stroke()</b> function. A line cannot be filled, * therefore the <b>fill()</b> function will not affect the color of a * line. 2D lines are drawn with a width of one pixel by default, but this * can be changed with the <b>strokeWeight()</b> function. The version with * six parameters allows the line to be placed anywhere within XYZ space. * Drawing this shape in 3D with the <b>z</b> parameter requires the P3D * parameter in combination with <b>size()</b> as shown in the above example. * * ( end auto-generated ) * @webref shape:2d_primitives * @param x1 x-coordinate of the first point * @param y1 y-coordinate of the first point * @param x2 x-coordinate of the second point * @param y2 y-coordinate of the second point * @see PGraphics#strokeWeight(float) * @see PGraphics#strokeJoin(int) * @see PGraphics#strokeCap(int) * @see PGraphics#beginShape() */ public void line(float x1, float y1, float x2, float y2) { if (recorder != null) recorder.line(x1, y1, x2, y2); g.line(x1, y1, x2, y2); } /** * @param z1 z-coordinate of the first point * @param z2 z-coordinate of the second point */ public void line(float x1, float y1, float z1, float x2, float y2, float z2) { if (recorder != null) recorder.line(x1, y1, z1, x2, y2, z2); g.line(x1, y1, z1, x2, y2, z2); } /** * ( begin auto-generated from triangle.xml ) * * A triangle is a plane created by connecting three points. The first two * arguments specify the first point, the middle two arguments specify the * second point, and the last two arguments specify the third point. * * ( end auto-generated ) * @webref shape:2d_primitives * @param x1 x-coordinate of the first point * @param y1 y-coordinate of the first point * @param x2 x-coordinate of the second point * @param y2 y-coordinate of the second point * @param x3 x-coordinate of the third point * @param y3 y-coordinate of the third point * @see PApplet#beginShape() */ public void triangle(float x1, float y1, float x2, float y2, float x3, float y3) { if (recorder != null) recorder.triangle(x1, y1, x2, y2, x3, y3); g.triangle(x1, y1, x2, y2, x3, y3); } /** * ( begin auto-generated from quad.xml ) * * A quad is a quadrilateral, a four sided polygon. It is similar to a * rectangle, but the angles between its edges are not constrained to * ninety degrees. The first pair of parameters (x1,y1) sets the first * vertex and the subsequent pairs should proceed clockwise or * counter-clockwise around the defined shape. * * ( end auto-generated ) * @webref shape:2d_primitives * @param x1 x-coordinate of the first corner * @param y1 y-coordinate of the first corner * @param x2 x-coordinate of the second corner * @param y2 y-coordinate of the second corner * @param x3 x-coordinate of the third corner * @param y3 y-coordinate of the third corner * @param x4 x-coordinate of the fourth corner * @param y4 y-coordinate of the fourth corner */ public void quad(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) { if (recorder != null) recorder.quad(x1, y1, x2, y2, x3, y3, x4, y4); g.quad(x1, y1, x2, y2, x3, y3, x4, y4); } /** * ( begin auto-generated from rectMode.xml ) * * Modifies the location from which rectangles draw. The default mode is * <b>rectMode(CORNER)</b>, which specifies the location to be the upper * left corner of the shape and uses the third and fourth parameters of * <b>rect()</b> to specify the width and height. The syntax * <b>rectMode(CORNERS)</b> uses the first and second parameters of * <b>rect()</b> to set the location of one corner and uses the third and * fourth parameters to set the opposite corner. The syntax * <b>rectMode(CENTER)</b> draws the image from its center point and uses * the third and forth parameters of <b>rect()</b> to specify the image's * width and height. The syntax <b>rectMode(RADIUS)</b> draws the image * from its center point and uses the third and forth parameters of * <b>rect()</b> to specify half of the image's width and height. The * parameter must be written in ALL CAPS because Processing is a case * sensitive language. Note: In version 125, the mode named CENTER_RADIUS * was shortened to RADIUS. * * ( end auto-generated ) * @webref shape:attributes * @param mode either CORNER, CORNERS, CENTER, or RADIUS * @see PGraphics#rect(float, float, float, float) */ public void rectMode(int mode) { if (recorder != null) recorder.rectMode(mode); g.rectMode(mode); } /** * ( begin auto-generated from rect.xml ) * * Draws a rectangle to the screen. A rectangle is a four-sided shape with * every angle at ninety degrees. By default, the first two parameters set * the location of the upper-left corner, the third sets the width, and the * fourth sets the height. These parameters may be changed with the * <b>rectMode()</b> function. * * ( end auto-generated ) * * @webref shape:2d_primitives * @param a x-coordinate of the rectangle by default * @param b y-coordinate of the rectangle by default * @param c width of the rectangle by default * @param d height of the rectangle by default * @see PGraphics#rectMode(int) * @see PGraphics#quad(float, float, float, float, float, float, float, float) */ public void rect(float a, float b, float c, float d) { if (recorder != null) recorder.rect(a, b, c, d); g.rect(a, b, c, d); } /** * @param r radii for all four corners */ public void rect(float a, float b, float c, float d, float r) { if (recorder != null) recorder.rect(a, b, c, d, r); g.rect(a, b, c, d, r); } /** * @param tl radius for top-left corner * @param tr radius for top-right corner * @param br radius for bottom-right corner * @param bl radius for bottom-left corner */ public void rect(float a, float b, float c, float d, float tl, float tr, float br, float bl) { if (recorder != null) recorder.rect(a, b, c, d, tl, tr, br, bl); g.rect(a, b, c, d, tl, tr, br, bl); } /** * ( begin auto-generated from ellipseMode.xml ) * * The origin of the ellipse is modified by the <b>ellipseMode()</b> * function. The default configuration is <b>ellipseMode(CENTER)</b>, which * specifies the location of the ellipse as the center of the shape. The * <b>RADIUS</b> mode is the same, but the width and height parameters to * <b>ellipse()</b> specify the radius of the ellipse, rather than the * diameter. The <b>CORNER</b> mode draws the shape from the upper-left * corner of its bounding box. The <b>CORNERS</b> mode uses the four * parameters to <b>ellipse()</b> to set two opposing corners of the * ellipse's bounding box. The parameter must be written in ALL CAPS * because Processing is a case-sensitive language. * * ( end auto-generated ) * @webref shape:attributes * @param mode either CENTER, RADIUS, CORNER, or CORNERS * @see PApplet#ellipse(float, float, float, float) * @see PApplet#arc(float, float, float, float, float, float) */ public void ellipseMode(int mode) { if (recorder != null) recorder.ellipseMode(mode); g.ellipseMode(mode); } /** * ( begin auto-generated from ellipse.xml ) * * Draws an ellipse (oval) in the display window. An ellipse with an equal * <b>width</b> and <b>height</b> is a circle. The first two parameters set * the location, the third sets the width, and the fourth sets the height. * The origin may be changed with the <b>ellipseMode()</b> function. * * ( end auto-generated ) * @webref shape:2d_primitives * @param a x-coordinate of the ellipse * @param b y-coordinate of the ellipse * @param c width of the ellipse by default * @param d height of the ellipse by default * @see PApplet#ellipseMode(int) * @see PApplet#arc(float, float, float, float, float, float) */ public void ellipse(float a, float b, float c, float d) { if (recorder != null) recorder.ellipse(a, b, c, d); g.ellipse(a, b, c, d); } /** * ( begin auto-generated from arc.xml ) * * Draws an arc in the display window. Arcs are drawn along the outer edge * of an ellipse defined by the <b>x</b>, <b>y</b>, <b>width</b> and * <b>height</b> parameters. The origin or the arc's ellipse may be changed * with the <b>ellipseMode()</b> function. The <b>start</b> and <b>stop</b> * parameters specify the angles at which to draw the arc. * * ( end auto-generated ) * @webref shape:2d_primitives * @param a x-coordinate of the arc's ellipse * @param b y-coordinate of the arc's ellipse * @param c width of the arc's ellipse by default * @param d height of the arc's ellipse by default * @param start angle to start the arc, specified in radians * @param stop angle to stop the arc, specified in radians * @see PApplet#ellipse(float, float, float, float) * @see PApplet#ellipseMode(int) * @see PApplet#radians(float) * @see PApplet#degrees(float) */ public void arc(float a, float b, float c, float d, float start, float stop) { if (recorder != null) recorder.arc(a, b, c, d, start, stop); g.arc(a, b, c, d, start, stop); } /* * @param mode either OPEN, CHORD, or PIE */ public void arc(float a, float b, float c, float d, float start, float stop, int mode) { if (recorder != null) recorder.arc(a, b, c, d, start, stop, mode); g.arc(a, b, c, d, start, stop, mode); } /** * ( begin auto-generated from box.xml ) * * A box is an extruded rectangle. A box with equal dimension on all sides * is a cube. * * ( end auto-generated ) * * @webref shape:3d_primitives * @param size dimension of the box in all dimensions (creates a cube) * @see PGraphics#sphere(float) */ public void box(float size) { if (recorder != null) recorder.box(size); g.box(size); } /** * @param w dimension of the box in the x-dimension * @param h dimension of the box in the y-dimension * @param d dimension of the box in the z-dimension */ public void box(float w, float h, float d) { if (recorder != null) recorder.box(w, h, d); g.box(w, h, d); } /** * ( begin auto-generated from sphereDetail.xml ) * * Controls the detail used to render a sphere by adjusting the number of * vertices of the sphere mesh. The default resolution is 30, which creates * a fairly detailed sphere definition with vertices every 360/30 = 12 * degrees. If you're going to render a great number of spheres per frame, * it is advised to reduce the level of detail using this function. The * setting stays active until <b>sphereDetail()</b> is called again with a * new parameter and so should <i>not</i> be called prior to every * <b>sphere()</b> statement, unless you wish to render spheres with * different settings, e.g. using less detail for smaller spheres or ones * further away from the camera. To control the detail of the horizontal * and vertical resolution independently, use the version of the functions * with two parameters. * * ( end auto-generated ) * * <h3>Advanced</h3> * Code for sphereDetail() submitted by toxi [031031]. * Code for enhanced u/v version from davbol [080801]. * * @param res number of segments (minimum 3) used per full circle revolution * @webref shape:3d_primitives * @see PGraphics#sphere(float) */ public void sphereDetail(int res) { if (recorder != null) recorder.sphereDetail(res); g.sphereDetail(res); } /** * @param ures number of segments used longitudinally per full circle revolutoin * @param vres number of segments used latitudinally from top to bottom */ public void sphereDetail(int ures, int vres) { if (recorder != null) recorder.sphereDetail(ures, vres); g.sphereDetail(ures, vres); } /** * ( begin auto-generated from sphere.xml ) * * A sphere is a hollow ball made from tessellated triangles. * * ( end auto-generated ) * * <h3>Advanced</h3> * <P> * Implementation notes: * <P> * cache all the points of the sphere in a static array * top and bottom are just a bunch of triangles that land * in the center point * <P> * sphere is a series of concentric circles who radii vary * along the shape, based on, er.. cos or something * <PRE> * [toxi 031031] new sphere code. removed all multiplies with * radius, as scale() will take care of that anyway * * [toxi 031223] updated sphere code (removed modulos) * and introduced sphereAt(x,y,z,r) * to avoid additional translate()'s on the user/sketch side * * [davbol 080801] now using separate sphereDetailU/V * </PRE> * * @webref shape:3d_primitives * @param r the radius of the sphere * @see PGraphics#sphereDetail(int) */ public void sphere(float r) { if (recorder != null) recorder.sphere(r); g.sphere(r); } /** * ( begin auto-generated from bezierPoint.xml ) * * Evaluates the Bezier at point t for points a, b, c, d. The parameter t * varies between 0 and 1, a and d are points on the curve, and b and c are * the control points. This can be done once with the x coordinates and a * second time with the y coordinates to get the location of a bezier curve * at t. * * ( end auto-generated ) * * <h3>Advanced</h3> * For instance, to convert the following example:<PRE> * stroke(255, 102, 0); * line(85, 20, 10, 10); * line(90, 90, 15, 80); * stroke(0, 0, 0); * bezier(85, 20, 10, 10, 90, 90, 15, 80); * * // draw it in gray, using 10 steps instead of the default 20 * // this is a slower way to do it, but useful if you need * // to do things with the coordinates at each step * stroke(128); * beginShape(LINE_STRIP); * for (int i = 0; i <= 10; i++) { * float t = i / 10.0f; * float x = bezierPoint(85, 10, 90, 15, t); * float y = bezierPoint(20, 10, 90, 80, t); * vertex(x, y); * } * endShape();</PRE> * * @webref shape:curves * @param a coordinate of first point on the curve * @param b coordinate of first control point * @param c coordinate of second control point * @param d coordinate of second point on the curve * @param t value between 0 and 1 * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#bezierVertex(float, float, float, float, float, float) * @see PGraphics#curvePoint(float, float, float, float, float) */ public float bezierPoint(float a, float b, float c, float d, float t) { return g.bezierPoint(a, b, c, d, t); } /** * ( begin auto-generated from bezierTangent.xml ) * * Calculates the tangent of a point on a Bezier curve. There is a good * definition of <a href="http://en.wikipedia.org/wiki/Tangent" * target="new"><em>tangent</em> on Wikipedia</a>. * * ( end auto-generated ) * * <h3>Advanced</h3> * Code submitted by Dave Bollinger (davol) for release 0136. * * @webref shape:curves * @param a coordinate of first point on the curve * @param b coordinate of first control point * @param c coordinate of second control point * @param d coordinate of second point on the curve * @param t value between 0 and 1 * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#bezierVertex(float, float, float, float, float, float) * @see PGraphics#curvePoint(float, float, float, float, float) */ public float bezierTangent(float a, float b, float c, float d, float t) { return g.bezierTangent(a, b, c, d, t); } /** * ( begin auto-generated from bezierDetail.xml ) * * Sets the resolution at which Beziers display. The default value is 20. * This function is only useful when using the P3D renderer as the default * P2D renderer does not use this information. * * ( end auto-generated ) * * @webref shape:curves * @param detail resolution of the curves * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float, float) * @see PGraphics#curveTightness(float) */ public void bezierDetail(int detail) { if (recorder != null) recorder.bezierDetail(detail); g.bezierDetail(detail); } public void bezier(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) { if (recorder != null) recorder.bezier(x1, y1, x2, y2, x3, y3, x4, y4); g.bezier(x1, y1, x2, y2, x3, y3, x4, y4); } /** * ( begin auto-generated from bezier.xml ) * * Draws a Bezier curve on the screen. These curves are defined by a series * of anchor and control points. The first two parameters specify the first * anchor point and the last two parameters specify the other anchor point. * The middle parameters specify the control points which define the shape * of the curve. Bezier curves were developed by French engineer Pierre * Bezier. Using the 3D version requires rendering with P3D (see the * Environment reference for more information). * * ( end auto-generated ) * * <h3>Advanced</h3> * Draw a cubic bezier curve. The first and last points are * the on-curve points. The middle two are the 'control' points, * or 'handles' in an application like Illustrator. * <P> * Identical to typing: * <PRE>beginShape(); * vertex(x1, y1); * bezierVertex(x2, y2, x3, y3, x4, y4); * endShape(); * </PRE> * In Postscript-speak, this would be: * <PRE>moveto(x1, y1); * curveto(x2, y2, x3, y3, x4, y4);</PRE> * If you were to try and continue that curve like so: * <PRE>curveto(x5, y5, x6, y6, x7, y7);</PRE> * This would be done in processing by adding these statements: * <PRE>bezierVertex(x5, y5, x6, y6, x7, y7) * </PRE> * To draw a quadratic (instead of cubic) curve, * use the control point twice by doubling it: * <PRE>bezier(x1, y1, cx, cy, cx, cy, x2, y2);</PRE> * * @webref shape:curves * @param x1 coordinates for the first anchor point * @param y1 coordinates for the first anchor point * @param z1 coordinates for the first anchor point * @param x2 coordinates for the first control point * @param y2 coordinates for the first control point * @param z2 coordinates for the first control point * @param x3 coordinates for the second control point * @param y3 coordinates for the second control point * @param z3 coordinates for the second control point * @param x4 coordinates for the second anchor point * @param y4 coordinates for the second anchor point * @param z4 coordinates for the second anchor point * * @see PGraphics#bezierVertex(float, float, float, float, float, float) * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) */ public void bezier(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, float x4, float y4, float z4) { if (recorder != null) recorder.bezier(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4); g.bezier(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4); } /** * ( begin auto-generated from curvePoint.xml ) * * Evalutes the curve at point t for points a, b, c, d. The parameter t * varies between 0 and 1, a and d are points on the curve, and b and c are * the control points. This can be done once with the x coordinates and a * second time with the y coordinates to get the location of a curve at t. * * ( end auto-generated ) * * @webref shape:curves * @param a coordinate of first point on the curve * @param b coordinate of second point on the curve * @param c coordinate of third point on the curve * @param d coordinate of fourth point on the curve * @param t value between 0 and 1 * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float) * @see PGraphics#bezierPoint(float, float, float, float, float) */ public float curvePoint(float a, float b, float c, float d, float t) { return g.curvePoint(a, b, c, d, t); } /** * ( begin auto-generated from curveTangent.xml ) * * Calculates the tangent of a point on a curve. There's a good definition * of <em><a href="http://en.wikipedia.org/wiki/Tangent" * target="new">tangent</em> on Wikipedia</a>. * * ( end auto-generated ) * * <h3>Advanced</h3> * Code thanks to Dave Bollinger (Bug #715) * * @webref shape:curves * @param a coordinate of first point on the curve * @param b coordinate of first control point * @param c coordinate of second control point * @param d coordinate of second point on the curve * @param t value between 0 and 1 * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float) * @see PGraphics#curvePoint(float, float, float, float, float) * @see PGraphics#bezierTangent(float, float, float, float, float) */ public float curveTangent(float a, float b, float c, float d, float t) { return g.curveTangent(a, b, c, d, t); } /** * ( begin auto-generated from curveDetail.xml ) * * Sets the resolution at which curves display. The default value is 20. * This function is only useful when using the P3D renderer as the default * P2D renderer does not use this information. * * ( end auto-generated ) * * @webref shape:curves * @param detail resolution of the curves * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float) * @see PGraphics#curveTightness(float) */ public void curveDetail(int detail) { if (recorder != null) recorder.curveDetail(detail); g.curveDetail(detail); } /** * ( begin auto-generated from curveTightness.xml ) * * Modifies the quality of forms created with <b>curve()</b> and * <b>curveVertex()</b>. The parameter <b>squishy</b> determines how the * curve fits to the vertex points. The value 0.0 is the default value for * <b>squishy</b> (this value defines the curves to be Catmull-Rom splines) * and the value 1.0 connects all the points with straight lines. Values * within the range -5.0 and 5.0 will deform the curves but will leave them * recognizable and as values increase in magnitude, they will continue to deform. * * ( end auto-generated ) * * @webref shape:curves * @param tightness amount of deformation from the original vertices * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float) */ public void curveTightness(float tightness) { if (recorder != null) recorder.curveTightness(tightness); g.curveTightness(tightness); } /** * ( begin auto-generated from curve.xml ) * * Draws a curved line on the screen. The first and second parameters * specify the beginning control point and the last two parameters specify * the ending control point. The middle parameters specify the start and * stop of the curve. Longer curves can be created by putting a series of * <b>curve()</b> functions together or using <b>curveVertex()</b>. An * additional function called <b>curveTightness()</b> provides control for * the visual quality of the curve. The <b>curve()</b> function is an * implementation of Catmull-Rom splines. Using the 3D version requires * rendering with P3D (see the Environment reference for more information). * * ( end auto-generated ) * * <h3>Advanced</h3> * As of revision 0070, this function no longer doubles the first * and last points. The curves are a bit more boring, but it's more * mathematically correct, and properly mirrored in curvePoint(). * <P> * Identical to typing out:<PRE> * beginShape(); * curveVertex(x1, y1); * curveVertex(x2, y2); * curveVertex(x3, y3); * curveVertex(x4, y4); * endShape(); * </PRE> * * @webref shape:curves * @param x1 coordinates for the beginning control point * @param y1 coordinates for the beginning control point * @param x2 coordinates for the first point * @param y2 coordinates for the first point * @param x3 coordinates for the second point * @param y3 coordinates for the second point * @param x4 coordinates for the ending control point * @param y4 coordinates for the ending control point * @see PGraphics#curveVertex(float, float) * @see PGraphics#curveTightness(float) * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) */ public void curve(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) { if (recorder != null) recorder.curve(x1, y1, x2, y2, x3, y3, x4, y4); g.curve(x1, y1, x2, y2, x3, y3, x4, y4); } /** * @param z1 coordinates for the beginning control point * @param z2 coordinates for the first point * @param z3 coordinates for the second point * @param z4 coordinates for the ending control point */ public void curve(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, float x4, float y4, float z4) { if (recorder != null) recorder.curve(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4); g.curve(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4); } /** * ( begin auto-generated from smooth.xml ) * * Draws all geometry with smooth (anti-aliased) edges. This will sometimes * slow down the frame rate of the application, but will enhance the visual * refinement. Note that <b>smooth()</b> will also improve image quality of * resized images, and <b>noSmooth()</b> will disable image (and font) * smoothing altogether. * * ( end auto-generated ) * * @webref shape:attributes * @see PGraphics#noSmooth() * @see PGraphics#hint(int) * @see PApplet#size(int, int, String) */ public void smooth() { if (recorder != null) recorder.smooth(); g.smooth(); } /** * * @param level either 2, 4, or 8 */ public void smooth(int level) { if (recorder != null) recorder.smooth(level); g.smooth(level); } /** * ( begin auto-generated from noSmooth.xml ) * * Draws all geometry with jagged (aliased) edges. * * ( end auto-generated ) * @webref shape:attributes * @see PGraphics#smooth() */ public void noSmooth() { if (recorder != null) recorder.noSmooth(); g.noSmooth(); } /** * ( begin auto-generated from imageMode.xml ) * * Modifies the location from which images draw. The default mode is * <b>imageMode(CORNER)</b>, which specifies the location to be the upper * left corner and uses the fourth and fifth parameters of <b>image()</b> * to set the image's width and height. The syntax * <b>imageMode(CORNERS)</b> uses the second and third parameters of * <b>image()</b> to set the location of one corner of the image and uses * the fourth and fifth parameters to set the opposite corner. Use * <b>imageMode(CENTER)</b> to draw images centered at the given x and y * position.<br /> * <br /> * The parameter to <b>imageMode()</b> must be written in ALL CAPS because * Processing is a case-sensitive language. * * ( end auto-generated ) * * @webref image:loading_displaying * @param mode either CORNER, CORNERS, or CENTER * @see PApplet#loadImage(String, String) * @see PImage * @see PGraphics#image(PImage, float, float, float, float) * @see PGraphics#background(float, float, float, float) */ public void imageMode(int mode) { if (recorder != null) recorder.imageMode(mode); g.imageMode(mode); } /** * ( begin auto-generated from image.xml ) * * Displays images to the screen. The images must be in the sketch's "data" * directory to load correctly. Select "Add file..." from the "Sketch" menu * to add the image. Processing currently works with GIF, JPEG, and Targa * images. The <b>img</b> parameter specifies the image to display and the * <b>x</b> and <b>y</b> parameters define the location of the image from * its upper-left corner. The image is displayed at its original size * unless the <b>width</b> and <b>height</b> parameters specify a different * size.<br /> * <br /> * The <b>imageMode()</b> function changes the way the parameters work. For * example, a call to <b>imageMode(CORNERS)</b> will change the * <b>width</b> and <b>height</b> parameters to define the x and y values * of the opposite corner of the image.<br /> * <br /> * The color of an image may be modified with the <b>tint()</b> function. * This function will maintain transparency for GIF and PNG images. * * ( end auto-generated ) * * <h3>Advanced</h3> * Starting with release 0124, when using the default (JAVA2D) renderer, * smooth() will also improve image quality of resized images. * * @webref image:loading_displaying * @param img the image to display * @param a x-coordinate of the image * @param b y-coordinate of the image * @see PApplet#loadImage(String, String) * @see PImage * @see PGraphics#imageMode(int) * @see PGraphics#tint(float) * @see PGraphics#background(float, float, float, float) * @see PGraphics#alpha(int) */ public void image(PImage img, float a, float b) { if (recorder != null) recorder.image(img, a, b); g.image(img, a, b); } /** * @param c width to display the image * @param d height to display the image */ public void image(PImage img, float a, float b, float c, float d) { if (recorder != null) recorder.image(img, a, b, c, d); g.image(img, a, b, c, d); } /** * Draw an image(), also specifying u/v coordinates. * In this method, the u, v coordinates are always based on image space * location, regardless of the current textureMode(). * * @nowebref */ public void image(PImage img, float a, float b, float c, float d, int u1, int v1, int u2, int v2) { if (recorder != null) recorder.image(img, a, b, c, d, u1, v1, u2, v2); g.image(img, a, b, c, d, u1, v1, u2, v2); } /** * ( begin auto-generated from shapeMode.xml ) * * Modifies the location from which shapes draw. The default mode is * <b>shapeMode(CORNER)</b>, which specifies the location to be the upper * left corner of the shape and uses the third and fourth parameters of * <b>shape()</b> to specify the width and height. The syntax * <b>shapeMode(CORNERS)</b> uses the first and second parameters of * <b>shape()</b> to set the location of one corner and uses the third and * fourth parameters to set the opposite corner. The syntax * <b>shapeMode(CENTER)</b> draws the shape from its center point and uses * the third and forth parameters of <b>shape()</b> to specify the width * and height. The parameter must be written in "ALL CAPS" because * Processing is a case sensitive language. * * ( end auto-generated ) * * @webref shape:loading_displaying * @param mode either CORNER, CORNERS, CENTER * @see PShape * @see PGraphics#shape(PShape) * @see PGraphics#rectMode(int) */ public void shapeMode(int mode) { if (recorder != null) recorder.shapeMode(mode); g.shapeMode(mode); } public void shape(PShape shape) { if (recorder != null) recorder.shape(shape); g.shape(shape); } /** * ( begin auto-generated from shape.xml ) * * Displays shapes to the screen. The shapes must be in the sketch's "data" * directory to load correctly. Select "Add file..." from the "Sketch" menu * to add the shape. Processing currently works with SVG shapes only. The * <b>sh</b> parameter specifies the shape to display and the <b>x</b> and * <b>y</b> parameters define the location of the shape from its upper-left * corner. The shape is displayed at its original size unless the * <b>width</b> and <b>height</b> parameters specify a different size. The * <b>shapeMode()</b> function changes the way the parameters work. A call * to <b>shapeMode(CORNERS)</b>, for example, will change the width and * height parameters to define the x and y values of the opposite corner of * the shape. * <br /><br /> * Note complex shapes may draw awkwardly with P3D. This renderer does not * yet support shapes that have holes or complicated breaks. * * ( end auto-generated ) * * @webref shape:loading_displaying * @param shape the shape to display * @param x x-coordinate of the shape * @param y y-coordinate of the shape * @see PShape * @see PApplet#loadShape(String) * @see PGraphics#shapeMode(int) * * Convenience method to draw at a particular location. */ public void shape(PShape shape, float x, float y) { if (recorder != null) recorder.shape(shape, x, y); g.shape(shape, x, y); } /** * @param a x-coordinate of the shape * @param b y-coordinate of the shape * @param c width to display the shape * @param d height to display the shape */ public void shape(PShape shape, float a, float b, float c, float d) { if (recorder != null) recorder.shape(shape, a, b, c, d); g.shape(shape, a, b, c, d); } public void textAlign(int alignX) { if (recorder != null) recorder.textAlign(alignX); g.textAlign(alignX); } /** * ( begin auto-generated from textAlign.xml ) * * Sets the current alignment for drawing text. The parameters LEFT, * CENTER, and RIGHT set the display characteristics of the letters in * relation to the values for the <b>x</b> and <b>y</b> parameters of the * <b>text()</b> function. * <br/> <br/> * In Processing 0125 and later, an optional second parameter can be used * to vertically align the text. BASELINE is the default, and the vertical * alignment will be reset to BASELINE if the second parameter is not used. * The TOP and CENTER parameters are straightforward. The BOTTOM parameter * offsets the line based on the current <b>textDescent()</b>. For multiple * lines, the final line will be aligned to the bottom, with the previous * lines appearing above it. * <br/> <br/> * When using <b>text()</b> with width and height parameters, BASELINE is * ignored, and treated as TOP. (Otherwise, text would by default draw * outside the box, since BASELINE is the default setting. BASELINE is not * a useful drawing mode for text drawn in a rectangle.) * <br/> <br/> * The vertical alignment is based on the value of <b>textAscent()</b>, * which many fonts do not specify correctly. It may be necessary to use a * hack and offset by a few pixels by hand so that the offset looks * correct. To do this as less of a hack, use some percentage of * <b>textAscent()</b> or <b>textDescent()</b> so that the hack works even * if you change the size of the font. * * ( end auto-generated ) * * @webref typography:attributes * @param alignX horizontal alignment, either LEFT, CENTER, or RIGHT * @param alignY vertical alignment, either TOP, BOTTOM, CENTER, or BASELINE * @see PApplet#loadFont(String) * @see PFont * @see PGraphics#text(String, float, float) */ public void textAlign(int alignX, int alignY) { if (recorder != null) recorder.textAlign(alignX, alignY); g.textAlign(alignX, alignY); } /** * ( begin auto-generated from textAscent.xml ) * * Returns ascent of the current font at its current size. This information * is useful for determining the height of the font above the baseline. For * example, adding the <b>textAscent()</b> and <b>textDescent()</b> values * will give you the total height of the line. * * ( end auto-generated ) * * @webref typography:metrics * @see PGraphics#textDescent() */ public float textAscent() { return g.textAscent(); } /** * ( begin auto-generated from textDescent.xml ) * * Returns descent of the current font at its current size. This * information is useful for determining the height of the font below the * baseline. For example, adding the <b>textAscent()</b> and * <b>textDescent()</b> values will give you the total height of the line. * * ( end auto-generated ) * * @webref typography:metrics * @see PGraphics#textAscent() */ public float textDescent() { return g.textDescent(); } /** * ( begin auto-generated from textFont.xml ) * * Sets the current font that will be drawn with the <b>text()</b> * function. Fonts must be loaded with <b>loadFont()</b> before it can be * used. This font will be used in all subsequent calls to the * <b>text()</b> function. If no <b>size</b> parameter is input, the font * will appear at its original size (the size it was created at with the * "Create Font..." tool) until it is changed with <b>textSize()</b>. <br * /> <br /> Because fonts are usually bitmaped, you should create fonts at * the sizes that will be used most commonly. Using <b>textFont()</b> * without the size parameter will result in the cleanest-looking text. <br * /><br /> With the default (JAVA2D) and PDF renderers, it's also possible * to enable the use of native fonts via the command * <b>hint(ENABLE_NATIVE_FONTS)</b>. This will produce vector text in * JAVA2D sketches and PDF output in cases where the vector data is * available: when the font is still installed, or the font is created via * the <b>createFont()</b> function (rather than the Create Font tool). * * ( end auto-generated ) * * @webref typography:loading_displaying * @param which any variable of the type PFont * @see PApplet#createFont(String, float, boolean) * @see PApplet#loadFont(String) * @see PFont * @see PGraphics#text(String, float, float) */ public void textFont(PFont which) { if (recorder != null) recorder.textFont(which); g.textFont(which); } /** * @param size the size of the letters in units of pixels */ public void textFont(PFont which, float size) { if (recorder != null) recorder.textFont(which, size); g.textFont(which, size); } /** * ( begin auto-generated from textLeading.xml ) * * Sets the spacing between lines of text in units of pixels. This setting * will be used in all subsequent calls to the <b>text()</b> function. * * ( end auto-generated ) * * @webref typography:attributes * @param leading the size in pixels for spacing between lines * @see PApplet#loadFont(String) * @see PFont#PFont * @see PGraphics#text(String, float, float) * @see PGraphics#textFont(PFont) */ public void textLeading(float leading) { if (recorder != null) recorder.textLeading(leading); g.textLeading(leading); } /** * ( begin auto-generated from textMode.xml ) * * Sets the way text draws to the screen. In the default configuration, the * <b>MODEL</b> mode, it's possible to rotate, scale, and place letters in * two and three dimensional space.<br /> * <br /> * The <b>SHAPE</b> mode draws text using the the glyph outlines of * individual characters rather than as textures. This mode is only * supported with the <b>PDF</b> and <b>P3D</b> renderer settings. With the * <b>PDF</b> renderer, you must call <b>textMode(SHAPE)</b> before any * other drawing occurs. If the outlines are not available, then * <b>textMode(SHAPE)</b> will be ignored and <b>textMode(MODEL)</b> will * be used instead.<br /> * <br /> * The <b>textMode(SHAPE)</b> option in <b>P3D</b> can be combined with * <b>beginRaw()</b> to write vector-accurate text to 2D and 3D output * files, for instance <b>DXF</b> or <b>PDF</b>. The <b>SHAPE</b> mode is * not currently optimized for <b>P3D</b>, so if recording shape data, use * <b>textMode(MODEL)</b> until you're ready to capture the geometry with <b>beginRaw()</b>. * * ( end auto-generated ) * * @webref typography:attributes * @param mode either MODEL or SHAPE * @see PApplet#loadFont(String) * @see PFont#PFont * @see PGraphics#text(String, float, float) * @see PGraphics#textFont(PFont) * @see PGraphics#beginRaw(PGraphics) * @see PApplet#createFont(String, float, boolean) */ public void textMode(int mode) { if (recorder != null) recorder.textMode(mode); g.textMode(mode); } /** * ( begin auto-generated from textSize.xml ) * * Sets the current font size. This size will be used in all subsequent * calls to the <b>text()</b> function. Font size is measured in units of pixels. * * ( end auto-generated ) * * @webref typography:attributes * @param size the size of the letters in units of pixels * @see PApplet#loadFont(String) * @see PFont#PFont * @see PGraphics#text(String, float, float) * @see PGraphics#textFont(PFont) */ public void textSize(float size) { if (recorder != null) recorder.textSize(size); g.textSize(size); } /** * @param c the character to measure */ public float textWidth(char c) { return g.textWidth(c); } /** * ( begin auto-generated from textWidth.xml ) * * Calculates and returns the width of any character or text string. * * ( end auto-generated ) * * @webref typography:attributes * @param str the String of characters to measure * @see PApplet#loadFont(String) * @see PFont#PFont * @see PGraphics#text(String, float, float) * @see PGraphics#textFont(PFont) */ public float textWidth(String str) { return g.textWidth(str); } /** * @nowebref */ public float textWidth(char[] chars, int start, int length) { return g.textWidth(chars, start, length); } /** * ( begin auto-generated from text.xml ) * * Draws text to the screen. Displays the information specified in the * <b>data</b> or <b>stringdata</b> parameters on the screen in the * position specified by the <b>x</b> and <b>y</b> parameters and the * optional <b>z</b> parameter. A default font will be used unless a font * is set with the <b>textFont()</b> function. Change the color of the text * with the <b>fill()</b> function. The text displays in relation to the * <b>textAlign()</b> function, which gives the option to draw to the left, * right, and center of the coordinates. * <br /><br /> * The <b>x2</b> and <b>y2</b> parameters define a rectangular area to * display within and may only be used with string data. For text drawn * inside a rectangle, the coordinates are interpreted based on the current * <b>rectMode()</b> setting. * * ( end auto-generated ) * * @webref typography:loading_displaying * @param c the alphanumeric character to be displayed * @param x x-coordinate of text * @param y y-coordinate of text * @see PGraphics#textAlign(int, int) * @see PGraphics#textMode(int) * @see PApplet#loadFont(String) * @see PGraphics#textFont(PFont) * @see PGraphics#rectMode(int) * @see PGraphics#fill(int, float) * @see_external String */ public void text(char c, float x, float y) { if (recorder != null) recorder.text(c, x, y); g.text(c, x, y); } /** * @param z z-coordinate of text */ public void text(char c, float x, float y, float z) { if (recorder != null) recorder.text(c, x, y, z); g.text(c, x, y, z); } /** * <h3>Advanced</h3> * Draw a chunk of text. * Newlines that are \n (Unix newline or linefeed char, ascii 10) * are honored, but \r (carriage return, Windows and Mac OS) are * ignored. */ public void text(String str, float x, float y) { if (recorder != null) recorder.text(str, x, y); g.text(str, x, y); } /** * <h3>Advanced</h3> * Method to draw text from an array of chars. This method will usually be * more efficient than drawing from a String object, because the String will * not be converted to a char array before drawing. * @param chars the alphanumberic symbols to be displayed * @param start array index at which to start writing characters * @param stop array index at which to stop writing characters */ public void text(char[] chars, int start, int stop, float x, float y) { if (recorder != null) recorder.text(chars, start, stop, x, y); g.text(chars, start, stop, x, y); } /** * Same as above but with a z coordinate. */ public void text(String str, float x, float y, float z) { if (recorder != null) recorder.text(str, x, y, z); g.text(str, x, y, z); } public void text(char[] chars, int start, int stop, float x, float y, float z) { if (recorder != null) recorder.text(chars, start, stop, x, y, z); g.text(chars, start, stop, x, y, z); } /** * <h3>Advanced</h3> * Draw text in a box that is constrained to a particular size. * The current rectMode() determines what the coordinates mean * (whether x1/y1/x2/y2 or x/y/w/h). * <P/> * Note that the x,y coords of the start of the box * will align with the *ascent* of the text, not the baseline, * as is the case for the other text() functions. * <P/> * Newlines that are \n (Unix newline or linefeed char, ascii 10) * are honored, and \r (carriage return, Windows and Mac OS) are * ignored. * * @param x1 by default, the x-coordinate of text, see rectMode() for more info * @param y1 by default, the x-coordinate of text, see rectMode() for more info * @param x2 by default, the width of the text box, see rectMode() for more info * @param y2 by default, the height of the text box, see rectMode() for more info */ public void text(String str, float x1, float y1, float x2, float y2) { if (recorder != null) recorder.text(str, x1, y1, x2, y2); g.text(str, x1, y1, x2, y2); } public void text(int num, float x, float y) { if (recorder != null) recorder.text(num, x, y); g.text(num, x, y); } public void text(int num, float x, float y, float z) { if (recorder != null) recorder.text(num, x, y, z); g.text(num, x, y, z); } /** * This does a basic number formatting, to avoid the * generally ugly appearance of printing floats. * Users who want more control should use their own nf() cmmand, * or if they want the long, ugly version of float, * use String.valueOf() to convert the float to a String first. * * @param num the numeric value to be displayed */ public void text(float num, float x, float y) { if (recorder != null) recorder.text(num, x, y); g.text(num, x, y); } public void text(float num, float x, float y, float z) { if (recorder != null) recorder.text(num, x, y, z); g.text(num, x, y, z); } /** * ( begin auto-generated from pushMatrix.xml ) * * Pushes the current transformation matrix onto the matrix stack. * Understanding <b>pushMatrix()</b> and <b>popMatrix()</b> requires * understanding the concept of a matrix stack. The <b>pushMatrix()</b> * function saves the current coordinate system to the stack and * <b>popMatrix()</b> restores the prior coordinate system. * <b>pushMatrix()</b> and <b>popMatrix()</b> are used in conjuction with * the other transformation functions and may be embedded to control the * scope of the transformations. * * ( end auto-generated ) * * @webref transform * @see PGraphics#popMatrix() * @see PGraphics#translate(float, float, float) * @see PGraphics#rotate(float) * @see PGraphics#rotateX(float) * @see PGraphics#rotateY(float) * @see PGraphics#rotateZ(float) */ public void pushMatrix() { if (recorder != null) recorder.pushMatrix(); g.pushMatrix(); } /** * ( begin auto-generated from popMatrix.xml ) * * Pops the current transformation matrix off the matrix stack. * Understanding pushing and popping requires understanding the concept of * a matrix stack. The <b>pushMatrix()</b> function saves the current * coordinate system to the stack and <b>popMatrix()</b> restores the prior * coordinate system. <b>pushMatrix()</b> and <b>popMatrix()</b> are used * in conjuction with the other transformation functions and may be * embedded to control the scope of the transformations. * * ( end auto-generated ) * * @webref transform * @see PGraphics#pushMatrix() */ public void popMatrix() { if (recorder != null) recorder.popMatrix(); g.popMatrix(); } /** * ( begin auto-generated from translate.xml ) * * Specifies an amount to displace objects within the display window. The * <b>x</b> parameter specifies left/right translation, the <b>y</b> * parameter specifies up/down translation, and the <b>z</b> parameter * specifies translations toward/away from the screen. Using this function * with the <b>z</b> parameter requires using P3D as a parameter in * combination with size as shown in the above example. Transformations * apply to everything that happens after and subsequent calls to the * function accumulates the effect. For example, calling <b>translate(50, * 0)</b> and then <b>translate(20, 0)</b> is the same as <b>translate(70, * 0)</b>. If <b>translate()</b> is called within <b>draw()</b>, the * transformation is reset when the loop begins again. This function can be * further controlled by the <b>pushMatrix()</b> and <b>popMatrix()</b>. * * ( end auto-generated ) * * @webref transform * @param x left/right translation * @param y up/down translation * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#rotate(float) * @see PGraphics#rotateX(float) * @see PGraphics#rotateY(float) * @see PGraphics#rotateZ(float) * @see PGraphics#scale(float, float, float) */ public void translate(float x, float y) { if (recorder != null) recorder.translate(x, y); g.translate(x, y); } /** * @param z forward/backward translation */ public void translate(float x, float y, float z) { if (recorder != null) recorder.translate(x, y, z); g.translate(x, y, z); } /** * ( begin auto-generated from rotate.xml ) * * Rotates a shape the amount specified by the <b>angle</b> parameter. * Angles should be specified in radians (values from 0 to TWO_PI) or * converted to radians with the <b>radians()</b> function. * <br/> <br/> * Objects are always rotated around their relative position to the origin * and positive numbers rotate objects in a clockwise direction. * Transformations apply to everything that happens after and subsequent * calls to the function accumulates the effect. For example, calling * <b>rotate(HALF_PI)</b> and then <b>rotate(HALF_PI)</b> is the same as * <b>rotate(PI)</b>. All tranformations are reset when <b>draw()</b> * begins again. * <br/> <br/> * Technically, <b>rotate()</b> multiplies the current transformation * matrix by a rotation matrix. This function can be further controlled by * the <b>pushMatrix()</b> and <b>popMatrix()</b>. * * ( end auto-generated ) * * @webref transform * @param angle angle of rotation specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#rotateX(float) * @see PGraphics#rotateY(float) * @see PGraphics#rotateZ(float) * @see PGraphics#scale(float, float, float) * @see PApplet#radians(float) */ public void rotate(float angle) { if (recorder != null) recorder.rotate(angle); g.rotate(angle); } /** * ( begin auto-generated from rotateX.xml ) * * Rotates a shape around the x-axis the amount specified by the * <b>angle</b> parameter. Angles should be specified in radians (values * from 0 to PI*2) or converted to radians with the <b>radians()</b> * function. Objects are always rotated around their relative position to * the origin and positive numbers rotate objects in a counterclockwise * direction. Transformations apply to everything that happens after and * subsequent calls to the function accumulates the effect. For example, * calling <b>rotateX(PI/2)</b> and then <b>rotateX(PI/2)</b> is the same * as <b>rotateX(PI)</b>. If <b>rotateX()</b> is called within the * <b>draw()</b>, the transformation is reset when the loop begins again. * This function requires using P3D as a third parameter to <b>size()</b> * as shown in the example above. * * ( end auto-generated ) * * @webref transform * @param angle angle of rotation specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#rotate(float) * @see PGraphics#rotateY(float) * @see PGraphics#rotateZ(float) * @see PGraphics#scale(float, float, float) * @see PGraphics#translate(float, float, float) */ public void rotateX(float angle) { if (recorder != null) recorder.rotateX(angle); g.rotateX(angle); } /** * ( begin auto-generated from rotateY.xml ) * * Rotates a shape around the y-axis the amount specified by the * <b>angle</b> parameter. Angles should be specified in radians (values * from 0 to PI*2) or converted to radians with the <b>radians()</b> * function. Objects are always rotated around their relative position to * the origin and positive numbers rotate objects in a counterclockwise * direction. Transformations apply to everything that happens after and * subsequent calls to the function accumulates the effect. For example, * calling <b>rotateY(PI/2)</b> and then <b>rotateY(PI/2)</b> is the same * as <b>rotateY(PI)</b>. If <b>rotateY()</b> is called within the * <b>draw()</b>, the transformation is reset when the loop begins again. * This function requires using P3D as a third parameter to <b>size()</b> * as shown in the examples above. * * ( end auto-generated ) * * @webref transform * @param angle angle of rotation specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#rotate(float) * @see PGraphics#rotateX(float) * @see PGraphics#rotateZ(float) * @see PGraphics#scale(float, float, float) * @see PGraphics#translate(float, float, float) */ public void rotateY(float angle) { if (recorder != null) recorder.rotateY(angle); g.rotateY(angle); } /** * ( begin auto-generated from rotateZ.xml ) * * Rotates a shape around the z-axis the amount specified by the * <b>angle</b> parameter. Angles should be specified in radians (values * from 0 to PI*2) or converted to radians with the <b>radians()</b> * function. Objects are always rotated around their relative position to * the origin and positive numbers rotate objects in a counterclockwise * direction. Transformations apply to everything that happens after and * subsequent calls to the function accumulates the effect. For example, * calling <b>rotateZ(PI/2)</b> and then <b>rotateZ(PI/2)</b> is the same * as <b>rotateZ(PI)</b>. If <b>rotateZ()</b> is called within the * <b>draw()</b>, the transformation is reset when the loop begins again. * This function requires using P3D as a third parameter to <b>size()</b> * as shown in the examples above. * * ( end auto-generated ) * * @webref transform * @param angle angle of rotation specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#rotate(float) * @see PGraphics#rotateX(float) * @see PGraphics#rotateY(float) * @see PGraphics#scale(float, float, float) * @see PGraphics#translate(float, float, float) */ public void rotateZ(float angle) { if (recorder != null) recorder.rotateZ(angle); g.rotateZ(angle); } /** * <h3>Advanced</h3> * Rotate about a vector in space. Same as the glRotatef() function. * @param x * @param y * @param z */ public void rotate(float angle, float x, float y, float z) { if (recorder != null) recorder.rotate(angle, x, y, z); g.rotate(angle, x, y, z); } /** * ( begin auto-generated from scale.xml ) * * Increases or decreases the size of a shape by expanding and contracting * vertices. Objects always scale from their relative origin to the * coordinate system. Scale values are specified as decimal percentages. * For example, the function call <b>scale(2.0)</b> increases the dimension * of a shape by 200%. Transformations apply to everything that happens * after and subsequent calls to the function multiply the effect. For * example, calling <b>scale(2.0)</b> and then <b>scale(1.5)</b> is the * same as <b>scale(3.0)</b>. If <b>scale()</b> is called within * <b>draw()</b>, the transformation is reset when the loop begins again. * Using this fuction with the <b>z</b> parameter requires using P3D as a * parameter for <b>size()</b> as shown in the example above. This function * can be further controlled by <b>pushMatrix()</b> and <b>popMatrix()</b>. * * ( end auto-generated ) * * @webref transform * @param s percentage to scale the object * @see PGraphics#pushMatrix() * @see PGraphics#popMatrix() * @see PGraphics#translate(float, float, float) * @see PGraphics#rotate(float) * @see PGraphics#rotateX(float) * @see PGraphics#rotateY(float) * @see PGraphics#rotateZ(float) */ public void scale(float s) { if (recorder != null) recorder.scale(s); g.scale(s); } /** * <h3>Advanced</h3> * Scale in X and Y. Equivalent to scale(sx, sy, 1). * * Not recommended for use in 3D, because the z-dimension is just * scaled by 1, since there's no way to know what else to scale it by. * * @param x percentage to scale the object in the x-axis * @param y percentage to scale the object in the y-axis */ public void scale(float x, float y) { if (recorder != null) recorder.scale(x, y); g.scale(x, y); } /** * @param z percentage to scale the object in the z-axis */ public void scale(float x, float y, float z) { if (recorder != null) recorder.scale(x, y, z); g.scale(x, y, z); } /** * ( begin auto-generated from shearX.xml ) * * Shears a shape around the x-axis the amount specified by the * <b>angle</b> parameter. Angles should be specified in radians (values * from 0 to PI*2) or converted to radians with the <b>radians()</b> * function. Objects are always sheared around their relative position to * the origin and positive numbers shear objects in a clockwise direction. * Transformations apply to everything that happens after and subsequent * calls to the function accumulates the effect. For example, calling * <b>shearX(PI/2)</b> and then <b>shearX(PI/2)</b> is the same as * <b>shearX(PI)</b>. If <b>shearX()</b> is called within the * <b>draw()</b>, the transformation is reset when the loop begins again. * <br/> <br/> * Technically, <b>shearX()</b> multiplies the current transformation * matrix by a rotation matrix. This function can be further controlled by * the <b>pushMatrix()</b> and <b>popMatrix()</b> functions. * * ( end auto-generated ) * * @webref transform * @param angle angle of shear specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#shearY(float) * @see PGraphics#scale(float, float, float) * @see PGraphics#translate(float, float, float) * @see PApplet#radians(float) */ public void shearX(float angle) { if (recorder != null) recorder.shearX(angle); g.shearX(angle); } /** * ( begin auto-generated from shearY.xml ) * * Shears a shape around the y-axis the amount specified by the * <b>angle</b> parameter. Angles should be specified in radians (values * from 0 to PI*2) or converted to radians with the <b>radians()</b> * function. Objects are always sheared around their relative position to * the origin and positive numbers shear objects in a clockwise direction. * Transformations apply to everything that happens after and subsequent * calls to the function accumulates the effect. For example, calling * <b>shearY(PI/2)</b> and then <b>shearY(PI/2)</b> is the same as * <b>shearY(PI)</b>. If <b>shearY()</b> is called within the * <b>draw()</b>, the transformation is reset when the loop begins again. * <br/> <br/> * Technically, <b>shearY()</b> multiplies the current transformation * matrix by a rotation matrix. This function can be further controlled by * the <b>pushMatrix()</b> and <b>popMatrix()</b> functions. * * ( end auto-generated ) * * @webref transform * @param angle angle of shear specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#shearX(float) * @see PGraphics#scale(float, float, float) * @see PGraphics#translate(float, float, float) * @see PApplet#radians(float) */ public void shearY(float angle) { if (recorder != null) recorder.shearY(angle); g.shearY(angle); } /** * ( begin auto-generated from resetMatrix.xml ) * * Replaces the current matrix with the identity matrix. The equivalent * function in OpenGL is glLoadIdentity(). * * ( end auto-generated ) * * @webref transform * @see PGraphics#pushMatrix() * @see PGraphics#popMatrix() * @see PGraphics#applyMatrix(PMatrix) * @see PGraphics#printMatrix() */ public void resetMatrix() { if (recorder != null) recorder.resetMatrix(); g.resetMatrix(); } /** * ( begin auto-generated from applyMatrix.xml ) * * Multiplies the current matrix by the one specified through the * parameters. This is very slow because it will try to calculate the * inverse of the transform, so avoid it whenever possible. The equivalent * function in OpenGL is glMultMatrix(). * * ( end auto-generated ) * * @webref transform * @source * @see PGraphics#pushMatrix() * @see PGraphics#popMatrix() * @see PGraphics#resetMatrix() * @see PGraphics#printMatrix() */ public void applyMatrix(PMatrix source) { if (recorder != null) recorder.applyMatrix(source); g.applyMatrix(source); } public void applyMatrix(PMatrix2D source) { if (recorder != null) recorder.applyMatrix(source); g.applyMatrix(source); } /** * @param n00 numbers which define the 4x4 matrix to be multiplied * @param n01 numbers which define the 4x4 matrix to be multiplied * @param n02 numbers which define the 4x4 matrix to be multiplied * @param n10 numbers which define the 4x4 matrix to be multiplied * @param n11 numbers which define the 4x4 matrix to be multiplied * @param n12 numbers which define the 4x4 matrix to be multiplied */ public void applyMatrix(float n00, float n01, float n02, float n10, float n11, float n12) { if (recorder != null) recorder.applyMatrix(n00, n01, n02, n10, n11, n12); g.applyMatrix(n00, n01, n02, n10, n11, n12); } public void applyMatrix(PMatrix3D source) { if (recorder != null) recorder.applyMatrix(source); g.applyMatrix(source); } /** * @param n03 numbers which define the 4x4 matrix to be multiplied * @param n13 numbers which define the 4x4 matrix to be multiplied * @param n20 numbers which define the 4x4 matrix to be multiplied * @param n21 numbers which define the 4x4 matrix to be multiplied * @param n22 numbers which define the 4x4 matrix to be multiplied * @param n23 numbers which define the 4x4 matrix to be multiplied * @param n30 numbers which define the 4x4 matrix to be multiplied * @param n31 numbers which define the 4x4 matrix to be multiplied * @param n32 numbers which define the 4x4 matrix to be multiplied * @param n33 numbers which define the 4x4 matrix to be multiplied */ public void applyMatrix(float n00, float n01, float n02, float n03, float n10, float n11, float n12, float n13, float n20, float n21, float n22, float n23, float n30, float n31, float n32, float n33) { if (recorder != null) recorder.applyMatrix(n00, n01, n02, n03, n10, n11, n12, n13, n20, n21, n22, n23, n30, n31, n32, n33); g.applyMatrix(n00, n01, n02, n03, n10, n11, n12, n13, n20, n21, n22, n23, n30, n31, n32, n33); } public PMatrix getMatrix() { return g.getMatrix(); } /** * Copy the current transformation matrix into the specified target. * Pass in null to create a new matrix. */ public PMatrix2D getMatrix(PMatrix2D target) { return g.getMatrix(target); } /** * Copy the current transformation matrix into the specified target. * Pass in null to create a new matrix. */ public PMatrix3D getMatrix(PMatrix3D target) { return g.getMatrix(target); } /** * Set the current transformation matrix to the contents of another. */ public void setMatrix(PMatrix source) { if (recorder != null) recorder.setMatrix(source); g.setMatrix(source); } /** * Set the current transformation to the contents of the specified source. */ public void setMatrix(PMatrix2D source) { if (recorder != null) recorder.setMatrix(source); g.setMatrix(source); } /** * Set the current transformation to the contents of the specified source. */ public void setMatrix(PMatrix3D source) { if (recorder != null) recorder.setMatrix(source); g.setMatrix(source); } /** * ( begin auto-generated from printMatrix.xml ) * * Prints the current matrix to the Console (the text window at the bottom * of Processing). * * ( end auto-generated ) * * @webref transform * @see PGraphics#pushMatrix() * @see PGraphics#popMatrix() * @see PGraphics#resetMatrix() * @see PGraphics#applyMatrix(PMatrix) */ public void printMatrix() { if (recorder != null) recorder.printMatrix(); g.printMatrix(); } /** * ( begin auto-generated from beginCamera.xml ) * * The <b>beginCamera()</b> and <b>endCamera()</b> functions enable * advanced customization of the camera space. The functions are useful if * you want to more control over camera movement, however for most users, * the <b>camera()</b> function will be sufficient.<br /><br />The camera * functions will replace any transformations (such as <b>rotate()</b> or * <b>translate()</b>) that occur before them in <b>draw()</b>, but they * will not automatically replace the camera transform itself. For this * reason, camera functions should be placed at the beginning of * <b>draw()</b> (so that transformations happen afterwards), and the * <b>camera()</b> function can be used after <b>beginCamera()</b> if you * want to reset the camera before applying transformations.<br /><br * />This function sets the matrix mode to the camera matrix so calls such * as <b>translate()</b>, <b>rotate()</b>, applyMatrix() and resetMatrix() * affect the camera. <b>beginCamera()</b> should always be used with a * following <b>endCamera()</b> and pairs of <b>beginCamera()</b> and * <b>endCamera()</b> cannot be nested. * * ( end auto-generated ) * * @webref lights_camera:camera * @see PGraphics#camera() * @see PGraphics#endCamera() * @see PGraphics#applyMatrix(PMatrix) * @see PGraphics#resetMatrix() * @see PGraphics#translate(float, float, float) * @see PGraphics#scale(float, float, float) */ public void beginCamera() { if (recorder != null) recorder.beginCamera(); g.beginCamera(); } /** * ( begin auto-generated from endCamera.xml ) * * The <b>beginCamera()</b> and <b>endCamera()</b> functions enable * advanced customization of the camera space. Please see the reference for * <b>beginCamera()</b> for a description of how the functions are used. * * ( end auto-generated ) * * @webref lights_camera:camera * @see PGraphics#camera(float, float, float, float, float, float, float, float, float) */ public void endCamera() { if (recorder != null) recorder.endCamera(); g.endCamera(); } /** * ( begin auto-generated from camera.xml ) * * Sets the position of the camera through setting the eye position, the * center of the scene, and which axis is facing upward. Moving the eye * position and the direction it is pointing (the center of the scene) * allows the images to be seen from different angles. The version without * any parameters sets the camera to the default position, pointing to the * center of the display window with the Y axis as up. The default values * are <b>camera(width/2.0, height/2.0, (height/2.0) / tan(PI*30.0 / * 180.0), width/2.0, height/2.0, 0, 0, 1, 0)</b>. This function is similar * to <b>gluLookAt()</b> in OpenGL, but it first clears the current camera settings. * * ( end auto-generated ) * * @webref lights_camera:camera * @see PGraphics#endCamera() * @see PGraphics#frustum(float, float, float, float, float, float) */ public void camera() { if (recorder != null) recorder.camera(); g.camera(); } /** * @param eyeX x-coordinate for the eye * @param eyeY y-coordinate for the eye * @param eyeZ z-coordinate for the eye * @param centerX x-coordinate for the center of the scene * @param centerY y-coordinate for the center of the scene * @param centerZ z-coordinate for the center of the scene * @param upX usually 0.0, 1.0, or -1.0 * @param upY usually 0.0, 1.0, or -1.0 * @param upZ usually 0.0, 1.0, or -1.0 */ public void camera(float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ) { if (recorder != null) recorder.camera(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ); g.camera(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ); } /** * ( begin auto-generated from printCamera.xml ) * * Prints the current camera matrix to the Console (the text window at the * bottom of Processing). * * ( end auto-generated ) * @webref lights_camera:camera * @see PGraphics#camera(float, float, float, float, float, float, float, float, float) */ public void printCamera() { if (recorder != null) recorder.printCamera(); g.printCamera(); } /** * ( begin auto-generated from ortho.xml ) * * Sets an orthographic projection and defines a parallel clipping volume. * All objects with the same dimension appear the same size, regardless of * whether they are near or far from the camera. The parameters to this * function specify the clipping volume where left and right are the * minimum and maximum x values, top and bottom are the minimum and maximum * y values, and near and far are the minimum and maximum z values. If no * parameters are given, the default is used: ortho(0, width, 0, height, * -10, 10). * * ( end auto-generated ) * * @webref lights_camera:camera */ public void ortho() { if (recorder != null) recorder.ortho(); g.ortho(); } /** * @param left left plane of the clipping volume * @param right right plane of the clipping volume * @param bottom bottom plane of the clipping volume * @param top top plane of the clipping volume */ public void ortho(float left, float right, float bottom, float top) { if (recorder != null) recorder.ortho(left, right, bottom, top); g.ortho(left, right, bottom, top); } /** * @param near maximum distance from the origin to the viewer * @param far maximum distance from the origin away from the viewer */ public void ortho(float left, float right, float bottom, float top, float near, float far) { if (recorder != null) recorder.ortho(left, right, bottom, top, near, far); g.ortho(left, right, bottom, top, near, far); } /** * ( begin auto-generated from perspective.xml ) * * Sets a perspective projection applying foreshortening, making distant * objects appear smaller than closer ones. The parameters define a viewing * volume with the shape of truncated pyramid. Objects near to the front of * the volume appear their actual size, while farther objects appear * smaller. This projection simulates the perspective of the world more * accurately than orthographic projection. The version of perspective * without parameters sets the default perspective and the version with * four parameters allows the programmer to set the area precisely. The * default values are: perspective(PI/3.0, width/height, cameraZ/10.0, * cameraZ*10.0) where cameraZ is ((height/2.0) / tan(PI*60.0/360.0)); * * ( end auto-generated ) * * @webref lights_camera:camera */ public void perspective() { if (recorder != null) recorder.perspective(); g.perspective(); } /** * @param fovy field-of-view angle (in radians) for vertical direction * @param aspect ratio of width to height * @param zNear z-position of nearest clipping plane * @param zFar z-position of farthest clipping plane */ public void perspective(float fovy, float aspect, float zNear, float zFar) { if (recorder != null) recorder.perspective(fovy, aspect, zNear, zFar); g.perspective(fovy, aspect, zNear, zFar); } /** * ( begin auto-generated from frustum.xml ) * * Sets a perspective matrix defined through the parameters. Works like * glFrustum, except it wipes out the current perspective matrix rather * than muliplying itself with it. * * ( end auto-generated ) * * @webref lights_camera:camera * @param left left coordinate of the clipping plane * @param right right coordinate of the clipping plane * @param bottom bottom coordinate of the clipping plane * @param top top coordinate of the clipping plane * @param near near component of the clipping plane; must be greater than zero * @param far far component of the clipping plane; must be greater than the near value * @see PGraphics#camera(float, float, float, float, float, float, float, float, float) * @see PGraphics#endCamera() * @see PGraphics#perspective(float, float, float, float) */ public void frustum(float left, float right, float bottom, float top, float near, float far) { if (recorder != null) recorder.frustum(left, right, bottom, top, near, far); g.frustum(left, right, bottom, top, near, far); } /** * ( begin auto-generated from printProjection.xml ) * * Prints the current projection matrix to the Console (the text window at * the bottom of Processing). * * ( end auto-generated ) * * @webref lights_camera:camera * @see PGraphics#camera(float, float, float, float, float, float, float, float, float) */ public void printProjection() { if (recorder != null) recorder.printProjection(); g.printProjection(); } /** * ( begin auto-generated from screenX.xml ) * * Takes a three-dimensional X, Y, Z position and returns the X value for * where it will appear on a (two-dimensional) screen. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @see PGraphics#screenY(float, float, float) * @see PGraphics#screenZ(float, float, float) */ public float screenX(float x, float y) { return g.screenX(x, y); } /** * ( begin auto-generated from screenY.xml ) * * Takes a three-dimensional X, Y, Z position and returns the Y value for * where it will appear on a (two-dimensional) screen. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @see PGraphics#screenX(float, float, float) * @see PGraphics#screenZ(float, float, float) */ public float screenY(float x, float y) { return g.screenY(x, y); } /** * @param z 3D z-coordinate to be mapped */ public float screenX(float x, float y, float z) { return g.screenX(x, y, z); } /** * @param z 3D z-coordinate to be mapped */ public float screenY(float x, float y, float z) { return g.screenY(x, y, z); } /** * ( begin auto-generated from screenZ.xml ) * * Takes a three-dimensional X, Y, Z position and returns the Z value for * where it will appear on a (two-dimensional) screen. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @param z 3D z-coordinate to be mapped * @see PGraphics#screenX(float, float, float) * @see PGraphics#screenY(float, float, float) */ public float screenZ(float x, float y, float z) { return g.screenZ(x, y, z); } /** * ( begin auto-generated from modelX.xml ) * * Returns the three-dimensional X, Y, Z position in model space. This * returns the X value for a given coordinate based on the current set of * transformations (scale, rotate, translate, etc.) The X value can be used * to place an object in space relative to the location of the original * point once the transformations are no longer in use. * <br/> <br/> * In the example, the <b>modelX()</b>, <b>modelY()</b>, and * <b>modelZ()</b> functions record the location of a box in space after * being placed using a series of translate and rotate commands. After * popMatrix() is called, those transformations no longer apply, but the * (x, y, z) coordinate returned by the model functions is used to place * another box in the same location. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @param z 3D z-coordinate to be mapped * @see PGraphics#modelY(float, float, float) * @see PGraphics#modelZ(float, float, float) */ public float modelX(float x, float y, float z) { return g.modelX(x, y, z); } /** * ( begin auto-generated from modelY.xml ) * * Returns the three-dimensional X, Y, Z position in model space. This * returns the Y value for a given coordinate based on the current set of * transformations (scale, rotate, translate, etc.) The Y value can be used * to place an object in space relative to the location of the original * point once the transformations are no longer in use.<br /> * <br /> * In the example, the <b>modelX()</b>, <b>modelY()</b>, and * <b>modelZ()</b> functions record the location of a box in space after * being placed using a series of translate and rotate commands. After * popMatrix() is called, those transformations no longer apply, but the * (x, y, z) coordinate returned by the model functions is used to place * another box in the same location. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @param z 3D z-coordinate to be mapped * @see PGraphics#modelX(float, float, float) * @see PGraphics#modelZ(float, float, float) */ public float modelY(float x, float y, float z) { return g.modelY(x, y, z); } /** * ( begin auto-generated from modelZ.xml ) * * Returns the three-dimensional X, Y, Z position in model space. This * returns the Z value for a given coordinate based on the current set of * transformations (scale, rotate, translate, etc.) The Z value can be used * to place an object in space relative to the location of the original * point once the transformations are no longer in use.<br /> * <br /> * In the example, the <b>modelX()</b>, <b>modelY()</b>, and * <b>modelZ()</b> functions record the location of a box in space after * being placed using a series of translate and rotate commands. After * popMatrix() is called, those transformations no longer apply, but the * (x, y, z) coordinate returned by the model functions is used to place * another box in the same location. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @param z 3D z-coordinate to be mapped * @see PGraphics#modelX(float, float, float) * @see PGraphics#modelY(float, float, float) */ public float modelZ(float x, float y, float z) { return g.modelZ(x, y, z); } /** * ( begin auto-generated from pushStyle.xml ) * * The <b>pushStyle()</b> function saves the current style settings and * <b>popStyle()</b> restores the prior settings. Note that these functions * are always used together. They allow you to change the style settings * and later return to what you had. When a new style is started with * <b>pushStyle()</b>, it builds on the current style information. The * <b>pushStyle()</b> and <b>popStyle()</b> functions can be embedded to * provide more control (see the second example above for a demonstration.) * <br /><br /> * The style information controlled by the following functions are included * in the style: * fill(), stroke(), tint(), strokeWeight(), strokeCap(), strokeJoin(), * imageMode(), rectMode(), ellipseMode(), shapeMode(), colorMode(), * textAlign(), textFont(), textMode(), textSize(), textLeading(), * emissive(), specular(), shininess(), ambient() * * ( end auto-generated ) * * @webref structure * @see PGraphics#popStyle() */ public void pushStyle() { if (recorder != null) recorder.pushStyle(); g.pushStyle(); } /** * ( begin auto-generated from popStyle.xml ) * * The <b>pushStyle()</b> function saves the current style settings and * <b>popStyle()</b> restores the prior settings; these functions are * always used together. They allow you to change the style settings and * later return to what you had. When a new style is started with * <b>pushStyle()</b>, it builds on the current style information. The * <b>pushStyle()</b> and <b>popStyle()</b> functions can be embedded to * provide more control (see the second example above for a demonstration.) * * ( end auto-generated ) * * @webref structure * @see PGraphics#pushStyle() */ public void popStyle() { if (recorder != null) recorder.popStyle(); g.popStyle(); } public void style(PStyle s) { if (recorder != null) recorder.style(s); g.style(s); } /** * ( begin auto-generated from strokeWeight.xml ) * * Sets the width of the stroke used for lines, points, and the border * around shapes. All widths are set in units of pixels. * <br/> <br/> * When drawing with P3D, series of connected lines (such as the stroke * around a polygon, triangle, or ellipse) produce unattractive results * when a thick stroke weight is set (<a * href="http://code.google.com/p/processing/issues/detail?id=123">see * Issue 123</a>). With P3D, the minimum and maximum values for * <b>strokeWeight()</b> are controlled by the graphics card and the * operating system's OpenGL implementation. For instance, the thickness * may not go higher than 10 pixels. * * ( end auto-generated ) * * @webref shape:attributes * @param weight the weight (in pixels) of the stroke * @see PGraphics#stroke(int, float) * @see PGraphics#strokeJoin(int) * @see PGraphics#strokeCap(int) */ public void strokeWeight(float weight) { if (recorder != null) recorder.strokeWeight(weight); g.strokeWeight(weight); } /** * ( begin auto-generated from strokeJoin.xml ) * * Sets the style of the joints which connect line segments. These joints * are either mitered, beveled, or rounded and specified with the * corresponding parameters MITER, BEVEL, and ROUND. The default joint is * MITER. * <br/> <br/> * This function is not available with the P3D renderer, (<a * href="http://code.google.com/p/processing/issues/detail?id=123">see * Issue 123</a>). More information about the renderers can be found in the * <b>size()</b> reference. * * ( end auto-generated ) * * @webref shape:attributes * @param join either MITER, BEVEL, ROUND * @see PGraphics#stroke(int, float) * @see PGraphics#strokeWeight(float) * @see PGraphics#strokeCap(int) */ public void strokeJoin(int join) { if (recorder != null) recorder.strokeJoin(join); g.strokeJoin(join); } /** * ( begin auto-generated from strokeCap.xml ) * * Sets the style for rendering line endings. These ends are either * squared, extended, or rounded and specified with the corresponding * parameters SQUARE, PROJECT, and ROUND. The default cap is ROUND. * <br/> <br/> * This function is not available with the P3D renderer (<a * href="http://code.google.com/p/processing/issues/detail?id=123">see * Issue 123</a>). More information about the renderers can be found in the * <b>size()</b> reference. * * ( end auto-generated ) * * @webref shape:attributes * @param cap either SQUARE, PROJECT, or ROUND * @see PGraphics#stroke(int, float) * @see PGraphics#strokeWeight(float) * @see PGraphics#strokeJoin(int) * @see PApplet#size(int, int, String, String) */ public void strokeCap(int cap) { if (recorder != null) recorder.strokeCap(cap); g.strokeCap(cap); } /** * ( begin auto-generated from noStroke.xml ) * * Disables drawing the stroke (outline). If both <b>noStroke()</b> and * <b>noFill()</b> are called, nothing will be drawn to the screen. * * ( end auto-generated ) * * @webref color:setting * @see PGraphics#stroke(float, float, float, float) */ public void noStroke() { if (recorder != null) recorder.noStroke(); g.noStroke(); } /** * ( begin auto-generated from stroke.xml ) * * Sets the color used to draw lines and borders around shapes. This color * is either specified in terms of the RGB or HSB color depending on the * current <b>colorMode()</b> (the default color space is RGB, with each * value in the range from 0 to 255). * <br/> <br/> * When using hexadecimal notation to specify a color, use "#" or "0x" * before the values (e.g. #CCFFAA, 0xFFCCFFAA). The # syntax uses six * digits to specify a color (the way colors are specified in HTML and * CSS). When using the hexadecimal notation starting with "0x", the * hexadecimal value must be specified with eight characters; the first two * characters define the alpha component and the remainder the red, green, * and blue components. * <br/> <br/> * The value for the parameter "gray" must be less than or equal to the * current maximum value as specified by <b>colorMode()</b>. The default * maximum value is 255. * * ( end auto-generated ) * * @param rgb color value in hexadecimal notation * @see PGraphics#noStroke() * @see PGraphics#fill(int, float) * @see PGraphics#tint(int, float) * @see PGraphics#background(float, float, float, float) * @see PGraphics#colorMode(int, float, float, float, float) */ public void stroke(int rgb) { if (recorder != null) recorder.stroke(rgb); g.stroke(rgb); } /** * @param alpha opacity of the stroke */ public void stroke(int rgb, float alpha) { if (recorder != null) recorder.stroke(rgb, alpha); g.stroke(rgb, alpha); } /** * @param gray specifies a value between white and black */ public void stroke(float gray) { if (recorder != null) recorder.stroke(gray); g.stroke(gray); } public void stroke(float gray, float alpha) { if (recorder != null) recorder.stroke(gray, alpha); g.stroke(gray, alpha); } /** * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) * @webref color:setting */ public void stroke(float v1, float v2, float v3) { if (recorder != null) recorder.stroke(v1, v2, v3); g.stroke(v1, v2, v3); } public void stroke(float v1, float v2, float v3, float alpha) { if (recorder != null) recorder.stroke(v1, v2, v3, alpha); g.stroke(v1, v2, v3, alpha); } /** * ( begin auto-generated from noTint.xml ) * * Removes the current fill value for displaying images and reverts to * displaying images with their original hues. * * ( end auto-generated ) * * @webref image:loading_displaying * @usage web_application * @see PGraphics#tint(float, float, float, float) * @see PGraphics#image(PImage, float, float, float, float) */ public void noTint() { if (recorder != null) recorder.noTint(); g.noTint(); } /** * ( begin auto-generated from tint.xml ) * * Sets the fill value for displaying images. Images can be tinted to * specified colors or made transparent by setting the alpha.<br /> * <br /> * To make an image transparent, but not change it's color, use white as * the tint color and specify an alpha value. For instance, tint(255, 128) * will make an image 50% transparent (unless <b>colorMode()</b> has been * used).<br /> * <br /> * When using hexadecimal notation to specify a color, use "#" or "0x" * before the values (e.g. #CCFFAA, 0xFFCCFFAA). The # syntax uses six * digits to specify a color (the way colors are specified in HTML and * CSS). When using the hexadecimal notation starting with "0x", the * hexadecimal value must be specified with eight characters; the first two * characters define the alpha component and the remainder the red, green, * and blue components.<br /> * <br /> * The value for the parameter "gray" must be less than or equal to the * current maximum value as specified by <b>colorMode()</b>. The default * maximum value is 255.<br /> * <br /> * The <b>tint()</b> function is also used to control the coloring of * textures in 3D. * * ( end auto-generated ) * * @webref image:loading_displaying * @usage web_application * @param rgb color value in hexadecimal notation * @see PGraphics#noTint() * @see PGraphics#image(PImage, float, float, float, float) */ public void tint(int rgb) { if (recorder != null) recorder.tint(rgb); g.tint(rgb); } /** * @param alpha opacity of the image */ public void tint(int rgb, float alpha) { if (recorder != null) recorder.tint(rgb, alpha); g.tint(rgb, alpha); } /** * @param gray specifies a value between white and black */ public void tint(float gray) { if (recorder != null) recorder.tint(gray); g.tint(gray); } public void tint(float gray, float alpha) { if (recorder != null) recorder.tint(gray, alpha); g.tint(gray, alpha); } /** * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) */ public void tint(float v1, float v2, float v3) { if (recorder != null) recorder.tint(v1, v2, v3); g.tint(v1, v2, v3); } public void tint(float v1, float v2, float v3, float alpha) { if (recorder != null) recorder.tint(v1, v2, v3, alpha); g.tint(v1, v2, v3, alpha); } /** * ( begin auto-generated from noFill.xml ) * * Disables filling geometry. If both <b>noStroke()</b> and <b>noFill()</b> * are called, nothing will be drawn to the screen. * * ( end auto-generated ) * * @webref color:setting * @usage web_application * @see PGraphics#fill(float, float, float, float) */ public void noFill() { if (recorder != null) recorder.noFill(); g.noFill(); } /** * ( begin auto-generated from fill.xml ) * * Sets the color used to fill shapes. For example, if you run <b>fill(204, * 102, 0)</b>, all subsequent shapes will be filled with orange. This * color is either specified in terms of the RGB or HSB color depending on * the current <b>colorMode()</b> (the default color space is RGB, with * each value in the range from 0 to 255). * <br/> <br/> * When using hexadecimal notation to specify a color, use "#" or "0x" * before the values (e.g. #CCFFAA, 0xFFCCFFAA). The # syntax uses six * digits to specify a color (the way colors are specified in HTML and * CSS). When using the hexadecimal notation starting with "0x", the * hexadecimal value must be specified with eight characters; the first two * characters define the alpha component and the remainder the red, green, * and blue components. * <br/> <br/> * The value for the parameter "gray" must be less than or equal to the * current maximum value as specified by <b>colorMode()</b>. The default * maximum value is 255. * <br/> <br/> * To change the color of an image (or a texture), use tint(). * * ( end auto-generated ) * * @webref color:setting * @usage web_application * @param rgb color variable or hex value * @see PGraphics#noFill() * @see PGraphics#stroke(int, float) * @see PGraphics#tint(int, float) * @see PGraphics#background(float, float, float, float) * @see PGraphics#colorMode(int, float, float, float, float) */ public void fill(int rgb) { if (recorder != null) recorder.fill(rgb); g.fill(rgb); } /** * @param alpha opacity of the fill */ public void fill(int rgb, float alpha) { if (recorder != null) recorder.fill(rgb, alpha); g.fill(rgb, alpha); } /** * @param gray number specifying value between white and black */ public void fill(float gray) { if (recorder != null) recorder.fill(gray); g.fill(gray); } public void fill(float gray, float alpha) { if (recorder != null) recorder.fill(gray, alpha); g.fill(gray, alpha); } /** * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) */ public void fill(float v1, float v2, float v3) { if (recorder != null) recorder.fill(v1, v2, v3); g.fill(v1, v2, v3); } public void fill(float v1, float v2, float v3, float alpha) { if (recorder != null) recorder.fill(v1, v2, v3, alpha); g.fill(v1, v2, v3, alpha); } /** * ( begin auto-generated from ambient.xml ) * * Sets the ambient reflectance for shapes drawn to the screen. This is * combined with the ambient light component of environment. The color * components set through the parameters define the reflectance. For * example in the default color mode, setting v1=255, v2=126, v3=0, would * cause all the red light to reflect and half of the green light to * reflect. Used in combination with <b>emissive()</b>, <b>specular()</b>, * and <b>shininess()</b> in setting the material properties of shapes. * * ( end auto-generated ) * * @webref lights_camera:material_properties * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#emissive(float, float, float) * @see PGraphics#specular(float, float, float) * @see PGraphics#shininess(float) */ public void ambient(int rgb) { if (recorder != null) recorder.ambient(rgb); g.ambient(rgb); } /** * @param gray number specifying value between white and black */ public void ambient(float gray) { if (recorder != null) recorder.ambient(gray); g.ambient(gray); } /** * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) */ public void ambient(float v1, float v2, float v3) { if (recorder != null) recorder.ambient(v1, v2, v3); g.ambient(v1, v2, v3); } /** * ( begin auto-generated from specular.xml ) * * Sets the specular color of the materials used for shapes drawn to the * screen, which sets the color of hightlights. Specular refers to light * which bounces off a surface in a perferred direction (rather than * bouncing in all directions like a diffuse light). Used in combination * with <b>emissive()</b>, <b>ambient()</b>, and <b>shininess()</b> in * setting the material properties of shapes. * * ( end auto-generated ) * * @webref lights_camera:material_properties * @usage web_application * @param rgb color to set * @see PGraphics#lightSpecular(float, float, float) * @see PGraphics#ambient(float, float, float) * @see PGraphics#emissive(float, float, float) * @see PGraphics#shininess(float) */ public void specular(int rgb) { if (recorder != null) recorder.specular(rgb); g.specular(rgb); } /** * gray number specifying value between white and black */ public void specular(float gray) { if (recorder != null) recorder.specular(gray); g.specular(gray); } /** * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) */ public void specular(float v1, float v2, float v3) { if (recorder != null) recorder.specular(v1, v2, v3); g.specular(v1, v2, v3); } /** * ( begin auto-generated from shininess.xml ) * * Sets the amount of gloss in the surface of shapes. Used in combination * with <b>ambient()</b>, <b>specular()</b>, and <b>emissive()</b> in * setting the material properties of shapes. * * ( end auto-generated ) * * @webref lights_camera:material_properties * @usage web_application * @param shine degree of shininess * @see PGraphics#emissive(float, float, float) * @see PGraphics#ambient(float, float, float) * @see PGraphics#specular(float, float, float) */ public void shininess(float shine) { if (recorder != null) recorder.shininess(shine); g.shininess(shine); } /** * ( begin auto-generated from emissive.xml ) * * Sets the emissive color of the material used for drawing shapes drawn to * the screen. Used in combination with <b>ambient()</b>, * <b>specular()</b>, and <b>shininess()</b> in setting the material * properties of shapes. * * ( end auto-generated ) * * @webref lights_camera:material_properties * @usage web_application * @param rgb color to set * @see PGraphics#ambient(float, float, float) * @see PGraphics#specular(float, float, float) * @see PGraphics#shininess(float) */ public void emissive(int rgb) { if (recorder != null) recorder.emissive(rgb); g.emissive(rgb); } /** * gray number specifying value between white and black */ public void emissive(float gray) { if (recorder != null) recorder.emissive(gray); g.emissive(gray); } /** * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) */ public void emissive(float v1, float v2, float v3) { if (recorder != null) recorder.emissive(v1, v2, v3); g.emissive(v1, v2, v3); } /** * ( begin auto-generated from lights.xml ) * * Sets the default ambient light, directional light, falloff, and specular * values. The defaults are ambientLight(128, 128, 128) and * directionalLight(128, 128, 128, 0, 0, -1), lightFalloff(1, 0, 0), and * lightSpecular(0, 0, 0). Lights need to be included in the draw() to * remain persistent in a looping program. Placing them in the setup() of a * looping program will cause them to only have an effect the first time * through the loop. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @see PGraphics#ambientLight(float, float, float, float, float, float) * @see PGraphics#directionalLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#noLights() */ public void lights() { if (recorder != null) recorder.lights(); g.lights(); } /** * ( begin auto-generated from noLights.xml ) * * Disable all lighting. Lighting is turned off by default and enabled with * the <b>lights()</b> function. This function can be used to disable * lighting so that 2D geometry (which does not require lighting) can be * drawn after a set of lighted 3D geometry. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @see PGraphics#lights() */ public void noLights() { if (recorder != null) recorder.noLights(); g.noLights(); } /** * ( begin auto-generated from ambientLight.xml ) * * Adds an ambient light. Ambient light doesn't come from a specific * direction, the rays have light have bounced around so much that objects * are evenly lit from all sides. Ambient lights are almost always used in * combination with other types of lights. Lights need to be included in * the <b>draw()</b> to remain persistent in a looping program. Placing * them in the <b>setup()</b> of a looping program will cause them to only * have an effect the first time through the loop. The effect of the * parameters is determined by the current color mode. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) * @see PGraphics#lights() * @see PGraphics#directionalLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) */ public void ambientLight(float v1, float v2, float v3) { if (recorder != null) recorder.ambientLight(v1, v2, v3); g.ambientLight(v1, v2, v3); } /** * @param x x-coordinate of the light * @param y y-coordinate of the light * @param z z-coordinate of the light */ public void ambientLight(float v1, float v2, float v3, float x, float y, float z) { if (recorder != null) recorder.ambientLight(v1, v2, v3, x, y, z); g.ambientLight(v1, v2, v3, x, y, z); } /** * ( begin auto-generated from directionalLight.xml ) * * Adds a directional light. Directional light comes from one direction and * is stronger when hitting a surface squarely and weaker if it hits at a a * gentle angle. After hitting a surface, a directional lights scatters in * all directions. Lights need to be included in the <b>draw()</b> to * remain persistent in a looping program. Placing them in the * <b>setup()</b> of a looping program will cause them to only have an * effect the first time through the loop. The affect of the <b>v1</b>, * <b>v2</b>, and <b>v3</b> parameters is determined by the current color * mode. The <b>nx</b>, <b>ny</b>, and <b>nz</b> parameters specify the * direction the light is facing. For example, setting <b>ny</b> to -1 will * cause the geometry to be lit from below (the light is facing directly upward). * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) * @param nx direction along the x-axis * @param ny direction along the y-axis * @param nz direction along the z-axis * @see PGraphics#lights() * @see PGraphics#ambientLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) */ public void directionalLight(float v1, float v2, float v3, float nx, float ny, float nz) { if (recorder != null) recorder.directionalLight(v1, v2, v3, nx, ny, nz); g.directionalLight(v1, v2, v3, nx, ny, nz); } /** * ( begin auto-generated from pointLight.xml ) * * Adds a point light. Lights need to be included in the <b>draw()</b> to * remain persistent in a looping program. Placing them in the * <b>setup()</b> of a looping program will cause them to only have an * effect the first time through the loop. The affect of the <b>v1</b>, * <b>v2</b>, and <b>v3</b> parameters is determined by the current color * mode. The <b>x</b>, <b>y</b>, and <b>z</b> parameters set the position * of the light. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) * @param x x-coordinate of the light * @param y y-coordinate of the light * @param z z-coordinate of the light * @see PGraphics#lights() * @see PGraphics#directionalLight(float, float, float, float, float, float) * @see PGraphics#ambientLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) */ public void pointLight(float v1, float v2, float v3, float x, float y, float z) { if (recorder != null) recorder.pointLight(v1, v2, v3, x, y, z); g.pointLight(v1, v2, v3, x, y, z); } /** * ( begin auto-generated from spotLight.xml ) * * Adds a spot light. Lights need to be included in the <b>draw()</b> to * remain persistent in a looping program. Placing them in the * <b>setup()</b> of a looping program will cause them to only have an * effect the first time through the loop. The affect of the <b>v1</b>, * <b>v2</b>, and <b>v3</b> parameters is determined by the current color * mode. The <b>x</b>, <b>y</b>, and <b>z</b> parameters specify the * position of the light and <b>nx</b>, <b>ny</b>, <b>nz</b> specify the * direction or light. The <b>angle</b> parameter affects angle of the * spotlight cone. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) * @param x x-coordinate of the light * @param y y-coordinate of the light * @param z z-coordinate of the light * @param nx direction along the x axis * @param ny direction along the y axis * @param nz direction along the z axis * @param angle angle of the spotlight cone * @param concentration exponent determining the center bias of the cone * @see PGraphics#lights() * @see PGraphics#directionalLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#ambientLight(float, float, float, float, float, float) */ public void spotLight(float v1, float v2, float v3, float x, float y, float z, float nx, float ny, float nz, float angle, float concentration) { if (recorder != null) recorder.spotLight(v1, v2, v3, x, y, z, nx, ny, nz, angle, concentration); g.spotLight(v1, v2, v3, x, y, z, nx, ny, nz, angle, concentration); } /** * ( begin auto-generated from lightFalloff.xml ) * * Sets the falloff rates for point lights, spot lights, and ambient * lights. The parameters are used to determine the falloff with the * following equation:<br /><br />d = distance from light position to * vertex position<br />falloff = 1 / (CONSTANT + d * LINEAR + (d*d) * * QUADRATIC)<br /><br />Like <b>fill()</b>, it affects only the elements * which are created after it in the code. The default value if * <b>LightFalloff(1.0, 0.0, 0.0)</b>. Thinking about an ambient light with * a falloff can be tricky. It is used, for example, if you wanted a region * of your scene to be lit ambiently one color and another region to be lit * ambiently by another color, you would use an ambient light with location * and falloff. You can think of it as a point light that doesn't care * which direction a surface is facing. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param constant constant value or determining falloff * @param linear linear value for determining falloff * @param quadratic quadratic value for determining falloff * @see PGraphics#lights() * @see PGraphics#ambientLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#lightSpecular(float, float, float) */ public void lightFalloff(float constant, float linear, float quadratic) { if (recorder != null) recorder.lightFalloff(constant, linear, quadratic); g.lightFalloff(constant, linear, quadratic); } /** * ( begin auto-generated from lightSpecular.xml ) * * Sets the specular color for lights. Like <b>fill()</b>, it affects only * the elements which are created after it in the code. Specular refers to * light which bounces off a surface in a perferred direction (rather than * bouncing in all directions like a diffuse light) and is used for * creating highlights. The specular quality of a light interacts with the * specular material qualities set through the <b>specular()</b> and * <b>shininess()</b> functions. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) * @see PGraphics#specular(float, float, float) * @see PGraphics#lights() * @see PGraphics#ambientLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) */ public void lightSpecular(float v1, float v2, float v3) { if (recorder != null) recorder.lightSpecular(v1, v2, v3); g.lightSpecular(v1, v2, v3); } /** * ( begin auto-generated from background.xml ) * * The <b>background()</b> function sets the color used for the background * of the Processing window. The default background is light gray. In the * <b>draw()</b> function, the background color is used to clear the * display window at the beginning of each frame. * <br/> <br/> * An image can also be used as the background for a sketch, however its * width and height must be the same size as the sketch window. To resize * an image 'b' to the size of the sketch window, use b.resize(width, height). * <br/> <br/> * Images used as background will ignore the current <b>tint()</b> setting. * <br/> <br/> * It is not possible to use transparency (alpha) in background colors with * the main drawing surface, however they will work properly with <b>createGraphics()</b>. * * ( end auto-generated ) * * <h3>Advanced</h3> * <p>Clear the background with a color that includes an alpha value. This can * only be used with objects created by createGraphics(), because the main * drawing surface cannot be set transparent.</p> * <p>It might be tempting to use this function to partially clear the screen * on each frame, however that's not how this function works. When calling * background(), the pixels will be replaced with pixels that have that level * of transparency. To do a semi-transparent overlay, use fill() with alpha * and draw a rectangle.</p> * * @webref color:setting * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#stroke(float) * @see PGraphics#fill(float) * @see PGraphics#tint(float) * @see PGraphics#colorMode(int) */ public void background(int rgb) { if (recorder != null) recorder.background(rgb); g.background(rgb); } /** * @param alpha opacity of the background */ public void background(int rgb, float alpha) { if (recorder != null) recorder.background(rgb, alpha); g.background(rgb, alpha); } /** * @param gray specifies a value between white and black */ public void background(float gray) { if (recorder != null) recorder.background(gray); g.background(gray); } public void background(float gray, float alpha) { if (recorder != null) recorder.background(gray, alpha); g.background(gray, alpha); } /** * @param v1 red or hue value (depending on the current color mode) * @param v2 green or saturation value (depending on the current color mode) * @param v3 blue or brightness value (depending on the current color mode) */ public void background(float v1, float v2, float v3) { if (recorder != null) recorder.background(v1, v2, v3); g.background(v1, v2, v3); } public void background(float v1, float v2, float v3, float alpha) { if (recorder != null) recorder.background(v1, v2, v3, alpha); g.background(v1, v2, v3, alpha); } /** * @webref color:setting */ public void clear() { if (recorder != null) recorder.clear(); g.clear(); } /** * Takes an RGB or ARGB image and sets it as the background. * The width and height of the image must be the same size as the sketch. * Use image.resize(width, height) to make short work of such a task.<br/> * <br/> * Note that even if the image is set as RGB, the high 8 bits of each pixel * should be set opaque (0xFF000000) because the image data will be copied * directly to the screen, and non-opaque background images may have strange * behavior. Use image.filter(OPAQUE) to handle this easily.<br/> * <br/> * When using 3D, this will also clear the zbuffer (if it exists). * * @param image PImage to set as background (must be same size as the sketch window) */ public void background(PImage image) { if (recorder != null) recorder.background(image); g.background(image); } /** * ( begin auto-generated from colorMode.xml ) * * Changes the way Processing interprets color data. By default, the * parameters for <b>fill()</b>, <b>stroke()</b>, <b>background()</b>, and * <b>color()</b> are defined by values between 0 and 255 using the RGB * color model. The <b>colorMode()</b> function is used to change the * numerical range used for specifying colors and to switch color systems. * For example, calling <b>colorMode(RGB, 1.0)</b> will specify that values * are specified between 0 and 1. The limits for defining colors are * altered by setting the parameters range1, range2, range3, and range 4. * * ( end auto-generated ) * * @webref color:setting * @usage web_application * @param mode Either RGB or HSB, corresponding to Red/Green/Blue and Hue/Saturation/Brightness * @see PGraphics#background(float) * @see PGraphics#fill(float) * @see PGraphics#stroke(float) */ public void colorMode(int mode) { if (recorder != null) recorder.colorMode(mode); g.colorMode(mode); } /** * @param max range for all color elements */ public void colorMode(int mode, float max) { if (recorder != null) recorder.colorMode(mode, max); g.colorMode(mode, max); } /** * @param max1 range for the red or hue depending on the current color mode * @param max2 range for the green or saturation depending on the current color mode * @param max3 range for the blue or brightness depending on the current color mode */ public void colorMode(int mode, float max1, float max2, float max3) { if (recorder != null) recorder.colorMode(mode, max1, max2, max3); g.colorMode(mode, max1, max2, max3); } /** * @param maxA range for the alpha */ public void colorMode(int mode, float max1, float max2, float max3, float maxA) { if (recorder != null) recorder.colorMode(mode, max1, max2, max3, maxA); g.colorMode(mode, max1, max2, max3, maxA); } /** * ( begin auto-generated from alpha.xml ) * * Extracts the alpha value from a color. * * ( end auto-generated ) * @webref color:creating_reading * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#green(int) * @see PGraphics#blue(int) * @see PGraphics#hue(int) * @see PGraphics#saturation(int) * @see PGraphics#brightness(int) */ public final float alpha(int rgb) { return g.alpha(rgb); } /** * ( begin auto-generated from red.xml ) * * Extracts the red value from a color, scaled to match current * <b>colorMode()</b>. This value is always returned as a float so be * careful not to assign it to an int value.<br /><br />The red() function * is easy to use and undestand, but is slower than another technique. To * achieve the same results when working in <b>colorMode(RGB, 255)</b>, but * with greater speed, use the &gt;&gt; (right shift) operator with a bit * mask. For example, the following two lines of code are equivalent:<br * /><pre>float r1 = red(myColor);<br />float r2 = myColor &gt;&gt; 16 * &amp; 0xFF;</pre> * * ( end auto-generated ) * * @webref color:creating_reading * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#green(int) * @see PGraphics#blue(int) * @see PGraphics#alpha(int) * @see PGraphics#hue(int) * @see PGraphics#saturation(int) * @see PGraphics#brightness(int) * @see_external rightshift */ public final float red(int rgb) { return g.red(rgb); } /** * ( begin auto-generated from green.xml ) * * Extracts the green value from a color, scaled to match current * <b>colorMode()</b>. This value is always returned as a float so be * careful not to assign it to an int value.<br /><br />The <b>green()</b> * function is easy to use and undestand, but is slower than another * technique. To achieve the same results when working in <b>colorMode(RGB, * 255)</b>, but with greater speed, use the &gt;&gt; (right shift) * operator with a bit mask. For example, the following two lines of code * are equivalent:<br /><pre>float r1 = green(myColor);<br />float r2 = * myColor &gt;&gt; 8 &amp; 0xFF;</pre> * * ( end auto-generated ) * * @webref color:creating_reading * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#blue(int) * @see PGraphics#alpha(int) * @see PGraphics#hue(int) * @see PGraphics#saturation(int) * @see PGraphics#brightness(int) * @see_external rightshift */ public final float green(int rgb) { return g.green(rgb); } /** * ( begin auto-generated from blue.xml ) * * Extracts the blue value from a color, scaled to match current * <b>colorMode()</b>. This value is always returned as a float so be * careful not to assign it to an int value.<br /><br />The <b>blue()</b> * function is easy to use and undestand, but is slower than another * technique. To achieve the same results when working in <b>colorMode(RGB, * 255)</b>, but with greater speed, use a bit mask to remove the other * color components. For example, the following two lines of code are * equivalent:<br /><pre>float r1 = blue(myColor);<br />float r2 = myColor * &amp; 0xFF;</pre> * * ( end auto-generated ) * * @webref color:creating_reading * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#green(int) * @see PGraphics#alpha(int) * @see PGraphics#hue(int) * @see PGraphics#saturation(int) * @see PGraphics#brightness(int) * @see_external rightshift */ public final float blue(int rgb) { return g.blue(rgb); } /** * ( begin auto-generated from hue.xml ) * * Extracts the hue value from a color. * * ( end auto-generated ) * @webref color:creating_reading * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#green(int) * @see PGraphics#blue(int) * @see PGraphics#alpha(int) * @see PGraphics#saturation(int) * @see PGraphics#brightness(int) */ public final float hue(int rgb) { return g.hue(rgb); } /** * ( begin auto-generated from saturation.xml ) * * Extracts the saturation value from a color. * * ( end auto-generated ) * @webref color:creating_reading * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#green(int) * @see PGraphics#blue(int) * @see PGraphics#alpha(int) * @see PGraphics#hue(int) * @see PGraphics#brightness(int) */ public final float saturation(int rgb) { return g.saturation(rgb); } /** * ( begin auto-generated from brightness.xml ) * * Extracts the brightness value from a color. * * ( end auto-generated ) * * @webref color:creating_reading * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#green(int) * @see PGraphics#blue(int) * @see PGraphics#alpha(int) * @see PGraphics#hue(int) * @see PGraphics#saturation(int) */ public final float brightness(int rgb) { return g.brightness(rgb); } /** * ( begin auto-generated from lerpColor.xml ) * * Calculates a color or colors between two color at a specific increment. * The <b>amt</b> parameter is the amount to interpolate between the two * values where 0.0 equal to the first point, 0.1 is very near the first * point, 0.5 is half-way in between, etc. * * ( end auto-generated ) * * @webref color:creating_reading * @usage web_application * @param c1 interpolate from this color * @param c2 interpolate to this color * @param amt between 0.0 and 1.0 * @see PImage#blendColor(int, int, int) * @see PGraphics#color(float, float, float, float) */ public int lerpColor(int c1, int c2, float amt) { return g.lerpColor(c1, c2, amt); } /** * @nowebref * Interpolate between two colors. Like lerp(), but for the * individual color components of a color supplied as an int value. */ static public int lerpColor(int c1, int c2, float amt, int mode) { return PGraphics.lerpColor(c1, c2, amt, mode); } /** * Display a warning that the specified method is only available with 3D. * @param method The method name (no parentheses) */ static public void showDepthWarning(String method) { PGraphics.showDepthWarning(method); } /** * Display a warning that the specified method that takes x, y, z parameters * can only be used with x and y parameters in this renderer. * @param method The method name (no parentheses) */ static public void showDepthWarningXYZ(String method) { PGraphics.showDepthWarningXYZ(method); } /** * Display a warning that the specified method is simply unavailable. */ static public void showMethodWarning(String method) { PGraphics.showMethodWarning(method); } /** * Error that a particular variation of a method is unavailable (even though * other variations are). For instance, if vertex(x, y, u, v) is not * available, but vertex(x, y) is just fine. */ static public void showVariationWarning(String str) { PGraphics.showVariationWarning(str); } /** * Display a warning that the specified method is not implemented, meaning * that it could be either a completely missing function, although other * variations of it may still work properly. */ static public void showMissingWarning(String method) { PGraphics.showMissingWarning(method); } /** * Return true if this renderer should be drawn to the screen. Defaults to * returning true, since nearly all renderers are on-screen beasts. But can * be overridden for subclasses like PDF so that a window doesn't open up. * <br/> <br/> * A better name? showFrame, displayable, isVisible, visible, shouldDisplay, * what to call this? */ public boolean displayable() { return g.displayable(); } /** * Return true if this renderer does rendering through OpenGL. Defaults to false. */ public boolean isGL() { return g.isGL(); } /** * ( begin auto-generated from PImage_get.xml ) * * Reads the color of any pixel or grabs a section of an image. If no * parameters are specified, the entire image is returned. Use the <b>x</b> * and <b>y</b> parameters to get the value of one pixel. Get a section of * the display window by specifying an additional <b>width</b> and * <b>height</b> parameter. When getting an image, the <b>x</b> and * <b>y</b> parameters define the coordinates for the upper-left corner of * the image, regardless of the current <b>imageMode()</b>.<br /> * <br /> * If the pixel requested is outside of the image window, black is * returned. The numbers returned are scaled according to the current color * ranges, but only RGB values are returned by this function. For example, * even though you may have drawn a shape with <b>colorMode(HSB)</b>, the * numbers returned will be in RGB format.<br /> * <br /> * Getting the color of a single pixel with <b>get(x, y)</b> is easy, but * not as fast as grabbing the data directly from <b>pixels[]</b>. The * equivalent statement to <b>get(x, y)</b> using <b>pixels[]</b> is * <b>pixels[y*width+x]</b>. See the reference for <b>pixels[]</b> for more information. * * ( end auto-generated ) * * <h3>Advanced</h3> * Returns an ARGB "color" type (a packed 32 bit int with the color. * If the coordinate is outside the image, zero is returned * (black, but completely transparent). * <P> * If the image is in RGB format (i.e. on a PVideo object), * the value will get its high bits set, just to avoid cases where * they haven't been set already. * <P> * If the image is in ALPHA format, this returns a white with its * alpha value set. * <P> * This function is included primarily for beginners. It is quite * slow because it has to check to see if the x, y that was provided * is inside the bounds, and then has to check to see what image * type it is. If you want things to be more efficient, access the * pixels[] array directly. * * @webref image:pixels * @brief Reads the color of any pixel or grabs a rectangle of pixels * @usage web_application * @param x x-coordinate of the pixel * @param y y-coordinate of the pixel * @see PApplet#set(int, int, int) * @see PApplet#pixels * @see PApplet#copy(PImage, int, int, int, int, int, int, int, int) */ public int get(int x, int y) { return g.get(x, y); } /** * @param w width of pixel rectangle to get * @param h height of pixel rectangle to get */ public PImage get(int x, int y, int w, int h) { return g.get(x, y, w, h); } /** * Returns a copy of this PImage. Equivalent to get(0, 0, width, height). */ public PImage get() { return g.get(); } /** * ( begin auto-generated from PImage_set.xml ) * * Changes the color of any pixel or writes an image directly into the * display window.<br /> * <br /> * The <b>x</b> and <b>y</b> parameters specify the pixel to change and the * <b>color</b> parameter specifies the color value. The color parameter is * affected by the current color mode (the default is RGB values from 0 to * 255). When setting an image, the <b>x</b> and <b>y</b> parameters define * the coordinates for the upper-left corner of the image, regardless of * the current <b>imageMode()</b>. * <br /><br /> * Setting the color of a single pixel with <b>set(x, y)</b> is easy, but * not as fast as putting the data directly into <b>pixels[]</b>. The * equivalent statement to <b>set(x, y, #000000)</b> using <b>pixels[]</b> * is <b>pixels[y*width+x] = #000000</b>. See the reference for * <b>pixels[]</b> for more information. * * ( end auto-generated ) * * @webref image:pixels * @brief writes a color to any pixel or writes an image into another * @usage web_application * @param x x-coordinate of the pixel * @param y y-coordinate of the pixel * @param c any value of the color datatype * @see PImage#get(int, int, int, int) * @see PImage#pixels * @see PImage#copy(PImage, int, int, int, int, int, int, int, int) */ public void set(int x, int y, int c) { if (recorder != null) recorder.set(x, y, c); g.set(x, y, c); } /** * <h3>Advanced</h3> * Efficient method of drawing an image's pixels directly to this surface. * No variations are employed, meaning that any scale, tint, or imageMode * settings will be ignored. * * @param img image to copy into the original image */ public void set(int x, int y, PImage img) { if (recorder != null) recorder.set(x, y, img); g.set(x, y, img); } /** * ( begin auto-generated from PImage_mask.xml ) * * Masks part of an image from displaying by loading another image and * using it as an alpha channel. This mask image should only contain * grayscale data, but only the blue color channel is used. The mask image * needs to be the same size as the image to which it is applied.<br /> * <br /> * In addition to using a mask image, an integer array containing the alpha * channel data can be specified directly. This method is useful for * creating dynamically generated alpha masks. This array must be of the * same length as the target image's pixels array and should contain only * grayscale data of values between 0-255. * * ( end auto-generated ) * * <h3>Advanced</h3> * * Set alpha channel for an image. Black colors in the source * image will make the destination image completely transparent, * and white will make things fully opaque. Gray values will * be in-between steps. * <P> * Strictly speaking the "blue" value from the source image is * used as the alpha color. For a fully grayscale image, this * is correct, but for a color image it's not 100% accurate. * For a more accurate conversion, first use filter(GRAY) * which will make the image into a "correct" grayscale by * performing a proper luminance-based conversion. * * @webref pimage:method * @usage web_application * @brief Masks part of an image with another image as an alpha channel * @param maskArray array of integers used as the alpha channel, needs to be the same length as the image's pixel array */ public void mask(PImage img) { if (recorder != null) recorder.mask(img); g.mask(img); } public void filter(int kind) { if (recorder != null) recorder.filter(kind); g.filter(kind); } /** * ( begin auto-generated from PImage_filter.xml ) * * Filters an image as defined by one of the following modes:<br /><br * />THRESHOLD - converts the image to black and white pixels depending if * they are above or below the threshold defined by the level parameter. * The level must be between 0.0 (black) and 1.0(white). If no level is * specified, 0.5 is used.<br /> * <br /> * GRAY - converts any colors in the image to grayscale equivalents<br /> * <br /> * INVERT - sets each pixel to its inverse value<br /> * <br /> * POSTERIZE - limits each channel of the image to the number of colors * specified as the level parameter<br /> * <br /> * BLUR - executes a Guassian blur with the level parameter specifying the * extent of the blurring. If no level parameter is used, the blur is * equivalent to Guassian blur of radius 1<br /> * <br /> * OPAQUE - sets the alpha channel to entirely opaque<br /> * <br /> * ERODE - reduces the light areas with the amount defined by the level * parameter<br /> * <br /> * DILATE - increases the light areas with the amount defined by the level parameter * * ( end auto-generated ) * * <h3>Advanced</h3> * Method to apply a variety of basic filters to this image. * <P> * <UL> * <LI>filter(BLUR) provides a basic blur. * <LI>filter(GRAY) converts the image to grayscale based on luminance. * <LI>filter(INVERT) will invert the color components in the image. * <LI>filter(OPAQUE) set all the high bits in the image to opaque * <LI>filter(THRESHOLD) converts the image to black and white. * <LI>filter(DILATE) grow white/light areas * <LI>filter(ERODE) shrink white/light areas * </UL> * Luminance conversion code contributed by * <A HREF="http://www.toxi.co.uk">toxi</A> * <P/> * Gaussian blur code contributed by * <A HREF="http://incubator.quasimondo.com">Mario Klingemann</A> * * @webref image:pixels * @brief Converts the image to grayscale or black and white * @usage web_application * @param kind Either THRESHOLD, GRAY, OPAQUE, INVERT, POSTERIZE, BLUR, ERODE, or DILATE * @param param unique for each, see above */ public void filter(int kind, float param) { if (recorder != null) recorder.filter(kind, param); g.filter(kind, param); } /** * ( begin auto-generated from PImage_copy.xml ) * * Copies a region of pixels from one image into another. If the source and * destination regions aren't the same size, it will automatically resize * source pixels to fit the specified target region. No alpha information * is used in the process, however if the source image has an alpha channel * set, it will be copied as well. * <br /><br /> * As of release 0149, this function ignores <b>imageMode()</b>. * * ( end auto-generated ) * * @webref image:pixels * @brief Copies the entire image * @usage web_application * @param sx X coordinate of the source's upper left corner * @param sy Y coordinate of the source's upper left corner * @param sw source image width * @param sh source image height * @param dx X coordinate of the destination's upper left corner * @param dy Y coordinate of the destination's upper left corner * @param dw destination image width * @param dh destination image height * @see PGraphics#alpha(int) * @see PImage#blend(PImage, int, int, int, int, int, int, int, int, int) */ public void copy(int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh) { if (recorder != null) recorder.copy(sx, sy, sw, sh, dx, dy, dw, dh); g.copy(sx, sy, sw, sh, dx, dy, dw, dh); } /** * @param src an image variable referring to the source image. */ public void copy(PImage src, int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh) { if (recorder != null) recorder.copy(src, sx, sy, sw, sh, dx, dy, dw, dh); g.copy(src, sx, sy, sw, sh, dx, dy, dw, dh); } public void blend(int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh, int mode) { if (recorder != null) recorder.blend(sx, sy, sw, sh, dx, dy, dw, dh, mode); g.blend(sx, sy, sw, sh, dx, dy, dw, dh, mode); } /** * ( begin auto-generated from PImage_blend.xml ) * * Blends a region of pixels into the image specified by the <b>img</b> * parameter. These copies utilize full alpha channel support and a choice * of the following modes to blend the colors of source pixels (A) with the * ones of pixels in the destination image (B):<br /> * <br /> * BLEND - linear interpolation of colours: C = A*factor + B<br /> * <br /> * ADD - additive blending with white clip: C = min(A*factor + B, 255)<br /> * <br /> * SUBTRACT - subtractive blending with black clip: C = max(B - A*factor, * 0)<br /> * <br /> * DARKEST - only the darkest colour succeeds: C = min(A*factor, B)<br /> * <br /> * LIGHTEST - only the lightest colour succeeds: C = max(A*factor, B)<br /> * <br /> * DIFFERENCE - subtract colors from underlying image.<br /> * <br /> * EXCLUSION - similar to DIFFERENCE, but less extreme.<br /> * <br /> * MULTIPLY - Multiply the colors, result will always be darker.<br /> * <br /> * SCREEN - Opposite multiply, uses inverse values of the colors.<br /> * <br /> * OVERLAY - A mix of MULTIPLY and SCREEN. Multiplies dark values, * and screens light values.<br /> * <br /> * HARD_LIGHT - SCREEN when greater than 50% gray, MULTIPLY when lower.<br /> * <br /> * SOFT_LIGHT - Mix of DARKEST and LIGHTEST. * Works like OVERLAY, but not as harsh.<br /> * <br /> * DODGE - Lightens light tones and increases contrast, ignores darks. * Called "Color Dodge" in Illustrator and Photoshop.<br /> * <br /> * BURN - Darker areas are applied, increasing contrast, ignores lights. * Called "Color Burn" in Illustrator and Photoshop.<br /> * <br /> * All modes use the alpha information (highest byte) of source image * pixels as the blending factor. If the source and destination regions are * different sizes, the image will be automatically resized to match the * destination size. If the <b>srcImg</b> parameter is not used, the * display window is used as the source image.<br /> * <br /> * As of release 0149, this function ignores <b>imageMode()</b>. * * ( end auto-generated ) * * @webref image:pixels * @brief Copies a pixel or rectangle of pixels using different blending modes * @param src an image variable referring to the source image * @param sx X coordinate of the source's upper left corner * @param sy Y coordinate of the source's upper left corner * @param sw source image width * @param sh source image height * @param dx X coordinate of the destinations's upper left corner * @param dy Y coordinate of the destinations's upper left corner * @param dw destination image width * @param dh destination image height * @param mode Either BLEND, ADD, SUBTRACT, LIGHTEST, DARKEST, DIFFERENCE, EXCLUSION, MULTIPLY, SCREEN, OVERLAY, HARD_LIGHT, SOFT_LIGHT, DODGE, BURN * * @see PApplet#alpha(int) * @see PImage#copy(PImage, int, int, int, int, int, int, int, int) * @see PImage#blendColor(int,int,int) */ public void blend(PImage src, int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh, int mode) { if (recorder != null) recorder.blend(src, sx, sy, sw, sh, dx, dy, dw, dh, mode); g.blend(src, sx, sy, sw, sh, dx, dy, dw, dh, mode); } }
public PImage loadImage(String filename, String extension) { //, Object params) { if (extension == null) { String lower = filename.toLowerCase(); int dot = filename.lastIndexOf('.'); if (dot == -1) { extension = "unknown"; // no extension found } extension = lower.substring(dot + 1); // check for, and strip any parameters on the url, i.e. // filename.jpg?blah=blah&something=that int question = extension.indexOf('?'); if (question != -1) { extension = extension.substring(0, question); } } // just in case. them users will try anything! extension = extension.toLowerCase(); if (extension.equals("tga")) { try { PImage image = loadImageTGA(filename); // if (params != null) { // image.setParams(g, params); // } return image; } catch (IOException e) { e.printStackTrace(); return null; } } if (extension.equals("tif") || extension.equals("tiff")) { byte bytes[] = loadBytes(filename); PImage image = (bytes == null) ? null : PImage.loadTIFF(bytes); // if (params != null) { // image.setParams(g, params); // } return image; } // For jpeg, gif, and png, load them using createImage(), // because the javax.imageio code was found to be much slower. // http://dev.processing.org/bugs/show_bug.cgi?id=392 try { if (extension.equals("jpg") || extension.equals("jpeg") || extension.equals("gif") || extension.equals("png") || extension.equals("unknown")) { byte bytes[] = loadBytes(filename); if (bytes == null) { return null; } else { Image awtImage = Toolkit.getDefaultToolkit().createImage(bytes); PImage image = loadImageMT(awtImage); if (image.width == -1) { System.err.println("The file " + filename + " contains bad image data, or may not be an image."); } // if it's a .gif image, test to see if it has transparency if (extension.equals("gif") || extension.equals("png")) { image.checkAlpha(); } // if (params != null) { // image.setParams(g, params); // } return image; } } } catch (Exception e) { // show error, but move on to the stuff below, see if it'll work e.printStackTrace(); } if (loadImageFormats == null) { loadImageFormats = ImageIO.getReaderFormatNames(); } if (loadImageFormats != null) { for (int i = 0; i < loadImageFormats.length; i++) { if (extension.equals(loadImageFormats[i])) { return loadImageIO(filename); // PImage image = loadImageIO(filename); // if (params != null) { // image.setParams(g, params); // } // return image; } } } // failed, could not load image after all those attempts System.err.println("Could not find a method to load " + filename); return null; } public PImage requestImage(String filename) { // return requestImage(filename, null, null); return requestImage(filename, null); } /** * ( begin auto-generated from requestImage.xml ) * * This function load images on a separate thread so that your sketch does * not freeze while images load during <b>setup()</b>. While the image is * loading, its width and height will be 0. If an error occurs while * loading the image, its width and height will be set to -1. You'll know * when the image has loaded properly because its width and height will be * greater than 0. Asynchronous image loading (particularly when * downloading from a server) can dramatically improve performance.<br /> * <br/> <b>extension</b> parameter is used to determine the image type in * cases where the image filename does not end with a proper extension. * Specify the extension as the second parameter to <b>requestImage()</b>. * * ( end auto-generated ) * * @webref image:loading_displaying * @param filename name of the file to load, can be .gif, .jpg, .tga, or a handful of other image types depending on your platform * @param extension the type of image to load, for example "png", "gif", "jpg" * @see PImage * @see PApplet#loadImage(String, String) */ public PImage requestImage(String filename, String extension) { PImage vessel = createImage(0, 0, ARGB); AsyncImageLoader ail = new AsyncImageLoader(filename, extension, vessel); ail.start(); return vessel; } // /** // * @nowebref // */ // public PImage requestImage(String filename, String extension, Object params) { // PImage vessel = createImage(0, 0, ARGB, params); // AsyncImageLoader ail = // new AsyncImageLoader(filename, extension, vessel); // ail.start(); // return vessel; // } /** * By trial and error, four image loading threads seem to work best when * loading images from online. This is consistent with the number of open * connections that web browsers will maintain. The variable is made public * (however no accessor has been added since it's esoteric) if you really * want to have control over the value used. For instance, when loading local * files, it might be better to only have a single thread (or two) loading * images so that you're disk isn't simply jumping around. */ public int requestImageMax = 4; volatile int requestImageCount; class AsyncImageLoader extends Thread { String filename; String extension; PImage vessel; public AsyncImageLoader(String filename, String extension, PImage vessel) { this.filename = filename; this.extension = extension; this.vessel = vessel; } @Override public void run() { while (requestImageCount == requestImageMax) { try { Thread.sleep(10); } catch (InterruptedException e) { } } requestImageCount++; PImage actual = loadImage(filename, extension); // An error message should have already printed if (actual == null) { vessel.width = -1; vessel.height = -1; } else { vessel.width = actual.width; vessel.height = actual.height; vessel.format = actual.format; vessel.pixels = actual.pixels; } requestImageCount--; } } /** * Load an AWT image synchronously by setting up a MediaTracker for * a single image, and blocking until it has loaded. */ protected PImage loadImageMT(Image awtImage) { MediaTracker tracker = new MediaTracker(this); tracker.addImage(awtImage, 0); try { tracker.waitForAll(); } catch (InterruptedException e) { //e.printStackTrace(); // non-fatal, right? } PImage image = new PImage(awtImage); image.parent = this; return image; } /** * Use Java 1.4 ImageIO methods to load an image. */ protected PImage loadImageIO(String filename) { InputStream stream = createInput(filename); if (stream == null) { System.err.println("The image " + filename + " could not be found."); return null; } try { BufferedImage bi = ImageIO.read(stream); PImage outgoing = new PImage(bi.getWidth(), bi.getHeight()); outgoing.parent = this; bi.getRGB(0, 0, outgoing.width, outgoing.height, outgoing.pixels, 0, outgoing.width); // check the alpha for this image // was gonna call getType() on the image to see if RGB or ARGB, // but it's not actually useful, since gif images will come through // as TYPE_BYTE_INDEXED, which means it'll still have to check for // the transparency. also, would have to iterate through all the other // types and guess whether alpha was in there, so.. just gonna stick // with the old method. outgoing.checkAlpha(); // return the image return outgoing; } catch (Exception e) { e.printStackTrace(); return null; } } /** * Targa image loader for RLE-compressed TGA files. * <p> * Rewritten for 0115 to read/write RLE-encoded targa images. * For 0125, non-RLE encoded images are now supported, along with * images whose y-order is reversed (which is standard for TGA files). */ protected PImage loadImageTGA(String filename) throws IOException { InputStream is = createInput(filename); if (is == null) return null; byte header[] = new byte[18]; int offset = 0; do { int count = is.read(header, offset, header.length - offset); if (count == -1) return null; offset += count; } while (offset < 18); /* header[2] image type code 2 (0x02) - Uncompressed, RGB images. 3 (0x03) - Uncompressed, black and white images. 10 (0x0A) - Runlength encoded RGB images. 11 (0x0B) - Compressed, black and white images. (grayscale?) header[16] is the bit depth (8, 24, 32) header[17] image descriptor (packed bits) 0x20 is 32 = origin upper-left 0x28 is 32 + 8 = origin upper-left + 32 bits 7 6 5 4 3 2 1 0 128 64 32 16 8 4 2 1 */ int format = 0; if (((header[2] == 3) || (header[2] == 11)) && // B&W, plus RLE or not (header[16] == 8) && // 8 bits ((header[17] == 0x8) || (header[17] == 0x28))) { // origin, 32 bit format = ALPHA; } else if (((header[2] == 2) || (header[2] == 10)) && // RGB, RLE or not (header[16] == 24) && // 24 bits ((header[17] == 0x20) || (header[17] == 0))) { // origin format = RGB; } else if (((header[2] == 2) || (header[2] == 10)) && (header[16] == 32) && ((header[17] == 0x8) || (header[17] == 0x28))) { // origin, 32 format = ARGB; } if (format == 0) { System.err.println("Unknown .tga file format for " + filename); //" (" + header[2] + " " + //(header[16] & 0xff) + " " + //hex(header[17], 2) + ")"); return null; } int w = ((header[13] & 0xff) << 8) + (header[12] & 0xff); int h = ((header[15] & 0xff) << 8) + (header[14] & 0xff); PImage outgoing = createImage(w, h, format); // where "reversed" means upper-left corner (normal for most of // the modernized world, but "reversed" for the tga spec) //boolean reversed = (header[17] & 0x20) != 0; // https://github.com/processing/processing/issues/1682 boolean reversed = (header[17] & 0x20) == 0; if ((header[2] == 2) || (header[2] == 3)) { // not RLE encoded if (reversed) { int index = (h-1) * w; switch (format) { case ALPHA: for (int y = h-1; y >= 0; y--) { for (int x = 0; x < w; x++) { outgoing.pixels[index + x] = is.read(); } index -= w; } break; case RGB: for (int y = h-1; y >= 0; y--) { for (int x = 0; x < w; x++) { outgoing.pixels[index + x] = is.read() | (is.read() << 8) | (is.read() << 16) | 0xff000000; } index -= w; } break; case ARGB: for (int y = h-1; y >= 0; y--) { for (int x = 0; x < w; x++) { outgoing.pixels[index + x] = is.read() | (is.read() << 8) | (is.read() << 16) | (is.read() << 24); } index -= w; } } } else { // not reversed int count = w * h; switch (format) { case ALPHA: for (int i = 0; i < count; i++) { outgoing.pixels[i] = is.read(); } break; case RGB: for (int i = 0; i < count; i++) { outgoing.pixels[i] = is.read() | (is.read() << 8) | (is.read() << 16) | 0xff000000; } break; case ARGB: for (int i = 0; i < count; i++) { outgoing.pixels[i] = is.read() | (is.read() << 8) | (is.read() << 16) | (is.read() << 24); } break; } } } else { // header[2] is 10 or 11 int index = 0; int px[] = outgoing.pixels; while (index < px.length) { int num = is.read(); boolean isRLE = (num & 0x80) != 0; if (isRLE) { num -= 127; // (num & 0x7F) + 1 int pixel = 0; switch (format) { case ALPHA: pixel = is.read(); break; case RGB: pixel = 0xFF000000 | is.read() | (is.read() << 8) | (is.read() << 16); //(is.read() << 16) | (is.read() << 8) | is.read(); break; case ARGB: pixel = is.read() | (is.read() << 8) | (is.read() << 16) | (is.read() << 24); break; } for (int i = 0; i < num; i++) { px[index++] = pixel; if (index == px.length) break; } } else { // write up to 127 bytes as uncompressed num += 1; switch (format) { case ALPHA: for (int i = 0; i < num; i++) { px[index++] = is.read(); } break; case RGB: for (int i = 0; i < num; i++) { px[index++] = 0xFF000000 | is.read() | (is.read() << 8) | (is.read() << 16); //(is.read() << 16) | (is.read() << 8) | is.read(); } break; case ARGB: for (int i = 0; i < num; i++) { px[index++] = is.read() | //(is.read() << 24) | (is.read() << 8) | (is.read() << 16) | (is.read() << 24); //(is.read() << 16) | (is.read() << 8) | is.read(); } break; } } } if (!reversed) { int[] temp = new int[w]; for (int y = 0; y < h/2; y++) { int z = (h-1) - y; System.arraycopy(px, y*w, temp, 0, w); System.arraycopy(px, z*w, px, y*w, w); System.arraycopy(temp, 0, px, z*w, w); } } } return outgoing; } ////////////////////////////////////////////////////////////// // DATA I/O // /** // * @webref input:files // * @brief Creates a new XML object // * @param name the name to be given to the root element of the new XML object // * @return an XML object, or null // * @see XML // * @see PApplet#loadXML(String) // * @see PApplet#parseXML(String) // * @see PApplet#saveXML(XML, String) // */ // public XML createXML(String name) { // try { // return new XML(name); // } catch (Exception e) { // e.printStackTrace(); // return null; // } // } /** * @webref input:files * @param filename name of a file in the data folder or a URL. * @see XML * @see PApplet#parseXML(String) * @see PApplet#saveXML(XML, String) * @see PApplet#loadBytes(String) * @see PApplet#loadStrings(String) * @see PApplet#loadTable(String) */ public XML loadXML(String filename) { return loadXML(filename, null); } // version that uses 'options' though there are currently no supported options /** * @nowebref */ public XML loadXML(String filename, String options) { try { return new XML(createReader(filename), options); } catch (Exception e) { e.printStackTrace(); return null; } } /** * @webref input:files * @brief Converts String content to an XML object * @param data the content to be parsed as XML * @return an XML object, or null * @see XML * @see PApplet#loadXML(String) * @see PApplet#saveXML(XML, String) */ public XML parseXML(String xmlString) { return parseXML(xmlString, null); } public XML parseXML(String xmlString, String options) { try { return XML.parse(xmlString, options); } catch (Exception e) { e.printStackTrace(); return null; } } /** * @webref output:files * @param xml the XML object to save to disk * @param filename name of the file to write to * @see XML * @see PApplet#loadXML(String) * @see PApplet#parseXML(String) */ public boolean saveXML(XML xml, String filename) { return saveXML(xml, filename, null); } public boolean saveXML(XML xml, String filename, String options) { return xml.save(saveFile(filename), options); } public JSONObject parseJSONObject(String input) { return new JSONObject(new StringReader(input)); } /** * @webref output:files * @param filename name of a file in the data folder or a URL * @see JSONObject * @see JSONArray * @see PApplet#loadJSONArray(String) * @see PApplet#saveJSONObject(JSONObject, String) * @see PApplet#saveJSONArray(JSONArray, String) */ public JSONObject loadJSONObject(String filename) { return new JSONObject(createReader(filename)); } /** * @webref output:files * @see JSONObject * @see JSONArray * @see PApplet#loadJSONObject(String) * @see PApplet#loadJSONArray(String) * @see PApplet#saveJSONArray(JSONArray, String) */ public boolean saveJSONObject(JSONObject json, String filename) { return saveJSONObject(json, filename, null); } public boolean saveJSONObject(JSONObject json, String filename, String options) { return json.save(saveFile(filename), options); } public JSONArray parseJSONArray(String input) { return new JSONArray(new StringReader(input)); } /** * @webref output:files * @param filename name of a file in the data folder or a URL * @see JSONObject * @see JSONArray * @see PApplet#loadJSONObject(String) * @see PApplet#saveJSONObject(JSONObject, String) * @see PApplet#saveJSONArray(JSONArray, String) */ public JSONArray loadJSONArray(String filename) { return new JSONArray(createReader(filename)); } /** * @webref output:files * @see JSONObject * @see JSONArray * @see PApplet#loadJSONObject(String) * @see PApplet#loadJSONArray(String) * @see PApplet#saveJSONObject(JSONObject, String) */ public boolean saveJSONArray(JSONArray json, String filename) { return saveJSONArray(json, filename, null); } public boolean saveJSONArray(JSONArray json, String filename, String options) { return json.save(saveFile(filename), options); } // /** // * @webref input:files // * @see Table // * @see PApplet#loadTable(String) // * @see PApplet#saveTable(Table, String) // */ // public Table createTable() { // return new Table(); // } /** * @webref input:files * @param filename name of a file in the data folder or a URL. * @see Table * @see PApplet#saveTable(Table, String) * @see PApplet#loadBytes(String) * @see PApplet#loadStrings(String) * @see PApplet#loadXML(String) */ public Table loadTable(String filename) { return loadTable(filename, null); } /** * @param options may contain "header", "tsv", "csv", or "bin" separated by commas */ public Table loadTable(String filename, String options) { try { // String ext = checkExtension(filename); // if (ext != null) { // if (ext.equals("csv") || ext.equals("tsv") || ext.equals("bin")) { // if (options == null) { // options = ext; // } else { // options = ext + "," + options; // } // } // } return new Table(createInput(filename), Table.extensionOptions(true, filename, options)); } catch (IOException e) { e.printStackTrace(); return null; } } /** * @webref input:files * @param table the Table object to save to a file * @param filename the filename to which the Table should be saved * @see Table * @see PApplet#loadTable(String) */ public boolean saveTable(Table table, String filename) { return saveTable(table, filename, null); } /** * @param options can be one of "tsv", "csv", "bin", or "html" */ public boolean saveTable(Table table, String filename, String options) { // String ext = checkExtension(filename); // if (ext != null) { // if (ext.equals("csv") || ext.equals("tsv") || ext.equals("bin") || ext.equals("html")) { // if (options == null) { // options = ext; // } else { // options = ext + "," + options; // } // } // } try { // Figure out location and make sure the target path exists File outputFile = saveFile(filename); // Open a stream and take care of .gz if necessary return table.save(outputFile, options); } catch (IOException e) { e.printStackTrace(); return false; } } ////////////////////////////////////////////////////////////// // FONT I/O /** * ( begin auto-generated from loadFont.xml ) * * Loads a font into a variable of type <b>PFont</b>. To load correctly, * fonts must be located in the data directory of the current sketch. To * create a font to use with Processing, select "Create Font..." from the * Tools menu. This will create a font in the format Processing requires * and also adds it to the current sketch's data directory.<br /> * <br /> * Like <b>loadImage()</b> and other functions that load data, the * <b>loadFont()</b> function should not be used inside <b>draw()</b>, * because it will slow down the sketch considerably, as the font will be * re-loaded from the disk (or network) on each frame.<br /> * <br /> * For most renderers, Processing displays fonts using the .vlw font * format, which uses images for each letter, rather than defining them * through vector data. When <b>hint(ENABLE_NATIVE_FONTS)</b> is used with * the JAVA2D renderer, the native version of a font will be used if it is * installed on the user's machine.<br /> * <br /> * Using <b>createFont()</b> (instead of loadFont) enables vector data to * be used with the JAVA2D (default) renderer setting. This can be helpful * when many font sizes are needed, or when using any renderer based on * JAVA2D, such as the PDF library. * * ( end auto-generated ) * @webref typography:loading_displaying * @param filename name of the font to load * @see PFont * @see PGraphics#textFont(PFont, float) * @see PApplet#createFont(String, float, boolean, char[]) */ public PFont loadFont(String filename) { try { InputStream input = createInput(filename); return new PFont(input); } catch (Exception e) { die("Could not load font " + filename + ". " + "Make sure that the font has been copied " + "to the data folder of your sketch.", e); } return null; } /** * Used by PGraphics to remove the requirement for loading a font! */ protected PFont createDefaultFont(float size) { // Font f = new Font("SansSerif", Font.PLAIN, 12); // println("n: " + f.getName()); // println("fn: " + f.getFontName()); // println("ps: " + f.getPSName()); return createFont("Lucida Sans", size, true, null); } public PFont createFont(String name, float size) { return createFont(name, size, true, null); } public PFont createFont(String name, float size, boolean smooth) { return createFont(name, size, smooth, null); } /** * ( begin auto-generated from createFont.xml ) * * Dynamically converts a font to the format used by Processing from either * a font name that's installed on the computer, or from a .ttf or .otf * file inside the sketches "data" folder. This function is an advanced * feature for precise control. On most occasions you should create fonts * through selecting "Create Font..." from the Tools menu. * <br /><br /> * Use the <b>PFont.list()</b> method to first determine the names for the * fonts recognized by the computer and are compatible with this function. * Because of limitations in Java, not all fonts can be used and some might * work with one operating system and not others. When sharing a sketch * with other people or posting it on the web, you may need to include a * .ttf or .otf version of your font in the data directory of the sketch * because other people might not have the font installed on their * computer. Only fonts that can legally be distributed should be included * with a sketch. * <br /><br /> * The <b>size</b> parameter states the font size you want to generate. The * <b>smooth</b> parameter specifies if the font should be antialiased or * not, and the <b>charset</b> parameter is an array of chars that * specifies the characters to generate. * <br /><br /> * This function creates a bitmapped version of a font in the same manner * as the Create Font tool. It loads a font by name, and converts it to a * series of images based on the size of the font. When possible, the * <b>text()</b> function will use a native font rather than the bitmapped * version created behind the scenes with <b>createFont()</b>. For * instance, when using P2D, the actual native version of the font will be * employed by the sketch, improving drawing quality and performance. With * the P3D renderer, the bitmapped version will be used. While this can * drastically improve speed and appearance, results are poor when * exporting if the sketch does not include the .otf or .ttf file, and the * requested font is not available on the machine running the sketch. * * ( end auto-generated ) * @webref typography:loading_displaying * @param name name of the font to load * @param size point size of the font * @param smooth true for an antialiased font, false for aliased * @param charset array containing characters to be generated * @see PFont * @see PGraphics#textFont(PFont, float) * @see PGraphics#text(String, float, float, float, float, float) * @see PApplet#loadFont(String) */ public PFont createFont(String name, float size, boolean smooth, char charset[]) { String lowerName = name.toLowerCase(); Font baseFont = null; try { InputStream stream = null; if (lowerName.endsWith(".otf") || lowerName.endsWith(".ttf")) { stream = createInput(name); if (stream == null) { System.err.println("The font \"" + name + "\" " + "is missing or inaccessible, make sure " + "the URL is valid or that the file has been " + "added to your sketch and is readable."); return null; } baseFont = Font.createFont(Font.TRUETYPE_FONT, createInput(name)); } else { baseFont = PFont.findFont(name); } return new PFont(baseFont.deriveFont(size), smooth, charset, stream != null); } catch (Exception e) { System.err.println("Problem createFont(" + name + ")"); e.printStackTrace(); return null; } } ////////////////////////////////////////////////////////////// // FILE/FOLDER SELECTION private Frame selectFrame; private Frame selectFrame() { if (frame != null) { selectFrame = frame; } else if (selectFrame == null) { Component comp = getParent(); while (comp != null) { if (comp instanceof Frame) { selectFrame = (Frame) comp; break; } comp = comp.getParent(); } // Who you callin' a hack? if (selectFrame == null) { selectFrame = new Frame(); } } return selectFrame; } /** * Open a platform-specific file chooser dialog to select a file for input. * After the selection is made, the selected File will be passed to the * 'callback' function. If the dialog is closed or canceled, null will be * sent to the function, so that the program is not waiting for additional * input. The callback is necessary because of how threading works. * * <pre> * void setup() { * selectInput("Select a file to process:", "fileSelected"); * } * * void fileSelected(File selection) { * if (selection == null) { * println("Window was closed or the user hit cancel."); * } else { * println("User selected " + fileSeleted.getAbsolutePath()); * } * } * </pre> * * For advanced users, the method must be 'public', which is true for all * methods inside a sketch when run from the PDE, but must explicitly be * set when using Eclipse or other development environments. * * @webref input:files * @param prompt message to the user * @param callback name of the method to be called when the selection is made */ public void selectInput(String prompt, String callback) { selectInput(prompt, callback, null); } public void selectInput(String prompt, String callback, File file) { selectInput(prompt, callback, file, this); } public void selectInput(String prompt, String callback, File file, Object callbackObject) { selectInput(prompt, callback, file, callbackObject, selectFrame()); } static public void selectInput(String prompt, String callbackMethod, File file, Object callbackObject, Frame parent) { selectImpl(prompt, callbackMethod, file, callbackObject, parent, FileDialog.LOAD); } /** * See selectInput() for details. * * @webref output:files * @param prompt message to the user * @param callback name of the method to be called when the selection is made */ public void selectOutput(String prompt, String callback) { selectOutput(prompt, callback, null); } public void selectOutput(String prompt, String callback, File file) { selectOutput(prompt, callback, file, this); } public void selectOutput(String prompt, String callback, File file, Object callbackObject) { selectOutput(prompt, callback, file, callbackObject, selectFrame()); } static public void selectOutput(String prompt, String callbackMethod, File file, Object callbackObject, Frame parent) { selectImpl(prompt, callbackMethod, file, callbackObject, parent, FileDialog.SAVE); } static protected void selectImpl(final String prompt, final String callbackMethod, final File defaultSelection, final Object callbackObject, final Frame parentFrame, final int mode) { EventQueue.invokeLater(new Runnable() { public void run() { File selectedFile = null; if (useNativeSelect) { FileDialog dialog = new FileDialog(parentFrame, prompt, mode); if (defaultSelection != null) { dialog.setDirectory(defaultSelection.getParent()); dialog.setFile(defaultSelection.getName()); } dialog.setVisible(true); String directory = dialog.getDirectory(); String filename = dialog.getFile(); if (filename != null) { selectedFile = new File(directory, filename); } } else { JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle(prompt); if (defaultSelection != null) { chooser.setSelectedFile(defaultSelection); } int result = -1; if (mode == FileDialog.SAVE) { result = chooser.showSaveDialog(parentFrame); } else if (mode == FileDialog.LOAD) { result = chooser.showOpenDialog(parentFrame); } if (result == JFileChooser.APPROVE_OPTION) { selectedFile = chooser.getSelectedFile(); } } selectCallback(selectedFile, callbackMethod, callbackObject); } }); } /** * See selectInput() for details. * * @webref input:files * @param prompt message to the user * @param callback name of the method to be called when the selection is made */ public void selectFolder(String prompt, String callback) { selectFolder(prompt, callback, null); } public void selectFolder(String prompt, String callback, File file) { selectFolder(prompt, callback, file, this); } public void selectFolder(String prompt, String callback, File file, Object callbackObject) { selectFolder(prompt, callback, file, callbackObject, selectFrame()); } static public void selectFolder(final String prompt, final String callbackMethod, final File defaultSelection, final Object callbackObject, final Frame parentFrame) { EventQueue.invokeLater(new Runnable() { public void run() { File selectedFile = null; if (platform == MACOSX && useNativeSelect != false) { FileDialog fileDialog = new FileDialog(parentFrame, prompt, FileDialog.LOAD); System.setProperty("apple.awt.fileDialogForDirectories", "true"); fileDialog.setVisible(true); System.setProperty("apple.awt.fileDialogForDirectories", "false"); String filename = fileDialog.getFile(); if (filename != null) { selectedFile = new File(fileDialog.getDirectory(), fileDialog.getFile()); } } else { JFileChooser fileChooser = new JFileChooser(); fileChooser.setDialogTitle(prompt); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); if (defaultSelection != null) { fileChooser.setSelectedFile(defaultSelection); } int result = fileChooser.showOpenDialog(parentFrame); if (result == JFileChooser.APPROVE_OPTION) { selectedFile = fileChooser.getSelectedFile(); } } selectCallback(selectedFile, callbackMethod, callbackObject); } }); } static private void selectCallback(File selectedFile, String callbackMethod, Object callbackObject) { try { Class<?> callbackClass = callbackObject.getClass(); Method selectMethod = callbackClass.getMethod(callbackMethod, new Class[] { File.class }); selectMethod.invoke(callbackObject, new Object[] { selectedFile }); } catch (IllegalAccessException iae) { System.err.println(callbackMethod + "() must be public"); } catch (InvocationTargetException ite) { ite.printStackTrace(); } catch (NoSuchMethodException nsme) { System.err.println(callbackMethod + "() could not be found"); } } ////////////////////////////////////////////////////////////// // EXTENSIONS /** * Get the compression-free extension for this filename. * @param filename The filename to check * @return an extension, skipping past .gz if it's present */ static public String checkExtension(String filename) { // Don't consider the .gz as part of the name, createInput() // and createOuput() will take care of fixing that up. if (filename.toLowerCase().endsWith(".gz")) { filename = filename.substring(0, filename.length() - 3); } int dotIndex = filename.lastIndexOf('.'); if (dotIndex != -1) { return filename.substring(dotIndex + 1).toLowerCase(); } return null; } ////////////////////////////////////////////////////////////// // READERS AND WRITERS /** * ( begin auto-generated from createReader.xml ) * * Creates a <b>BufferedReader</b> object that can be used to read files * line-by-line as individual <b>String</b> objects. This is the complement * to the <b>createWriter()</b> function. * <br/> <br/> * Starting with Processing release 0134, all files loaded and saved by the * Processing API use UTF-8 encoding. In previous releases, the default * encoding for your platform was used, which causes problems when files * are moved to other platforms. * * ( end auto-generated ) * @webref input:files * @param filename name of the file to be opened * @see BufferedReader * @see PApplet#createWriter(String) * @see PrintWriter */ public BufferedReader createReader(String filename) { try { InputStream is = createInput(filename); if (is == null) { System.err.println(filename + " does not exist or could not be read"); return null; } return createReader(is); } catch (Exception e) { if (filename == null) { System.err.println("Filename passed to reader() was null"); } else { System.err.println("Couldn't create a reader for " + filename); } } return null; } /** * @nowebref */ static public BufferedReader createReader(File file) { try { InputStream is = new FileInputStream(file); if (file.getName().toLowerCase().endsWith(".gz")) { is = new GZIPInputStream(is); } return createReader(is); } catch (Exception e) { if (file == null) { throw new RuntimeException("File passed to createReader() was null"); } else { e.printStackTrace(); throw new RuntimeException("Couldn't create a reader for " + file.getAbsolutePath()); } } //return null; } /** * @nowebref * I want to read lines from a stream. If I have to type the * following lines any more I'm gonna send Sun my medical bills. */ static public BufferedReader createReader(InputStream input) { InputStreamReader isr = null; try { isr = new InputStreamReader(input, "UTF-8"); } catch (UnsupportedEncodingException e) { } // not gonna happen return new BufferedReader(isr); } /** * ( begin auto-generated from createWriter.xml ) * * Creates a new file in the sketch folder, and a <b>PrintWriter</b> object * to write to it. For the file to be made correctly, it should be flushed * and must be closed with its <b>flush()</b> and <b>close()</b> methods * (see above example). * <br/> <br/> * Starting with Processing release 0134, all files loaded and saved by the * Processing API use UTF-8 encoding. In previous releases, the default * encoding for your platform was used, which causes problems when files * are moved to other platforms. * * ( end auto-generated ) * * @webref output:files * @param filename name of the file to be created * @see PrintWriter * @see PApplet#createReader * @see BufferedReader */ public PrintWriter createWriter(String filename) { return createWriter(saveFile(filename)); } /** * @nowebref * I want to print lines to a file. I have RSI from typing these * eight lines of code so many times. */ static public PrintWriter createWriter(File file) { try { createPath(file); // make sure in-between folders exist OutputStream output = new FileOutputStream(file); if (file.getName().toLowerCase().endsWith(".gz")) { output = new GZIPOutputStream(output); } return createWriter(output); } catch (Exception e) { if (file == null) { throw new RuntimeException("File passed to createWriter() was null"); } else { e.printStackTrace(); throw new RuntimeException("Couldn't create a writer for " + file.getAbsolutePath()); } } //return null; } /** * @nowebref * I want to print lines to a file. Why am I always explaining myself? * It's the JavaSoft API engineers who need to explain themselves. */ static public PrintWriter createWriter(OutputStream output) { try { BufferedOutputStream bos = new BufferedOutputStream(output, 8192); OutputStreamWriter osw = new OutputStreamWriter(bos, "UTF-8"); return new PrintWriter(osw); } catch (UnsupportedEncodingException e) { } // not gonna happen return null; } ////////////////////////////////////////////////////////////// // FILE INPUT /** * @deprecated As of release 0136, use createInput() instead. */ public InputStream openStream(String filename) { return createInput(filename); } /** * ( begin auto-generated from createInput.xml ) * * This is a function for advanced programmers to open a Java InputStream. * It's useful if you want to use the facilities provided by PApplet to * easily open files from the data folder or from a URL, but want an * InputStream object so that you can use other parts of Java to take more * control of how the stream is read.<br /> * <br /> * The filename passed in can be:<br /> * - A URL, for instance <b>openStream("http://processing.org/")</b><br /> * - A file in the sketch's <b>data</b> folder<br /> * - The full path to a file to be opened locally (when running as an * application)<br /> * <br /> * If the requested item doesn't exist, null is returned. If not online, * this will also check to see if the user is asking for a file whose name * isn't properly capitalized. If capitalization is different, an error * will be printed to the console. This helps prevent issues that appear * when a sketch is exported to the web, where case sensitivity matters, as * opposed to running from inside the Processing Development Environment on * Windows or Mac OS, where case sensitivity is preserved but ignored.<br /> * <br /> * If the file ends with <b>.gz</b>, the stream will automatically be gzip * decompressed. If you don't want the automatic decompression, use the * related function <b>createInputRaw()</b>. * <br /> * In earlier releases, this function was called <b>openStream()</b>.<br /> * <br /> * * ( end auto-generated ) * * <h3>Advanced</h3> * Simplified method to open a Java InputStream. * <p> * This method is useful if you want to use the facilities provided * by PApplet to easily open things from the data folder or from a URL, * but want an InputStream object so that you can use other Java * methods to take more control of how the stream is read. * <p> * If the requested item doesn't exist, null is returned. * (Prior to 0096, die() would be called, killing the applet) * <p> * For 0096+, the "data" folder is exported intact with subfolders, * and openStream() properly handles subdirectories from the data folder * <p> * If not online, this will also check to see if the user is asking * for a file whose name isn't properly capitalized. This helps prevent * issues when a sketch is exported to the web, where case sensitivity * matters, as opposed to Windows and the Mac OS default where * case sensitivity is preserved but ignored. * <p> * It is strongly recommended that libraries use this method to open * data files, so that the loading sequence is handled in the same way * as functions like loadBytes(), loadImage(), etc. * <p> * The filename passed in can be: * <UL> * <LI>A URL, for instance openStream("http://processing.org/"); * <LI>A file in the sketch's data folder * <LI>Another file to be opened locally (when running as an application) * </UL> * * @webref input:files * @param filename the name of the file to use as input * @see PApplet#createOutput(String) * @see PApplet#selectOutput(String) * @see PApplet#selectInput(String) * */ public InputStream createInput(String filename) { InputStream input = createInputRaw(filename); if ((input != null) && filename.toLowerCase().endsWith(".gz")) { try { return new GZIPInputStream(input); } catch (IOException e) { e.printStackTrace(); return null; } } return input; } /** * Call openStream() without automatic gzip decompression. */ public InputStream createInputRaw(String filename) { InputStream stream = null; if (filename == null) return null; if (filename.length() == 0) { // an error will be called by the parent function //System.err.println("The filename passed to openStream() was empty."); return null; } // safe to check for this as a url first. this will prevent online // access logs from being spammed with GET /sketchfolder/http://blahblah if (filename.contains(":")) { // at least smells like URL try { URL url = new URL(filename); stream = url.openStream(); return stream; } catch (MalformedURLException mfue) { // not a url, that's fine } catch (FileNotFoundException fnfe) { // Java 1.5 likes to throw this when URL not available. (fix for 0119) // http://dev.processing.org/bugs/show_bug.cgi?id=403 } catch (IOException e) { // changed for 0117, shouldn't be throwing exception e.printStackTrace(); //System.err.println("Error downloading from URL " + filename); return null; //throw new RuntimeException("Error downloading from URL " + filename); } } // Moved this earlier than the getResourceAsStream() checks, because // calling getResourceAsStream() on a directory lists its contents. // http://dev.processing.org/bugs/show_bug.cgi?id=716 try { // First see if it's in a data folder. This may fail by throwing // a SecurityException. If so, this whole block will be skipped. File file = new File(dataPath(filename)); if (!file.exists()) { // next see if it's just in the sketch folder file = sketchFile(filename); } if (file.isDirectory()) { return null; } if (file.exists()) { try { // handle case sensitivity check String filePath = file.getCanonicalPath(); String filenameActual = new File(filePath).getName(); // make sure there isn't a subfolder prepended to the name String filenameShort = new File(filename).getName(); // if the actual filename is the same, but capitalized // differently, warn the user. //if (filenameActual.equalsIgnoreCase(filenameShort) && //!filenameActual.equals(filenameShort)) { if (!filenameActual.equals(filenameShort)) { throw new RuntimeException("This file is named " + filenameActual + " not " + filename + ". Rename the file " + "or change your code."); } } catch (IOException e) { } } // if this file is ok, may as well just load it stream = new FileInputStream(file); if (stream != null) return stream; // have to break these out because a general Exception might // catch the RuntimeException being thrown above } catch (IOException ioe) { } catch (SecurityException se) { } // Using getClassLoader() prevents java from converting dots // to slashes or requiring a slash at the beginning. // (a slash as a prefix means that it'll load from the root of // the jar, rather than trying to dig into the package location) ClassLoader cl = getClass().getClassLoader(); // by default, data files are exported to the root path of the jar. // (not the data folder) so check there first. stream = cl.getResourceAsStream("data/" + filename); if (stream != null) { String cn = stream.getClass().getName(); // this is an irritation of sun's java plug-in, which will return // a non-null stream for an object that doesn't exist. like all good // things, this is probably introduced in java 1.5. awesome! // http://dev.processing.org/bugs/show_bug.cgi?id=359 if (!cn.equals("sun.plugin.cache.EmptyInputStream")) { return stream; } } // When used with an online script, also need to check without the // data folder, in case it's not in a subfolder called 'data'. // http://dev.processing.org/bugs/show_bug.cgi?id=389 stream = cl.getResourceAsStream(filename); if (stream != null) { String cn = stream.getClass().getName(); if (!cn.equals("sun.plugin.cache.EmptyInputStream")) { return stream; } } // Finally, something special for the Internet Explorer users. Turns out // that we can't get files that are part of the same folder using the // methods above when using IE, so we have to resort to the old skool // getDocumentBase() from teh applet dayz. 1996, my brotha. try { URL base = getDocumentBase(); if (base != null) { URL url = new URL(base, filename); URLConnection conn = url.openConnection(); return conn.getInputStream(); // if (conn instanceof HttpURLConnection) { // HttpURLConnection httpConnection = (HttpURLConnection) conn; // // test for 401 result (HTTP only) // int responseCode = httpConnection.getResponseCode(); // } } } catch (Exception e) { } // IO or NPE or... // Now try it with a 'data' subfolder. getting kinda desperate for data... try { URL base = getDocumentBase(); if (base != null) { URL url = new URL(base, "data/" + filename); URLConnection conn = url.openConnection(); return conn.getInputStream(); } } catch (Exception e) { } try { // attempt to load from a local file, used when running as // an application, or as a signed applet try { // first try to catch any security exceptions try { stream = new FileInputStream(dataPath(filename)); if (stream != null) return stream; } catch (IOException e2) { } try { stream = new FileInputStream(sketchPath(filename)); if (stream != null) return stream; } catch (Exception e) { } // ignored try { stream = new FileInputStream(filename); if (stream != null) return stream; } catch (IOException e1) { } } catch (SecurityException se) { } // online, whups } catch (Exception e) { //die(e.getMessage(), e); e.printStackTrace(); } return null; } /** * @nowebref */ static public InputStream createInput(File file) { if (file == null) { throw new IllegalArgumentException("File passed to createInput() was null"); } try { InputStream input = new FileInputStream(file); if (file.getName().toLowerCase().endsWith(".gz")) { return new GZIPInputStream(input); } return input; } catch (IOException e) { System.err.println("Could not createInput() for " + file); e.printStackTrace(); return null; } } /** * ( begin auto-generated from loadBytes.xml ) * * Reads the contents of a file or url and places it in a byte array. If a * file is specified, it must be located in the sketch's "data" * directory/folder.<br /> * <br /> * The filename parameter can also be a URL to a file found online. For * security reasons, a Processing sketch found online can only download * files from the same server from which it came. Getting around this * restriction requires a <a * href="http://wiki.processing.org/w/Sign_an_Applet">signed applet</a>. * * ( end auto-generated ) * @webref input:files * @param filename name of a file in the data folder or a URL. * @see PApplet#loadStrings(String) * @see PApplet#saveStrings(String, String[]) * @see PApplet#saveBytes(String, byte[]) * */ public byte[] loadBytes(String filename) { InputStream is = createInput(filename); if (is != null) { byte[] outgoing = loadBytes(is); try { is.close(); } catch (IOException e) { e.printStackTrace(); // shouldn't happen } return outgoing; } System.err.println("The file \"" + filename + "\" " + "is missing or inaccessible, make sure " + "the URL is valid or that the file has been " + "added to your sketch and is readable."); return null; } /** * @nowebref */ static public byte[] loadBytes(InputStream input) { try { BufferedInputStream bis = new BufferedInputStream(input); ByteArrayOutputStream out = new ByteArrayOutputStream(); int c = bis.read(); while (c != -1) { out.write(c); c = bis.read(); } return out.toByteArray(); } catch (IOException e) { e.printStackTrace(); //throw new RuntimeException("Couldn't load bytes from stream"); } return null; } /** * @nowebref */ static public byte[] loadBytes(File file) { InputStream is = createInput(file); return loadBytes(is); } /** * @nowebref */ static public String[] loadStrings(File file) { InputStream is = createInput(file); if (is != null) { String[] outgoing = loadStrings(is); try { is.close(); } catch (IOException e) { e.printStackTrace(); } return outgoing; } return null; } /** * ( begin auto-generated from loadStrings.xml ) * * Reads the contents of a file or url and creates a String array of its * individual lines. If a file is specified, it must be located in the * sketch's "data" directory/folder.<br /> * <br /> * The filename parameter can also be a URL to a file found online. For * security reasons, a Processing sketch found online can only download * files from the same server from which it came. Getting around this * restriction requires a <a * href="http://wiki.processing.org/w/Sign_an_Applet">signed applet</a>. * <br /> * If the file is not available or an error occurs, <b>null</b> will be * returned and an error message will be printed to the console. The error * message does not halt the program, however the null value may cause a * NullPointerException if your code does not check whether the value * returned is null. * <br/> <br/> * Starting with Processing release 0134, all files loaded and saved by the * Processing API use UTF-8 encoding. In previous releases, the default * encoding for your platform was used, which causes problems when files * are moved to other platforms. * * ( end auto-generated ) * * <h3>Advanced</h3> * Load data from a file and shove it into a String array. * <p> * Exceptions are handled internally, when an error, occurs, an * exception is printed to the console and 'null' is returned, * but the program continues running. This is a tradeoff between * 1) showing the user that there was a problem but 2) not requiring * that all i/o code is contained in try/catch blocks, for the sake * of new users (or people who are just trying to get things done * in a "scripting" fashion. If you want to handle exceptions, * use Java methods for I/O. * * @webref input:files * @param filename name of the file or url to load * @see PApplet#loadBytes(String) * @see PApplet#saveStrings(String, String[]) * @see PApplet#saveBytes(String, byte[]) */ public String[] loadStrings(String filename) { InputStream is = createInput(filename); if (is != null) return loadStrings(is); System.err.println("The file \"" + filename + "\" " + "is missing or inaccessible, make sure " + "the URL is valid or that the file has been " + "added to your sketch and is readable."); return null; } /** * @nowebref */ static public String[] loadStrings(InputStream input) { try { BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8")); return loadStrings(reader); } catch (IOException e) { e.printStackTrace(); } return null; } static public String[] loadStrings(BufferedReader reader) { try { String lines[] = new String[100]; int lineCount = 0; String line = null; while ((line = reader.readLine()) != null) { if (lineCount == lines.length) { String temp[] = new String[lineCount << 1]; System.arraycopy(lines, 0, temp, 0, lineCount); lines = temp; } lines[lineCount++] = line; } reader.close(); if (lineCount == lines.length) { return lines; } // resize array to appropriate amount for these lines String output[] = new String[lineCount]; System.arraycopy(lines, 0, output, 0, lineCount); return output; } catch (IOException e) { e.printStackTrace(); //throw new RuntimeException("Error inside loadStrings()"); } return null; } ////////////////////////////////////////////////////////////// // FILE OUTPUT /** * ( begin auto-generated from createOutput.xml ) * * Similar to <b>createInput()</b>, this creates a Java <b>OutputStream</b> * for a given filename or path. The file will be created in the sketch * folder, or in the same folder as an exported application. * <br /><br /> * If the path does not exist, intermediate folders will be created. If an * exception occurs, it will be printed to the console, and <b>null</b> * will be returned. * <br /><br /> * This function is a convenience over the Java approach that requires you * to 1) create a FileOutputStream object, 2) determine the exact file * location, and 3) handle exceptions. Exceptions are handled internally by * the function, which is more appropriate for "sketch" projects. * <br /><br /> * If the output filename ends with <b>.gz</b>, the output will be * automatically GZIP compressed as it is written. * * ( end auto-generated ) * @webref output:files * @param filename name of the file to open * @see PApplet#createInput(String) * @see PApplet#selectOutput() */ public OutputStream createOutput(String filename) { return createOutput(saveFile(filename)); } /** * @nowebref */ static public OutputStream createOutput(File file) { try { createPath(file); // make sure the path exists FileOutputStream fos = new FileOutputStream(file); if (file.getName().toLowerCase().endsWith(".gz")) { return new GZIPOutputStream(fos); } return fos; } catch (IOException e) { e.printStackTrace(); } return null; } /** * ( begin auto-generated from saveStream.xml ) * * Save the contents of a stream to a file in the sketch folder. This is * basically <b>saveBytes(blah, loadBytes())</b>, but done more efficiently * (and with less confusing syntax).<br /> * <br /> * When using the <b>targetFile</b> parameter, it writes to a <b>File</b> * object for greater control over the file location. (Note that unlike * some other functions, this will not automatically compress or uncompress * gzip files.) * * ( end auto-generated ) * * @webref output:files * @param target name of the file to write to * @param source location to read from (a filename, path, or URL) * @see PApplet#createOutput(String) */ public boolean saveStream(String target, String source) { return saveStream(saveFile(target), source); } /** * Identical to the other saveStream(), but writes to a File * object, for greater control over the file location. * <p/> * Note that unlike other api methods, this will not automatically * compress or uncompress gzip files. */ public boolean saveStream(File target, String source) { return saveStream(target, createInputRaw(source)); } /** * @nowebref */ public boolean saveStream(String target, InputStream source) { return saveStream(saveFile(target), source); } /** * @nowebref */ static public boolean saveStream(File target, InputStream source) { File tempFile = null; try { File parentDir = target.getParentFile(); // make sure that this path actually exists before writing createPath(target); tempFile = File.createTempFile(target.getName(), null, parentDir); FileOutputStream targetStream = new FileOutputStream(tempFile); saveStream(targetStream, source); targetStream.close(); targetStream = null; if (target.exists()) { if (!target.delete()) { System.err.println("Could not replace " + target.getAbsolutePath() + "."); } } if (!tempFile.renameTo(target)) { System.err.println("Could not rename temporary file " + tempFile.getAbsolutePath()); return false; } return true; } catch (IOException e) { if (tempFile != null) { tempFile.delete(); } e.printStackTrace(); return false; } } /** * @nowebref */ static public void saveStream(OutputStream target, InputStream source) throws IOException { BufferedInputStream bis = new BufferedInputStream(source, 16384); BufferedOutputStream bos = new BufferedOutputStream(target); byte[] buffer = new byte[8192]; int bytesRead; while ((bytesRead = bis.read(buffer)) != -1) { bos.write(buffer, 0, bytesRead); } bos.flush(); } /** * ( begin auto-generated from saveBytes.xml ) * * Opposite of <b>loadBytes()</b>, will write an entire array of bytes to a * file. The data is saved in binary format. This file is saved to the * sketch's folder, which is opened by selecting "Show sketch folder" from * the "Sketch" menu.<br /> * <br /> * It is not possible to use saveXxxxx() functions inside a web browser * unless the sketch is <a * href="http://wiki.processing.org/w/Sign_an_Applet">signed applet</A>. To * save a file back to a server, see the <a * href="http://wiki.processing.org/w/Saving_files_to_a_web-server">save to * web</A> code snippet on the Processing Wiki. * * ( end auto-generated ) * * @webref output:files * @param filename name of the file to write to * @param data array of bytes to be written * @see PApplet#loadStrings(String) * @see PApplet#loadBytes(String) * @see PApplet#saveStrings(String, String[]) */ public void saveBytes(String filename, byte[] data) { saveBytes(saveFile(filename), data); } /** * @nowebref * Saves bytes to a specific File location specified by the user. */ static public void saveBytes(File file, byte[] data) { File tempFile = null; try { File parentDir = file.getParentFile(); tempFile = File.createTempFile(file.getName(), null, parentDir); OutputStream output = createOutput(tempFile); saveBytes(output, data); output.close(); output = null; if (file.exists()) { if (!file.delete()) { System.err.println("Could not replace " + file.getAbsolutePath()); } } if (!tempFile.renameTo(file)) { System.err.println("Could not rename temporary file " + tempFile.getAbsolutePath()); } } catch (IOException e) { System.err.println("error saving bytes to " + file); if (tempFile != null) { tempFile.delete(); } e.printStackTrace(); } } /** * @nowebref * Spews a buffer of bytes to an OutputStream. */ static public void saveBytes(OutputStream output, byte[] data) { try { output.write(data); output.flush(); } catch (IOException e) { e.printStackTrace(); } } // /** * ( begin auto-generated from saveStrings.xml ) * * Writes an array of strings to a file, one line per string. This file is * saved to the sketch's folder, which is opened by selecting "Show sketch * folder" from the "Sketch" menu.<br /> * <br /> * It is not possible to use saveXxxxx() functions inside a web browser * unless the sketch is <a * href="http://wiki.processing.org/w/Sign_an_Applet">signed applet</A>. To * save a file back to a server, see the <a * href="http://wiki.processing.org/w/Saving_files_to_a_web-server">save to * web</A> code snippet on the Processing Wiki.<br/> * <br/ > * Starting with Processing 1.0, all files loaded and saved by the * Processing API use UTF-8 encoding. In previous releases, the default * encoding for your platform was used, which causes problems when files * are moved to other platforms. * * ( end auto-generated ) * @webref output:files * @param filename filename for output * @param data string array to be written * @see PApplet#loadStrings(String) * @see PApplet#loadBytes(String) * @see PApplet#saveBytes(String, byte[]) */ public void saveStrings(String filename, String data[]) { saveStrings(saveFile(filename), data); } /** * @nowebref */ static public void saveStrings(File file, String data[]) { saveStrings(createOutput(file), data); } /** * @nowebref */ static public void saveStrings(OutputStream output, String[] data) { PrintWriter writer = createWriter(output); for (int i = 0; i < data.length; i++) { writer.println(data[i]); } writer.flush(); writer.close(); } ////////////////////////////////////////////////////////////// /** * Prepend the sketch folder path to the filename (or path) that is * passed in. External libraries should use this function to save to * the sketch folder. * <p/> * Note that when running as an applet inside a web browser, * the sketchPath will be set to null, because security restrictions * prevent applets from accessing that information. * <p/> * This will also cause an error if the sketch is not inited properly, * meaning that init() was never called on the PApplet when hosted * my some other main() or by other code. For proper use of init(), * see the examples in the main description text for PApplet. */ public String sketchPath(String where) { if (sketchPath == null) { return where; // throw new RuntimeException("The applet was not inited properly, " + // "or security restrictions prevented " + // "it from determining its path."); } // isAbsolute() could throw an access exception, but so will writing // to the local disk using the sketch path, so this is safe here. // for 0120, added a try/catch anyways. try { if (new File(where).isAbsolute()) return where; } catch (Exception e) { } return sketchPath + File.separator + where; } public File sketchFile(String where) { return new File(sketchPath(where)); } /** * Returns a path inside the applet folder to save to. Like sketchPath(), * but creates any in-between folders so that things save properly. * <p/> * All saveXxxx() functions use the path to the sketch folder, rather than * its data folder. Once exported, the data folder will be found inside the * jar file of the exported application or applet. In this case, it's not * possible to save data into the jar file, because it will often be running * from a server, or marked in-use if running from a local file system. * With this in mind, saving to the data path doesn't make sense anyway. * If you know you're running locally, and want to save to the data folder, * use <TT>saveXxxx("data/blah.dat")</TT>. */ public String savePath(String where) { if (where == null) return null; String filename = sketchPath(where); createPath(filename); return filename; } /** * Identical to savePath(), but returns a File object. */ public File saveFile(String where) { return new File(savePath(where)); } /** * Return a full path to an item in the data folder. * <p> * This is only available with applications, not applets or Android. * On Windows and Linux, this is simply the data folder, which is located * in the same directory as the EXE file and lib folders. On Mac OS X, this * is a path to the data folder buried inside Contents/Resources/Java. * For the latter point, that also means that the data folder should not be * considered writable. Use sketchPath() for now, or inputPath() and * outputPath() once they're available in the 2.0 release. * <p> * dataPath() is not supported with applets because applets have their data * folder wrapped into the JAR file. To read data from the data folder that * works with an applet, you should use other methods such as createInput(), * createReader(), or loadStrings(). */ public String dataPath(String where) { return dataFile(where).getAbsolutePath(); } /** * Return a full path to an item in the data folder as a File object. * See the dataPath() method for more information. */ public File dataFile(String where) { // isAbsolute() could throw an access exception, but so will writing // to the local disk using the sketch path, so this is safe here. File why = new File(where); if (why.isAbsolute()) return why; String jarPath = getClass().getProtectionDomain().getCodeSource().getLocation().getPath(); if (jarPath.contains("Contents/Resources/Java/")) { // The path will be URL encoded (%20 for spaces) coming from above // http://code.google.com/p/processing/issues/detail?id=1073 File containingFolder = new File(urlDecode(jarPath)).getParentFile(); File dataFolder = new File(containingFolder, "data"); return new File(dataFolder, where); } // Windows, Linux, or when not using a Mac OS X .app file return new File(sketchPath + File.separator + "data" + File.separator + where); } /** * On Windows and Linux, this is simply the data folder. On Mac OS X, this is * the path to the data folder buried inside Contents/Resources/Java */ // public File inputFile(String where) { // } // public String inputPath(String where) { // } /** * Takes a path and creates any in-between folders if they don't * already exist. Useful when trying to save to a subfolder that * may not actually exist. */ static public void createPath(String path) { createPath(new File(path)); } static public void createPath(File file) { try { String parent = file.getParent(); if (parent != null) { File unit = new File(parent); if (!unit.exists()) unit.mkdirs(); } } catch (SecurityException se) { System.err.println("You don't have permissions to create " + file.getAbsolutePath()); } } static public String getExtension(String filename) { String extension; String lower = filename.toLowerCase(); int dot = filename.lastIndexOf('.'); if (dot == -1) { extension = "unknown"; // no extension found } extension = lower.substring(dot + 1); // check for, and strip any parameters on the url, i.e. // filename.jpg?blah=blah&something=that int question = extension.indexOf('?'); if (question != -1) { extension = extension.substring(0, question); } return extension; } ////////////////////////////////////////////////////////////// // URL ENCODING static public String urlEncode(String str) { try { return URLEncoder.encode(str, "UTF-8"); } catch (UnsupportedEncodingException e) { // oh c'mon return null; } } static public String urlDecode(String str) { try { return URLDecoder.decode(str, "UTF-8"); } catch (UnsupportedEncodingException e) { // safe per the JDK source return null; } } ////////////////////////////////////////////////////////////// // SORT /** * ( begin auto-generated from sort.xml ) * * Sorts an array of numbers from smallest to largest and puts an array of * words in alphabetical order. The original array is not modified, a * re-ordered array is returned. The <b>count</b> parameter states the * number of elements to sort. For example if there are 12 elements in an * array and if count is the value 5, only the first five elements on the * array will be sorted. <!--As of release 0126, the alphabetical ordering * is case insensitive.--> * * ( end auto-generated ) * @webref data:array_functions * @param list array to sort * @see PApplet#reverse(boolean[]) */ static public byte[] sort(byte list[]) { return sort(list, list.length); } /** * @param count number of elements to sort, starting from 0 */ static public byte[] sort(byte[] list, int count) { byte[] outgoing = new byte[list.length]; System.arraycopy(list, 0, outgoing, 0, list.length); Arrays.sort(outgoing, 0, count); return outgoing; } static public char[] sort(char list[]) { return sort(list, list.length); } static public char[] sort(char[] list, int count) { char[] outgoing = new char[list.length]; System.arraycopy(list, 0, outgoing, 0, list.length); Arrays.sort(outgoing, 0, count); return outgoing; } static public int[] sort(int list[]) { return sort(list, list.length); } static public int[] sort(int[] list, int count) { int[] outgoing = new int[list.length]; System.arraycopy(list, 0, outgoing, 0, list.length); Arrays.sort(outgoing, 0, count); return outgoing; } static public float[] sort(float list[]) { return sort(list, list.length); } static public float[] sort(float[] list, int count) { float[] outgoing = new float[list.length]; System.arraycopy(list, 0, outgoing, 0, list.length); Arrays.sort(outgoing, 0, count); return outgoing; } static public String[] sort(String list[]) { return sort(list, list.length); } static public String[] sort(String[] list, int count) { String[] outgoing = new String[list.length]; System.arraycopy(list, 0, outgoing, 0, list.length); Arrays.sort(outgoing, 0, count); return outgoing; } ////////////////////////////////////////////////////////////// // ARRAY UTILITIES /** * ( begin auto-generated from arrayCopy.xml ) * * Copies an array (or part of an array) to another array. The <b>src</b> * array is copied to the <b>dst</b> array, beginning at the position * specified by <b>srcPos</b> and into the position specified by * <b>dstPos</b>. The number of elements to copy is determined by * <b>length</b>. The simplified version with two arguments copies an * entire array to another of the same size. It is equivalent to * "arrayCopy(src, 0, dst, 0, src.length)". This function is far more * efficient for copying array data than iterating through a <b>for</b> and * copying each element. * * ( end auto-generated ) * @webref data:array_functions * @param src the source array * @param srcPosition starting position in the source array * @param dst the destination array of the same data type as the source array * @param dstPosition starting position in the destination array * @param length number of array elements to be copied * @see PApplet#concat(boolean[], boolean[]) */ static public void arrayCopy(Object src, int srcPosition, Object dst, int dstPosition, int length) { System.arraycopy(src, srcPosition, dst, dstPosition, length); } /** * Convenience method for arraycopy(). * Identical to <CODE>arraycopy(src, 0, dst, 0, length);</CODE> */ static public void arrayCopy(Object src, Object dst, int length) { System.arraycopy(src, 0, dst, 0, length); } /** * Shortcut to copy the entire contents of * the source into the destination array. * Identical to <CODE>arraycopy(src, 0, dst, 0, src.length);</CODE> */ static public void arrayCopy(Object src, Object dst) { System.arraycopy(src, 0, dst, 0, Array.getLength(src)); } // /** * @deprecated Use arrayCopy() instead. */ static public void arraycopy(Object src, int srcPosition, Object dst, int dstPosition, int length) { System.arraycopy(src, srcPosition, dst, dstPosition, length); } /** * @deprecated Use arrayCopy() instead. */ static public void arraycopy(Object src, Object dst, int length) { System.arraycopy(src, 0, dst, 0, length); } /** * @deprecated Use arrayCopy() instead. */ static public void arraycopy(Object src, Object dst) { System.arraycopy(src, 0, dst, 0, Array.getLength(src)); } /** * ( begin auto-generated from expand.xml ) * * Increases the size of an array. By default, this function doubles the * size of the array, but the optional <b>newSize</b> parameter provides * precise control over the increase in size. * <br/> <br/> * When using an array of objects, the data returned from the function must * be cast to the object array's data type. For example: <em>SomeClass[] * items = (SomeClass[]) expand(originalArray)</em>. * * ( end auto-generated ) * * @webref data:array_functions * @param list the array to expand * @see PApplet#shorten(boolean[]) */ static public boolean[] expand(boolean list[]) { return expand(list, list.length << 1); } /** * @param newSize new size for the array */ static public boolean[] expand(boolean list[], int newSize) { boolean temp[] = new boolean[newSize]; System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } static public byte[] expand(byte list[]) { return expand(list, list.length << 1); } static public byte[] expand(byte list[], int newSize) { byte temp[] = new byte[newSize]; System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } static public char[] expand(char list[]) { return expand(list, list.length << 1); } static public char[] expand(char list[], int newSize) { char temp[] = new char[newSize]; System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } static public int[] expand(int list[]) { return expand(list, list.length << 1); } static public int[] expand(int list[], int newSize) { int temp[] = new int[newSize]; System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } static public long[] expand(long list[]) { return expand(list, list.length << 1); } static public long[] expand(long list[], int newSize) { long temp[] = new long[newSize]; System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } static public float[] expand(float list[]) { return expand(list, list.length << 1); } static public float[] expand(float list[], int newSize) { float temp[] = new float[newSize]; System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } static public double[] expand(double list[]) { return expand(list, list.length << 1); } static public double[] expand(double list[], int newSize) { double temp[] = new double[newSize]; System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } static public String[] expand(String list[]) { return expand(list, list.length << 1); } static public String[] expand(String list[], int newSize) { String temp[] = new String[newSize]; // in case the new size is smaller than list.length System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } /** * @nowebref */ static public Object expand(Object array) { return expand(array, Array.getLength(array) << 1); } static public Object expand(Object list, int newSize) { Class<?> type = list.getClass().getComponentType(); Object temp = Array.newInstance(type, newSize); System.arraycopy(list, 0, temp, 0, Math.min(Array.getLength(list), newSize)); return temp; } // contract() has been removed in revision 0124, use subset() instead. // (expand() is also functionally equivalent) /** * ( begin auto-generated from append.xml ) * * Expands an array by one element and adds data to the new position. The * datatype of the <b>element</b> parameter must be the same as the * datatype of the array. * <br/> <br/> * When using an array of objects, the data returned from the function must * be cast to the object array's data type. For example: <em>SomeClass[] * items = (SomeClass[]) append(originalArray, element)</em>. * * ( end auto-generated ) * * @webref data:array_functions * @param array array to append * @param value new data for the array * @see PApplet#shorten(boolean[]) * @see PApplet#expand(boolean[]) */ static public byte[] append(byte array[], byte value) { array = expand(array, array.length + 1); array[array.length-1] = value; return array; } static public char[] append(char array[], char value) { array = expand(array, array.length + 1); array[array.length-1] = value; return array; } static public int[] append(int array[], int value) { array = expand(array, array.length + 1); array[array.length-1] = value; return array; } static public float[] append(float array[], float value) { array = expand(array, array.length + 1); array[array.length-1] = value; return array; } static public String[] append(String array[], String value) { array = expand(array, array.length + 1); array[array.length-1] = value; return array; } static public Object append(Object array, Object value) { int length = Array.getLength(array); array = expand(array, length + 1); Array.set(array, length, value); return array; } /** * ( begin auto-generated from shorten.xml ) * * Decreases an array by one element and returns the shortened array. * <br/> <br/> * When using an array of objects, the data returned from the function must * be cast to the object array's data type. For example: <em>SomeClass[] * items = (SomeClass[]) shorten(originalArray)</em>. * * ( end auto-generated ) * * @webref data:array_functions * @param list array to shorten * @see PApplet#append(byte[], byte) * @see PApplet#expand(boolean[]) */ static public boolean[] shorten(boolean list[]) { return subset(list, 0, list.length-1); } static public byte[] shorten(byte list[]) { return subset(list, 0, list.length-1); } static public char[] shorten(char list[]) { return subset(list, 0, list.length-1); } static public int[] shorten(int list[]) { return subset(list, 0, list.length-1); } static public float[] shorten(float list[]) { return subset(list, 0, list.length-1); } static public String[] shorten(String list[]) { return subset(list, 0, list.length-1); } static public Object shorten(Object list) { int length = Array.getLength(list); return subset(list, 0, length - 1); } /** * ( begin auto-generated from splice.xml ) * * Inserts a value or array of values into an existing array. The first two * parameters must be of the same datatype. The <b>array</b> parameter * defines the array which will be modified and the second parameter * defines the data which will be inserted. * <br/> <br/> * When using an array of objects, the data returned from the function must * be cast to the object array's data type. For example: <em>SomeClass[] * items = (SomeClass[]) splice(array1, array2, index)</em>. * * ( end auto-generated ) * @webref data:array_functions * @param list array to splice into * @param value value to be spliced in * @param index position in the array from which to insert data * @see PApplet#concat(boolean[], boolean[]) * @see PApplet#subset(boolean[], int, int) */ static final public boolean[] splice(boolean list[], boolean value, int index) { boolean outgoing[] = new boolean[list.length + 1]; System.arraycopy(list, 0, outgoing, 0, index); outgoing[index] = value; System.arraycopy(list, index, outgoing, index + 1, list.length - index); return outgoing; } static final public boolean[] splice(boolean list[], boolean value[], int index) { boolean outgoing[] = new boolean[list.length + value.length]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(value, 0, outgoing, index, value.length); System.arraycopy(list, index, outgoing, index + value.length, list.length - index); return outgoing; } static final public byte[] splice(byte list[], byte value, int index) { byte outgoing[] = new byte[list.length + 1]; System.arraycopy(list, 0, outgoing, 0, index); outgoing[index] = value; System.arraycopy(list, index, outgoing, index + 1, list.length - index); return outgoing; } static final public byte[] splice(byte list[], byte value[], int index) { byte outgoing[] = new byte[list.length + value.length]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(value, 0, outgoing, index, value.length); System.arraycopy(list, index, outgoing, index + value.length, list.length - index); return outgoing; } static final public char[] splice(char list[], char value, int index) { char outgoing[] = new char[list.length + 1]; System.arraycopy(list, 0, outgoing, 0, index); outgoing[index] = value; System.arraycopy(list, index, outgoing, index + 1, list.length - index); return outgoing; } static final public char[] splice(char list[], char value[], int index) { char outgoing[] = new char[list.length + value.length]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(value, 0, outgoing, index, value.length); System.arraycopy(list, index, outgoing, index + value.length, list.length - index); return outgoing; } static final public int[] splice(int list[], int value, int index) { int outgoing[] = new int[list.length + 1]; System.arraycopy(list, 0, outgoing, 0, index); outgoing[index] = value; System.arraycopy(list, index, outgoing, index + 1, list.length - index); return outgoing; } static final public int[] splice(int list[], int value[], int index) { int outgoing[] = new int[list.length + value.length]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(value, 0, outgoing, index, value.length); System.arraycopy(list, index, outgoing, index + value.length, list.length - index); return outgoing; } static final public float[] splice(float list[], float value, int index) { float outgoing[] = new float[list.length + 1]; System.arraycopy(list, 0, outgoing, 0, index); outgoing[index] = value; System.arraycopy(list, index, outgoing, index + 1, list.length - index); return outgoing; } static final public float[] splice(float list[], float value[], int index) { float outgoing[] = new float[list.length + value.length]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(value, 0, outgoing, index, value.length); System.arraycopy(list, index, outgoing, index + value.length, list.length - index); return outgoing; } static final public String[] splice(String list[], String value, int index) { String outgoing[] = new String[list.length + 1]; System.arraycopy(list, 0, outgoing, 0, index); outgoing[index] = value; System.arraycopy(list, index, outgoing, index + 1, list.length - index); return outgoing; } static final public String[] splice(String list[], String value[], int index) { String outgoing[] = new String[list.length + value.length]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(value, 0, outgoing, index, value.length); System.arraycopy(list, index, outgoing, index + value.length, list.length - index); return outgoing; } static final public Object splice(Object list, Object value, int index) { Object[] outgoing = null; int length = Array.getLength(list); // check whether item being spliced in is an array if (value.getClass().getName().charAt(0) == '[') { int vlength = Array.getLength(value); outgoing = new Object[length + vlength]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(value, 0, outgoing, index, vlength); System.arraycopy(list, index, outgoing, index + vlength, length - index); } else { outgoing = new Object[length + 1]; System.arraycopy(list, 0, outgoing, 0, index); Array.set(outgoing, index, value); System.arraycopy(list, index, outgoing, index + 1, length - index); } return outgoing; } static public boolean[] subset(boolean list[], int start) { return subset(list, start, list.length - start); } /** * ( begin auto-generated from subset.xml ) * * Extracts an array of elements from an existing array. The <b>array</b> * parameter defines the array from which the elements will be copied and * the <b>offset</b> and <b>length</b> parameters determine which elements * to extract. If no <b>length</b> is given, elements will be extracted * from the <b>offset</b> to the end of the array. When specifying the * <b>offset</b> remember the first array element is 0. This function does * not change the source array. * <br/> <br/> * When using an array of objects, the data returned from the function must * be cast to the object array's data type. For example: <em>SomeClass[] * items = (SomeClass[]) subset(originalArray, 0, 4)</em>. * * ( end auto-generated ) * @webref data:array_functions * @param list array to extract from * @param start position to begin * @param count number of values to extract * @see PApplet#splice(boolean[], boolean, int) */ static public boolean[] subset(boolean list[], int start, int count) { boolean output[] = new boolean[count]; System.arraycopy(list, start, output, 0, count); return output; } static public byte[] subset(byte list[], int start) { return subset(list, start, list.length - start); } static public byte[] subset(byte list[], int start, int count) { byte output[] = new byte[count]; System.arraycopy(list, start, output, 0, count); return output; } static public char[] subset(char list[], int start) { return subset(list, start, list.length - start); } static public char[] subset(char list[], int start, int count) { char output[] = new char[count]; System.arraycopy(list, start, output, 0, count); return output; } static public int[] subset(int list[], int start) { return subset(list, start, list.length - start); } static public int[] subset(int list[], int start, int count) { int output[] = new int[count]; System.arraycopy(list, start, output, 0, count); return output; } static public float[] subset(float list[], int start) { return subset(list, start, list.length - start); } static public float[] subset(float list[], int start, int count) { float output[] = new float[count]; System.arraycopy(list, start, output, 0, count); return output; } static public String[] subset(String list[], int start) { return subset(list, start, list.length - start); } static public String[] subset(String list[], int start, int count) { String output[] = new String[count]; System.arraycopy(list, start, output, 0, count); return output; } static public Object subset(Object list, int start) { int length = Array.getLength(list); return subset(list, start, length - start); } static public Object subset(Object list, int start, int count) { Class<?> type = list.getClass().getComponentType(); Object outgoing = Array.newInstance(type, count); System.arraycopy(list, start, outgoing, 0, count); return outgoing; } /** * ( begin auto-generated from concat.xml ) * * Concatenates two arrays. For example, concatenating the array { 1, 2, 3 * } and the array { 4, 5, 6 } yields { 1, 2, 3, 4, 5, 6 }. Both parameters * must be arrays of the same datatype. * <br/> <br/> * When using an array of objects, the data returned from the function must * be cast to the object array's data type. For example: <em>SomeClass[] * items = (SomeClass[]) concat(array1, array2)</em>. * * ( end auto-generated ) * @webref data:array_functions * @param a first array to concatenate * @param b second array to concatenate * @see PApplet#splice(boolean[], boolean, int) * @see PApplet#arrayCopy(Object, int, Object, int, int) */ static public boolean[] concat(boolean a[], boolean b[]) { boolean c[] = new boolean[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } static public byte[] concat(byte a[], byte b[]) { byte c[] = new byte[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } static public char[] concat(char a[], char b[]) { char c[] = new char[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } static public int[] concat(int a[], int b[]) { int c[] = new int[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } static public float[] concat(float a[], float b[]) { float c[] = new float[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } static public String[] concat(String a[], String b[]) { String c[] = new String[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } static public Object concat(Object a, Object b) { Class<?> type = a.getClass().getComponentType(); int alength = Array.getLength(a); int blength = Array.getLength(b); Object outgoing = Array.newInstance(type, alength + blength); System.arraycopy(a, 0, outgoing, 0, alength); System.arraycopy(b, 0, outgoing, alength, blength); return outgoing; } // /** * ( begin auto-generated from reverse.xml ) * * Reverses the order of an array. * * ( end auto-generated ) * @webref data:array_functions * @param list booleans[], bytes[], chars[], ints[], floats[], or Strings[] * @see PApplet#sort(String[], int) */ static public boolean[] reverse(boolean list[]) { boolean outgoing[] = new boolean[list.length]; int length1 = list.length - 1; for (int i = 0; i < list.length; i++) { outgoing[i] = list[length1 - i]; } return outgoing; } static public byte[] reverse(byte list[]) { byte outgoing[] = new byte[list.length]; int length1 = list.length - 1; for (int i = 0; i < list.length; i++) { outgoing[i] = list[length1 - i]; } return outgoing; } static public char[] reverse(char list[]) { char outgoing[] = new char[list.length]; int length1 = list.length - 1; for (int i = 0; i < list.length; i++) { outgoing[i] = list[length1 - i]; } return outgoing; } static public int[] reverse(int list[]) { int outgoing[] = new int[list.length]; int length1 = list.length - 1; for (int i = 0; i < list.length; i++) { outgoing[i] = list[length1 - i]; } return outgoing; } static public float[] reverse(float list[]) { float outgoing[] = new float[list.length]; int length1 = list.length - 1; for (int i = 0; i < list.length; i++) { outgoing[i] = list[length1 - i]; } return outgoing; } static public String[] reverse(String list[]) { String outgoing[] = new String[list.length]; int length1 = list.length - 1; for (int i = 0; i < list.length; i++) { outgoing[i] = list[length1 - i]; } return outgoing; } static public Object reverse(Object list) { Class<?> type = list.getClass().getComponentType(); int length = Array.getLength(list); Object outgoing = Array.newInstance(type, length); for (int i = 0; i < length; i++) { Array.set(outgoing, i, Array.get(list, (length - 1) - i)); } return outgoing; } ////////////////////////////////////////////////////////////// // STRINGS /** * ( begin auto-generated from trim.xml ) * * Removes whitespace characters from the beginning and end of a String. In * addition to standard whitespace characters such as space, carriage * return, and tab, this function also removes the Unicode "nbsp" character. * * ( end auto-generated ) * @webref data:string_functions * @param str any string * @see PApplet#split(String, String) * @see PApplet#join(String[], char) */ static public String trim(String str) { return str.replace('\u00A0', ' ').trim(); } /** * @param array a String array */ static public String[] trim(String[] array) { String[] outgoing = new String[array.length]; for (int i = 0; i < array.length; i++) { if (array[i] != null) { outgoing[i] = array[i].replace('\u00A0', ' ').trim(); } } return outgoing; } /** * ( begin auto-generated from join.xml ) * * Combines an array of Strings into one String, each separated by the * character(s) used for the <b>separator</b> parameter. To join arrays of * ints or floats, it's necessary to first convert them to strings using * <b>nf()</b> or <b>nfs()</b>. * * ( end auto-generated ) * @webref data:string_functions * @param list array of Strings * @param separator char or String to be placed between each item * @see PApplet#split(String, String) * @see PApplet#trim(String) * @see PApplet#nf(float, int, int) * @see PApplet#nfs(float, int, int) */ static public String join(String[] list, char separator) { return join(list, String.valueOf(separator)); } static public String join(String[] list, String separator) { StringBuffer buffer = new StringBuffer(); for (int i = 0; i < list.length; i++) { if (i != 0) buffer.append(separator); buffer.append(list[i]); } return buffer.toString(); } static public String[] splitTokens(String value) { return splitTokens(value, WHITESPACE); } /** * ( begin auto-generated from splitTokens.xml ) * * The splitTokens() function splits a String at one or many character * "tokens." The <b>tokens</b> parameter specifies the character or * characters to be used as a boundary. * <br/> <br/> * If no <b>tokens</b> character is specified, any whitespace character is * used to split. Whitespace characters include tab (\\t), line feed (\\n), * carriage return (\\r), form feed (\\f), and space. To convert a String * to an array of integers or floats, use the datatype conversion functions * <b>int()</b> and <b>float()</b> to convert the array of Strings. * * ( end auto-generated ) * @webref data:string_functions * @param value the String to be split * @param delim list of individual characters that will be used as separators * @see PApplet#split(String, String) * @see PApplet#join(String[], String) * @see PApplet#trim(String) */ static public String[] splitTokens(String value, String delim) { StringTokenizer toker = new StringTokenizer(value, delim); String pieces[] = new String[toker.countTokens()]; int index = 0; while (toker.hasMoreTokens()) { pieces[index++] = toker.nextToken(); } return pieces; } /** * ( begin auto-generated from split.xml ) * * The split() function breaks a string into pieces using a character or * string as the divider. The <b>delim</b> parameter specifies the * character or characters that mark the boundaries between each piece. A * String[] array is returned that contains each of the pieces. * <br/> <br/> * If the result is a set of numbers, you can convert the String[] array to * to a float[] or int[] array using the datatype conversion functions * <b>int()</b> and <b>float()</b> (see example above). * <br/> <br/> * The <b>splitTokens()</b> function works in a similar fashion, except * that it splits using a range of characters instead of a specific * character or sequence. * <!-- /><br /> * This function uses regular expressions to determine how the <b>delim</b> * parameter divides the <b>str</b> parameter. Therefore, if you use * characters such parentheses and brackets that are used with regular * expressions as a part of the <b>delim</b> parameter, you'll need to put * two blackslashes (\\\\) in front of the character (see example above). * You can read more about <a * href="http://en.wikipedia.org/wiki/Regular_expression">regular * expressions</a> and <a * href="http://en.wikipedia.org/wiki/Escape_character">escape * characters</a> on Wikipedia. * --> * * ( end auto-generated ) * @webref data:string_functions * @usage web_application * @param value the String to be split * @param delim the character or String used to separate the data */ static public String[] split(String value, char delim) { // do this so that the exception occurs inside the user's // program, rather than appearing to be a bug inside split() if (value == null) return null; //return split(what, String.valueOf(delim)); // huh char chars[] = value.toCharArray(); int splitCount = 0; //1; for (int i = 0; i < chars.length; i++) { if (chars[i] == delim) splitCount++; } // make sure that there is something in the input string //if (chars.length > 0) { // if the last char is a delimeter, get rid of it.. //if (chars[chars.length-1] == delim) splitCount--; // on second thought, i don't agree with this, will disable //} if (splitCount == 0) { String splits[] = new String[1]; splits[0] = new String(value); return splits; } //int pieceCount = splitCount + 1; String splits[] = new String[splitCount + 1]; int splitIndex = 0; int startIndex = 0; for (int i = 0; i < chars.length; i++) { if (chars[i] == delim) { splits[splitIndex++] = new String(chars, startIndex, i-startIndex); startIndex = i + 1; } } //if (startIndex != chars.length) { splits[splitIndex] = new String(chars, startIndex, chars.length-startIndex); //} return splits; } static public String[] split(String value, String delim) { ArrayList<String> items = new ArrayList<String>(); int index; int offset = 0; while ((index = value.indexOf(delim, offset)) != -1) { items.add(value.substring(offset, index)); offset = index + delim.length(); } items.add(value.substring(offset)); String[] outgoing = new String[items.size()]; items.toArray(outgoing); return outgoing; } static protected HashMap<String, Pattern> matchPatterns; static Pattern matchPattern(String regexp) { Pattern p = null; if (matchPatterns == null) { matchPatterns = new HashMap<String, Pattern>(); } else { p = matchPatterns.get(regexp); } if (p == null) { if (matchPatterns.size() == 10) { // Just clear out the match patterns here if more than 10 are being // used. It's not terribly efficient, but changes that you have >10 // different match patterns are very slim, unless you're doing // something really tricky (like custom match() methods), in which // case match() won't be efficient anyway. (And you should just be // using your own Java code.) The alternative is using a queue here, // but that's a silly amount of work for negligible benefit. matchPatterns.clear(); } p = Pattern.compile(regexp, Pattern.MULTILINE | Pattern.DOTALL); matchPatterns.put(regexp, p); } return p; } /** * ( begin auto-generated from match.xml ) * * The match() function is used to apply a regular expression to a piece of * text, and return matching groups (elements found inside parentheses) as * a String array. No match will return null. If no groups are specified in * the regexp, but the sequence matches, an array of length one (with the * matched text as the first element of the array) will be returned.<br /> * <br /> * To use the function, first check to see if the result is null. If the * result is null, then the sequence did not match. If the sequence did * match, an array is returned. * If there are groups (specified by sets of parentheses) in the regexp, * then the contents of each will be returned in the array. * Element [0] of a regexp match returns the entire matching string, and * the match groups start at element [1] (the first group is [1], the * second [2], and so on).<br /> * <br /> * The syntax can be found in the reference for Java's <a * href="http://download.oracle.com/javase/6/docs/api/">Pattern</a> class. * For regular expression syntax, read the <a * href="http://download.oracle.com/javase/tutorial/essential/regex/">Java * Tutorial</a> on the topic. * * ( end auto-generated ) * @webref data:string_functions * @param str the String to be searched * @param regexp the regexp to be used for matching * @see PApplet#matchAll(String, String) * @see PApplet#split(String, String) * @see PApplet#splitTokens(String, String) * @see PApplet#join(String[], String) * @see PApplet#trim(String) */ static public String[] match(String str, String regexp) { Pattern p = matchPattern(regexp); Matcher m = p.matcher(str); if (m.find()) { int count = m.groupCount() + 1; String[] groups = new String[count]; for (int i = 0; i < count; i++) { groups[i] = m.group(i); } return groups; } return null; } /** * ( begin auto-generated from matchAll.xml ) * * This function is used to apply a regular expression to a piece of text, * and return a list of matching groups (elements found inside parentheses) * as a two-dimensional String array. No matches will return null. If no * groups are specified in the regexp, but the sequence matches, a two * dimensional array is still returned, but the second dimension is only of * length one.<br /> * <br /> * To use the function, first check to see if the result is null. If the * result is null, then the sequence did not match at all. If the sequence * did match, a 2D array is returned. If there are groups (specified by * sets of parentheses) in the regexp, then the contents of each will be * returned in the array. * Assuming, a loop with counter variable i, element [i][0] of a regexp * match returns the entire matching string, and the match groups start at * element [i][1] (the first group is [i][1], the second [i][2], and so * on).<br /> * <br /> * The syntax can be found in the reference for Java's <a * href="http://download.oracle.com/javase/6/docs/api/">Pattern</a> class. * For regular expression syntax, read the <a * href="http://download.oracle.com/javase/tutorial/essential/regex/">Java * Tutorial</a> on the topic. * * ( end auto-generated ) * @webref data:string_functions * @param str the String to be searched * @param regexp the regexp to be used for matching * @see PApplet#match(String, String) * @see PApplet#split(String, String) * @see PApplet#splitTokens(String, String) * @see PApplet#join(String[], String) * @see PApplet#trim(String) */ static public String[][] matchAll(String str, String regexp) { Pattern p = matchPattern(regexp); Matcher m = p.matcher(str); ArrayList<String[]> results = new ArrayList<String[]>(); int count = m.groupCount() + 1; while (m.find()) { String[] groups = new String[count]; for (int i = 0; i < count; i++) { groups[i] = m.group(i); } results.add(groups); } if (results.isEmpty()) { return null; } String[][] matches = new String[results.size()][count]; for (int i = 0; i < matches.length; i++) { matches[i] = results.get(i); } return matches; } ////////////////////////////////////////////////////////////// // CASTING FUNCTIONS, INSERTED BY PREPROC /** * Convert a char to a boolean. 'T', 't', and '1' will become the * boolean value true, while 'F', 'f', or '0' will become false. */ /* static final public boolean parseBoolean(char what) { return ((what == 't') || (what == 'T') || (what == '1')); } */ /** * <p>Convert an integer to a boolean. Because of how Java handles upgrading * numbers, this will also cover byte and char (as they will upgrade to * an int without any sort of explicit cast).</p> * <p>The preprocessor will convert boolean(what) to parseBoolean(what).</p> * @return false if 0, true if any other number */ static final public boolean parseBoolean(int what) { return (what != 0); } /* // removed because this makes no useful sense static final public boolean parseBoolean(float what) { return (what != 0); } */ /** * Convert the string "true" or "false" to a boolean. * @return true if 'what' is "true" or "TRUE", false otherwise */ static final public boolean parseBoolean(String what) { return new Boolean(what).booleanValue(); } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /* // removed, no need to introduce strange syntax from other languages static final public boolean[] parseBoolean(char what[]) { boolean outgoing[] = new boolean[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = ((what[i] == 't') || (what[i] == 'T') || (what[i] == '1')); } return outgoing; } */ /** * Convert a byte array to a boolean array. Each element will be * evaluated identical to the integer case, where a byte equal * to zero will return false, and any other value will return true. * @return array of boolean elements */ /* static final public boolean[] parseBoolean(byte what[]) { boolean outgoing[] = new boolean[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (what[i] != 0); } return outgoing; } */ /** * Convert an int array to a boolean array. An int equal * to zero will return false, and any other value will return true. * @return array of boolean elements */ static final public boolean[] parseBoolean(int what[]) { boolean outgoing[] = new boolean[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (what[i] != 0); } return outgoing; } /* // removed, not necessary... if necessary, convert to int array first static final public boolean[] parseBoolean(float what[]) { boolean outgoing[] = new boolean[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (what[i] != 0); } return outgoing; } */ static final public boolean[] parseBoolean(String what[]) { boolean outgoing[] = new boolean[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = new Boolean(what[i]).booleanValue(); } return outgoing; } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static final public byte parseByte(boolean what) { return what ? (byte)1 : 0; } static final public byte parseByte(char what) { return (byte) what; } static final public byte parseByte(int what) { return (byte) what; } static final public byte parseByte(float what) { return (byte) what; } /* // nixed, no precedent static final public byte[] parseByte(String what) { // note: array[] return what.getBytes(); } */ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static final public byte[] parseByte(boolean what[]) { byte outgoing[] = new byte[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = what[i] ? (byte)1 : 0; } return outgoing; } static final public byte[] parseByte(char what[]) { byte outgoing[] = new byte[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (byte) what[i]; } return outgoing; } static final public byte[] parseByte(int what[]) { byte outgoing[] = new byte[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (byte) what[i]; } return outgoing; } static final public byte[] parseByte(float what[]) { byte outgoing[] = new byte[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (byte) what[i]; } return outgoing; } /* static final public byte[][] parseByte(String what[]) { // note: array[][] byte outgoing[][] = new byte[what.length][]; for (int i = 0; i < what.length; i++) { outgoing[i] = what[i].getBytes(); } return outgoing; } */ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /* static final public char parseChar(boolean what) { // 0/1 or T/F ? return what ? 't' : 'f'; } */ static final public char parseChar(byte what) { return (char) (what & 0xff); } static final public char parseChar(int what) { return (char) what; } /* static final public char parseChar(float what) { // nonsensical return (char) what; } static final public char[] parseChar(String what) { // note: array[] return what.toCharArray(); } */ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /* static final public char[] parseChar(boolean what[]) { // 0/1 or T/F ? char outgoing[] = new char[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = what[i] ? 't' : 'f'; } return outgoing; } */ static final public char[] parseChar(byte what[]) { char outgoing[] = new char[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (char) (what[i] & 0xff); } return outgoing; } static final public char[] parseChar(int what[]) { char outgoing[] = new char[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (char) what[i]; } return outgoing; } /* static final public char[] parseChar(float what[]) { // nonsensical char outgoing[] = new char[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (char) what[i]; } return outgoing; } static final public char[][] parseChar(String what[]) { // note: array[][] char outgoing[][] = new char[what.length][]; for (int i = 0; i < what.length; i++) { outgoing[i] = what[i].toCharArray(); } return outgoing; } */ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static final public int parseInt(boolean what) { return what ? 1 : 0; } /** * Note that parseInt() will un-sign a signed byte value. */ static final public int parseInt(byte what) { return what & 0xff; } /** * Note that parseInt('5') is unlike String in the sense that it * won't return 5, but the ascii value. This is because ((int) someChar) * returns the ascii value, and parseInt() is just longhand for the cast. */ static final public int parseInt(char what) { return what; } /** * Same as floor(), or an (int) cast. */ static final public int parseInt(float what) { return (int) what; } /** * Parse a String into an int value. Returns 0 if the value is bad. */ static final public int parseInt(String what) { return parseInt(what, 0); } /** * Parse a String to an int, and provide an alternate value that * should be used when the number is invalid. */ static final public int parseInt(String what, int otherwise) { try { int offset = what.indexOf('.'); if (offset == -1) { return Integer.parseInt(what); } else { return Integer.parseInt(what.substring(0, offset)); } } catch (NumberFormatException e) { } return otherwise; } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static final public int[] parseInt(boolean what[]) { int list[] = new int[what.length]; for (int i = 0; i < what.length; i++) { list[i] = what[i] ? 1 : 0; } return list; } static final public int[] parseInt(byte what[]) { // note this unsigns int list[] = new int[what.length]; for (int i = 0; i < what.length; i++) { list[i] = (what[i] & 0xff); } return list; } static final public int[] parseInt(char what[]) { int list[] = new int[what.length]; for (int i = 0; i < what.length; i++) { list[i] = what[i]; } return list; } static public int[] parseInt(float what[]) { int inties[] = new int[what.length]; for (int i = 0; i < what.length; i++) { inties[i] = (int)what[i]; } return inties; } /** * Make an array of int elements from an array of String objects. * If the String can't be parsed as a number, it will be set to zero. * * String s[] = { "1", "300", "44" }; * int numbers[] = parseInt(s); * * numbers will contain { 1, 300, 44 } */ static public int[] parseInt(String what[]) { return parseInt(what, 0); } /** * Make an array of int elements from an array of String objects. * If the String can't be parsed as a number, its entry in the * array will be set to the value of the "missing" parameter. * * String s[] = { "1", "300", "apple", "44" }; * int numbers[] = parseInt(s, 9999); * * numbers will contain { 1, 300, 9999, 44 } */ static public int[] parseInt(String what[], int missing) { int output[] = new int[what.length]; for (int i = 0; i < what.length; i++) { try { output[i] = Integer.parseInt(what[i]); } catch (NumberFormatException e) { output[i] = missing; } } return output; } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /* static final public float parseFloat(boolean what) { return what ? 1 : 0; } */ /** * Convert an int to a float value. Also handles bytes because of * Java's rules for upgrading values. */ static final public float parseFloat(int what) { // also handles byte return what; } static final public float parseFloat(String what) { return parseFloat(what, Float.NaN); } static final public float parseFloat(String what, float otherwise) { try { return new Float(what).floatValue(); } catch (NumberFormatException e) { } return otherwise; } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /* static final public float[] parseFloat(boolean what[]) { float floaties[] = new float[what.length]; for (int i = 0; i < what.length; i++) { floaties[i] = what[i] ? 1 : 0; } return floaties; } static final public float[] parseFloat(char what[]) { float floaties[] = new float[what.length]; for (int i = 0; i < what.length; i++) { floaties[i] = (char) what[i]; } return floaties; } */ static final public float[] parseByte(byte what[]) { float floaties[] = new float[what.length]; for (int i = 0; i < what.length; i++) { floaties[i] = what[i]; } return floaties; } static final public float[] parseFloat(int what[]) { float floaties[] = new float[what.length]; for (int i = 0; i < what.length; i++) { floaties[i] = what[i]; } return floaties; } static final public float[] parseFloat(String what[]) { return parseFloat(what, Float.NaN); } static final public float[] parseFloat(String what[], float missing) { float output[] = new float[what.length]; for (int i = 0; i < what.length; i++) { try { output[i] = new Float(what[i]).floatValue(); } catch (NumberFormatException e) { output[i] = missing; } } return output; } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static final public String str(boolean x) { return String.valueOf(x); } static final public String str(byte x) { return String.valueOf(x); } static final public String str(char x) { return String.valueOf(x); } static final public String str(int x) { return String.valueOf(x); } static final public String str(float x) { return String.valueOf(x); } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static final public String[] str(boolean x[]) { String s[] = new String[x.length]; for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]); return s; } static final public String[] str(byte x[]) { String s[] = new String[x.length]; for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]); return s; } static final public String[] str(char x[]) { String s[] = new String[x.length]; for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]); return s; } static final public String[] str(int x[]) { String s[] = new String[x.length]; for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]); return s; } static final public String[] str(float x[]) { String s[] = new String[x.length]; for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]); return s; } ////////////////////////////////////////////////////////////// // INT NUMBER FORMATTING /** * Integer number formatter. */ static private NumberFormat int_nf; static private int int_nf_digits; static private boolean int_nf_commas; static public String[] nf(int num[], int digits) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nf(num[i], digits); } return formatted; } /** * ( begin auto-generated from nf.xml ) * * Utility function for formatting numbers into strings. There are two * versions, one for formatting floats and one for formatting ints. The * values for the <b>digits</b>, <b>left</b>, and <b>right</b> parameters * should always be positive integers.<br /><br />As shown in the above * example, <b>nf()</b> is used to add zeros to the left and/or right of a * number. This is typically for aligning a list of numbers. To * <em>remove</em> digits from a floating-point number, use the * <b>int()</b>, <b>ceil()</b>, <b>floor()</b>, or <b>round()</b> * functions. * * ( end auto-generated ) * @webref data:string_functions * @param num the number(s) to format * @param digits number of digits to pad with zero * @see PApplet#nfs(float, int, int) * @see PApplet#nfp(float, int, int) * @see PApplet#nfc(float, int) * @see PApplet#int(float) */ static public String nf(int num, int digits) { if ((int_nf != null) && (int_nf_digits == digits) && !int_nf_commas) { return int_nf.format(num); } int_nf = NumberFormat.getInstance(); int_nf.setGroupingUsed(false); // no commas int_nf_commas = false; int_nf.setMinimumIntegerDigits(digits); int_nf_digits = digits; return int_nf.format(num); } /** * ( begin auto-generated from nfc.xml ) * * Utility function for formatting numbers into strings and placing * appropriate commas to mark units of 1000. There are two versions, one * for formatting ints and one for formatting an array of ints. The value * for the <b>digits</b> parameter should always be a positive integer. * <br/> <br/> * For a non-US locale, this will insert periods instead of commas, or * whatever is apprioriate for that region. * * ( end auto-generated ) * @webref data:string_functions * @param num the number(s) to format * @see PApplet#nf(float, int, int) * @see PApplet#nfp(float, int, int) * @see PApplet#nfc(float, int) */ static public String[] nfc(int num[]) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nfc(num[i]); } return formatted; } /** * nfc() or "number format with commas". This is an unfortunate misnomer * because in locales where a comma is not the separator for numbers, it * won't actually be outputting a comma, it'll use whatever makes sense for * the locale. */ static public String nfc(int num) { if ((int_nf != null) && (int_nf_digits == 0) && int_nf_commas) { return int_nf.format(num); } int_nf = NumberFormat.getInstance(); int_nf.setGroupingUsed(true); int_nf_commas = true; int_nf.setMinimumIntegerDigits(0); int_nf_digits = 0; return int_nf.format(num); } /** * number format signed (or space) * Formats a number but leaves a blank space in the front * when it's positive so that it can be properly aligned with * numbers that have a negative sign in front of them. */ /** * ( begin auto-generated from nfs.xml ) * * Utility function for formatting numbers into strings. Similar to * <b>nf()</b> but leaves a blank space in front of positive numbers so * they align with negative numbers in spite of the minus symbol. There are * two versions, one for formatting floats and one for formatting ints. The * values for the <b>digits</b>, <b>left</b>, and <b>right</b> parameters * should always be positive integers. * * ( end auto-generated ) * @webref data:string_functions * @param num the number(s) to format * @param digits number of digits to pad with zeroes * @see PApplet#nf(float, int, int) * @see PApplet#nfp(float, int, int) * @see PApplet#nfc(float, int) */ static public String nfs(int num, int digits) { return (num < 0) ? nf(num, digits) : (' ' + nf(num, digits)); } static public String[] nfs(int num[], int digits) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nfs(num[i], digits); } return formatted; } // /** * number format positive (or plus) * Formats a number, always placing a - or + sign * in the front when it's negative or positive. */ /** * ( begin auto-generated from nfp.xml ) * * Utility function for formatting numbers into strings. Similar to * <b>nf()</b> but puts a "+" in front of positive numbers and a "-" in * front of negative numbers. There are two versions, one for formatting * floats and one for formatting ints. The values for the <b>digits</b>, * <b>left</b>, and <b>right</b> parameters should always be positive integers. * * ( end auto-generated ) * @webref data:string_functions * @param num the number(s) to format * @param digits number of digits to pad with zeroes * @see PApplet#nf(float, int, int) * @see PApplet#nfs(float, int, int) * @see PApplet#nfc(float, int) */ static public String nfp(int num, int digits) { return (num < 0) ? nf(num, digits) : ('+' + nf(num, digits)); } static public String[] nfp(int num[], int digits) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nfp(num[i], digits); } return formatted; } ////////////////////////////////////////////////////////////// // FLOAT NUMBER FORMATTING static private NumberFormat float_nf; static private int float_nf_left, float_nf_right; static private boolean float_nf_commas; static public String[] nf(float num[], int left, int right) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nf(num[i], left, right); } return formatted; } /** * @param num[] the number(s) to format * @param left number of digits to the left of the decimal point * @param right number of digits to the right of the decimal point */ static public String nf(float num, int left, int right) { if ((float_nf != null) && (float_nf_left == left) && (float_nf_right == right) && !float_nf_commas) { return float_nf.format(num); } float_nf = NumberFormat.getInstance(); float_nf.setGroupingUsed(false); float_nf_commas = false; if (left != 0) float_nf.setMinimumIntegerDigits(left); if (right != 0) { float_nf.setMinimumFractionDigits(right); float_nf.setMaximumFractionDigits(right); } float_nf_left = left; float_nf_right = right; return float_nf.format(num); } /** * @param num[] the number(s) to format * @param right number of digits to the right of the decimal point */ static public String[] nfc(float num[], int right) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nfc(num[i], right); } return formatted; } static public String nfc(float num, int right) { if ((float_nf != null) && (float_nf_left == 0) && (float_nf_right == right) && float_nf_commas) { return float_nf.format(num); } float_nf = NumberFormat.getInstance(); float_nf.setGroupingUsed(true); float_nf_commas = true; if (right != 0) { float_nf.setMinimumFractionDigits(right); float_nf.setMaximumFractionDigits(right); } float_nf_left = 0; float_nf_right = right; return float_nf.format(num); } /** * @param num[] the number(s) to format * @param left the number of digits to the left of the decimal point * @param right the number of digits to the right of the decimal point */ static public String[] nfs(float num[], int left, int right) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nfs(num[i], left, right); } return formatted; } static public String nfs(float num, int left, int right) { return (num < 0) ? nf(num, left, right) : (' ' + nf(num, left, right)); } /** * @param left the number of digits to the left of the decimal point * @param right the number of digits to the right of the decimal point */ static public String[] nfp(float num[], int left, int right) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nfp(num[i], left, right); } return formatted; } static public String nfp(float num, int left, int right) { return (num < 0) ? nf(num, left, right) : ('+' + nf(num, left, right)); } ////////////////////////////////////////////////////////////// // HEX/BINARY CONVERSION /** * ( begin auto-generated from hex.xml ) * * Converts a byte, char, int, or color to a String containing the * equivalent hexadecimal notation. For example color(0, 102, 153) will * convert to the String "FF006699". This function can help make your geeky * debugging sessions much happier. * <br/> <br/> * Note that the maximum number of digits is 8, because an int value can * only represent up to 32 bits. Specifying more than eight digits will * simply shorten the string to eight anyway. * * ( end auto-generated ) * @webref data:conversion * @param value the value to convert * @see PApplet#unhex(String) * @see PApplet#binary(byte) * @see PApplet#unbinary(String) */ static final public String hex(byte value) { return hex(value, 2); } static final public String hex(char value) { return hex(value, 4); } static final public String hex(int value) { return hex(value, 8); } /** * @param digits the number of digits (maximum 8) */ static final public String hex(int value, int digits) { String stuff = Integer.toHexString(value).toUpperCase(); if (digits > 8) { digits = 8; } int length = stuff.length(); if (length > digits) { return stuff.substring(length - digits); } else if (length < digits) { return "00000000".substring(8 - (digits-length)) + stuff; } return stuff; } /** * ( begin auto-generated from unhex.xml ) * * Converts a String representation of a hexadecimal number to its * equivalent integer value. * * ( end auto-generated ) * * @webref data:conversion * @param value String to convert to an integer * @see PApplet#hex(int, int) * @see PApplet#binary(byte) * @see PApplet#unbinary(String) */ static final public int unhex(String value) { // has to parse as a Long so that it'll work for numbers bigger than 2^31 return (int) (Long.parseLong(value, 16)); } // /** * Returns a String that contains the binary value of a byte. * The returned value will always have 8 digits. */ static final public String binary(byte value) { return binary(value, 8); } /** * Returns a String that contains the binary value of a char. * The returned value will always have 16 digits because chars * are two bytes long. */ static final public String binary(char value) { return binary(value, 16); } /** * Returns a String that contains the binary value of an int. The length * depends on the size of the number itself. If you want a specific number * of digits use binary(int what, int digits) to specify how many. */ static final public String binary(int value) { return binary(value, 32); } /* * Returns a String that contains the binary value of an int. * The digits parameter determines how many digits will be used. */ /** * ( begin auto-generated from binary.xml ) * * Converts a byte, char, int, or color to a String containing the * equivalent binary notation. For example color(0, 102, 153, 255) will * convert to the String "11111111000000000110011010011001". This function * can help make your geeky debugging sessions much happier. * <br/> <br/> * Note that the maximum number of digits is 32, because an int value can * only represent up to 32 bits. Specifying more than 32 digits will simply * shorten the string to 32 anyway. * * ( end auto-generated ) * @webref data:conversion * @param value value to convert * @param digits number of digits to return * @see PApplet#unbinary(String) * @see PApplet#hex(int,int) * @see PApplet#unhex(String) */ static final public String binary(int value, int digits) { String stuff = Integer.toBinaryString(value); if (digits > 32) { digits = 32; } int length = stuff.length(); if (length > digits) { return stuff.substring(length - digits); } else if (length < digits) { int offset = 32 - (digits-length); return "00000000000000000000000000000000".substring(offset) + stuff; } return stuff; } /** * ( begin auto-generated from unbinary.xml ) * * Converts a String representation of a binary number to its equivalent * integer value. For example, unbinary("00001000") will return 8. * * ( end auto-generated ) * @webref data:conversion * @param value String to convert to an integer * @see PApplet#binary(byte) * @see PApplet#hex(int,int) * @see PApplet#unhex(String) */ static final public int unbinary(String value) { return Integer.parseInt(value, 2); } ////////////////////////////////////////////////////////////// // COLOR FUNCTIONS // moved here so that they can work without // the graphics actually being instantiated (outside setup) /** * ( begin auto-generated from color.xml ) * * Creates colors for storing in variables of the <b>color</b> datatype. * The parameters are interpreted as RGB or HSB values depending on the * current <b>colorMode()</b>. The default mode is RGB values from 0 to 255 * and therefore, the function call <b>color(255, 204, 0)</b> will return a * bright yellow color. More about how colors are stored can be found in * the reference for the <a href="color_datatype.html">color</a> datatype. * * ( end auto-generated ) * @webref color:creating_reading * @param gray number specifying value between white and black * @see PApplet#colorMode(int) */ public final int color(int gray) { if (g == null) { if (gray > 255) gray = 255; else if (gray < 0) gray = 0; return 0xff000000 | (gray << 16) | (gray << 8) | gray; } return g.color(gray); } /** * @nowebref * @param fgray number specifying value between white and black */ public final int color(float fgray) { if (g == null) { int gray = (int) fgray; if (gray > 255) gray = 255; else if (gray < 0) gray = 0; return 0xff000000 | (gray << 16) | (gray << 8) | gray; } return g.color(fgray); } /** * As of 0116 this also takes color(#FF8800, alpha) * @param alpha relative to current color range */ public final int color(int gray, int alpha) { if (g == null) { if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0; if (gray > 255) { // then assume this is actually a #FF8800 return (alpha << 24) | (gray & 0xFFFFFF); } else { //if (gray > 255) gray = 255; else if (gray < 0) gray = 0; return (alpha << 24) | (gray << 16) | (gray << 8) | gray; } } return g.color(gray, alpha); } /** * @nowebref */ public final int color(float fgray, float falpha) { if (g == null) { int gray = (int) fgray; int alpha = (int) falpha; if (gray > 255) gray = 255; else if (gray < 0) gray = 0; if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0; return 0xff000000 | (gray << 16) | (gray << 8) | gray; } return g.color(fgray, falpha); } /** * @param v1 red or hue values relative to the current color range * @param v2 green or saturation values relative to the current color range * @param v3 blue or brightness values relative to the current color range */ public final int color(int v1, int v2, int v3) { if (g == null) { if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0; if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0; if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0; return 0xff000000 | (v1 << 16) | (v2 << 8) | v3; } return g.color(v1, v2, v3); } public final int color(int v1, int v2, int v3, int alpha) { if (g == null) { if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0; if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0; if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0; if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0; return (alpha << 24) | (v1 << 16) | (v2 << 8) | v3; } return g.color(v1, v2, v3, alpha); } public final int color(float v1, float v2, float v3) { if (g == null) { if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0; if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0; if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0; return 0xff000000 | ((int)v1 << 16) | ((int)v2 << 8) | (int)v3; } return g.color(v1, v2, v3); } public final int color(float v1, float v2, float v3, float alpha) { if (g == null) { if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0; if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0; if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0; if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0; return ((int)alpha << 24) | ((int)v1 << 16) | ((int)v2 << 8) | (int)v3; } return g.color(v1, v2, v3, alpha); } static public int blendColor(int c1, int c2, int mode) { return PImage.blendColor(c1, c2, mode); } ////////////////////////////////////////////////////////////// // MAIN /** * Set this sketch to communicate its state back to the PDE. * <p/> * This uses the stderr stream to write positions of the window * (so that it will be saved by the PDE for the next run) and * notify on quit. See more notes in the Worker class. */ public void setupExternalMessages() { frame.addComponentListener(new ComponentAdapter() { @Override public void componentMoved(ComponentEvent e) { Point where = ((Frame) e.getSource()).getLocation(); System.err.println(PApplet.EXTERNAL_MOVE + " " + where.x + " " + where.y); System.err.flush(); // doesn't seem to help or hurt } }); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { // System.err.println(PApplet.EXTERNAL_QUIT); // System.err.flush(); // important // System.exit(0); exit(); // don't quit, need to just shut everything down (0133) } }); } /** * Set up a listener that will fire proper component resize events * in cases where frame.setResizable(true) is called. */ public void setupFrameResizeListener() { frame.addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { // Ignore bad resize events fired during setup to fix // http://dev.processing.org/bugs/show_bug.cgi?id=341 // This should also fix the blank screen on Linux bug // http://dev.processing.org/bugs/show_bug.cgi?id=282 if (frame.isResizable()) { // might be multiple resize calls before visible (i.e. first // when pack() is called, then when it's resized for use). // ignore them because it's not the user resizing things. Frame farm = (Frame) e.getComponent(); if (farm.isVisible()) { Insets insets = farm.getInsets(); Dimension windowSize = farm.getSize(); Rectangle newBounds = new Rectangle(insets.left, insets.top, windowSize.width - insets.left - insets.right, windowSize.height - insets.top - insets.bottom); Rectangle oldBounds = getBounds(); if (!newBounds.equals(oldBounds)) { // the ComponentListener in PApplet will handle calling size() setBounds(newBounds); } } } } }); } // /** // * GIF image of the Processing logo. // */ // static public final byte[] ICON_IMAGE = { // 71, 73, 70, 56, 57, 97, 16, 0, 16, 0, -77, 0, 0, 0, 0, 0, -1, -1, -1, 12, // 12, 13, -15, -15, -14, 45, 57, 74, 54, 80, 111, 47, 71, 97, 62, 88, 117, // 1, 14, 27, 7, 41, 73, 15, 52, 85, 2, 31, 55, 4, 54, 94, 18, 69, 109, 37, // 87, 126, -1, -1, -1, 33, -7, 4, 1, 0, 0, 15, 0, 44, 0, 0, 0, 0, 16, 0, 16, // 0, 0, 4, 122, -16, -107, 114, -86, -67, 83, 30, -42, 26, -17, -100, -45, // 56, -57, -108, 48, 40, 122, -90, 104, 67, -91, -51, 32, -53, 77, -78, -100, // 47, -86, 12, 76, -110, -20, -74, -101, 97, -93, 27, 40, 20, -65, 65, 48, // -111, 99, -20, -112, -117, -123, -47, -105, 24, 114, -112, 74, 69, 84, 25, // 93, 88, -75, 9, 46, 2, 49, 88, -116, -67, 7, -19, -83, 60, 38, 3, -34, 2, // 66, -95, 27, -98, 13, 4, -17, 55, 33, 109, 11, 11, -2, -128, 121, 123, 62, // 91, 120, -128, 127, 122, 115, 102, 2, 119, 0, -116, -113, -119, 6, 102, // 121, -108, -126, 5, 18, 6, 4, -102, -101, -100, 114, 15, 17, 0, 59 // }; static ArrayList<Image> iconImages; protected void setIconImage(Frame frame) { // On OS X, this only affects what shows up in the dock when minimized. // So this is actually a step backwards. Brilliant. if (platform != MACOSX) { //Image image = Toolkit.getDefaultToolkit().createImage(ICON_IMAGE); //frame.setIconImage(image); try { if (iconImages == null) { iconImages = new ArrayList<Image>(); final int[] sizes = { 16, 32, 48, 64 }; for (int sz : sizes) { URL url = getClass().getResource("/icon/icon-" + sz + ".png"); Image image = Toolkit.getDefaultToolkit().getImage(url); iconImages.add(image); //iconImages.add(Toolkit.getLibImage("icons/pde-" + sz + ".png", frame)); } } frame.setIconImages(iconImages); } catch (Exception e) { //e.printStackTrace(); // more or less harmless; don't spew errors } } } // Not gonna do this dynamically, only on startup. Too much headache. // public void fullscreen() { // if (frame != null) { // if (PApplet.platform == MACOSX) { // japplemenubar.JAppleMenuBar.hide(); // } // GraphicsConfiguration gc = frame.getGraphicsConfiguration(); // Rectangle rect = gc.getBounds(); //// GraphicsDevice device = gc.getDevice(); // frame.setBounds(rect.x, rect.y, rect.width, rect.height); // } // } /** * main() method for running this class from the command line. * <p> * <B>The options shown here are not yet finalized and will be * changing over the next several releases.</B> * <p> * The simplest way to turn and applet into an application is to * add the following code to your program: * <PRE>static public void main(String args[]) { * PApplet.main("YourSketchName", args); * }</PRE> * This will properly launch your applet from a double-clickable * .jar or from the command line. * <PRE> * Parameters useful for launching or also used by the PDE: * * --location=x,y upper-lefthand corner of where the applet * should appear on screen. if not used, * the default is to center on the main screen. * * --full-screen put the applet into full screen "present" mode. * * --hide-stop use to hide the stop button in situations where * you don't want to allow users to exit. also * see the FAQ on information for capturing the ESC * key when running in presentation mode. * * --stop-color=#xxxxxx color of the 'stop' text used to quit an * sketch when it's in present mode. * * --bgcolor=#xxxxxx background color of the window. * * --sketch-path location of where to save files from functions * like saveStrings() or saveFrame(). defaults to * the folder that the java application was * launched from, which means if this isn't set by * the pde, everything goes into the same folder * as processing.exe. * * --display=n set what display should be used by this sketch. * displays are numbered starting from 0. * * Parameters used by Processing when running via the PDE * * --external set when the applet is being used by the PDE * * --editor-location=x,y position of the upper-lefthand corner of the * editor window, for placement of applet window * </PRE> */ static public void main(final String[] args) { runSketch(args, null); } /** * Convenience method so that PApplet.main("YourSketch") launches a sketch, * rather than having to wrap it into a String array. * @param mainClass name of the class to load (with package if any) */ static public void main(final String mainClass) { main(mainClass, null); } /** * Convenience method so that PApplet.main("YourSketch", args) launches a * sketch, rather than having to wrap it into a String array, and appending * the 'args' array when not null. * @param mainClass name of the class to load (with package if any) * @param args command line arguments to pass to the sketch */ static public void main(final String mainClass, final String[] passedArgs) { String[] args = new String[] { mainClass }; if (passedArgs != null) { args = concat(args, passedArgs); } runSketch(args, null); } static public void runSketch(final String args[], final PApplet constructedApplet) { // Disable abyssmally slow Sun renderer on OS X 10.5. if (platform == MACOSX) { // Only run this on OS X otherwise it can cause a permissions error. // http://dev.processing.org/bugs/show_bug.cgi?id=976 System.setProperty("apple.awt.graphics.UseQuartz", String.valueOf(useQuartz)); } // Doesn't seem to do much to help avoid flicker System.setProperty("sun.awt.noerasebackground", "true"); // This doesn't do anything. // if (platform == WINDOWS) { // // For now, disable the D3D renderer on Java 6u10 because // // it causes problems with Present mode. // // http://dev.processing.org/bugs/show_bug.cgi?id=1009 // System.setProperty("sun.java2d.d3d", "false"); // } if (args.length < 1) { System.err.println("Usage: PApplet <appletname>"); System.err.println("For additional options, " + "see the Javadoc for PApplet"); System.exit(1); } // EventQueue.invokeLater(new Runnable() { // public void run() { // runSketchEDT(args, constructedApplet); // } // }); // } // // // static public void runSketchEDT(final String args[], final PApplet constructedApplet) { boolean external = false; int[] location = null; int[] editorLocation = null; String name = null; boolean present = false; // boolean exclusive = false; // Color backgroundColor = Color.BLACK; Color backgroundColor = null; //Color.BLACK; Color stopColor = Color.GRAY; GraphicsDevice displayDevice = null; boolean hideStop = false; String param = null, value = null; // try to get the user folder. if running under java web start, // this may cause a security exception if the code is not signed. // http://processing.org/discourse/yabb_beta/YaBB.cgi?board=Integrate;action=display;num=1159386274 String folder = null; try { folder = System.getProperty("user.dir"); } catch (Exception e) { } int argIndex = 0; while (argIndex < args.length) { int equals = args[argIndex].indexOf('='); if (equals != -1) { param = args[argIndex].substring(0, equals); value = args[argIndex].substring(equals + 1); if (param.equals(ARGS_EDITOR_LOCATION)) { external = true; editorLocation = parseInt(split(value, ',')); } else if (param.equals(ARGS_DISPLAY)) { int deviceIndex = Integer.parseInt(value); GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice devices[] = environment.getScreenDevices(); if ((deviceIndex >= 0) && (deviceIndex < devices.length)) { displayDevice = devices[deviceIndex]; } else { System.err.println("Display " + value + " does not exist, " + "using the default display instead."); for (int i = 0; i < devices.length; i++) { System.err.println(i + " is " + devices[i]); } } } else if (param.equals(ARGS_BGCOLOR)) { if (value.charAt(0) == '#') value = value.substring(1); backgroundColor = new Color(Integer.parseInt(value, 16)); } else if (param.equals(ARGS_STOP_COLOR)) { if (value.charAt(0) == '#') value = value.substring(1); stopColor = new Color(Integer.parseInt(value, 16)); } else if (param.equals(ARGS_SKETCH_FOLDER)) { folder = value; } else if (param.equals(ARGS_LOCATION)) { location = parseInt(split(value, ',')); } } else { if (args[argIndex].equals(ARGS_PRESENT)) { // keep for compatability present = true; } else if (args[argIndex].equals(ARGS_FULL_SCREEN)) { present = true; // } else if (args[argIndex].equals(ARGS_EXCLUSIVE)) { // exclusive = true; } else if (args[argIndex].equals(ARGS_HIDE_STOP)) { hideStop = true; } else if (args[argIndex].equals(ARGS_EXTERNAL)) { external = true; } else { name = args[argIndex]; break; // because of break, argIndex won't increment again } } argIndex++; } // Now that sketch path is passed in args after the sketch name // it's not set in the above loop(the above loop breaks after // finding sketch name). So setting sketch path here. for (int i = 0; i < args.length; i++) { if(args[i].startsWith(ARGS_SKETCH_FOLDER)){ folder = args[i].substring(args[i].indexOf('=') + 1); //System.err.println("SF set " + folder); } } // Set this property before getting into any GUI init code //System.setProperty("com.apple.mrj.application.apple.menu.about.name", name); // This )*)(*@#$ Apple crap don't work no matter where you put it // (static method of the class, at the top of main, wherever) if (displayDevice == null) { GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment(); displayDevice = environment.getDefaultScreenDevice(); } Frame frame = new Frame(displayDevice.getDefaultConfiguration()); frame.setBackground(new Color(0xCC, 0xCC, 0xCC)); // default Processing gray // JFrame frame = new JFrame(displayDevice.getDefaultConfiguration()); /* Frame frame = null; if (displayDevice != null) { frame = new Frame(displayDevice.getDefaultConfiguration()); } else { frame = new Frame(); } */ //Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); // remove the grow box by default // users who want it back can call frame.setResizable(true) // frame.setResizable(false); // moved later (issue #467) final PApplet applet; if (constructedApplet != null) { applet = constructedApplet; } else { try { Class<?> c = Thread.currentThread().getContextClassLoader().loadClass(name); applet = (PApplet) c.newInstance(); } catch (Exception e) { throw new RuntimeException(e); } } // Set the trimmings around the image applet.setIconImage(frame); frame.setTitle(name); // frame.setIgnoreRepaint(true); // does nothing // frame.addComponentListener(new ComponentAdapter() { // public void componentResized(ComponentEvent e) { // Component c = e.getComponent(); //// Rectangle bounds = c.getBounds(); // System.out.println(" " + c.getName() + " wants to be: " + c.getSize()); // } // }); // frame.addComponentListener(new ComponentListener() { // // public void componentShown(ComponentEvent e) { // debug("frame: " + e); // debug(" applet valid? " + applet.isValid()); //// ((PGraphicsJava2D) applet.g).redraw(); // } // // public void componentResized(ComponentEvent e) { // println("frame: " + e + " " + applet.frame.getInsets()); // Insets insets = applet.frame.getInsets(); // int wide = e.getComponent().getWidth() - (insets.left + insets.right); // int high = e.getComponent().getHeight() - (insets.top + insets.bottom); // if (applet.getWidth() != wide || applet.getHeight() != high) { // debug("Frame.componentResized() setting applet size " + wide + " " + high); // applet.setSize(wide, high); // } // } // // public void componentMoved(ComponentEvent e) { // //println("frame: " + e + " " + applet.frame.getInsets()); // Insets insets = applet.frame.getInsets(); // int wide = e.getComponent().getWidth() - (insets.left + insets.right); // int high = e.getComponent().getHeight() - (insets.top + insets.bottom); // //applet.g.setsi // if (applet.getWidth() != wide || applet.getHeight() != high) { // debug("Frame.componentMoved() setting applet size " + wide + " " + high); // applet.setSize(wide, high); // } // } // // public void componentHidden(ComponentEvent e) { // debug("frame: " + e); // } // }); // A handful of things that need to be set before init/start. applet.frame = frame; applet.sketchPath = folder; // If the applet doesn't call for full screen, but the command line does, // enable it. Conversely, if the command line does not, don't disable it. // applet.fullScreen |= present; // Query the applet to see if it wants to be full screen all the time. present |= applet.sketchFullScreen(); // pass everything after the class name in as args to the sketch itself // (fixed for 2.0a5, this was just subsetting by 1, which didn't skip opts) applet.args = PApplet.subset(args, argIndex + 1); applet.external = external; // Need to save the window bounds at full screen, // because pack() will cause the bounds to go to zero. // http://dev.processing.org/bugs/show_bug.cgi?id=923 Rectangle screenRect = displayDevice.getDefaultConfiguration().getBounds(); // DisplayMode doesn't work here, because we can't get the upper-left // corner of the display, which is important for multi-display setups. // Sketch has already requested to be the same as the screen's // width and height, so let's roll with full screen mode. if (screenRect.width == applet.sketchWidth() && screenRect.height == applet.sketchHeight()) { present = true; } // For 0149, moving this code (up to the pack() method) before init(). // For OpenGL (and perhaps other renderers in the future), a peer is // needed before a GLDrawable can be created. So pack() needs to be // called on the Frame before applet.init(), which itself calls size(), // and launches the Thread that will kick off setup(). // http://dev.processing.org/bugs/show_bug.cgi?id=891 // http://dev.processing.org/bugs/show_bug.cgi?id=908 if (present) { // if (platform == MACOSX) { // // Call some native code to remove the menu bar on OS X. Not necessary // // on Linux and Windows, who are happy to make full screen windows. // japplemenubar.JAppleMenuBar.hide(); // } frame.setUndecorated(true); if (backgroundColor != null) { frame.setBackground(backgroundColor); } // if (exclusive) { // displayDevice.setFullScreenWindow(frame); // // this trashes the location of the window on os x // //frame.setExtendedState(java.awt.Frame.MAXIMIZED_BOTH); // fullScreenRect = frame.getBounds(); // } else { frame.setBounds(screenRect); frame.setVisible(true); // } } frame.setLayout(null); frame.add(applet); if (present) { frame.invalidate(); } else { frame.pack(); } // insufficient, places the 100x100 sketches offset strangely //frame.validate(); // disabling resize has to happen after pack() to avoid apparent Apple bug // http://code.google.com/p/processing/issues/detail?id=467 frame.setResizable(false); applet.init(); // applet.start(); // Wait until the applet has figured out its width. // In a static mode app, this will be after setup() has completed, // and the empty draw() has set "finished" to true. // TODO make sure this won't hang if the applet has an exception. while (applet.defaultSize && !applet.finished) { //System.out.println("default size"); try { Thread.sleep(5); } catch (InterruptedException e) { //System.out.println("interrupt"); } } // // If 'present' wasn't already set, but the applet initializes // // to full screen, attempt to make things full screen anyway. // if (!present && // applet.width == screenRect.width && // applet.height == screenRect.height) { // // bounds will be set below, but can't change to setUndecorated() now // present = true; // } // // Opting not to do this, because we can't remove the decorations on the // // window at this point. And re-opening a new winodw is a lot of mess. // // Better all around to just encourage the use of sketchFullScreen() // // or cmd/ctrl-shift-R in the PDE. if (present) { if (platform == MACOSX) { // Call some native code to remove the menu bar on OS X. Not necessary // on Linux and Windows, who are happy to make full screen windows. japplemenubar.JAppleMenuBar.hide(); } // After the pack(), the screen bounds are gonna be 0s frame.setBounds(screenRect); applet.setBounds((screenRect.width - applet.width) / 2, (screenRect.height - applet.height) / 2, applet.width, applet.height); if (!hideStop) { Label label = new Label("stop"); label.setForeground(stopColor); label.addMouseListener(new MouseAdapter() { @Override public void mousePressed(java.awt.event.MouseEvent e) { System.exit(0); } }); frame.add(label); Dimension labelSize = label.getPreferredSize(); // sometimes shows up truncated on mac //System.out.println("label width is " + labelSize.width); labelSize = new Dimension(100, labelSize.height); label.setSize(labelSize); label.setLocation(20, screenRect.height - labelSize.height - 20); } // not always running externally when in present mode if (external) { applet.setupExternalMessages(); } } else { // if not presenting // can't do pack earlier cuz present mode don't like it // (can't go full screen with a frame after calling pack) // frame.pack(); // get insets. get more. Insets insets = frame.getInsets(); int windowW = Math.max(applet.width, MIN_WINDOW_WIDTH) + insets.left + insets.right; int windowH = Math.max(applet.height, MIN_WINDOW_HEIGHT) + insets.top + insets.bottom; frame.setSize(windowW, windowH); if (location != null) { // a specific location was received from the Runner // (applet has been run more than once, user placed window) frame.setLocation(location[0], location[1]); } else if (external && editorLocation != null) { int locationX = editorLocation[0] - 20; int locationY = editorLocation[1]; if (locationX - windowW > 10) { // if it fits to the left of the window frame.setLocation(locationX - windowW, locationY); } else { // doesn't fit // if it fits inside the editor window, // offset slightly from upper lefthand corner // so that it's plunked inside the text area locationX = editorLocation[0] + 66; locationY = editorLocation[1] + 66; if ((locationX + windowW > applet.displayWidth - 33) || (locationY + windowH > applet.displayHeight - 33)) { // otherwise center on screen locationX = (applet.displayWidth - windowW) / 2; locationY = (applet.displayHeight - windowH) / 2; } frame.setLocation(locationX, locationY); } } else { // just center on screen // Can't use frame.setLocationRelativeTo(null) because it sends the // frame to the main display, which undermines the --display setting. frame.setLocation(screenRect.x + (screenRect.width - applet.width) / 2, screenRect.y + (screenRect.height - applet.height) / 2); } Point frameLoc = frame.getLocation(); if (frameLoc.y < 0) { // Windows actually allows you to place frames where they can't be // closed. Awesome. http://dev.processing.org/bugs/show_bug.cgi?id=1508 frame.setLocation(frameLoc.x, 30); } if (backgroundColor != null) { // if (backgroundColor == Color.black) { //BLACK) { // // this means no bg color unless specified // backgroundColor = SystemColor.control; // } frame.setBackground(backgroundColor); } int usableWindowH = windowH - insets.top - insets.bottom; applet.setBounds((windowW - applet.width)/2, insets.top + (usableWindowH - applet.height)/2, applet.width, applet.height); if (external) { applet.setupExternalMessages(); } else { // !external frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); } // handle frame resizing events applet.setupFrameResizeListener(); // all set for rockin if (applet.displayable()) { frame.setVisible(true); } } // Disabling for 0185, because it causes an assertion failure on OS X // http://code.google.com/p/processing/issues/detail?id=258 // (Although this doesn't seem to be the one that was causing problems.) //applet.requestFocus(); // ask for keydowns } /** * These methods provide a means for running an already-constructed * sketch. In particular, it makes it easy to launch a sketch in * Jython: * * <pre>class MySketch(PApplet): * pass * *MySketch().runSketch();</pre> */ protected void runSketch(final String[] args) { final String[] argsWithSketchName = new String[args.length + 1]; System.arraycopy(args, 0, argsWithSketchName, 0, args.length); final String className = this.getClass().getSimpleName(); final String cleanedClass = className.replaceAll("__[^_]+__\\$", "").replaceAll("\\$\\d+", ""); argsWithSketchName[args.length] = cleanedClass; runSketch(argsWithSketchName, this); } protected void runSketch() { runSketch(new String[0]); } ////////////////////////////////////////////////////////////// /** * ( begin auto-generated from beginRecord.xml ) * * Opens a new file and all subsequent drawing functions are echoed to this * file as well as the display window. The <b>beginRecord()</b> function * requires two parameters, the first is the renderer and the second is the * file name. This function is always used with <b>endRecord()</b> to stop * the recording process and close the file. * <br /> <br /> * Note that beginRecord() will only pick up any settings that happen after * it has been called. For instance, if you call textFont() before * beginRecord(), then that font will not be set for the file that you're * recording to. * * ( end auto-generated ) * * @webref output:files * @param renderer for example, PDF * @param filename filename for output * @see PApplet#endRecord() */ public PGraphics beginRecord(String renderer, String filename) { filename = insertFrame(filename); PGraphics rec = createGraphics(width, height, renderer, filename); beginRecord(rec); return rec; } /** * @nowebref * Begin recording (echoing) commands to the specified PGraphics object. */ public void beginRecord(PGraphics recorder) { this.recorder = recorder; recorder.beginDraw(); } /** * ( begin auto-generated from endRecord.xml ) * * Stops the recording process started by <b>beginRecord()</b> and closes * the file. * * ( end auto-generated ) * @webref output:files * @see PApplet#beginRecord(String, String) */ public void endRecord() { if (recorder != null) { recorder.endDraw(); recorder.dispose(); recorder = null; } } /** * ( begin auto-generated from beginRaw.xml ) * * To create vectors from 3D data, use the <b>beginRaw()</b> and * <b>endRaw()</b> commands. These commands will grab the shape data just * before it is rendered to the screen. At this stage, your entire scene is * nothing but a long list of individual lines and triangles. This means * that a shape created with <b>sphere()</b> function will be made up of * hundreds of triangles, rather than a single object. Or that a * multi-segment line shape (such as a curve) will be rendered as * individual segments. * <br /><br /> * When using <b>beginRaw()</b> and <b>endRaw()</b>, it's possible to write * to either a 2D or 3D renderer. For instance, <b>beginRaw()</b> with the * PDF library will write the geometry as flattened triangles and lines, * even if recording from the <b>P3D</b> renderer. * <br /><br /> * If you want a background to show up in your files, use <b>rect(0, 0, * width, height)</b> after setting the <b>fill()</b> to the background * color. Otherwise the background will not be rendered to the file because * the background is not shape. * <br /><br /> * Using <b>hint(ENABLE_DEPTH_SORT)</b> can improve the appearance of 3D * geometry drawn to 2D file formats. See the <b>hint()</b> reference for * more details. * <br /><br /> * See examples in the reference for the <b>PDF</b> and <b>DXF</b> * libraries for more information. * * ( end auto-generated ) * * @webref output:files * @param renderer for example, PDF or DXF * @param filename filename for output * @see PApplet#endRaw() * @see PApplet#hint(int) */ public PGraphics beginRaw(String renderer, String filename) { filename = insertFrame(filename); PGraphics rec = createGraphics(width, height, renderer, filename); g.beginRaw(rec); return rec; } /** * @nowebref * Begin recording raw shape data to the specified renderer. * * This simply echoes to g.beginRaw(), but since is placed here (rather than * generated by preproc.pl) for clarity and so that it doesn't echo the * command should beginRecord() be in use. * * @param rawGraphics ??? */ public void beginRaw(PGraphics rawGraphics) { g.beginRaw(rawGraphics); } /** * ( begin auto-generated from endRaw.xml ) * * Complement to <b>beginRaw()</b>; they must always be used together. See * the <b>beginRaw()</b> reference for details. * * ( end auto-generated ) * * @webref output:files * @see PApplet#beginRaw(String, String) */ public void endRaw() { g.endRaw(); } /** * Starts shape recording and returns the PShape object that will * contain the geometry. */ /* public PShape beginRecord() { return g.beginRecord(); } */ ////////////////////////////////////////////////////////////// /** * ( begin auto-generated from loadPixels.xml ) * * Loads the pixel data for the display window into the <b>pixels[]</b> * array. This function must always be called before reading from or * writing to <b>pixels[]</b>. * <br/><br/> renderers may or may not seem to require <b>loadPixels()</b> * or <b>updatePixels()</b>. However, the rule is that any time you want to * manipulate the <b>pixels[]</b> array, you must first call * <b>loadPixels()</b>, and after changes have been made, call * <b>updatePixels()</b>. Even if the renderer may not seem to use this * function in the current Processing release, this will always be subject * to change. * * ( end auto-generated ) * <h3>Advanced</h3> * Override the g.pixels[] function to set the pixels[] array * that's part of the PApplet object. Allows the use of * pixels[] in the code, rather than g.pixels[]. * * @webref image:pixels * @see PApplet#pixels * @see PApplet#updatePixels() */ public void loadPixels() { g.loadPixels(); pixels = g.pixels; } /** * ( begin auto-generated from updatePixels.xml ) * * Updates the display window with the data in the <b>pixels[]</b> array. * Use in conjunction with <b>loadPixels()</b>. If you're only reading * pixels from the array, there's no need to call <b>updatePixels()</b> * unless there are changes. * <br/><br/> renderers may or may not seem to require <b>loadPixels()</b> * or <b>updatePixels()</b>. However, the rule is that any time you want to * manipulate the <b>pixels[]</b> array, you must first call * <b>loadPixels()</b>, and after changes have been made, call * <b>updatePixels()</b>. Even if the renderer may not seem to use this * function in the current Processing release, this will always be subject * to change. * <br/> <br/> * Currently, none of the renderers use the additional parameters to * <b>updatePixels()</b>, however this may be implemented in the future. * * ( end auto-generated ) * @webref image:pixels * @see PApplet#loadPixels() * @see PApplet#pixels */ public void updatePixels() { g.updatePixels(); } /** * @nowebref * @param x1 x-coordinate of the upper-left corner * @param y1 y-coordinate of the upper-left corner * @param x2 width of the region * @param y2 height of the region */ public void updatePixels(int x1, int y1, int x2, int y2) { g.updatePixels(x1, y1, x2, y2); } ////////////////////////////////////////////////////////////// // EVERYTHING BELOW THIS LINE IS AUTOMATICALLY GENERATED. DO NOT TOUCH! // This includes the Javadoc comments, which are automatically copied from // the PImage and PGraphics source code files. // public functions for processing.core /** * Store data of some kind for the renderer that requires extra metadata of * some kind. Usually this is a renderer-specific representation of the * image data, for instance a BufferedImage with tint() settings applied for * PGraphicsJava2D, or resized image data and OpenGL texture indices for * PGraphicsOpenGL. * @param renderer The PGraphics renderer associated to the image * @param storage The metadata required by the renderer */ public void setCache(PImage image, Object storage) { if (recorder != null) recorder.setCache(image, storage); g.setCache(image, storage); } /** * Get cache storage data for the specified renderer. Because each renderer * will cache data in different formats, it's necessary to store cache data * keyed by the renderer object. Otherwise, attempting to draw the same * image to both a PGraphicsJava2D and a PGraphicsOpenGL will cause errors. * @param renderer The PGraphics renderer associated to the image * @return metadata stored for the specified renderer */ public Object getCache(PImage image) { return g.getCache(image); } /** * Remove information associated with this renderer from the cache, if any. * @param renderer The PGraphics renderer whose cache data should be removed */ public void removeCache(PImage image) { if (recorder != null) recorder.removeCache(image); g.removeCache(image); } public PGL beginPGL() { return g.beginPGL(); } public void endPGL() { if (recorder != null) recorder.endPGL(); g.endPGL(); } public void flush() { if (recorder != null) recorder.flush(); g.flush(); } public void hint(int which) { if (recorder != null) recorder.hint(which); g.hint(which); } /** * Start a new shape of type POLYGON */ public void beginShape() { if (recorder != null) recorder.beginShape(); g.beginShape(); } /** * ( begin auto-generated from beginShape.xml ) * * Using the <b>beginShape()</b> and <b>endShape()</b> functions allow * creating more complex forms. <b>beginShape()</b> begins recording * vertices for a shape and <b>endShape()</b> stops recording. The value of * the <b>MODE</b> parameter tells it which types of shapes to create from * the provided vertices. With no mode specified, the shape can be any * irregular polygon. The parameters available for beginShape() are POINTS, * LINES, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, QUADS, and QUAD_STRIP. * After calling the <b>beginShape()</b> function, a series of * <b>vertex()</b> commands must follow. To stop drawing the shape, call * <b>endShape()</b>. The <b>vertex()</b> function with two parameters * specifies a position in 2D and the <b>vertex()</b> function with three * parameters specifies a position in 3D. Each shape will be outlined with * the current stroke color and filled with the fill color. * <br/> <br/> * Transformations such as <b>translate()</b>, <b>rotate()</b>, and * <b>scale()</b> do not work within <b>beginShape()</b>. It is also not * possible to use other shapes, such as <b>ellipse()</b> or <b>rect()</b> * within <b>beginShape()</b>. * <br/> <br/> * The P3D renderer settings allow <b>stroke()</b> and <b>fill()</b> * settings to be altered per-vertex, however the default P2D renderer does * not. Settings such as <b>strokeWeight()</b>, <b>strokeCap()</b>, and * <b>strokeJoin()</b> cannot be changed while inside a * <b>beginShape()</b>/<b>endShape()</b> block with any renderer. * * ( end auto-generated ) * @webref shape:vertex * @param kind Either POINTS, LINES, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, QUADS, or QUAD_STRIP * @see PShape * @see PGraphics#endShape() * @see PGraphics#vertex(float, float, float, float, float) * @see PGraphics#curveVertex(float, float, float) * @see PGraphics#bezierVertex(float, float, float, float, float, float, float, float, float) */ public void beginShape(int kind) { if (recorder != null) recorder.beginShape(kind); g.beginShape(kind); } /** * Sets whether the upcoming vertex is part of an edge. * Equivalent to glEdgeFlag(), for people familiar with OpenGL. */ public void edge(boolean edge) { if (recorder != null) recorder.edge(edge); g.edge(edge); } /** * ( begin auto-generated from normal.xml ) * * Sets the current normal vector. This is for drawing three dimensional * shapes and surfaces and specifies a vector perpendicular to the surface * of the shape which determines how lighting affects it. Processing * attempts to automatically assign normals to shapes, but since that's * imperfect, this is a better option when you want more control. This * function is identical to glNormal3f() in OpenGL. * * ( end auto-generated ) * @webref lights_camera:lights * @param nx x direction * @param ny y direction * @param nz z direction * @see PGraphics#beginShape(int) * @see PGraphics#endShape(int) * @see PGraphics#lights() */ public void normal(float nx, float ny, float nz) { if (recorder != null) recorder.normal(nx, ny, nz); g.normal(nx, ny, nz); } /** * ( begin auto-generated from textureMode.xml ) * * Sets the coordinate space for texture mapping. There are two options, * IMAGE, which refers to the actual coordinates of the image, and * NORMAL, which refers to a normalized space of values ranging from 0 * to 1. The default mode is IMAGE. In IMAGE, if an image is 100 x 200 * pixels, mapping the image onto the entire size of a quad would require * the points (0,0) (0,100) (100,200) (0,200). The same mapping in * NORMAL_SPACE is (0,0) (0,1) (1,1) (0,1). * * ( end auto-generated ) * @webref image:textures * @param mode either IMAGE or NORMAL * @see PGraphics#texture(PImage) * @see PGraphics#textureWrap(int) */ public void textureMode(int mode) { if (recorder != null) recorder.textureMode(mode); g.textureMode(mode); } /** * ( begin auto-generated from textureWrap.xml ) * * Description to come... * * ( end auto-generated from textureWrap.xml ) * * @webref image:textures * @param wrap Either CLAMP (default) or REPEAT * @see PGraphics#texture(PImage) * @see PGraphics#textureMode(int) */ public void textureWrap(int wrap) { if (recorder != null) recorder.textureWrap(wrap); g.textureWrap(wrap); } /** * ( begin auto-generated from texture.xml ) * * Sets a texture to be applied to vertex points. The <b>texture()</b> * function must be called between <b>beginShape()</b> and * <b>endShape()</b> and before any calls to <b>vertex()</b>. * <br/> <br/> * When textures are in use, the fill color is ignored. Instead, use tint() * to specify the color of the texture as it is applied to the shape. * * ( end auto-generated ) * @webref image:textures * @param image reference to a PImage object * @see PGraphics#textureMode(int) * @see PGraphics#textureWrap(int) * @see PGraphics#beginShape(int) * @see PGraphics#endShape(int) * @see PGraphics#vertex(float, float, float, float, float) */ public void texture(PImage image) { if (recorder != null) recorder.texture(image); g.texture(image); } /** * Removes texture image for current shape. * Needs to be called between beginShape and endShape * */ public void noTexture() { if (recorder != null) recorder.noTexture(); g.noTexture(); } public void vertex(float x, float y) { if (recorder != null) recorder.vertex(x, y); g.vertex(x, y); } public void vertex(float x, float y, float z) { if (recorder != null) recorder.vertex(x, y, z); g.vertex(x, y, z); } /** * Used by renderer subclasses or PShape to efficiently pass in already * formatted vertex information. * @param v vertex parameters, as a float array of length VERTEX_FIELD_COUNT */ public void vertex(float[] v) { if (recorder != null) recorder.vertex(v); g.vertex(v); } public void vertex(float x, float y, float u, float v) { if (recorder != null) recorder.vertex(x, y, u, v); g.vertex(x, y, u, v); } /** * ( begin auto-generated from vertex.xml ) * * All shapes are constructed by connecting a series of vertices. * <b>vertex()</b> is used to specify the vertex coordinates for points, * lines, triangles, quads, and polygons and is used exclusively within the * <b>beginShape()</b> and <b>endShape()</b> function.<br /> * <br /> * Drawing a vertex in 3D using the <b>z</b> parameter requires the P3D * parameter in combination with size as shown in the above example.<br /> * <br /> * This function is also used to map a texture onto the geometry. The * <b>texture()</b> function declares the texture to apply to the geometry * and the <b>u</b> and <b>v</b> coordinates set define the mapping of this * texture to the form. By default, the coordinates used for <b>u</b> and * <b>v</b> are specified in relation to the image's size in pixels, but * this relation can be changed with <b>textureMode()</b>. * * ( end auto-generated ) * @webref shape:vertex * @param x x-coordinate of the vertex * @param y y-coordinate of the vertex * @param z z-coordinate of the vertex * @param u horizontal coordinate for the texture mapping * @param v vertical coordinate for the texture mapping * @see PGraphics#beginShape(int) * @see PGraphics#endShape(int) * @see PGraphics#bezierVertex(float, float, float, float, float, float, float, float, float) * @see PGraphics#quadraticVertex(float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float, float) * @see PGraphics#texture(PImage) */ public void vertex(float x, float y, float z, float u, float v) { if (recorder != null) recorder.vertex(x, y, z, u, v); g.vertex(x, y, z, u, v); } /** * @webref shape:vertex */ public void beginContour() { if (recorder != null) recorder.beginContour(); g.beginContour(); } /** * @webref shape:vertex */ public void endContour() { if (recorder != null) recorder.endContour(); g.endContour(); } public void endShape() { if (recorder != null) recorder.endShape(); g.endShape(); } /** * ( begin auto-generated from endShape.xml ) * * The <b>endShape()</b> function is the companion to <b>beginShape()</b> * and may only be called after <b>beginShape()</b>. When <b>endshape()</b> * is called, all of image data defined since the previous call to * <b>beginShape()</b> is written into the image buffer. The constant CLOSE * as the value for the MODE parameter to close the shape (to connect the * beginning and the end). * * ( end auto-generated ) * @webref shape:vertex * @param mode use CLOSE to close the shape * @see PShape * @see PGraphics#beginShape(int) */ public void endShape(int mode) { if (recorder != null) recorder.endShape(mode); g.endShape(mode); } /** * @webref shape * @param filename name of file to load, can be .svg or .obj * @see PShape * @see PApplet#createShape() */ public PShape loadShape(String filename) { return g.loadShape(filename); } public PShape loadShape(String filename, String options) { return g.loadShape(filename, options); } /** * @webref shape * @see PShape * @see PShape#endShape() * @see PApplet#loadShape(String) */ public PShape createShape() { return g.createShape(); } public PShape createShape(PShape source) { return g.createShape(source); } /** * @param type either POINTS, LINES, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, QUADS, QUAD_STRIP */ public PShape createShape(int type) { return g.createShape(type); } /** * @param kind either LINE, TRIANGLE, RECT, ELLIPSE, ARC, SPHERE, BOX * @param p parameters that match the kind of shape */ public PShape createShape(int kind, float... p) { return g.createShape(kind, p); } /** * ( begin auto-generated from loadShader.xml ) * * This is a new reference entry for Processing 2.0. It will be updated shortly. * * ( end auto-generated ) * * @webref rendering:shaders * @param fragFilename name of fragment shader file */ public PShader loadShader(String fragFilename) { return g.loadShader(fragFilename); } /** * @param vertFilename name of vertex shader file */ public PShader loadShader(String fragFilename, String vertFilename) { return g.loadShader(fragFilename, vertFilename); } /** * ( begin auto-generated from shader.xml ) * * This is a new reference entry for Processing 2.0. It will be updated shortly. * * ( end auto-generated ) * * @webref rendering:shaders * @param shader name of shader file */ public void shader(PShader shader) { if (recorder != null) recorder.shader(shader); g.shader(shader); } /** * @param kind type of shader, either POINTS, LINES, or TRIANGLES */ public void shader(PShader shader, int kind) { if (recorder != null) recorder.shader(shader, kind); g.shader(shader, kind); } /** * ( begin auto-generated from resetShader.xml ) * * This is a new reference entry for Processing 2.0. It will be updated shortly. * * ( end auto-generated ) * * @webref rendering:shaders */ public void resetShader() { if (recorder != null) recorder.resetShader(); g.resetShader(); } /** * @param kind type of shader, either POINTS, LINES, or TRIANGLES */ public void resetShader(int kind) { if (recorder != null) recorder.resetShader(kind); g.resetShader(kind); } /** * @param shader the fragment shader to apply */ public void filter(PShader shader) { if (recorder != null) recorder.filter(shader); g.filter(shader); } /* * @webref rendering:shaders * @param a x-coordinate of the rectangle by default * @param b y-coordinate of the rectangle by default * @param c width of the rectangle by default * @param d height of the rectangle by default */ public void clip(float a, float b, float c, float d) { if (recorder != null) recorder.clip(a, b, c, d); g.clip(a, b, c, d); } /* * @webref rendering:shaders */ public void noClip() { if (recorder != null) recorder.noClip(); g.noClip(); } /** * ( begin auto-generated from blendMode.xml ) * * This is a new reference entry for Processing 2.0. It will be updated shortly. * * ( end auto-generated ) * * @webref Rendering * @param mode the blending mode to use */ public void blendMode(int mode) { if (recorder != null) recorder.blendMode(mode); g.blendMode(mode); } public void bezierVertex(float x2, float y2, float x3, float y3, float x4, float y4) { if (recorder != null) recorder.bezierVertex(x2, y2, x3, y3, x4, y4); g.bezierVertex(x2, y2, x3, y3, x4, y4); } /** * ( begin auto-generated from bezierVertex.xml ) * * Specifies vertex coordinates for Bezier curves. Each call to * <b>bezierVertex()</b> defines the position of two control points and one * anchor point of a Bezier curve, adding a new segment to a line or shape. * The first time <b>bezierVertex()</b> is used within a * <b>beginShape()</b> call, it must be prefaced with a call to * <b>vertex()</b> to set the first anchor point. This function must be * used between <b>beginShape()</b> and <b>endShape()</b> and only when * there is no MODE parameter specified to <b>beginShape()</b>. Using the * 3D version requires rendering with P3D (see the Environment reference * for more information). * * ( end auto-generated ) * @webref shape:vertex * @param x2 the x-coordinate of the 1st control point * @param y2 the y-coordinate of the 1st control point * @param z2 the z-coordinate of the 1st control point * @param x3 the x-coordinate of the 2nd control point * @param y3 the y-coordinate of the 2nd control point * @param z3 the z-coordinate of the 2nd control point * @param x4 the x-coordinate of the anchor point * @param y4 the y-coordinate of the anchor point * @param z4 the z-coordinate of the anchor point * @see PGraphics#curveVertex(float, float, float) * @see PGraphics#vertex(float, float, float, float, float) * @see PGraphics#quadraticVertex(float, float, float, float, float, float) * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) */ public void bezierVertex(float x2, float y2, float z2, float x3, float y3, float z3, float x4, float y4, float z4) { if (recorder != null) recorder.bezierVertex(x2, y2, z2, x3, y3, z3, x4, y4, z4); g.bezierVertex(x2, y2, z2, x3, y3, z3, x4, y4, z4); } /** * @webref shape:vertex * @param cx the x-coordinate of the control point * @param cy the y-coordinate of the control point * @param x3 the x-coordinate of the anchor point * @param y3 the y-coordinate of the anchor point * @see PGraphics#curveVertex(float, float, float) * @see PGraphics#vertex(float, float, float, float, float) * @see PGraphics#bezierVertex(float, float, float, float, float, float) * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) */ public void quadraticVertex(float cx, float cy, float x3, float y3) { if (recorder != null) recorder.quadraticVertex(cx, cy, x3, y3); g.quadraticVertex(cx, cy, x3, y3); } /** * @param cz the z-coordinate of the control point * @param z3 the z-coordinate of the anchor point */ public void quadraticVertex(float cx, float cy, float cz, float x3, float y3, float z3) { if (recorder != null) recorder.quadraticVertex(cx, cy, cz, x3, y3, z3); g.quadraticVertex(cx, cy, cz, x3, y3, z3); } /** * ( begin auto-generated from curveVertex.xml ) * * Specifies vertex coordinates for curves. This function may only be used * between <b>beginShape()</b> and <b>endShape()</b> and only when there is * no MODE parameter specified to <b>beginShape()</b>. The first and last * points in a series of <b>curveVertex()</b> lines will be used to guide * the beginning and end of a the curve. A minimum of four points is * required to draw a tiny curve between the second and third points. * Adding a fifth point with <b>curveVertex()</b> will draw the curve * between the second, third, and fourth points. The <b>curveVertex()</b> * function is an implementation of Catmull-Rom splines. Using the 3D * version requires rendering with P3D (see the Environment reference for * more information). * * ( end auto-generated ) * * @webref shape:vertex * @param x the x-coordinate of the vertex * @param y the y-coordinate of the vertex * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#beginShape(int) * @see PGraphics#endShape(int) * @see PGraphics#vertex(float, float, float, float, float) * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#quadraticVertex(float, float, float, float, float, float) */ public void curveVertex(float x, float y) { if (recorder != null) recorder.curveVertex(x, y); g.curveVertex(x, y); } /** * @param z the z-coordinate of the vertex */ public void curveVertex(float x, float y, float z) { if (recorder != null) recorder.curveVertex(x, y, z); g.curveVertex(x, y, z); } /** * ( begin auto-generated from point.xml ) * * Draws a point, a coordinate in space at the dimension of one pixel. The * first parameter is the horizontal value for the point, the second value * is the vertical value for the point, and the optional third value is the * depth value. Drawing this shape in 3D with the <b>z</b> parameter * requires the P3D parameter in combination with <b>size()</b> as shown in * the above example. * * ( end auto-generated ) * * @webref shape:2d_primitives * @param x x-coordinate of the point * @param y y-coordinate of the point */ public void point(float x, float y) { if (recorder != null) recorder.point(x, y); g.point(x, y); } /** * @param z z-coordinate of the point */ public void point(float x, float y, float z) { if (recorder != null) recorder.point(x, y, z); g.point(x, y, z); } /** * ( begin auto-generated from line.xml ) * * Draws a line (a direct path between two points) to the screen. The * version of <b>line()</b> with four parameters draws the line in 2D. To * color a line, use the <b>stroke()</b> function. A line cannot be filled, * therefore the <b>fill()</b> function will not affect the color of a * line. 2D lines are drawn with a width of one pixel by default, but this * can be changed with the <b>strokeWeight()</b> function. The version with * six parameters allows the line to be placed anywhere within XYZ space. * Drawing this shape in 3D with the <b>z</b> parameter requires the P3D * parameter in combination with <b>size()</b> as shown in the above example. * * ( end auto-generated ) * @webref shape:2d_primitives * @param x1 x-coordinate of the first point * @param y1 y-coordinate of the first point * @param x2 x-coordinate of the second point * @param y2 y-coordinate of the second point * @see PGraphics#strokeWeight(float) * @see PGraphics#strokeJoin(int) * @see PGraphics#strokeCap(int) * @see PGraphics#beginShape() */ public void line(float x1, float y1, float x2, float y2) { if (recorder != null) recorder.line(x1, y1, x2, y2); g.line(x1, y1, x2, y2); } /** * @param z1 z-coordinate of the first point * @param z2 z-coordinate of the second point */ public void line(float x1, float y1, float z1, float x2, float y2, float z2) { if (recorder != null) recorder.line(x1, y1, z1, x2, y2, z2); g.line(x1, y1, z1, x2, y2, z2); } /** * ( begin auto-generated from triangle.xml ) * * A triangle is a plane created by connecting three points. The first two * arguments specify the first point, the middle two arguments specify the * second point, and the last two arguments specify the third point. * * ( end auto-generated ) * @webref shape:2d_primitives * @param x1 x-coordinate of the first point * @param y1 y-coordinate of the first point * @param x2 x-coordinate of the second point * @param y2 y-coordinate of the second point * @param x3 x-coordinate of the third point * @param y3 y-coordinate of the third point * @see PApplet#beginShape() */ public void triangle(float x1, float y1, float x2, float y2, float x3, float y3) { if (recorder != null) recorder.triangle(x1, y1, x2, y2, x3, y3); g.triangle(x1, y1, x2, y2, x3, y3); } /** * ( begin auto-generated from quad.xml ) * * A quad is a quadrilateral, a four sided polygon. It is similar to a * rectangle, but the angles between its edges are not constrained to * ninety degrees. The first pair of parameters (x1,y1) sets the first * vertex and the subsequent pairs should proceed clockwise or * counter-clockwise around the defined shape. * * ( end auto-generated ) * @webref shape:2d_primitives * @param x1 x-coordinate of the first corner * @param y1 y-coordinate of the first corner * @param x2 x-coordinate of the second corner * @param y2 y-coordinate of the second corner * @param x3 x-coordinate of the third corner * @param y3 y-coordinate of the third corner * @param x4 x-coordinate of the fourth corner * @param y4 y-coordinate of the fourth corner */ public void quad(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) { if (recorder != null) recorder.quad(x1, y1, x2, y2, x3, y3, x4, y4); g.quad(x1, y1, x2, y2, x3, y3, x4, y4); } /** * ( begin auto-generated from rectMode.xml ) * * Modifies the location from which rectangles draw. The default mode is * <b>rectMode(CORNER)</b>, which specifies the location to be the upper * left corner of the shape and uses the third and fourth parameters of * <b>rect()</b> to specify the width and height. The syntax * <b>rectMode(CORNERS)</b> uses the first and second parameters of * <b>rect()</b> to set the location of one corner and uses the third and * fourth parameters to set the opposite corner. The syntax * <b>rectMode(CENTER)</b> draws the image from its center point and uses * the third and forth parameters of <b>rect()</b> to specify the image's * width and height. The syntax <b>rectMode(RADIUS)</b> draws the image * from its center point and uses the third and forth parameters of * <b>rect()</b> to specify half of the image's width and height. The * parameter must be written in ALL CAPS because Processing is a case * sensitive language. Note: In version 125, the mode named CENTER_RADIUS * was shortened to RADIUS. * * ( end auto-generated ) * @webref shape:attributes * @param mode either CORNER, CORNERS, CENTER, or RADIUS * @see PGraphics#rect(float, float, float, float) */ public void rectMode(int mode) { if (recorder != null) recorder.rectMode(mode); g.rectMode(mode); } /** * ( begin auto-generated from rect.xml ) * * Draws a rectangle to the screen. A rectangle is a four-sided shape with * every angle at ninety degrees. By default, the first two parameters set * the location of the upper-left corner, the third sets the width, and the * fourth sets the height. These parameters may be changed with the * <b>rectMode()</b> function. * * ( end auto-generated ) * * @webref shape:2d_primitives * @param a x-coordinate of the rectangle by default * @param b y-coordinate of the rectangle by default * @param c width of the rectangle by default * @param d height of the rectangle by default * @see PGraphics#rectMode(int) * @see PGraphics#quad(float, float, float, float, float, float, float, float) */ public void rect(float a, float b, float c, float d) { if (recorder != null) recorder.rect(a, b, c, d); g.rect(a, b, c, d); } /** * @param r radii for all four corners */ public void rect(float a, float b, float c, float d, float r) { if (recorder != null) recorder.rect(a, b, c, d, r); g.rect(a, b, c, d, r); } /** * @param tl radius for top-left corner * @param tr radius for top-right corner * @param br radius for bottom-right corner * @param bl radius for bottom-left corner */ public void rect(float a, float b, float c, float d, float tl, float tr, float br, float bl) { if (recorder != null) recorder.rect(a, b, c, d, tl, tr, br, bl); g.rect(a, b, c, d, tl, tr, br, bl); } /** * ( begin auto-generated from ellipseMode.xml ) * * The origin of the ellipse is modified by the <b>ellipseMode()</b> * function. The default configuration is <b>ellipseMode(CENTER)</b>, which * specifies the location of the ellipse as the center of the shape. The * <b>RADIUS</b> mode is the same, but the width and height parameters to * <b>ellipse()</b> specify the radius of the ellipse, rather than the * diameter. The <b>CORNER</b> mode draws the shape from the upper-left * corner of its bounding box. The <b>CORNERS</b> mode uses the four * parameters to <b>ellipse()</b> to set two opposing corners of the * ellipse's bounding box. The parameter must be written in ALL CAPS * because Processing is a case-sensitive language. * * ( end auto-generated ) * @webref shape:attributes * @param mode either CENTER, RADIUS, CORNER, or CORNERS * @see PApplet#ellipse(float, float, float, float) * @see PApplet#arc(float, float, float, float, float, float) */ public void ellipseMode(int mode) { if (recorder != null) recorder.ellipseMode(mode); g.ellipseMode(mode); } /** * ( begin auto-generated from ellipse.xml ) * * Draws an ellipse (oval) in the display window. An ellipse with an equal * <b>width</b> and <b>height</b> is a circle. The first two parameters set * the location, the third sets the width, and the fourth sets the height. * The origin may be changed with the <b>ellipseMode()</b> function. * * ( end auto-generated ) * @webref shape:2d_primitives * @param a x-coordinate of the ellipse * @param b y-coordinate of the ellipse * @param c width of the ellipse by default * @param d height of the ellipse by default * @see PApplet#ellipseMode(int) * @see PApplet#arc(float, float, float, float, float, float) */ public void ellipse(float a, float b, float c, float d) { if (recorder != null) recorder.ellipse(a, b, c, d); g.ellipse(a, b, c, d); } /** * ( begin auto-generated from arc.xml ) * * Draws an arc in the display window. Arcs are drawn along the outer edge * of an ellipse defined by the <b>x</b>, <b>y</b>, <b>width</b> and * <b>height</b> parameters. The origin or the arc's ellipse may be changed * with the <b>ellipseMode()</b> function. The <b>start</b> and <b>stop</b> * parameters specify the angles at which to draw the arc. * * ( end auto-generated ) * @webref shape:2d_primitives * @param a x-coordinate of the arc's ellipse * @param b y-coordinate of the arc's ellipse * @param c width of the arc's ellipse by default * @param d height of the arc's ellipse by default * @param start angle to start the arc, specified in radians * @param stop angle to stop the arc, specified in radians * @see PApplet#ellipse(float, float, float, float) * @see PApplet#ellipseMode(int) * @see PApplet#radians(float) * @see PApplet#degrees(float) */ public void arc(float a, float b, float c, float d, float start, float stop) { if (recorder != null) recorder.arc(a, b, c, d, start, stop); g.arc(a, b, c, d, start, stop); } /* * @param mode either OPEN, CHORD, or PIE */ public void arc(float a, float b, float c, float d, float start, float stop, int mode) { if (recorder != null) recorder.arc(a, b, c, d, start, stop, mode); g.arc(a, b, c, d, start, stop, mode); } /** * ( begin auto-generated from box.xml ) * * A box is an extruded rectangle. A box with equal dimension on all sides * is a cube. * * ( end auto-generated ) * * @webref shape:3d_primitives * @param size dimension of the box in all dimensions (creates a cube) * @see PGraphics#sphere(float) */ public void box(float size) { if (recorder != null) recorder.box(size); g.box(size); } /** * @param w dimension of the box in the x-dimension * @param h dimension of the box in the y-dimension * @param d dimension of the box in the z-dimension */ public void box(float w, float h, float d) { if (recorder != null) recorder.box(w, h, d); g.box(w, h, d); } /** * ( begin auto-generated from sphereDetail.xml ) * * Controls the detail used to render a sphere by adjusting the number of * vertices of the sphere mesh. The default resolution is 30, which creates * a fairly detailed sphere definition with vertices every 360/30 = 12 * degrees. If you're going to render a great number of spheres per frame, * it is advised to reduce the level of detail using this function. The * setting stays active until <b>sphereDetail()</b> is called again with a * new parameter and so should <i>not</i> be called prior to every * <b>sphere()</b> statement, unless you wish to render spheres with * different settings, e.g. using less detail for smaller spheres or ones * further away from the camera. To control the detail of the horizontal * and vertical resolution independently, use the version of the functions * with two parameters. * * ( end auto-generated ) * * <h3>Advanced</h3> * Code for sphereDetail() submitted by toxi [031031]. * Code for enhanced u/v version from davbol [080801]. * * @param res number of segments (minimum 3) used per full circle revolution * @webref shape:3d_primitives * @see PGraphics#sphere(float) */ public void sphereDetail(int res) { if (recorder != null) recorder.sphereDetail(res); g.sphereDetail(res); } /** * @param ures number of segments used longitudinally per full circle revolutoin * @param vres number of segments used latitudinally from top to bottom */ public void sphereDetail(int ures, int vres) { if (recorder != null) recorder.sphereDetail(ures, vres); g.sphereDetail(ures, vres); } /** * ( begin auto-generated from sphere.xml ) * * A sphere is a hollow ball made from tessellated triangles. * * ( end auto-generated ) * * <h3>Advanced</h3> * <P> * Implementation notes: * <P> * cache all the points of the sphere in a static array * top and bottom are just a bunch of triangles that land * in the center point * <P> * sphere is a series of concentric circles who radii vary * along the shape, based on, er.. cos or something * <PRE> * [toxi 031031] new sphere code. removed all multiplies with * radius, as scale() will take care of that anyway * * [toxi 031223] updated sphere code (removed modulos) * and introduced sphereAt(x,y,z,r) * to avoid additional translate()'s on the user/sketch side * * [davbol 080801] now using separate sphereDetailU/V * </PRE> * * @webref shape:3d_primitives * @param r the radius of the sphere * @see PGraphics#sphereDetail(int) */ public void sphere(float r) { if (recorder != null) recorder.sphere(r); g.sphere(r); } /** * ( begin auto-generated from bezierPoint.xml ) * * Evaluates the Bezier at point t for points a, b, c, d. The parameter t * varies between 0 and 1, a and d are points on the curve, and b and c are * the control points. This can be done once with the x coordinates and a * second time with the y coordinates to get the location of a bezier curve * at t. * * ( end auto-generated ) * * <h3>Advanced</h3> * For instance, to convert the following example:<PRE> * stroke(255, 102, 0); * line(85, 20, 10, 10); * line(90, 90, 15, 80); * stroke(0, 0, 0); * bezier(85, 20, 10, 10, 90, 90, 15, 80); * * // draw it in gray, using 10 steps instead of the default 20 * // this is a slower way to do it, but useful if you need * // to do things with the coordinates at each step * stroke(128); * beginShape(LINE_STRIP); * for (int i = 0; i <= 10; i++) { * float t = i / 10.0f; * float x = bezierPoint(85, 10, 90, 15, t); * float y = bezierPoint(20, 10, 90, 80, t); * vertex(x, y); * } * endShape();</PRE> * * @webref shape:curves * @param a coordinate of first point on the curve * @param b coordinate of first control point * @param c coordinate of second control point * @param d coordinate of second point on the curve * @param t value between 0 and 1 * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#bezierVertex(float, float, float, float, float, float) * @see PGraphics#curvePoint(float, float, float, float, float) */ public float bezierPoint(float a, float b, float c, float d, float t) { return g.bezierPoint(a, b, c, d, t); } /** * ( begin auto-generated from bezierTangent.xml ) * * Calculates the tangent of a point on a Bezier curve. There is a good * definition of <a href="http://en.wikipedia.org/wiki/Tangent" * target="new"><em>tangent</em> on Wikipedia</a>. * * ( end auto-generated ) * * <h3>Advanced</h3> * Code submitted by Dave Bollinger (davol) for release 0136. * * @webref shape:curves * @param a coordinate of first point on the curve * @param b coordinate of first control point * @param c coordinate of second control point * @param d coordinate of second point on the curve * @param t value between 0 and 1 * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#bezierVertex(float, float, float, float, float, float) * @see PGraphics#curvePoint(float, float, float, float, float) */ public float bezierTangent(float a, float b, float c, float d, float t) { return g.bezierTangent(a, b, c, d, t); } /** * ( begin auto-generated from bezierDetail.xml ) * * Sets the resolution at which Beziers display. The default value is 20. * This function is only useful when using the P3D renderer as the default * P2D renderer does not use this information. * * ( end auto-generated ) * * @webref shape:curves * @param detail resolution of the curves * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float, float) * @see PGraphics#curveTightness(float) */ public void bezierDetail(int detail) { if (recorder != null) recorder.bezierDetail(detail); g.bezierDetail(detail); } public void bezier(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) { if (recorder != null) recorder.bezier(x1, y1, x2, y2, x3, y3, x4, y4); g.bezier(x1, y1, x2, y2, x3, y3, x4, y4); } /** * ( begin auto-generated from bezier.xml ) * * Draws a Bezier curve on the screen. These curves are defined by a series * of anchor and control points. The first two parameters specify the first * anchor point and the last two parameters specify the other anchor point. * The middle parameters specify the control points which define the shape * of the curve. Bezier curves were developed by French engineer Pierre * Bezier. Using the 3D version requires rendering with P3D (see the * Environment reference for more information). * * ( end auto-generated ) * * <h3>Advanced</h3> * Draw a cubic bezier curve. The first and last points are * the on-curve points. The middle two are the 'control' points, * or 'handles' in an application like Illustrator. * <P> * Identical to typing: * <PRE>beginShape(); * vertex(x1, y1); * bezierVertex(x2, y2, x3, y3, x4, y4); * endShape(); * </PRE> * In Postscript-speak, this would be: * <PRE>moveto(x1, y1); * curveto(x2, y2, x3, y3, x4, y4);</PRE> * If you were to try and continue that curve like so: * <PRE>curveto(x5, y5, x6, y6, x7, y7);</PRE> * This would be done in processing by adding these statements: * <PRE>bezierVertex(x5, y5, x6, y6, x7, y7) * </PRE> * To draw a quadratic (instead of cubic) curve, * use the control point twice by doubling it: * <PRE>bezier(x1, y1, cx, cy, cx, cy, x2, y2);</PRE> * * @webref shape:curves * @param x1 coordinates for the first anchor point * @param y1 coordinates for the first anchor point * @param z1 coordinates for the first anchor point * @param x2 coordinates for the first control point * @param y2 coordinates for the first control point * @param z2 coordinates for the first control point * @param x3 coordinates for the second control point * @param y3 coordinates for the second control point * @param z3 coordinates for the second control point * @param x4 coordinates for the second anchor point * @param y4 coordinates for the second anchor point * @param z4 coordinates for the second anchor point * * @see PGraphics#bezierVertex(float, float, float, float, float, float) * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) */ public void bezier(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, float x4, float y4, float z4) { if (recorder != null) recorder.bezier(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4); g.bezier(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4); } /** * ( begin auto-generated from curvePoint.xml ) * * Evalutes the curve at point t for points a, b, c, d. The parameter t * varies between 0 and 1, a and d are points on the curve, and b and c are * the control points. This can be done once with the x coordinates and a * second time with the y coordinates to get the location of a curve at t. * * ( end auto-generated ) * * @webref shape:curves * @param a coordinate of first point on the curve * @param b coordinate of second point on the curve * @param c coordinate of third point on the curve * @param d coordinate of fourth point on the curve * @param t value between 0 and 1 * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float) * @see PGraphics#bezierPoint(float, float, float, float, float) */ public float curvePoint(float a, float b, float c, float d, float t) { return g.curvePoint(a, b, c, d, t); } /** * ( begin auto-generated from curveTangent.xml ) * * Calculates the tangent of a point on a curve. There's a good definition * of <em><a href="http://en.wikipedia.org/wiki/Tangent" * target="new">tangent</em> on Wikipedia</a>. * * ( end auto-generated ) * * <h3>Advanced</h3> * Code thanks to Dave Bollinger (Bug #715) * * @webref shape:curves * @param a coordinate of first point on the curve * @param b coordinate of first control point * @param c coordinate of second control point * @param d coordinate of second point on the curve * @param t value between 0 and 1 * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float) * @see PGraphics#curvePoint(float, float, float, float, float) * @see PGraphics#bezierTangent(float, float, float, float, float) */ public float curveTangent(float a, float b, float c, float d, float t) { return g.curveTangent(a, b, c, d, t); } /** * ( begin auto-generated from curveDetail.xml ) * * Sets the resolution at which curves display. The default value is 20. * This function is only useful when using the P3D renderer as the default * P2D renderer does not use this information. * * ( end auto-generated ) * * @webref shape:curves * @param detail resolution of the curves * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float) * @see PGraphics#curveTightness(float) */ public void curveDetail(int detail) { if (recorder != null) recorder.curveDetail(detail); g.curveDetail(detail); } /** * ( begin auto-generated from curveTightness.xml ) * * Modifies the quality of forms created with <b>curve()</b> and * <b>curveVertex()</b>. The parameter <b>squishy</b> determines how the * curve fits to the vertex points. The value 0.0 is the default value for * <b>squishy</b> (this value defines the curves to be Catmull-Rom splines) * and the value 1.0 connects all the points with straight lines. Values * within the range -5.0 and 5.0 will deform the curves but will leave them * recognizable and as values increase in magnitude, they will continue to deform. * * ( end auto-generated ) * * @webref shape:curves * @param tightness amount of deformation from the original vertices * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float) */ public void curveTightness(float tightness) { if (recorder != null) recorder.curveTightness(tightness); g.curveTightness(tightness); } /** * ( begin auto-generated from curve.xml ) * * Draws a curved line on the screen. The first and second parameters * specify the beginning control point and the last two parameters specify * the ending control point. The middle parameters specify the start and * stop of the curve. Longer curves can be created by putting a series of * <b>curve()</b> functions together or using <b>curveVertex()</b>. An * additional function called <b>curveTightness()</b> provides control for * the visual quality of the curve. The <b>curve()</b> function is an * implementation of Catmull-Rom splines. Using the 3D version requires * rendering with P3D (see the Environment reference for more information). * * ( end auto-generated ) * * <h3>Advanced</h3> * As of revision 0070, this function no longer doubles the first * and last points. The curves are a bit more boring, but it's more * mathematically correct, and properly mirrored in curvePoint(). * <P> * Identical to typing out:<PRE> * beginShape(); * curveVertex(x1, y1); * curveVertex(x2, y2); * curveVertex(x3, y3); * curveVertex(x4, y4); * endShape(); * </PRE> * * @webref shape:curves * @param x1 coordinates for the beginning control point * @param y1 coordinates for the beginning control point * @param x2 coordinates for the first point * @param y2 coordinates for the first point * @param x3 coordinates for the second point * @param y3 coordinates for the second point * @param x4 coordinates for the ending control point * @param y4 coordinates for the ending control point * @see PGraphics#curveVertex(float, float) * @see PGraphics#curveTightness(float) * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) */ public void curve(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) { if (recorder != null) recorder.curve(x1, y1, x2, y2, x3, y3, x4, y4); g.curve(x1, y1, x2, y2, x3, y3, x4, y4); } /** * @param z1 coordinates for the beginning control point * @param z2 coordinates for the first point * @param z3 coordinates for the second point * @param z4 coordinates for the ending control point */ public void curve(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, float x4, float y4, float z4) { if (recorder != null) recorder.curve(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4); g.curve(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4); } /** * ( begin auto-generated from smooth.xml ) * * Draws all geometry with smooth (anti-aliased) edges. This will sometimes * slow down the frame rate of the application, but will enhance the visual * refinement. Note that <b>smooth()</b> will also improve image quality of * resized images, and <b>noSmooth()</b> will disable image (and font) * smoothing altogether. * * ( end auto-generated ) * * @webref shape:attributes * @see PGraphics#noSmooth() * @see PGraphics#hint(int) * @see PApplet#size(int, int, String) */ public void smooth() { if (recorder != null) recorder.smooth(); g.smooth(); } /** * * @param level either 2, 4, or 8 */ public void smooth(int level) { if (recorder != null) recorder.smooth(level); g.smooth(level); } /** * ( begin auto-generated from noSmooth.xml ) * * Draws all geometry with jagged (aliased) edges. * * ( end auto-generated ) * @webref shape:attributes * @see PGraphics#smooth() */ public void noSmooth() { if (recorder != null) recorder.noSmooth(); g.noSmooth(); } /** * ( begin auto-generated from imageMode.xml ) * * Modifies the location from which images draw. The default mode is * <b>imageMode(CORNER)</b>, which specifies the location to be the upper * left corner and uses the fourth and fifth parameters of <b>image()</b> * to set the image's width and height. The syntax * <b>imageMode(CORNERS)</b> uses the second and third parameters of * <b>image()</b> to set the location of one corner of the image and uses * the fourth and fifth parameters to set the opposite corner. Use * <b>imageMode(CENTER)</b> to draw images centered at the given x and y * position.<br /> * <br /> * The parameter to <b>imageMode()</b> must be written in ALL CAPS because * Processing is a case-sensitive language. * * ( end auto-generated ) * * @webref image:loading_displaying * @param mode either CORNER, CORNERS, or CENTER * @see PApplet#loadImage(String, String) * @see PImage * @see PGraphics#image(PImage, float, float, float, float) * @see PGraphics#background(float, float, float, float) */ public void imageMode(int mode) { if (recorder != null) recorder.imageMode(mode); g.imageMode(mode); } /** * ( begin auto-generated from image.xml ) * * Displays images to the screen. The images must be in the sketch's "data" * directory to load correctly. Select "Add file..." from the "Sketch" menu * to add the image. Processing currently works with GIF, JPEG, and Targa * images. The <b>img</b> parameter specifies the image to display and the * <b>x</b> and <b>y</b> parameters define the location of the image from * its upper-left corner. The image is displayed at its original size * unless the <b>width</b> and <b>height</b> parameters specify a different * size.<br /> * <br /> * The <b>imageMode()</b> function changes the way the parameters work. For * example, a call to <b>imageMode(CORNERS)</b> will change the * <b>width</b> and <b>height</b> parameters to define the x and y values * of the opposite corner of the image.<br /> * <br /> * The color of an image may be modified with the <b>tint()</b> function. * This function will maintain transparency for GIF and PNG images. * * ( end auto-generated ) * * <h3>Advanced</h3> * Starting with release 0124, when using the default (JAVA2D) renderer, * smooth() will also improve image quality of resized images. * * @webref image:loading_displaying * @param img the image to display * @param a x-coordinate of the image * @param b y-coordinate of the image * @see PApplet#loadImage(String, String) * @see PImage * @see PGraphics#imageMode(int) * @see PGraphics#tint(float) * @see PGraphics#background(float, float, float, float) * @see PGraphics#alpha(int) */ public void image(PImage img, float a, float b) { if (recorder != null) recorder.image(img, a, b); g.image(img, a, b); } /** * @param c width to display the image * @param d height to display the image */ public void image(PImage img, float a, float b, float c, float d) { if (recorder != null) recorder.image(img, a, b, c, d); g.image(img, a, b, c, d); } /** * Draw an image(), also specifying u/v coordinates. * In this method, the u, v coordinates are always based on image space * location, regardless of the current textureMode(). * * @nowebref */ public void image(PImage img, float a, float b, float c, float d, int u1, int v1, int u2, int v2) { if (recorder != null) recorder.image(img, a, b, c, d, u1, v1, u2, v2); g.image(img, a, b, c, d, u1, v1, u2, v2); } /** * ( begin auto-generated from shapeMode.xml ) * * Modifies the location from which shapes draw. The default mode is * <b>shapeMode(CORNER)</b>, which specifies the location to be the upper * left corner of the shape and uses the third and fourth parameters of * <b>shape()</b> to specify the width and height. The syntax * <b>shapeMode(CORNERS)</b> uses the first and second parameters of * <b>shape()</b> to set the location of one corner and uses the third and * fourth parameters to set the opposite corner. The syntax * <b>shapeMode(CENTER)</b> draws the shape from its center point and uses * the third and forth parameters of <b>shape()</b> to specify the width * and height. The parameter must be written in "ALL CAPS" because * Processing is a case sensitive language. * * ( end auto-generated ) * * @webref shape:loading_displaying * @param mode either CORNER, CORNERS, CENTER * @see PShape * @see PGraphics#shape(PShape) * @see PGraphics#rectMode(int) */ public void shapeMode(int mode) { if (recorder != null) recorder.shapeMode(mode); g.shapeMode(mode); } public void shape(PShape shape) { if (recorder != null) recorder.shape(shape); g.shape(shape); } /** * ( begin auto-generated from shape.xml ) * * Displays shapes to the screen. The shapes must be in the sketch's "data" * directory to load correctly. Select "Add file..." from the "Sketch" menu * to add the shape. Processing currently works with SVG shapes only. The * <b>sh</b> parameter specifies the shape to display and the <b>x</b> and * <b>y</b> parameters define the location of the shape from its upper-left * corner. The shape is displayed at its original size unless the * <b>width</b> and <b>height</b> parameters specify a different size. The * <b>shapeMode()</b> function changes the way the parameters work. A call * to <b>shapeMode(CORNERS)</b>, for example, will change the width and * height parameters to define the x and y values of the opposite corner of * the shape. * <br /><br /> * Note complex shapes may draw awkwardly with P3D. This renderer does not * yet support shapes that have holes or complicated breaks. * * ( end auto-generated ) * * @webref shape:loading_displaying * @param shape the shape to display * @param x x-coordinate of the shape * @param y y-coordinate of the shape * @see PShape * @see PApplet#loadShape(String) * @see PGraphics#shapeMode(int) * * Convenience method to draw at a particular location. */ public void shape(PShape shape, float x, float y) { if (recorder != null) recorder.shape(shape, x, y); g.shape(shape, x, y); } /** * @param a x-coordinate of the shape * @param b y-coordinate of the shape * @param c width to display the shape * @param d height to display the shape */ public void shape(PShape shape, float a, float b, float c, float d) { if (recorder != null) recorder.shape(shape, a, b, c, d); g.shape(shape, a, b, c, d); } public void textAlign(int alignX) { if (recorder != null) recorder.textAlign(alignX); g.textAlign(alignX); } /** * ( begin auto-generated from textAlign.xml ) * * Sets the current alignment for drawing text. The parameters LEFT, * CENTER, and RIGHT set the display characteristics of the letters in * relation to the values for the <b>x</b> and <b>y</b> parameters of the * <b>text()</b> function. * <br/> <br/> * In Processing 0125 and later, an optional second parameter can be used * to vertically align the text. BASELINE is the default, and the vertical * alignment will be reset to BASELINE if the second parameter is not used. * The TOP and CENTER parameters are straightforward. The BOTTOM parameter * offsets the line based on the current <b>textDescent()</b>. For multiple * lines, the final line will be aligned to the bottom, with the previous * lines appearing above it. * <br/> <br/> * When using <b>text()</b> with width and height parameters, BASELINE is * ignored, and treated as TOP. (Otherwise, text would by default draw * outside the box, since BASELINE is the default setting. BASELINE is not * a useful drawing mode for text drawn in a rectangle.) * <br/> <br/> * The vertical alignment is based on the value of <b>textAscent()</b>, * which many fonts do not specify correctly. It may be necessary to use a * hack and offset by a few pixels by hand so that the offset looks * correct. To do this as less of a hack, use some percentage of * <b>textAscent()</b> or <b>textDescent()</b> so that the hack works even * if you change the size of the font. * * ( end auto-generated ) * * @webref typography:attributes * @param alignX horizontal alignment, either LEFT, CENTER, or RIGHT * @param alignY vertical alignment, either TOP, BOTTOM, CENTER, or BASELINE * @see PApplet#loadFont(String) * @see PFont * @see PGraphics#text(String, float, float) */ public void textAlign(int alignX, int alignY) { if (recorder != null) recorder.textAlign(alignX, alignY); g.textAlign(alignX, alignY); } /** * ( begin auto-generated from textAscent.xml ) * * Returns ascent of the current font at its current size. This information * is useful for determining the height of the font above the baseline. For * example, adding the <b>textAscent()</b> and <b>textDescent()</b> values * will give you the total height of the line. * * ( end auto-generated ) * * @webref typography:metrics * @see PGraphics#textDescent() */ public float textAscent() { return g.textAscent(); } /** * ( begin auto-generated from textDescent.xml ) * * Returns descent of the current font at its current size. This * information is useful for determining the height of the font below the * baseline. For example, adding the <b>textAscent()</b> and * <b>textDescent()</b> values will give you the total height of the line. * * ( end auto-generated ) * * @webref typography:metrics * @see PGraphics#textAscent() */ public float textDescent() { return g.textDescent(); } /** * ( begin auto-generated from textFont.xml ) * * Sets the current font that will be drawn with the <b>text()</b> * function. Fonts must be loaded with <b>loadFont()</b> before it can be * used. This font will be used in all subsequent calls to the * <b>text()</b> function. If no <b>size</b> parameter is input, the font * will appear at its original size (the size it was created at with the * "Create Font..." tool) until it is changed with <b>textSize()</b>. <br * /> <br /> Because fonts are usually bitmaped, you should create fonts at * the sizes that will be used most commonly. Using <b>textFont()</b> * without the size parameter will result in the cleanest-looking text. <br * /><br /> With the default (JAVA2D) and PDF renderers, it's also possible * to enable the use of native fonts via the command * <b>hint(ENABLE_NATIVE_FONTS)</b>. This will produce vector text in * JAVA2D sketches and PDF output in cases where the vector data is * available: when the font is still installed, or the font is created via * the <b>createFont()</b> function (rather than the Create Font tool). * * ( end auto-generated ) * * @webref typography:loading_displaying * @param which any variable of the type PFont * @see PApplet#createFont(String, float, boolean) * @see PApplet#loadFont(String) * @see PFont * @see PGraphics#text(String, float, float) */ public void textFont(PFont which) { if (recorder != null) recorder.textFont(which); g.textFont(which); } /** * @param size the size of the letters in units of pixels */ public void textFont(PFont which, float size) { if (recorder != null) recorder.textFont(which, size); g.textFont(which, size); } /** * ( begin auto-generated from textLeading.xml ) * * Sets the spacing between lines of text in units of pixels. This setting * will be used in all subsequent calls to the <b>text()</b> function. * * ( end auto-generated ) * * @webref typography:attributes * @param leading the size in pixels for spacing between lines * @see PApplet#loadFont(String) * @see PFont#PFont * @see PGraphics#text(String, float, float) * @see PGraphics#textFont(PFont) */ public void textLeading(float leading) { if (recorder != null) recorder.textLeading(leading); g.textLeading(leading); } /** * ( begin auto-generated from textMode.xml ) * * Sets the way text draws to the screen. In the default configuration, the * <b>MODEL</b> mode, it's possible to rotate, scale, and place letters in * two and three dimensional space.<br /> * <br /> * The <b>SHAPE</b> mode draws text using the the glyph outlines of * individual characters rather than as textures. This mode is only * supported with the <b>PDF</b> and <b>P3D</b> renderer settings. With the * <b>PDF</b> renderer, you must call <b>textMode(SHAPE)</b> before any * other drawing occurs. If the outlines are not available, then * <b>textMode(SHAPE)</b> will be ignored and <b>textMode(MODEL)</b> will * be used instead.<br /> * <br /> * The <b>textMode(SHAPE)</b> option in <b>P3D</b> can be combined with * <b>beginRaw()</b> to write vector-accurate text to 2D and 3D output * files, for instance <b>DXF</b> or <b>PDF</b>. The <b>SHAPE</b> mode is * not currently optimized for <b>P3D</b>, so if recording shape data, use * <b>textMode(MODEL)</b> until you're ready to capture the geometry with <b>beginRaw()</b>. * * ( end auto-generated ) * * @webref typography:attributes * @param mode either MODEL or SHAPE * @see PApplet#loadFont(String) * @see PFont#PFont * @see PGraphics#text(String, float, float) * @see PGraphics#textFont(PFont) * @see PGraphics#beginRaw(PGraphics) * @see PApplet#createFont(String, float, boolean) */ public void textMode(int mode) { if (recorder != null) recorder.textMode(mode); g.textMode(mode); } /** * ( begin auto-generated from textSize.xml ) * * Sets the current font size. This size will be used in all subsequent * calls to the <b>text()</b> function. Font size is measured in units of pixels. * * ( end auto-generated ) * * @webref typography:attributes * @param size the size of the letters in units of pixels * @see PApplet#loadFont(String) * @see PFont#PFont * @see PGraphics#text(String, float, float) * @see PGraphics#textFont(PFont) */ public void textSize(float size) { if (recorder != null) recorder.textSize(size); g.textSize(size); } /** * @param c the character to measure */ public float textWidth(char c) { return g.textWidth(c); } /** * ( begin auto-generated from textWidth.xml ) * * Calculates and returns the width of any character or text string. * * ( end auto-generated ) * * @webref typography:attributes * @param str the String of characters to measure * @see PApplet#loadFont(String) * @see PFont#PFont * @see PGraphics#text(String, float, float) * @see PGraphics#textFont(PFont) */ public float textWidth(String str) { return g.textWidth(str); } /** * @nowebref */ public float textWidth(char[] chars, int start, int length) { return g.textWidth(chars, start, length); } /** * ( begin auto-generated from text.xml ) * * Draws text to the screen. Displays the information specified in the * <b>data</b> or <b>stringdata</b> parameters on the screen in the * position specified by the <b>x</b> and <b>y</b> parameters and the * optional <b>z</b> parameter. A default font will be used unless a font * is set with the <b>textFont()</b> function. Change the color of the text * with the <b>fill()</b> function. The text displays in relation to the * <b>textAlign()</b> function, which gives the option to draw to the left, * right, and center of the coordinates. * <br /><br /> * The <b>x2</b> and <b>y2</b> parameters define a rectangular area to * display within and may only be used with string data. For text drawn * inside a rectangle, the coordinates are interpreted based on the current * <b>rectMode()</b> setting. * * ( end auto-generated ) * * @webref typography:loading_displaying * @param c the alphanumeric character to be displayed * @param x x-coordinate of text * @param y y-coordinate of text * @see PGraphics#textAlign(int, int) * @see PGraphics#textMode(int) * @see PApplet#loadFont(String) * @see PGraphics#textFont(PFont) * @see PGraphics#rectMode(int) * @see PGraphics#fill(int, float) * @see_external String */ public void text(char c, float x, float y) { if (recorder != null) recorder.text(c, x, y); g.text(c, x, y); } /** * @param z z-coordinate of text */ public void text(char c, float x, float y, float z) { if (recorder != null) recorder.text(c, x, y, z); g.text(c, x, y, z); } /** * <h3>Advanced</h3> * Draw a chunk of text. * Newlines that are \n (Unix newline or linefeed char, ascii 10) * are honored, but \r (carriage return, Windows and Mac OS) are * ignored. */ public void text(String str, float x, float y) { if (recorder != null) recorder.text(str, x, y); g.text(str, x, y); } /** * <h3>Advanced</h3> * Method to draw text from an array of chars. This method will usually be * more efficient than drawing from a String object, because the String will * not be converted to a char array before drawing. * @param chars the alphanumberic symbols to be displayed * @param start array index at which to start writing characters * @param stop array index at which to stop writing characters */ public void text(char[] chars, int start, int stop, float x, float y) { if (recorder != null) recorder.text(chars, start, stop, x, y); g.text(chars, start, stop, x, y); } /** * Same as above but with a z coordinate. */ public void text(String str, float x, float y, float z) { if (recorder != null) recorder.text(str, x, y, z); g.text(str, x, y, z); } public void text(char[] chars, int start, int stop, float x, float y, float z) { if (recorder != null) recorder.text(chars, start, stop, x, y, z); g.text(chars, start, stop, x, y, z); } /** * <h3>Advanced</h3> * Draw text in a box that is constrained to a particular size. * The current rectMode() determines what the coordinates mean * (whether x1/y1/x2/y2 or x/y/w/h). * <P/> * Note that the x,y coords of the start of the box * will align with the *ascent* of the text, not the baseline, * as is the case for the other text() functions. * <P/> * Newlines that are \n (Unix newline or linefeed char, ascii 10) * are honored, and \r (carriage return, Windows and Mac OS) are * ignored. * * @param x1 by default, the x-coordinate of text, see rectMode() for more info * @param y1 by default, the x-coordinate of text, see rectMode() for more info * @param x2 by default, the width of the text box, see rectMode() for more info * @param y2 by default, the height of the text box, see rectMode() for more info */ public void text(String str, float x1, float y1, float x2, float y2) { if (recorder != null) recorder.text(str, x1, y1, x2, y2); g.text(str, x1, y1, x2, y2); } public void text(int num, float x, float y) { if (recorder != null) recorder.text(num, x, y); g.text(num, x, y); } public void text(int num, float x, float y, float z) { if (recorder != null) recorder.text(num, x, y, z); g.text(num, x, y, z); } /** * This does a basic number formatting, to avoid the * generally ugly appearance of printing floats. * Users who want more control should use their own nf() cmmand, * or if they want the long, ugly version of float, * use String.valueOf() to convert the float to a String first. * * @param num the numeric value to be displayed */ public void text(float num, float x, float y) { if (recorder != null) recorder.text(num, x, y); g.text(num, x, y); } public void text(float num, float x, float y, float z) { if (recorder != null) recorder.text(num, x, y, z); g.text(num, x, y, z); } /** * ( begin auto-generated from pushMatrix.xml ) * * Pushes the current transformation matrix onto the matrix stack. * Understanding <b>pushMatrix()</b> and <b>popMatrix()</b> requires * understanding the concept of a matrix stack. The <b>pushMatrix()</b> * function saves the current coordinate system to the stack and * <b>popMatrix()</b> restores the prior coordinate system. * <b>pushMatrix()</b> and <b>popMatrix()</b> are used in conjuction with * the other transformation functions and may be embedded to control the * scope of the transformations. * * ( end auto-generated ) * * @webref transform * @see PGraphics#popMatrix() * @see PGraphics#translate(float, float, float) * @see PGraphics#rotate(float) * @see PGraphics#rotateX(float) * @see PGraphics#rotateY(float) * @see PGraphics#rotateZ(float) */ public void pushMatrix() { if (recorder != null) recorder.pushMatrix(); g.pushMatrix(); } /** * ( begin auto-generated from popMatrix.xml ) * * Pops the current transformation matrix off the matrix stack. * Understanding pushing and popping requires understanding the concept of * a matrix stack. The <b>pushMatrix()</b> function saves the current * coordinate system to the stack and <b>popMatrix()</b> restores the prior * coordinate system. <b>pushMatrix()</b> and <b>popMatrix()</b> are used * in conjuction with the other transformation functions and may be * embedded to control the scope of the transformations. * * ( end auto-generated ) * * @webref transform * @see PGraphics#pushMatrix() */ public void popMatrix() { if (recorder != null) recorder.popMatrix(); g.popMatrix(); } /** * ( begin auto-generated from translate.xml ) * * Specifies an amount to displace objects within the display window. The * <b>x</b> parameter specifies left/right translation, the <b>y</b> * parameter specifies up/down translation, and the <b>z</b> parameter * specifies translations toward/away from the screen. Using this function * with the <b>z</b> parameter requires using P3D as a parameter in * combination with size as shown in the above example. Transformations * apply to everything that happens after and subsequent calls to the * function accumulates the effect. For example, calling <b>translate(50, * 0)</b> and then <b>translate(20, 0)</b> is the same as <b>translate(70, * 0)</b>. If <b>translate()</b> is called within <b>draw()</b>, the * transformation is reset when the loop begins again. This function can be * further controlled by the <b>pushMatrix()</b> and <b>popMatrix()</b>. * * ( end auto-generated ) * * @webref transform * @param x left/right translation * @param y up/down translation * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#rotate(float) * @see PGraphics#rotateX(float) * @see PGraphics#rotateY(float) * @see PGraphics#rotateZ(float) * @see PGraphics#scale(float, float, float) */ public void translate(float x, float y) { if (recorder != null) recorder.translate(x, y); g.translate(x, y); } /** * @param z forward/backward translation */ public void translate(float x, float y, float z) { if (recorder != null) recorder.translate(x, y, z); g.translate(x, y, z); } /** * ( begin auto-generated from rotate.xml ) * * Rotates a shape the amount specified by the <b>angle</b> parameter. * Angles should be specified in radians (values from 0 to TWO_PI) or * converted to radians with the <b>radians()</b> function. * <br/> <br/> * Objects are always rotated around their relative position to the origin * and positive numbers rotate objects in a clockwise direction. * Transformations apply to everything that happens after and subsequent * calls to the function accumulates the effect. For example, calling * <b>rotate(HALF_PI)</b> and then <b>rotate(HALF_PI)</b> is the same as * <b>rotate(PI)</b>. All tranformations are reset when <b>draw()</b> * begins again. * <br/> <br/> * Technically, <b>rotate()</b> multiplies the current transformation * matrix by a rotation matrix. This function can be further controlled by * the <b>pushMatrix()</b> and <b>popMatrix()</b>. * * ( end auto-generated ) * * @webref transform * @param angle angle of rotation specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#rotateX(float) * @see PGraphics#rotateY(float) * @see PGraphics#rotateZ(float) * @see PGraphics#scale(float, float, float) * @see PApplet#radians(float) */ public void rotate(float angle) { if (recorder != null) recorder.rotate(angle); g.rotate(angle); } /** * ( begin auto-generated from rotateX.xml ) * * Rotates a shape around the x-axis the amount specified by the * <b>angle</b> parameter. Angles should be specified in radians (values * from 0 to PI*2) or converted to radians with the <b>radians()</b> * function. Objects are always rotated around their relative position to * the origin and positive numbers rotate objects in a counterclockwise * direction. Transformations apply to everything that happens after and * subsequent calls to the function accumulates the effect. For example, * calling <b>rotateX(PI/2)</b> and then <b>rotateX(PI/2)</b> is the same * as <b>rotateX(PI)</b>. If <b>rotateX()</b> is called within the * <b>draw()</b>, the transformation is reset when the loop begins again. * This function requires using P3D as a third parameter to <b>size()</b> * as shown in the example above. * * ( end auto-generated ) * * @webref transform * @param angle angle of rotation specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#rotate(float) * @see PGraphics#rotateY(float) * @see PGraphics#rotateZ(float) * @see PGraphics#scale(float, float, float) * @see PGraphics#translate(float, float, float) */ public void rotateX(float angle) { if (recorder != null) recorder.rotateX(angle); g.rotateX(angle); } /** * ( begin auto-generated from rotateY.xml ) * * Rotates a shape around the y-axis the amount specified by the * <b>angle</b> parameter. Angles should be specified in radians (values * from 0 to PI*2) or converted to radians with the <b>radians()</b> * function. Objects are always rotated around their relative position to * the origin and positive numbers rotate objects in a counterclockwise * direction. Transformations apply to everything that happens after and * subsequent calls to the function accumulates the effect. For example, * calling <b>rotateY(PI/2)</b> and then <b>rotateY(PI/2)</b> is the same * as <b>rotateY(PI)</b>. If <b>rotateY()</b> is called within the * <b>draw()</b>, the transformation is reset when the loop begins again. * This function requires using P3D as a third parameter to <b>size()</b> * as shown in the examples above. * * ( end auto-generated ) * * @webref transform * @param angle angle of rotation specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#rotate(float) * @see PGraphics#rotateX(float) * @see PGraphics#rotateZ(float) * @see PGraphics#scale(float, float, float) * @see PGraphics#translate(float, float, float) */ public void rotateY(float angle) { if (recorder != null) recorder.rotateY(angle); g.rotateY(angle); } /** * ( begin auto-generated from rotateZ.xml ) * * Rotates a shape around the z-axis the amount specified by the * <b>angle</b> parameter. Angles should be specified in radians (values * from 0 to PI*2) or converted to radians with the <b>radians()</b> * function. Objects are always rotated around their relative position to * the origin and positive numbers rotate objects in a counterclockwise * direction. Transformations apply to everything that happens after and * subsequent calls to the function accumulates the effect. For example, * calling <b>rotateZ(PI/2)</b> and then <b>rotateZ(PI/2)</b> is the same * as <b>rotateZ(PI)</b>. If <b>rotateZ()</b> is called within the * <b>draw()</b>, the transformation is reset when the loop begins again. * This function requires using P3D as a third parameter to <b>size()</b> * as shown in the examples above. * * ( end auto-generated ) * * @webref transform * @param angle angle of rotation specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#rotate(float) * @see PGraphics#rotateX(float) * @see PGraphics#rotateY(float) * @see PGraphics#scale(float, float, float) * @see PGraphics#translate(float, float, float) */ public void rotateZ(float angle) { if (recorder != null) recorder.rotateZ(angle); g.rotateZ(angle); } /** * <h3>Advanced</h3> * Rotate about a vector in space. Same as the glRotatef() function. * @param x * @param y * @param z */ public void rotate(float angle, float x, float y, float z) { if (recorder != null) recorder.rotate(angle, x, y, z); g.rotate(angle, x, y, z); } /** * ( begin auto-generated from scale.xml ) * * Increases or decreases the size of a shape by expanding and contracting * vertices. Objects always scale from their relative origin to the * coordinate system. Scale values are specified as decimal percentages. * For example, the function call <b>scale(2.0)</b> increases the dimension * of a shape by 200%. Transformations apply to everything that happens * after and subsequent calls to the function multiply the effect. For * example, calling <b>scale(2.0)</b> and then <b>scale(1.5)</b> is the * same as <b>scale(3.0)</b>. If <b>scale()</b> is called within * <b>draw()</b>, the transformation is reset when the loop begins again. * Using this fuction with the <b>z</b> parameter requires using P3D as a * parameter for <b>size()</b> as shown in the example above. This function * can be further controlled by <b>pushMatrix()</b> and <b>popMatrix()</b>. * * ( end auto-generated ) * * @webref transform * @param s percentage to scale the object * @see PGraphics#pushMatrix() * @see PGraphics#popMatrix() * @see PGraphics#translate(float, float, float) * @see PGraphics#rotate(float) * @see PGraphics#rotateX(float) * @see PGraphics#rotateY(float) * @see PGraphics#rotateZ(float) */ public void scale(float s) { if (recorder != null) recorder.scale(s); g.scale(s); } /** * <h3>Advanced</h3> * Scale in X and Y. Equivalent to scale(sx, sy, 1). * * Not recommended for use in 3D, because the z-dimension is just * scaled by 1, since there's no way to know what else to scale it by. * * @param x percentage to scale the object in the x-axis * @param y percentage to scale the object in the y-axis */ public void scale(float x, float y) { if (recorder != null) recorder.scale(x, y); g.scale(x, y); } /** * @param z percentage to scale the object in the z-axis */ public void scale(float x, float y, float z) { if (recorder != null) recorder.scale(x, y, z); g.scale(x, y, z); } /** * ( begin auto-generated from shearX.xml ) * * Shears a shape around the x-axis the amount specified by the * <b>angle</b> parameter. Angles should be specified in radians (values * from 0 to PI*2) or converted to radians with the <b>radians()</b> * function. Objects are always sheared around their relative position to * the origin and positive numbers shear objects in a clockwise direction. * Transformations apply to everything that happens after and subsequent * calls to the function accumulates the effect. For example, calling * <b>shearX(PI/2)</b> and then <b>shearX(PI/2)</b> is the same as * <b>shearX(PI)</b>. If <b>shearX()</b> is called within the * <b>draw()</b>, the transformation is reset when the loop begins again. * <br/> <br/> * Technically, <b>shearX()</b> multiplies the current transformation * matrix by a rotation matrix. This function can be further controlled by * the <b>pushMatrix()</b> and <b>popMatrix()</b> functions. * * ( end auto-generated ) * * @webref transform * @param angle angle of shear specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#shearY(float) * @see PGraphics#scale(float, float, float) * @see PGraphics#translate(float, float, float) * @see PApplet#radians(float) */ public void shearX(float angle) { if (recorder != null) recorder.shearX(angle); g.shearX(angle); } /** * ( begin auto-generated from shearY.xml ) * * Shears a shape around the y-axis the amount specified by the * <b>angle</b> parameter. Angles should be specified in radians (values * from 0 to PI*2) or converted to radians with the <b>radians()</b> * function. Objects are always sheared around their relative position to * the origin and positive numbers shear objects in a clockwise direction. * Transformations apply to everything that happens after and subsequent * calls to the function accumulates the effect. For example, calling * <b>shearY(PI/2)</b> and then <b>shearY(PI/2)</b> is the same as * <b>shearY(PI)</b>. If <b>shearY()</b> is called within the * <b>draw()</b>, the transformation is reset when the loop begins again. * <br/> <br/> * Technically, <b>shearY()</b> multiplies the current transformation * matrix by a rotation matrix. This function can be further controlled by * the <b>pushMatrix()</b> and <b>popMatrix()</b> functions. * * ( end auto-generated ) * * @webref transform * @param angle angle of shear specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#shearX(float) * @see PGraphics#scale(float, float, float) * @see PGraphics#translate(float, float, float) * @see PApplet#radians(float) */ public void shearY(float angle) { if (recorder != null) recorder.shearY(angle); g.shearY(angle); } /** * ( begin auto-generated from resetMatrix.xml ) * * Replaces the current matrix with the identity matrix. The equivalent * function in OpenGL is glLoadIdentity(). * * ( end auto-generated ) * * @webref transform * @see PGraphics#pushMatrix() * @see PGraphics#popMatrix() * @see PGraphics#applyMatrix(PMatrix) * @see PGraphics#printMatrix() */ public void resetMatrix() { if (recorder != null) recorder.resetMatrix(); g.resetMatrix(); } /** * ( begin auto-generated from applyMatrix.xml ) * * Multiplies the current matrix by the one specified through the * parameters. This is very slow because it will try to calculate the * inverse of the transform, so avoid it whenever possible. The equivalent * function in OpenGL is glMultMatrix(). * * ( end auto-generated ) * * @webref transform * @source * @see PGraphics#pushMatrix() * @see PGraphics#popMatrix() * @see PGraphics#resetMatrix() * @see PGraphics#printMatrix() */ public void applyMatrix(PMatrix source) { if (recorder != null) recorder.applyMatrix(source); g.applyMatrix(source); } public void applyMatrix(PMatrix2D source) { if (recorder != null) recorder.applyMatrix(source); g.applyMatrix(source); } /** * @param n00 numbers which define the 4x4 matrix to be multiplied * @param n01 numbers which define the 4x4 matrix to be multiplied * @param n02 numbers which define the 4x4 matrix to be multiplied * @param n10 numbers which define the 4x4 matrix to be multiplied * @param n11 numbers which define the 4x4 matrix to be multiplied * @param n12 numbers which define the 4x4 matrix to be multiplied */ public void applyMatrix(float n00, float n01, float n02, float n10, float n11, float n12) { if (recorder != null) recorder.applyMatrix(n00, n01, n02, n10, n11, n12); g.applyMatrix(n00, n01, n02, n10, n11, n12); } public void applyMatrix(PMatrix3D source) { if (recorder != null) recorder.applyMatrix(source); g.applyMatrix(source); } /** * @param n03 numbers which define the 4x4 matrix to be multiplied * @param n13 numbers which define the 4x4 matrix to be multiplied * @param n20 numbers which define the 4x4 matrix to be multiplied * @param n21 numbers which define the 4x4 matrix to be multiplied * @param n22 numbers which define the 4x4 matrix to be multiplied * @param n23 numbers which define the 4x4 matrix to be multiplied * @param n30 numbers which define the 4x4 matrix to be multiplied * @param n31 numbers which define the 4x4 matrix to be multiplied * @param n32 numbers which define the 4x4 matrix to be multiplied * @param n33 numbers which define the 4x4 matrix to be multiplied */ public void applyMatrix(float n00, float n01, float n02, float n03, float n10, float n11, float n12, float n13, float n20, float n21, float n22, float n23, float n30, float n31, float n32, float n33) { if (recorder != null) recorder.applyMatrix(n00, n01, n02, n03, n10, n11, n12, n13, n20, n21, n22, n23, n30, n31, n32, n33); g.applyMatrix(n00, n01, n02, n03, n10, n11, n12, n13, n20, n21, n22, n23, n30, n31, n32, n33); } public PMatrix getMatrix() { return g.getMatrix(); } /** * Copy the current transformation matrix into the specified target. * Pass in null to create a new matrix. */ public PMatrix2D getMatrix(PMatrix2D target) { return g.getMatrix(target); } /** * Copy the current transformation matrix into the specified target. * Pass in null to create a new matrix. */ public PMatrix3D getMatrix(PMatrix3D target) { return g.getMatrix(target); } /** * Set the current transformation matrix to the contents of another. */ public void setMatrix(PMatrix source) { if (recorder != null) recorder.setMatrix(source); g.setMatrix(source); } /** * Set the current transformation to the contents of the specified source. */ public void setMatrix(PMatrix2D source) { if (recorder != null) recorder.setMatrix(source); g.setMatrix(source); } /** * Set the current transformation to the contents of the specified source. */ public void setMatrix(PMatrix3D source) { if (recorder != null) recorder.setMatrix(source); g.setMatrix(source); } /** * ( begin auto-generated from printMatrix.xml ) * * Prints the current matrix to the Console (the text window at the bottom * of Processing). * * ( end auto-generated ) * * @webref transform * @see PGraphics#pushMatrix() * @see PGraphics#popMatrix() * @see PGraphics#resetMatrix() * @see PGraphics#applyMatrix(PMatrix) */ public void printMatrix() { if (recorder != null) recorder.printMatrix(); g.printMatrix(); } /** * ( begin auto-generated from beginCamera.xml ) * * The <b>beginCamera()</b> and <b>endCamera()</b> functions enable * advanced customization of the camera space. The functions are useful if * you want to more control over camera movement, however for most users, * the <b>camera()</b> function will be sufficient.<br /><br />The camera * functions will replace any transformations (such as <b>rotate()</b> or * <b>translate()</b>) that occur before them in <b>draw()</b>, but they * will not automatically replace the camera transform itself. For this * reason, camera functions should be placed at the beginning of * <b>draw()</b> (so that transformations happen afterwards), and the * <b>camera()</b> function can be used after <b>beginCamera()</b> if you * want to reset the camera before applying transformations.<br /><br * />This function sets the matrix mode to the camera matrix so calls such * as <b>translate()</b>, <b>rotate()</b>, applyMatrix() and resetMatrix() * affect the camera. <b>beginCamera()</b> should always be used with a * following <b>endCamera()</b> and pairs of <b>beginCamera()</b> and * <b>endCamera()</b> cannot be nested. * * ( end auto-generated ) * * @webref lights_camera:camera * @see PGraphics#camera() * @see PGraphics#endCamera() * @see PGraphics#applyMatrix(PMatrix) * @see PGraphics#resetMatrix() * @see PGraphics#translate(float, float, float) * @see PGraphics#scale(float, float, float) */ public void beginCamera() { if (recorder != null) recorder.beginCamera(); g.beginCamera(); } /** * ( begin auto-generated from endCamera.xml ) * * The <b>beginCamera()</b> and <b>endCamera()</b> functions enable * advanced customization of the camera space. Please see the reference for * <b>beginCamera()</b> for a description of how the functions are used. * * ( end auto-generated ) * * @webref lights_camera:camera * @see PGraphics#camera(float, float, float, float, float, float, float, float, float) */ public void endCamera() { if (recorder != null) recorder.endCamera(); g.endCamera(); } /** * ( begin auto-generated from camera.xml ) * * Sets the position of the camera through setting the eye position, the * center of the scene, and which axis is facing upward. Moving the eye * position and the direction it is pointing (the center of the scene) * allows the images to be seen from different angles. The version without * any parameters sets the camera to the default position, pointing to the * center of the display window with the Y axis as up. The default values * are <b>camera(width/2.0, height/2.0, (height/2.0) / tan(PI*30.0 / * 180.0), width/2.0, height/2.0, 0, 0, 1, 0)</b>. This function is similar * to <b>gluLookAt()</b> in OpenGL, but it first clears the current camera settings. * * ( end auto-generated ) * * @webref lights_camera:camera * @see PGraphics#endCamera() * @see PGraphics#frustum(float, float, float, float, float, float) */ public void camera() { if (recorder != null) recorder.camera(); g.camera(); } /** * @param eyeX x-coordinate for the eye * @param eyeY y-coordinate for the eye * @param eyeZ z-coordinate for the eye * @param centerX x-coordinate for the center of the scene * @param centerY y-coordinate for the center of the scene * @param centerZ z-coordinate for the center of the scene * @param upX usually 0.0, 1.0, or -1.0 * @param upY usually 0.0, 1.0, or -1.0 * @param upZ usually 0.0, 1.0, or -1.0 */ public void camera(float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ) { if (recorder != null) recorder.camera(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ); g.camera(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ); } /** * ( begin auto-generated from printCamera.xml ) * * Prints the current camera matrix to the Console (the text window at the * bottom of Processing). * * ( end auto-generated ) * @webref lights_camera:camera * @see PGraphics#camera(float, float, float, float, float, float, float, float, float) */ public void printCamera() { if (recorder != null) recorder.printCamera(); g.printCamera(); } /** * ( begin auto-generated from ortho.xml ) * * Sets an orthographic projection and defines a parallel clipping volume. * All objects with the same dimension appear the same size, regardless of * whether they are near or far from the camera. The parameters to this * function specify the clipping volume where left and right are the * minimum and maximum x values, top and bottom are the minimum and maximum * y values, and near and far are the minimum and maximum z values. If no * parameters are given, the default is used: ortho(0, width, 0, height, * -10, 10). * * ( end auto-generated ) * * @webref lights_camera:camera */ public void ortho() { if (recorder != null) recorder.ortho(); g.ortho(); } /** * @param left left plane of the clipping volume * @param right right plane of the clipping volume * @param bottom bottom plane of the clipping volume * @param top top plane of the clipping volume */ public void ortho(float left, float right, float bottom, float top) { if (recorder != null) recorder.ortho(left, right, bottom, top); g.ortho(left, right, bottom, top); } /** * @param near maximum distance from the origin to the viewer * @param far maximum distance from the origin away from the viewer */ public void ortho(float left, float right, float bottom, float top, float near, float far) { if (recorder != null) recorder.ortho(left, right, bottom, top, near, far); g.ortho(left, right, bottom, top, near, far); } /** * ( begin auto-generated from perspective.xml ) * * Sets a perspective projection applying foreshortening, making distant * objects appear smaller than closer ones. The parameters define a viewing * volume with the shape of truncated pyramid. Objects near to the front of * the volume appear their actual size, while farther objects appear * smaller. This projection simulates the perspective of the world more * accurately than orthographic projection. The version of perspective * without parameters sets the default perspective and the version with * four parameters allows the programmer to set the area precisely. The * default values are: perspective(PI/3.0, width/height, cameraZ/10.0, * cameraZ*10.0) where cameraZ is ((height/2.0) / tan(PI*60.0/360.0)); * * ( end auto-generated ) * * @webref lights_camera:camera */ public void perspective() { if (recorder != null) recorder.perspective(); g.perspective(); } /** * @param fovy field-of-view angle (in radians) for vertical direction * @param aspect ratio of width to height * @param zNear z-position of nearest clipping plane * @param zFar z-position of farthest clipping plane */ public void perspective(float fovy, float aspect, float zNear, float zFar) { if (recorder != null) recorder.perspective(fovy, aspect, zNear, zFar); g.perspective(fovy, aspect, zNear, zFar); } /** * ( begin auto-generated from frustum.xml ) * * Sets a perspective matrix defined through the parameters. Works like * glFrustum, except it wipes out the current perspective matrix rather * than muliplying itself with it. * * ( end auto-generated ) * * @webref lights_camera:camera * @param left left coordinate of the clipping plane * @param right right coordinate of the clipping plane * @param bottom bottom coordinate of the clipping plane * @param top top coordinate of the clipping plane * @param near near component of the clipping plane; must be greater than zero * @param far far component of the clipping plane; must be greater than the near value * @see PGraphics#camera(float, float, float, float, float, float, float, float, float) * @see PGraphics#endCamera() * @see PGraphics#perspective(float, float, float, float) */ public void frustum(float left, float right, float bottom, float top, float near, float far) { if (recorder != null) recorder.frustum(left, right, bottom, top, near, far); g.frustum(left, right, bottom, top, near, far); } /** * ( begin auto-generated from printProjection.xml ) * * Prints the current projection matrix to the Console (the text window at * the bottom of Processing). * * ( end auto-generated ) * * @webref lights_camera:camera * @see PGraphics#camera(float, float, float, float, float, float, float, float, float) */ public void printProjection() { if (recorder != null) recorder.printProjection(); g.printProjection(); } /** * ( begin auto-generated from screenX.xml ) * * Takes a three-dimensional X, Y, Z position and returns the X value for * where it will appear on a (two-dimensional) screen. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @see PGraphics#screenY(float, float, float) * @see PGraphics#screenZ(float, float, float) */ public float screenX(float x, float y) { return g.screenX(x, y); } /** * ( begin auto-generated from screenY.xml ) * * Takes a three-dimensional X, Y, Z position and returns the Y value for * where it will appear on a (two-dimensional) screen. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @see PGraphics#screenX(float, float, float) * @see PGraphics#screenZ(float, float, float) */ public float screenY(float x, float y) { return g.screenY(x, y); } /** * @param z 3D z-coordinate to be mapped */ public float screenX(float x, float y, float z) { return g.screenX(x, y, z); } /** * @param z 3D z-coordinate to be mapped */ public float screenY(float x, float y, float z) { return g.screenY(x, y, z); } /** * ( begin auto-generated from screenZ.xml ) * * Takes a three-dimensional X, Y, Z position and returns the Z value for * where it will appear on a (two-dimensional) screen. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @param z 3D z-coordinate to be mapped * @see PGraphics#screenX(float, float, float) * @see PGraphics#screenY(float, float, float) */ public float screenZ(float x, float y, float z) { return g.screenZ(x, y, z); } /** * ( begin auto-generated from modelX.xml ) * * Returns the three-dimensional X, Y, Z position in model space. This * returns the X value for a given coordinate based on the current set of * transformations (scale, rotate, translate, etc.) The X value can be used * to place an object in space relative to the location of the original * point once the transformations are no longer in use. * <br/> <br/> * In the example, the <b>modelX()</b>, <b>modelY()</b>, and * <b>modelZ()</b> functions record the location of a box in space after * being placed using a series of translate and rotate commands. After * popMatrix() is called, those transformations no longer apply, but the * (x, y, z) coordinate returned by the model functions is used to place * another box in the same location. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @param z 3D z-coordinate to be mapped * @see PGraphics#modelY(float, float, float) * @see PGraphics#modelZ(float, float, float) */ public float modelX(float x, float y, float z) { return g.modelX(x, y, z); } /** * ( begin auto-generated from modelY.xml ) * * Returns the three-dimensional X, Y, Z position in model space. This * returns the Y value for a given coordinate based on the current set of * transformations (scale, rotate, translate, etc.) The Y value can be used * to place an object in space relative to the location of the original * point once the transformations are no longer in use.<br /> * <br /> * In the example, the <b>modelX()</b>, <b>modelY()</b>, and * <b>modelZ()</b> functions record the location of a box in space after * being placed using a series of translate and rotate commands. After * popMatrix() is called, those transformations no longer apply, but the * (x, y, z) coordinate returned by the model functions is used to place * another box in the same location. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @param z 3D z-coordinate to be mapped * @see PGraphics#modelX(float, float, float) * @see PGraphics#modelZ(float, float, float) */ public float modelY(float x, float y, float z) { return g.modelY(x, y, z); } /** * ( begin auto-generated from modelZ.xml ) * * Returns the three-dimensional X, Y, Z position in model space. This * returns the Z value for a given coordinate based on the current set of * transformations (scale, rotate, translate, etc.) The Z value can be used * to place an object in space relative to the location of the original * point once the transformations are no longer in use.<br /> * <br /> * In the example, the <b>modelX()</b>, <b>modelY()</b>, and * <b>modelZ()</b> functions record the location of a box in space after * being placed using a series of translate and rotate commands. After * popMatrix() is called, those transformations no longer apply, but the * (x, y, z) coordinate returned by the model functions is used to place * another box in the same location. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @param z 3D z-coordinate to be mapped * @see PGraphics#modelX(float, float, float) * @see PGraphics#modelY(float, float, float) */ public float modelZ(float x, float y, float z) { return g.modelZ(x, y, z); } /** * ( begin auto-generated from pushStyle.xml ) * * The <b>pushStyle()</b> function saves the current style settings and * <b>popStyle()</b> restores the prior settings. Note that these functions * are always used together. They allow you to change the style settings * and later return to what you had. When a new style is started with * <b>pushStyle()</b>, it builds on the current style information. The * <b>pushStyle()</b> and <b>popStyle()</b> functions can be embedded to * provide more control (see the second example above for a demonstration.) * <br /><br /> * The style information controlled by the following functions are included * in the style: * fill(), stroke(), tint(), strokeWeight(), strokeCap(), strokeJoin(), * imageMode(), rectMode(), ellipseMode(), shapeMode(), colorMode(), * textAlign(), textFont(), textMode(), textSize(), textLeading(), * emissive(), specular(), shininess(), ambient() * * ( end auto-generated ) * * @webref structure * @see PGraphics#popStyle() */ public void pushStyle() { if (recorder != null) recorder.pushStyle(); g.pushStyle(); } /** * ( begin auto-generated from popStyle.xml ) * * The <b>pushStyle()</b> function saves the current style settings and * <b>popStyle()</b> restores the prior settings; these functions are * always used together. They allow you to change the style settings and * later return to what you had. When a new style is started with * <b>pushStyle()</b>, it builds on the current style information. The * <b>pushStyle()</b> and <b>popStyle()</b> functions can be embedded to * provide more control (see the second example above for a demonstration.) * * ( end auto-generated ) * * @webref structure * @see PGraphics#pushStyle() */ public void popStyle() { if (recorder != null) recorder.popStyle(); g.popStyle(); } public void style(PStyle s) { if (recorder != null) recorder.style(s); g.style(s); } /** * ( begin auto-generated from strokeWeight.xml ) * * Sets the width of the stroke used for lines, points, and the border * around shapes. All widths are set in units of pixels. * <br/> <br/> * When drawing with P3D, series of connected lines (such as the stroke * around a polygon, triangle, or ellipse) produce unattractive results * when a thick stroke weight is set (<a * href="http://code.google.com/p/processing/issues/detail?id=123">see * Issue 123</a>). With P3D, the minimum and maximum values for * <b>strokeWeight()</b> are controlled by the graphics card and the * operating system's OpenGL implementation. For instance, the thickness * may not go higher than 10 pixels. * * ( end auto-generated ) * * @webref shape:attributes * @param weight the weight (in pixels) of the stroke * @see PGraphics#stroke(int, float) * @see PGraphics#strokeJoin(int) * @see PGraphics#strokeCap(int) */ public void strokeWeight(float weight) { if (recorder != null) recorder.strokeWeight(weight); g.strokeWeight(weight); } /** * ( begin auto-generated from strokeJoin.xml ) * * Sets the style of the joints which connect line segments. These joints * are either mitered, beveled, or rounded and specified with the * corresponding parameters MITER, BEVEL, and ROUND. The default joint is * MITER. * <br/> <br/> * This function is not available with the P3D renderer, (<a * href="http://code.google.com/p/processing/issues/detail?id=123">see * Issue 123</a>). More information about the renderers can be found in the * <b>size()</b> reference. * * ( end auto-generated ) * * @webref shape:attributes * @param join either MITER, BEVEL, ROUND * @see PGraphics#stroke(int, float) * @see PGraphics#strokeWeight(float) * @see PGraphics#strokeCap(int) */ public void strokeJoin(int join) { if (recorder != null) recorder.strokeJoin(join); g.strokeJoin(join); } /** * ( begin auto-generated from strokeCap.xml ) * * Sets the style for rendering line endings. These ends are either * squared, extended, or rounded and specified with the corresponding * parameters SQUARE, PROJECT, and ROUND. The default cap is ROUND. * <br/> <br/> * This function is not available with the P3D renderer (<a * href="http://code.google.com/p/processing/issues/detail?id=123">see * Issue 123</a>). More information about the renderers can be found in the * <b>size()</b> reference. * * ( end auto-generated ) * * @webref shape:attributes * @param cap either SQUARE, PROJECT, or ROUND * @see PGraphics#stroke(int, float) * @see PGraphics#strokeWeight(float) * @see PGraphics#strokeJoin(int) * @see PApplet#size(int, int, String, String) */ public void strokeCap(int cap) { if (recorder != null) recorder.strokeCap(cap); g.strokeCap(cap); } /** * ( begin auto-generated from noStroke.xml ) * * Disables drawing the stroke (outline). If both <b>noStroke()</b> and * <b>noFill()</b> are called, nothing will be drawn to the screen. * * ( end auto-generated ) * * @webref color:setting * @see PGraphics#stroke(float, float, float, float) */ public void noStroke() { if (recorder != null) recorder.noStroke(); g.noStroke(); } /** * ( begin auto-generated from stroke.xml ) * * Sets the color used to draw lines and borders around shapes. This color * is either specified in terms of the RGB or HSB color depending on the * current <b>colorMode()</b> (the default color space is RGB, with each * value in the range from 0 to 255). * <br/> <br/> * When using hexadecimal notation to specify a color, use "#" or "0x" * before the values (e.g. #CCFFAA, 0xFFCCFFAA). The # syntax uses six * digits to specify a color (the way colors are specified in HTML and * CSS). When using the hexadecimal notation starting with "0x", the * hexadecimal value must be specified with eight characters; the first two * characters define the alpha component and the remainder the red, green, * and blue components. * <br/> <br/> * The value for the parameter "gray" must be less than or equal to the * current maximum value as specified by <b>colorMode()</b>. The default * maximum value is 255. * * ( end auto-generated ) * * @param rgb color value in hexadecimal notation * @see PGraphics#noStroke() * @see PGraphics#fill(int, float) * @see PGraphics#tint(int, float) * @see PGraphics#background(float, float, float, float) * @see PGraphics#colorMode(int, float, float, float, float) */ public void stroke(int rgb) { if (recorder != null) recorder.stroke(rgb); g.stroke(rgb); } /** * @param alpha opacity of the stroke */ public void stroke(int rgb, float alpha) { if (recorder != null) recorder.stroke(rgb, alpha); g.stroke(rgb, alpha); } /** * @param gray specifies a value between white and black */ public void stroke(float gray) { if (recorder != null) recorder.stroke(gray); g.stroke(gray); } public void stroke(float gray, float alpha) { if (recorder != null) recorder.stroke(gray, alpha); g.stroke(gray, alpha); } /** * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) * @webref color:setting */ public void stroke(float v1, float v2, float v3) { if (recorder != null) recorder.stroke(v1, v2, v3); g.stroke(v1, v2, v3); } public void stroke(float v1, float v2, float v3, float alpha) { if (recorder != null) recorder.stroke(v1, v2, v3, alpha); g.stroke(v1, v2, v3, alpha); } /** * ( begin auto-generated from noTint.xml ) * * Removes the current fill value for displaying images and reverts to * displaying images with their original hues. * * ( end auto-generated ) * * @webref image:loading_displaying * @usage web_application * @see PGraphics#tint(float, float, float, float) * @see PGraphics#image(PImage, float, float, float, float) */ public void noTint() { if (recorder != null) recorder.noTint(); g.noTint(); } /** * ( begin auto-generated from tint.xml ) * * Sets the fill value for displaying images. Images can be tinted to * specified colors or made transparent by setting the alpha.<br /> * <br /> * To make an image transparent, but not change it's color, use white as * the tint color and specify an alpha value. For instance, tint(255, 128) * will make an image 50% transparent (unless <b>colorMode()</b> has been * used).<br /> * <br /> * When using hexadecimal notation to specify a color, use "#" or "0x" * before the values (e.g. #CCFFAA, 0xFFCCFFAA). The # syntax uses six * digits to specify a color (the way colors are specified in HTML and * CSS). When using the hexadecimal notation starting with "0x", the * hexadecimal value must be specified with eight characters; the first two * characters define the alpha component and the remainder the red, green, * and blue components.<br /> * <br /> * The value for the parameter "gray" must be less than or equal to the * current maximum value as specified by <b>colorMode()</b>. The default * maximum value is 255.<br /> * <br /> * The <b>tint()</b> function is also used to control the coloring of * textures in 3D. * * ( end auto-generated ) * * @webref image:loading_displaying * @usage web_application * @param rgb color value in hexadecimal notation * @see PGraphics#noTint() * @see PGraphics#image(PImage, float, float, float, float) */ public void tint(int rgb) { if (recorder != null) recorder.tint(rgb); g.tint(rgb); } /** * @param alpha opacity of the image */ public void tint(int rgb, float alpha) { if (recorder != null) recorder.tint(rgb, alpha); g.tint(rgb, alpha); } /** * @param gray specifies a value between white and black */ public void tint(float gray) { if (recorder != null) recorder.tint(gray); g.tint(gray); } public void tint(float gray, float alpha) { if (recorder != null) recorder.tint(gray, alpha); g.tint(gray, alpha); } /** * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) */ public void tint(float v1, float v2, float v3) { if (recorder != null) recorder.tint(v1, v2, v3); g.tint(v1, v2, v3); } public void tint(float v1, float v2, float v3, float alpha) { if (recorder != null) recorder.tint(v1, v2, v3, alpha); g.tint(v1, v2, v3, alpha); } /** * ( begin auto-generated from noFill.xml ) * * Disables filling geometry. If both <b>noStroke()</b> and <b>noFill()</b> * are called, nothing will be drawn to the screen. * * ( end auto-generated ) * * @webref color:setting * @usage web_application * @see PGraphics#fill(float, float, float, float) */ public void noFill() { if (recorder != null) recorder.noFill(); g.noFill(); } /** * ( begin auto-generated from fill.xml ) * * Sets the color used to fill shapes. For example, if you run <b>fill(204, * 102, 0)</b>, all subsequent shapes will be filled with orange. This * color is either specified in terms of the RGB or HSB color depending on * the current <b>colorMode()</b> (the default color space is RGB, with * each value in the range from 0 to 255). * <br/> <br/> * When using hexadecimal notation to specify a color, use "#" or "0x" * before the values (e.g. #CCFFAA, 0xFFCCFFAA). The # syntax uses six * digits to specify a color (the way colors are specified in HTML and * CSS). When using the hexadecimal notation starting with "0x", the * hexadecimal value must be specified with eight characters; the first two * characters define the alpha component and the remainder the red, green, * and blue components. * <br/> <br/> * The value for the parameter "gray" must be less than or equal to the * current maximum value as specified by <b>colorMode()</b>. The default * maximum value is 255. * <br/> <br/> * To change the color of an image (or a texture), use tint(). * * ( end auto-generated ) * * @webref color:setting * @usage web_application * @param rgb color variable or hex value * @see PGraphics#noFill() * @see PGraphics#stroke(int, float) * @see PGraphics#tint(int, float) * @see PGraphics#background(float, float, float, float) * @see PGraphics#colorMode(int, float, float, float, float) */ public void fill(int rgb) { if (recorder != null) recorder.fill(rgb); g.fill(rgb); } /** * @param alpha opacity of the fill */ public void fill(int rgb, float alpha) { if (recorder != null) recorder.fill(rgb, alpha); g.fill(rgb, alpha); } /** * @param gray number specifying value between white and black */ public void fill(float gray) { if (recorder != null) recorder.fill(gray); g.fill(gray); } public void fill(float gray, float alpha) { if (recorder != null) recorder.fill(gray, alpha); g.fill(gray, alpha); } /** * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) */ public void fill(float v1, float v2, float v3) { if (recorder != null) recorder.fill(v1, v2, v3); g.fill(v1, v2, v3); } public void fill(float v1, float v2, float v3, float alpha) { if (recorder != null) recorder.fill(v1, v2, v3, alpha); g.fill(v1, v2, v3, alpha); } /** * ( begin auto-generated from ambient.xml ) * * Sets the ambient reflectance for shapes drawn to the screen. This is * combined with the ambient light component of environment. The color * components set through the parameters define the reflectance. For * example in the default color mode, setting v1=255, v2=126, v3=0, would * cause all the red light to reflect and half of the green light to * reflect. Used in combination with <b>emissive()</b>, <b>specular()</b>, * and <b>shininess()</b> in setting the material properties of shapes. * * ( end auto-generated ) * * @webref lights_camera:material_properties * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#emissive(float, float, float) * @see PGraphics#specular(float, float, float) * @see PGraphics#shininess(float) */ public void ambient(int rgb) { if (recorder != null) recorder.ambient(rgb); g.ambient(rgb); } /** * @param gray number specifying value between white and black */ public void ambient(float gray) { if (recorder != null) recorder.ambient(gray); g.ambient(gray); } /** * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) */ public void ambient(float v1, float v2, float v3) { if (recorder != null) recorder.ambient(v1, v2, v3); g.ambient(v1, v2, v3); } /** * ( begin auto-generated from specular.xml ) * * Sets the specular color of the materials used for shapes drawn to the * screen, which sets the color of hightlights. Specular refers to light * which bounces off a surface in a perferred direction (rather than * bouncing in all directions like a diffuse light). Used in combination * with <b>emissive()</b>, <b>ambient()</b>, and <b>shininess()</b> in * setting the material properties of shapes. * * ( end auto-generated ) * * @webref lights_camera:material_properties * @usage web_application * @param rgb color to set * @see PGraphics#lightSpecular(float, float, float) * @see PGraphics#ambient(float, float, float) * @see PGraphics#emissive(float, float, float) * @see PGraphics#shininess(float) */ public void specular(int rgb) { if (recorder != null) recorder.specular(rgb); g.specular(rgb); } /** * gray number specifying value between white and black */ public void specular(float gray) { if (recorder != null) recorder.specular(gray); g.specular(gray); } /** * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) */ public void specular(float v1, float v2, float v3) { if (recorder != null) recorder.specular(v1, v2, v3); g.specular(v1, v2, v3); } /** * ( begin auto-generated from shininess.xml ) * * Sets the amount of gloss in the surface of shapes. Used in combination * with <b>ambient()</b>, <b>specular()</b>, and <b>emissive()</b> in * setting the material properties of shapes. * * ( end auto-generated ) * * @webref lights_camera:material_properties * @usage web_application * @param shine degree of shininess * @see PGraphics#emissive(float, float, float) * @see PGraphics#ambient(float, float, float) * @see PGraphics#specular(float, float, float) */ public void shininess(float shine) { if (recorder != null) recorder.shininess(shine); g.shininess(shine); } /** * ( begin auto-generated from emissive.xml ) * * Sets the emissive color of the material used for drawing shapes drawn to * the screen. Used in combination with <b>ambient()</b>, * <b>specular()</b>, and <b>shininess()</b> in setting the material * properties of shapes. * * ( end auto-generated ) * * @webref lights_camera:material_properties * @usage web_application * @param rgb color to set * @see PGraphics#ambient(float, float, float) * @see PGraphics#specular(float, float, float) * @see PGraphics#shininess(float) */ public void emissive(int rgb) { if (recorder != null) recorder.emissive(rgb); g.emissive(rgb); } /** * gray number specifying value between white and black */ public void emissive(float gray) { if (recorder != null) recorder.emissive(gray); g.emissive(gray); } /** * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) */ public void emissive(float v1, float v2, float v3) { if (recorder != null) recorder.emissive(v1, v2, v3); g.emissive(v1, v2, v3); } /** * ( begin auto-generated from lights.xml ) * * Sets the default ambient light, directional light, falloff, and specular * values. The defaults are ambientLight(128, 128, 128) and * directionalLight(128, 128, 128, 0, 0, -1), lightFalloff(1, 0, 0), and * lightSpecular(0, 0, 0). Lights need to be included in the draw() to * remain persistent in a looping program. Placing them in the setup() of a * looping program will cause them to only have an effect the first time * through the loop. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @see PGraphics#ambientLight(float, float, float, float, float, float) * @see PGraphics#directionalLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#noLights() */ public void lights() { if (recorder != null) recorder.lights(); g.lights(); } /** * ( begin auto-generated from noLights.xml ) * * Disable all lighting. Lighting is turned off by default and enabled with * the <b>lights()</b> function. This function can be used to disable * lighting so that 2D geometry (which does not require lighting) can be * drawn after a set of lighted 3D geometry. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @see PGraphics#lights() */ public void noLights() { if (recorder != null) recorder.noLights(); g.noLights(); } /** * ( begin auto-generated from ambientLight.xml ) * * Adds an ambient light. Ambient light doesn't come from a specific * direction, the rays have light have bounced around so much that objects * are evenly lit from all sides. Ambient lights are almost always used in * combination with other types of lights. Lights need to be included in * the <b>draw()</b> to remain persistent in a looping program. Placing * them in the <b>setup()</b> of a looping program will cause them to only * have an effect the first time through the loop. The effect of the * parameters is determined by the current color mode. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) * @see PGraphics#lights() * @see PGraphics#directionalLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) */ public void ambientLight(float v1, float v2, float v3) { if (recorder != null) recorder.ambientLight(v1, v2, v3); g.ambientLight(v1, v2, v3); } /** * @param x x-coordinate of the light * @param y y-coordinate of the light * @param z z-coordinate of the light */ public void ambientLight(float v1, float v2, float v3, float x, float y, float z) { if (recorder != null) recorder.ambientLight(v1, v2, v3, x, y, z); g.ambientLight(v1, v2, v3, x, y, z); } /** * ( begin auto-generated from directionalLight.xml ) * * Adds a directional light. Directional light comes from one direction and * is stronger when hitting a surface squarely and weaker if it hits at a a * gentle angle. After hitting a surface, a directional lights scatters in * all directions. Lights need to be included in the <b>draw()</b> to * remain persistent in a looping program. Placing them in the * <b>setup()</b> of a looping program will cause them to only have an * effect the first time through the loop. The affect of the <b>v1</b>, * <b>v2</b>, and <b>v3</b> parameters is determined by the current color * mode. The <b>nx</b>, <b>ny</b>, and <b>nz</b> parameters specify the * direction the light is facing. For example, setting <b>ny</b> to -1 will * cause the geometry to be lit from below (the light is facing directly upward). * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) * @param nx direction along the x-axis * @param ny direction along the y-axis * @param nz direction along the z-axis * @see PGraphics#lights() * @see PGraphics#ambientLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) */ public void directionalLight(float v1, float v2, float v3, float nx, float ny, float nz) { if (recorder != null) recorder.directionalLight(v1, v2, v3, nx, ny, nz); g.directionalLight(v1, v2, v3, nx, ny, nz); } /** * ( begin auto-generated from pointLight.xml ) * * Adds a point light. Lights need to be included in the <b>draw()</b> to * remain persistent in a looping program. Placing them in the * <b>setup()</b> of a looping program will cause them to only have an * effect the first time through the loop. The affect of the <b>v1</b>, * <b>v2</b>, and <b>v3</b> parameters is determined by the current color * mode. The <b>x</b>, <b>y</b>, and <b>z</b> parameters set the position * of the light. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) * @param x x-coordinate of the light * @param y y-coordinate of the light * @param z z-coordinate of the light * @see PGraphics#lights() * @see PGraphics#directionalLight(float, float, float, float, float, float) * @see PGraphics#ambientLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) */ public void pointLight(float v1, float v2, float v3, float x, float y, float z) { if (recorder != null) recorder.pointLight(v1, v2, v3, x, y, z); g.pointLight(v1, v2, v3, x, y, z); } /** * ( begin auto-generated from spotLight.xml ) * * Adds a spot light. Lights need to be included in the <b>draw()</b> to * remain persistent in a looping program. Placing them in the * <b>setup()</b> of a looping program will cause them to only have an * effect the first time through the loop. The affect of the <b>v1</b>, * <b>v2</b>, and <b>v3</b> parameters is determined by the current color * mode. The <b>x</b>, <b>y</b>, and <b>z</b> parameters specify the * position of the light and <b>nx</b>, <b>ny</b>, <b>nz</b> specify the * direction or light. The <b>angle</b> parameter affects angle of the * spotlight cone. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) * @param x x-coordinate of the light * @param y y-coordinate of the light * @param z z-coordinate of the light * @param nx direction along the x axis * @param ny direction along the y axis * @param nz direction along the z axis * @param angle angle of the spotlight cone * @param concentration exponent determining the center bias of the cone * @see PGraphics#lights() * @see PGraphics#directionalLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#ambientLight(float, float, float, float, float, float) */ public void spotLight(float v1, float v2, float v3, float x, float y, float z, float nx, float ny, float nz, float angle, float concentration) { if (recorder != null) recorder.spotLight(v1, v2, v3, x, y, z, nx, ny, nz, angle, concentration); g.spotLight(v1, v2, v3, x, y, z, nx, ny, nz, angle, concentration); } /** * ( begin auto-generated from lightFalloff.xml ) * * Sets the falloff rates for point lights, spot lights, and ambient * lights. The parameters are used to determine the falloff with the * following equation:<br /><br />d = distance from light position to * vertex position<br />falloff = 1 / (CONSTANT + d * LINEAR + (d*d) * * QUADRATIC)<br /><br />Like <b>fill()</b>, it affects only the elements * which are created after it in the code. The default value if * <b>LightFalloff(1.0, 0.0, 0.0)</b>. Thinking about an ambient light with * a falloff can be tricky. It is used, for example, if you wanted a region * of your scene to be lit ambiently one color and another region to be lit * ambiently by another color, you would use an ambient light with location * and falloff. You can think of it as a point light that doesn't care * which direction a surface is facing. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param constant constant value or determining falloff * @param linear linear value for determining falloff * @param quadratic quadratic value for determining falloff * @see PGraphics#lights() * @see PGraphics#ambientLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#lightSpecular(float, float, float) */ public void lightFalloff(float constant, float linear, float quadratic) { if (recorder != null) recorder.lightFalloff(constant, linear, quadratic); g.lightFalloff(constant, linear, quadratic); } /** * ( begin auto-generated from lightSpecular.xml ) * * Sets the specular color for lights. Like <b>fill()</b>, it affects only * the elements which are created after it in the code. Specular refers to * light which bounces off a surface in a perferred direction (rather than * bouncing in all directions like a diffuse light) and is used for * creating highlights. The specular quality of a light interacts with the * specular material qualities set through the <b>specular()</b> and * <b>shininess()</b> functions. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) * @see PGraphics#specular(float, float, float) * @see PGraphics#lights() * @see PGraphics#ambientLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) */ public void lightSpecular(float v1, float v2, float v3) { if (recorder != null) recorder.lightSpecular(v1, v2, v3); g.lightSpecular(v1, v2, v3); } /** * ( begin auto-generated from background.xml ) * * The <b>background()</b> function sets the color used for the background * of the Processing window. The default background is light gray. In the * <b>draw()</b> function, the background color is used to clear the * display window at the beginning of each frame. * <br/> <br/> * An image can also be used as the background for a sketch, however its * width and height must be the same size as the sketch window. To resize * an image 'b' to the size of the sketch window, use b.resize(width, height). * <br/> <br/> * Images used as background will ignore the current <b>tint()</b> setting. * <br/> <br/> * It is not possible to use transparency (alpha) in background colors with * the main drawing surface, however they will work properly with <b>createGraphics()</b>. * * ( end auto-generated ) * * <h3>Advanced</h3> * <p>Clear the background with a color that includes an alpha value. This can * only be used with objects created by createGraphics(), because the main * drawing surface cannot be set transparent.</p> * <p>It might be tempting to use this function to partially clear the screen * on each frame, however that's not how this function works. When calling * background(), the pixels will be replaced with pixels that have that level * of transparency. To do a semi-transparent overlay, use fill() with alpha * and draw a rectangle.</p> * * @webref color:setting * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#stroke(float) * @see PGraphics#fill(float) * @see PGraphics#tint(float) * @see PGraphics#colorMode(int) */ public void background(int rgb) { if (recorder != null) recorder.background(rgb); g.background(rgb); } /** * @param alpha opacity of the background */ public void background(int rgb, float alpha) { if (recorder != null) recorder.background(rgb, alpha); g.background(rgb, alpha); } /** * @param gray specifies a value between white and black */ public void background(float gray) { if (recorder != null) recorder.background(gray); g.background(gray); } public void background(float gray, float alpha) { if (recorder != null) recorder.background(gray, alpha); g.background(gray, alpha); } /** * @param v1 red or hue value (depending on the current color mode) * @param v2 green or saturation value (depending on the current color mode) * @param v3 blue or brightness value (depending on the current color mode) */ public void background(float v1, float v2, float v3) { if (recorder != null) recorder.background(v1, v2, v3); g.background(v1, v2, v3); } public void background(float v1, float v2, float v3, float alpha) { if (recorder != null) recorder.background(v1, v2, v3, alpha); g.background(v1, v2, v3, alpha); } /** * @webref color:setting */ public void clear() { if (recorder != null) recorder.clear(); g.clear(); } /** * Takes an RGB or ARGB image and sets it as the background. * The width and height of the image must be the same size as the sketch. * Use image.resize(width, height) to make short work of such a task.<br/> * <br/> * Note that even if the image is set as RGB, the high 8 bits of each pixel * should be set opaque (0xFF000000) because the image data will be copied * directly to the screen, and non-opaque background images may have strange * behavior. Use image.filter(OPAQUE) to handle this easily.<br/> * <br/> * When using 3D, this will also clear the zbuffer (if it exists). * * @param image PImage to set as background (must be same size as the sketch window) */ public void background(PImage image) { if (recorder != null) recorder.background(image); g.background(image); } /** * ( begin auto-generated from colorMode.xml ) * * Changes the way Processing interprets color data. By default, the * parameters for <b>fill()</b>, <b>stroke()</b>, <b>background()</b>, and * <b>color()</b> are defined by values between 0 and 255 using the RGB * color model. The <b>colorMode()</b> function is used to change the * numerical range used for specifying colors and to switch color systems. * For example, calling <b>colorMode(RGB, 1.0)</b> will specify that values * are specified between 0 and 1. The limits for defining colors are * altered by setting the parameters range1, range2, range3, and range 4. * * ( end auto-generated ) * * @webref color:setting * @usage web_application * @param mode Either RGB or HSB, corresponding to Red/Green/Blue and Hue/Saturation/Brightness * @see PGraphics#background(float) * @see PGraphics#fill(float) * @see PGraphics#stroke(float) */ public void colorMode(int mode) { if (recorder != null) recorder.colorMode(mode); g.colorMode(mode); } /** * @param max range for all color elements */ public void colorMode(int mode, float max) { if (recorder != null) recorder.colorMode(mode, max); g.colorMode(mode, max); } /** * @param max1 range for the red or hue depending on the current color mode * @param max2 range for the green or saturation depending on the current color mode * @param max3 range for the blue or brightness depending on the current color mode */ public void colorMode(int mode, float max1, float max2, float max3) { if (recorder != null) recorder.colorMode(mode, max1, max2, max3); g.colorMode(mode, max1, max2, max3); } /** * @param maxA range for the alpha */ public void colorMode(int mode, float max1, float max2, float max3, float maxA) { if (recorder != null) recorder.colorMode(mode, max1, max2, max3, maxA); g.colorMode(mode, max1, max2, max3, maxA); } /** * ( begin auto-generated from alpha.xml ) * * Extracts the alpha value from a color. * * ( end auto-generated ) * @webref color:creating_reading * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#green(int) * @see PGraphics#blue(int) * @see PGraphics#hue(int) * @see PGraphics#saturation(int) * @see PGraphics#brightness(int) */ public final float alpha(int rgb) { return g.alpha(rgb); } /** * ( begin auto-generated from red.xml ) * * Extracts the red value from a color, scaled to match current * <b>colorMode()</b>. This value is always returned as a float so be * careful not to assign it to an int value.<br /><br />The red() function * is easy to use and undestand, but is slower than another technique. To * achieve the same results when working in <b>colorMode(RGB, 255)</b>, but * with greater speed, use the &gt;&gt; (right shift) operator with a bit * mask. For example, the following two lines of code are equivalent:<br * /><pre>float r1 = red(myColor);<br />float r2 = myColor &gt;&gt; 16 * &amp; 0xFF;</pre> * * ( end auto-generated ) * * @webref color:creating_reading * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#green(int) * @see PGraphics#blue(int) * @see PGraphics#alpha(int) * @see PGraphics#hue(int) * @see PGraphics#saturation(int) * @see PGraphics#brightness(int) * @see_external rightshift */ public final float red(int rgb) { return g.red(rgb); } /** * ( begin auto-generated from green.xml ) * * Extracts the green value from a color, scaled to match current * <b>colorMode()</b>. This value is always returned as a float so be * careful not to assign it to an int value.<br /><br />The <b>green()</b> * function is easy to use and undestand, but is slower than another * technique. To achieve the same results when working in <b>colorMode(RGB, * 255)</b>, but with greater speed, use the &gt;&gt; (right shift) * operator with a bit mask. For example, the following two lines of code * are equivalent:<br /><pre>float r1 = green(myColor);<br />float r2 = * myColor &gt;&gt; 8 &amp; 0xFF;</pre> * * ( end auto-generated ) * * @webref color:creating_reading * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#blue(int) * @see PGraphics#alpha(int) * @see PGraphics#hue(int) * @see PGraphics#saturation(int) * @see PGraphics#brightness(int) * @see_external rightshift */ public final float green(int rgb) { return g.green(rgb); } /** * ( begin auto-generated from blue.xml ) * * Extracts the blue value from a color, scaled to match current * <b>colorMode()</b>. This value is always returned as a float so be * careful not to assign it to an int value.<br /><br />The <b>blue()</b> * function is easy to use and undestand, but is slower than another * technique. To achieve the same results when working in <b>colorMode(RGB, * 255)</b>, but with greater speed, use a bit mask to remove the other * color components. For example, the following two lines of code are * equivalent:<br /><pre>float r1 = blue(myColor);<br />float r2 = myColor * &amp; 0xFF;</pre> * * ( end auto-generated ) * * @webref color:creating_reading * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#green(int) * @see PGraphics#alpha(int) * @see PGraphics#hue(int) * @see PGraphics#saturation(int) * @see PGraphics#brightness(int) * @see_external rightshift */ public final float blue(int rgb) { return g.blue(rgb); } /** * ( begin auto-generated from hue.xml ) * * Extracts the hue value from a color. * * ( end auto-generated ) * @webref color:creating_reading * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#green(int) * @see PGraphics#blue(int) * @see PGraphics#alpha(int) * @see PGraphics#saturation(int) * @see PGraphics#brightness(int) */ public final float hue(int rgb) { return g.hue(rgb); } /** * ( begin auto-generated from saturation.xml ) * * Extracts the saturation value from a color. * * ( end auto-generated ) * @webref color:creating_reading * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#green(int) * @see PGraphics#blue(int) * @see PGraphics#alpha(int) * @see PGraphics#hue(int) * @see PGraphics#brightness(int) */ public final float saturation(int rgb) { return g.saturation(rgb); } /** * ( begin auto-generated from brightness.xml ) * * Extracts the brightness value from a color. * * ( end auto-generated ) * * @webref color:creating_reading * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#green(int) * @see PGraphics#blue(int) * @see PGraphics#alpha(int) * @see PGraphics#hue(int) * @see PGraphics#saturation(int) */ public final float brightness(int rgb) { return g.brightness(rgb); } /** * ( begin auto-generated from lerpColor.xml ) * * Calculates a color or colors between two color at a specific increment. * The <b>amt</b> parameter is the amount to interpolate between the two * values where 0.0 equal to the first point, 0.1 is very near the first * point, 0.5 is half-way in between, etc. * * ( end auto-generated ) * * @webref color:creating_reading * @usage web_application * @param c1 interpolate from this color * @param c2 interpolate to this color * @param amt between 0.0 and 1.0 * @see PImage#blendColor(int, int, int) * @see PGraphics#color(float, float, float, float) */ public int lerpColor(int c1, int c2, float amt) { return g.lerpColor(c1, c2, amt); } /** * @nowebref * Interpolate between two colors. Like lerp(), but for the * individual color components of a color supplied as an int value. */ static public int lerpColor(int c1, int c2, float amt, int mode) { return PGraphics.lerpColor(c1, c2, amt, mode); } /** * Display a warning that the specified method is only available with 3D. * @param method The method name (no parentheses) */ static public void showDepthWarning(String method) { PGraphics.showDepthWarning(method); } /** * Display a warning that the specified method that takes x, y, z parameters * can only be used with x and y parameters in this renderer. * @param method The method name (no parentheses) */ static public void showDepthWarningXYZ(String method) { PGraphics.showDepthWarningXYZ(method); } /** * Display a warning that the specified method is simply unavailable. */ static public void showMethodWarning(String method) { PGraphics.showMethodWarning(method); } /** * Error that a particular variation of a method is unavailable (even though * other variations are). For instance, if vertex(x, y, u, v) is not * available, but vertex(x, y) is just fine. */ static public void showVariationWarning(String str) { PGraphics.showVariationWarning(str); } /** * Display a warning that the specified method is not implemented, meaning * that it could be either a completely missing function, although other * variations of it may still work properly. */ static public void showMissingWarning(String method) { PGraphics.showMissingWarning(method); } /** * Return true if this renderer should be drawn to the screen. Defaults to * returning true, since nearly all renderers are on-screen beasts. But can * be overridden for subclasses like PDF so that a window doesn't open up. * <br/> <br/> * A better name? showFrame, displayable, isVisible, visible, shouldDisplay, * what to call this? */ public boolean displayable() { return g.displayable(); } /** * Return true if this renderer does rendering through OpenGL. Defaults to false. */ public boolean isGL() { return g.isGL(); } /** * ( begin auto-generated from PImage_get.xml ) * * Reads the color of any pixel or grabs a section of an image. If no * parameters are specified, the entire image is returned. Use the <b>x</b> * and <b>y</b> parameters to get the value of one pixel. Get a section of * the display window by specifying an additional <b>width</b> and * <b>height</b> parameter. When getting an image, the <b>x</b> and * <b>y</b> parameters define the coordinates for the upper-left corner of * the image, regardless of the current <b>imageMode()</b>.<br /> * <br /> * If the pixel requested is outside of the image window, black is * returned. The numbers returned are scaled according to the current color * ranges, but only RGB values are returned by this function. For example, * even though you may have drawn a shape with <b>colorMode(HSB)</b>, the * numbers returned will be in RGB format.<br /> * <br /> * Getting the color of a single pixel with <b>get(x, y)</b> is easy, but * not as fast as grabbing the data directly from <b>pixels[]</b>. The * equivalent statement to <b>get(x, y)</b> using <b>pixels[]</b> is * <b>pixels[y*width+x]</b>. See the reference for <b>pixels[]</b> for more information. * * ( end auto-generated ) * * <h3>Advanced</h3> * Returns an ARGB "color" type (a packed 32 bit int with the color. * If the coordinate is outside the image, zero is returned * (black, but completely transparent). * <P> * If the image is in RGB format (i.e. on a PVideo object), * the value will get its high bits set, just to avoid cases where * they haven't been set already. * <P> * If the image is in ALPHA format, this returns a white with its * alpha value set. * <P> * This function is included primarily for beginners. It is quite * slow because it has to check to see if the x, y that was provided * is inside the bounds, and then has to check to see what image * type it is. If you want things to be more efficient, access the * pixels[] array directly. * * @webref image:pixels * @brief Reads the color of any pixel or grabs a rectangle of pixels * @usage web_application * @param x x-coordinate of the pixel * @param y y-coordinate of the pixel * @see PApplet#set(int, int, int) * @see PApplet#pixels * @see PApplet#copy(PImage, int, int, int, int, int, int, int, int) */ public int get(int x, int y) { return g.get(x, y); } /** * @param w width of pixel rectangle to get * @param h height of pixel rectangle to get */ public PImage get(int x, int y, int w, int h) { return g.get(x, y, w, h); } /** * Returns a copy of this PImage. Equivalent to get(0, 0, width, height). */ public PImage get() { return g.get(); } /** * ( begin auto-generated from PImage_set.xml ) * * Changes the color of any pixel or writes an image directly into the * display window.<br /> * <br /> * The <b>x</b> and <b>y</b> parameters specify the pixel to change and the * <b>color</b> parameter specifies the color value. The color parameter is * affected by the current color mode (the default is RGB values from 0 to * 255). When setting an image, the <b>x</b> and <b>y</b> parameters define * the coordinates for the upper-left corner of the image, regardless of * the current <b>imageMode()</b>. * <br /><br /> * Setting the color of a single pixel with <b>set(x, y)</b> is easy, but * not as fast as putting the data directly into <b>pixels[]</b>. The * equivalent statement to <b>set(x, y, #000000)</b> using <b>pixels[]</b> * is <b>pixels[y*width+x] = #000000</b>. See the reference for * <b>pixels[]</b> for more information. * * ( end auto-generated ) * * @webref image:pixels * @brief writes a color to any pixel or writes an image into another * @usage web_application * @param x x-coordinate of the pixel * @param y y-coordinate of the pixel * @param c any value of the color datatype * @see PImage#get(int, int, int, int) * @see PImage#pixels * @see PImage#copy(PImage, int, int, int, int, int, int, int, int) */ public void set(int x, int y, int c) { if (recorder != null) recorder.set(x, y, c); g.set(x, y, c); } /** * <h3>Advanced</h3> * Efficient method of drawing an image's pixels directly to this surface. * No variations are employed, meaning that any scale, tint, or imageMode * settings will be ignored. * * @param img image to copy into the original image */ public void set(int x, int y, PImage img) { if (recorder != null) recorder.set(x, y, img); g.set(x, y, img); } /** * ( begin auto-generated from PImage_mask.xml ) * * Masks part of an image from displaying by loading another image and * using it as an alpha channel. This mask image should only contain * grayscale data, but only the blue color channel is used. The mask image * needs to be the same size as the image to which it is applied.<br /> * <br /> * In addition to using a mask image, an integer array containing the alpha * channel data can be specified directly. This method is useful for * creating dynamically generated alpha masks. This array must be of the * same length as the target image's pixels array and should contain only * grayscale data of values between 0-255. * * ( end auto-generated ) * * <h3>Advanced</h3> * * Set alpha channel for an image. Black colors in the source * image will make the destination image completely transparent, * and white will make things fully opaque. Gray values will * be in-between steps. * <P> * Strictly speaking the "blue" value from the source image is * used as the alpha color. For a fully grayscale image, this * is correct, but for a color image it's not 100% accurate. * For a more accurate conversion, first use filter(GRAY) * which will make the image into a "correct" grayscale by * performing a proper luminance-based conversion. * * @webref pimage:method * @usage web_application * @brief Masks part of an image with another image as an alpha channel * @param maskArray array of integers used as the alpha channel, needs to be the same length as the image's pixel array */ public void mask(PImage img) { if (recorder != null) recorder.mask(img); g.mask(img); } public void filter(int kind) { if (recorder != null) recorder.filter(kind); g.filter(kind); } /** * ( begin auto-generated from PImage_filter.xml ) * * Filters an image as defined by one of the following modes:<br /><br * />THRESHOLD - converts the image to black and white pixels depending if * they are above or below the threshold defined by the level parameter. * The level must be between 0.0 (black) and 1.0(white). If no level is * specified, 0.5 is used.<br /> * <br /> * GRAY - converts any colors in the image to grayscale equivalents<br /> * <br /> * INVERT - sets each pixel to its inverse value<br /> * <br /> * POSTERIZE - limits each channel of the image to the number of colors * specified as the level parameter<br /> * <br /> * BLUR - executes a Guassian blur with the level parameter specifying the * extent of the blurring. If no level parameter is used, the blur is * equivalent to Guassian blur of radius 1<br /> * <br /> * OPAQUE - sets the alpha channel to entirely opaque<br /> * <br /> * ERODE - reduces the light areas with the amount defined by the level * parameter<br /> * <br /> * DILATE - increases the light areas with the amount defined by the level parameter * * ( end auto-generated ) * * <h3>Advanced</h3> * Method to apply a variety of basic filters to this image. * <P> * <UL> * <LI>filter(BLUR) provides a basic blur. * <LI>filter(GRAY) converts the image to grayscale based on luminance. * <LI>filter(INVERT) will invert the color components in the image. * <LI>filter(OPAQUE) set all the high bits in the image to opaque * <LI>filter(THRESHOLD) converts the image to black and white. * <LI>filter(DILATE) grow white/light areas * <LI>filter(ERODE) shrink white/light areas * </UL> * Luminance conversion code contributed by * <A HREF="http://www.toxi.co.uk">toxi</A> * <P/> * Gaussian blur code contributed by * <A HREF="http://incubator.quasimondo.com">Mario Klingemann</A> * * @webref image:pixels * @brief Converts the image to grayscale or black and white * @usage web_application * @param kind Either THRESHOLD, GRAY, OPAQUE, INVERT, POSTERIZE, BLUR, ERODE, or DILATE * @param param unique for each, see above */ public void filter(int kind, float param) { if (recorder != null) recorder.filter(kind, param); g.filter(kind, param); } /** * ( begin auto-generated from PImage_copy.xml ) * * Copies a region of pixels from one image into another. If the source and * destination regions aren't the same size, it will automatically resize * source pixels to fit the specified target region. No alpha information * is used in the process, however if the source image has an alpha channel * set, it will be copied as well. * <br /><br /> * As of release 0149, this function ignores <b>imageMode()</b>. * * ( end auto-generated ) * * @webref image:pixels * @brief Copies the entire image * @usage web_application * @param sx X coordinate of the source's upper left corner * @param sy Y coordinate of the source's upper left corner * @param sw source image width * @param sh source image height * @param dx X coordinate of the destination's upper left corner * @param dy Y coordinate of the destination's upper left corner * @param dw destination image width * @param dh destination image height * @see PGraphics#alpha(int) * @see PImage#blend(PImage, int, int, int, int, int, int, int, int, int) */ public void copy(int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh) { if (recorder != null) recorder.copy(sx, sy, sw, sh, dx, dy, dw, dh); g.copy(sx, sy, sw, sh, dx, dy, dw, dh); } /** * @param src an image variable referring to the source image. */ public void copy(PImage src, int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh) { if (recorder != null) recorder.copy(src, sx, sy, sw, sh, dx, dy, dw, dh); g.copy(src, sx, sy, sw, sh, dx, dy, dw, dh); } public void blend(int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh, int mode) { if (recorder != null) recorder.blend(sx, sy, sw, sh, dx, dy, dw, dh, mode); g.blend(sx, sy, sw, sh, dx, dy, dw, dh, mode); } /** * ( begin auto-generated from PImage_blend.xml ) * * Blends a region of pixels into the image specified by the <b>img</b> * parameter. These copies utilize full alpha channel support and a choice * of the following modes to blend the colors of source pixels (A) with the * ones of pixels in the destination image (B):<br /> * <br /> * BLEND - linear interpolation of colours: C = A*factor + B<br /> * <br /> * ADD - additive blending with white clip: C = min(A*factor + B, 255)<br /> * <br /> * SUBTRACT - subtractive blending with black clip: C = max(B - A*factor, * 0)<br /> * <br /> * DARKEST - only the darkest colour succeeds: C = min(A*factor, B)<br /> * <br /> * LIGHTEST - only the lightest colour succeeds: C = max(A*factor, B)<br /> * <br /> * DIFFERENCE - subtract colors from underlying image.<br /> * <br /> * EXCLUSION - similar to DIFFERENCE, but less extreme.<br /> * <br /> * MULTIPLY - Multiply the colors, result will always be darker.<br /> * <br /> * SCREEN - Opposite multiply, uses inverse values of the colors.<br /> * <br /> * OVERLAY - A mix of MULTIPLY and SCREEN. Multiplies dark values, * and screens light values.<br /> * <br /> * HARD_LIGHT - SCREEN when greater than 50% gray, MULTIPLY when lower.<br /> * <br /> * SOFT_LIGHT - Mix of DARKEST and LIGHTEST. * Works like OVERLAY, but not as harsh.<br /> * <br /> * DODGE - Lightens light tones and increases contrast, ignores darks. * Called "Color Dodge" in Illustrator and Photoshop.<br /> * <br /> * BURN - Darker areas are applied, increasing contrast, ignores lights. * Called "Color Burn" in Illustrator and Photoshop.<br /> * <br /> * All modes use the alpha information (highest byte) of source image * pixels as the blending factor. If the source and destination regions are * different sizes, the image will be automatically resized to match the * destination size. If the <b>srcImg</b> parameter is not used, the * display window is used as the source image.<br /> * <br /> * As of release 0149, this function ignores <b>imageMode()</b>. * * ( end auto-generated ) * * @webref image:pixels * @brief Copies a pixel or rectangle of pixels using different blending modes * @param src an image variable referring to the source image * @param sx X coordinate of the source's upper left corner * @param sy Y coordinate of the source's upper left corner * @param sw source image width * @param sh source image height * @param dx X coordinate of the destinations's upper left corner * @param dy Y coordinate of the destinations's upper left corner * @param dw destination image width * @param dh destination image height * @param mode Either BLEND, ADD, SUBTRACT, LIGHTEST, DARKEST, DIFFERENCE, EXCLUSION, MULTIPLY, SCREEN, OVERLAY, HARD_LIGHT, SOFT_LIGHT, DODGE, BURN * * @see PApplet#alpha(int) * @see PImage#copy(PImage, int, int, int, int, int, int, int, int) * @see PImage#blendColor(int,int,int) */ public void blend(PImage src, int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh, int mode) { if (recorder != null) recorder.blend(src, sx, sy, sw, sh, dx, dy, dw, dh, mode); g.blend(src, sx, sy, sw, sh, dx, dy, dw, dh, mode); } }
diff --git a/nuxeo-platform-search-api/src/main/java/org/nuxeo/ecm/core/search/api/client/querymodel/QueryModel.java b/nuxeo-platform-search-api/src/main/java/org/nuxeo/ecm/core/search/api/client/querymodel/QueryModel.java index c13906382..966534d6a 100644 --- a/nuxeo-platform-search-api/src/main/java/org/nuxeo/ecm/core/search/api/client/querymodel/QueryModel.java +++ b/nuxeo-platform-search-api/src/main/java/org/nuxeo/ecm/core/search/api/client/querymodel/QueryModel.java @@ -1,295 +1,296 @@ /* * (C) Copyright 2006-2009 Nuxeo SA (http://nuxeo.com/) and contributors. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This library 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 * Lesser General Public License for more details. * * Contributors: * Olivier Grisel * Georges Racinet * Florent Guillaume */ package org.nuxeo.ecm.core.search.api.client.querymodel; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.nuxeo.ecm.core.api.ClientException; import org.nuxeo.ecm.core.api.ClientRuntimeException; import org.nuxeo.ecm.core.api.CoreSession; import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.core.api.DocumentModelList; import org.nuxeo.ecm.core.api.DocumentSecurityException; import org.nuxeo.ecm.core.api.PagedDocumentsProvider; import org.nuxeo.ecm.core.api.SortInfo; import org.nuxeo.ecm.core.api.impl.DocumentModelImpl; import org.nuxeo.ecm.core.api.model.PropertyException; import org.nuxeo.ecm.core.search.api.client.query.QueryException; import org.nuxeo.ecm.core.search.api.client.querymodel.descriptor.FieldDescriptor; import org.nuxeo.ecm.core.search.api.client.querymodel.descriptor.QueryModelDescriptor; import org.nuxeo.ecm.core.search.api.client.search.results.ResultItem; import org.nuxeo.ecm.core.search.api.client.search.results.ResultSet; import org.nuxeo.ecm.core.search.api.client.search.results.document.SearchPageProvider; import org.nuxeo.ecm.core.search.api.client.search.results.impl.DocumentModelResultItem; import org.nuxeo.ecm.core.search.api.client.search.results.impl.ResultSetImpl; import org.nuxeo.runtime.api.Framework; /** * Query model maintaining the context about a query descriptor, and for * stateful models a document containing parameters that can be used by the * model. * * @author Olivier Grisel * @author Georges Racinet * @author Florent Guillaume */ public class QueryModel implements Serializable { private static final long serialVersionUID = 762348097532723566L; private static final Log log = LogFactory.getLog(QueryModel.class); protected transient QueryModelDescriptor descriptor; protected String descriptorName; protected int max; protected final DocumentModel documentModel; protected final DocumentModel originalDocumentModel; protected boolean isPersisted = false; protected transient QueryModelService queryModelService; public QueryModel(QueryModelDescriptor descriptor, DocumentModel documentModel) { this.descriptor = descriptor; if (descriptor != null) { descriptorName = descriptor.getName(); max = descriptor.getMax() == null ? 0 : descriptor.getMax().intValue(); } this.documentModel = documentModel; if (documentModel == null) { originalDocumentModel = null; } else { // detach and keep a copy of the original to be able to reset try { ((DocumentModelImpl) documentModel).detach(true); } catch (ClientException e) { throw new ClientRuntimeException(e); } originalDocumentModel = new DocumentModelImpl( documentModel.getType()); try { originalDocumentModel.copyContent(documentModel); } catch (ClientException e) { throw new ClientRuntimeException(e); } } } public QueryModel(QueryModelDescriptor descriptor) { this(descriptor, null); } public boolean isPersisted() { return isPersisted; } public void setPersisted(boolean isPersisted) { this.isPersisted = isPersisted; } public DocumentModel getDocumentModel() { return documentModel; } public DocumentModelList getDocuments(CoreSession session) throws ClientException, QueryException { return getDocuments(session, null); } public DocumentModelList getDocuments(CoreSession session, Object[] params) throws ClientException, QueryException { return getResultsProvider(session, params).getCurrentPage(); } /** * Used to reconstruct the descriptor after a ser/de-serialization cycle */ private void checkDescriptor() { if (descriptor == null) { if (queryModelService == null) { queryModelService = (QueryModelService) Framework.getRuntime().getComponent( QueryModelService.NAME); } descriptor = queryModelService.getQueryModelDescriptor(descriptorName); } } public PagedDocumentsProvider getResultsProvider(CoreSession session, Object[] params) throws ClientException, QueryException { return getResultsProvider(session, params, null); } public PagedDocumentsProvider getResultsProvider(CoreSession session, Object[] params, SortInfo sortInfo) throws ClientException, QueryException { checkDescriptor(); if (sortInfo == null) { sortInfo = descriptor.getDefaultSortInfo(documentModel); } String query; if (descriptor.isStateful()) { query = descriptor.getQuery(documentModel, sortInfo); } else { query = descriptor.getQuery(params, sortInfo); } if (log.isDebugEnabled()) { log.debug("execute query: " + query.replace('\n', ' ')); } - DocumentModelList documentModelList = session.query(query, max); + DocumentModelList documentModelList = session.query(query, null, max, + 0, true); int size = documentModelList.size(); List<ResultItem> resultItems = new ArrayList<ResultItem>(size); for (DocumentModel doc : documentModelList) { if (doc == null) { log.error("Got null document from query: " + query); continue; } // detach the document so that we can use it beyond the session try { ((DocumentModelImpl) doc).detach(true); } catch (DocumentSecurityException e) { // no access to the document (why?) continue; } resultItems.add(new DocumentModelResultItem(doc)); } ResultSet resultSet = new ResultSetImpl(query, session, 0, max, - resultItems, size, size); + resultItems, (int) documentModelList.totalSize(), size); return new SearchPageProvider(resultSet, isSortable(), sortInfo, query); } public QueryModelDescriptor getDescriptor() { checkDescriptor(); return descriptor; } /* * Convenience API */ public Object getProperty(String schemaName, String name) { try { return documentModel.getProperty(schemaName, name); } catch (ClientException e) { throw new ClientRuntimeException(e); } } public void setProperty(String schemaName, String name, Object value) { try { documentModel.setProperty(schemaName, name, value); } catch (ClientException e) { throw new ClientRuntimeException(e); } } public Object getPropertyValue(String xpath) { try { return documentModel.getPropertyValue(xpath); } catch (PropertyException e) { throw new ClientRuntimeException(e); } catch (ClientException e) { throw new ClientRuntimeException(e); } } public void setPropertyValue(String xpath, Serializable value) { try { documentModel.setPropertyValue(xpath, value); } catch (PropertyException e) { throw new ClientRuntimeException(e); } catch (ClientException e) { throw new ClientRuntimeException(e); } } public void setSortColumn(String value) { FieldDescriptor fd = getDescriptor().getSortColumnField(); if (fd.getXpath() != null) { setPropertyValue(fd.getXpath(), value); } else { setProperty(fd.getSchema(), fd.getName(), value); } } public String getSortColumn() { FieldDescriptor fd = getDescriptor().getSortColumnField(); if (fd.getXpath() != null) { return (String) getPropertyValue(fd.getXpath()); } else { return (String) getProperty(fd.getSchema(), fd.getName()); } } public boolean getSortAscending() { FieldDescriptor fd = getDescriptor().getSortAscendingField(); Boolean result; if (fd.getXpath() != null) { result = (Boolean) getPropertyValue(fd.getXpath()); } else { result = (Boolean) getProperty(fd.getSchema(), fd.getName()); } return Boolean.TRUE.equals(result); } public void setSortAscending(boolean sortAscending) { FieldDescriptor fd = getDescriptor().getSortAscendingField(); if (fd.getXpath() != null) { setPropertyValue(fd.getXpath(), Boolean.valueOf(sortAscending)); } else { setProperty(fd.getSchema(), fd.getName(), Boolean.valueOf(sortAscending)); } } public boolean isSortable() { return getDescriptor().isSortable(); } public void reset() { try { documentModel.copyContent(originalDocumentModel); } catch (ClientException e) { throw new ClientRuntimeException(e); } } public int getMax() { return max; } public void setMax(int max) { this.max = max; } }
false
true
public PagedDocumentsProvider getResultsProvider(CoreSession session, Object[] params, SortInfo sortInfo) throws ClientException, QueryException { checkDescriptor(); if (sortInfo == null) { sortInfo = descriptor.getDefaultSortInfo(documentModel); } String query; if (descriptor.isStateful()) { query = descriptor.getQuery(documentModel, sortInfo); } else { query = descriptor.getQuery(params, sortInfo); } if (log.isDebugEnabled()) { log.debug("execute query: " + query.replace('\n', ' ')); } DocumentModelList documentModelList = session.query(query, max); int size = documentModelList.size(); List<ResultItem> resultItems = new ArrayList<ResultItem>(size); for (DocumentModel doc : documentModelList) { if (doc == null) { log.error("Got null document from query: " + query); continue; } // detach the document so that we can use it beyond the session try { ((DocumentModelImpl) doc).detach(true); } catch (DocumentSecurityException e) { // no access to the document (why?) continue; } resultItems.add(new DocumentModelResultItem(doc)); } ResultSet resultSet = new ResultSetImpl(query, session, 0, max, resultItems, size, size); return new SearchPageProvider(resultSet, isSortable(), sortInfo, query); }
public PagedDocumentsProvider getResultsProvider(CoreSession session, Object[] params, SortInfo sortInfo) throws ClientException, QueryException { checkDescriptor(); if (sortInfo == null) { sortInfo = descriptor.getDefaultSortInfo(documentModel); } String query; if (descriptor.isStateful()) { query = descriptor.getQuery(documentModel, sortInfo); } else { query = descriptor.getQuery(params, sortInfo); } if (log.isDebugEnabled()) { log.debug("execute query: " + query.replace('\n', ' ')); } DocumentModelList documentModelList = session.query(query, null, max, 0, true); int size = documentModelList.size(); List<ResultItem> resultItems = new ArrayList<ResultItem>(size); for (DocumentModel doc : documentModelList) { if (doc == null) { log.error("Got null document from query: " + query); continue; } // detach the document so that we can use it beyond the session try { ((DocumentModelImpl) doc).detach(true); } catch (DocumentSecurityException e) { // no access to the document (why?) continue; } resultItems.add(new DocumentModelResultItem(doc)); } ResultSet resultSet = new ResultSetImpl(query, session, 0, max, resultItems, (int) documentModelList.totalSize(), size); return new SearchPageProvider(resultSet, isSortable(), sortInfo, query); }
diff --git a/java/telehash-core/src/main/java/org/telehash/SeeHandler.java b/java/telehash-core/src/main/java/org/telehash/SeeHandler.java index 69a2c71..b5d577a 100644 --- a/java/telehash-core/src/main/java/org/telehash/SeeHandler.java +++ b/java/telehash-core/src/main/java/org/telehash/SeeHandler.java @@ -1,92 +1,92 @@ package org.telehash; import java.net.InetSocketAddress; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.telehash.model.Line; import org.telehash.model.TelehashFactory; import org.telehash.model.TelehashPackage; import org.telehash.model.Telex; public class SeeHandler implements TelexHandler { static private Logger logger = LoggerFactory.getLogger(SeeHandler.class); static private TelehashFactory tf = TelehashFactory.eINSTANCE; @Override public boolean isMatch(Telex telex) { return telex.isSetSee(); } @Override public void telexReceived(SwitchHandler switchHandler, Line line, Telex telex) { SeeCommandHandler command = new SeeCommandHandler(switchHandler, line, telex); command.execute(); } private class SeeCommandHandler { private SwitchHandler switchHandler; private Line recvLine; private Telex telex; private SeeCommandHandler(SwitchHandler switchHandler, Line line, Telex telex) { this.switchHandler = switchHandler; this.recvLine = line; this.telex = telex; } public void execute() { logger.debug("BEGIN .see HANDLER"); for (InetSocketAddress seeAddr : telex.getSee()) { if (seeAddr.equals(switchHandler.getAddress())) { continue; } // they're making themselves visible now, awesome if (seeAddr.equals(recvLine.getAddress()) && !recvLine.isVisible()) { logger.debug("VISIBLE " + recvLine.getAddress()); recvLine.setVisible(true); recvLine.getNeighbors().addAll( switchHandler.nearTo(recvLine.getEnd(), switchHandler.getAddress())); - switchHandler.nearTo(recvLine.getEnd(), recvLine.getAddress()); // injects this switch as hints into it's neighbors, fully seeded now + switchHandler.nearTo(recvLine.getEnd(), recvLine.getAddress()); // injects this switch as hints into its neighbors, fully seeded now } Hash seeHash = Hash.of(seeAddr); if (switchHandler.getLine(seeHash) != null) { continue; } // XXX todo: if we're dialing we'd want to reach out to any of these closer to that $tap_end // also check to see if we want them in a bucket if (bucketWant(seeAddr, seeHash)) { // send direct (should open our outgoing to them) Telex telexOut = tf.createTelex().withTo(seeAddr) .withEnd(switchHandler.getAddressHash()); switchHandler.send(telexOut); // send pop signal back to the switch who .see'd us in case the new one is behind a nat telexOut = (Telex) tf.createTelex().withTo(recvLine) .withEnd(seeHash) .with("+pop", "th:" + tf.convertToString(TelehashPackage.Literals.ENDPOINT, switchHandler.getAddress())) .with("_hop", 1); switchHandler.send(telexOut); } } logger.debug("END .see HANDLER"); } private boolean bucketWant(InetSocketAddress seeAddr, Hash seeHash) { int dist = seeHash.diffBit(switchHandler.getAddressHash()); logger.debug("BUCKET WANT[{} -> {} -> {}]", new Object[]{ seeAddr, Integer.toString(dist), switchHandler.getAddress()}); return dist >= 0; } } }
true
true
public void execute() { logger.debug("BEGIN .see HANDLER"); for (InetSocketAddress seeAddr : telex.getSee()) { if (seeAddr.equals(switchHandler.getAddress())) { continue; } // they're making themselves visible now, awesome if (seeAddr.equals(recvLine.getAddress()) && !recvLine.isVisible()) { logger.debug("VISIBLE " + recvLine.getAddress()); recvLine.setVisible(true); recvLine.getNeighbors().addAll( switchHandler.nearTo(recvLine.getEnd(), switchHandler.getAddress())); switchHandler.nearTo(recvLine.getEnd(), recvLine.getAddress()); // injects this switch as hints into it's neighbors, fully seeded now } Hash seeHash = Hash.of(seeAddr); if (switchHandler.getLine(seeHash) != null) { continue; } // XXX todo: if we're dialing we'd want to reach out to any of these closer to that $tap_end // also check to see if we want them in a bucket if (bucketWant(seeAddr, seeHash)) { // send direct (should open our outgoing to them) Telex telexOut = tf.createTelex().withTo(seeAddr) .withEnd(switchHandler.getAddressHash()); switchHandler.send(telexOut); // send pop signal back to the switch who .see'd us in case the new one is behind a nat telexOut = (Telex) tf.createTelex().withTo(recvLine) .withEnd(seeHash) .with("+pop", "th:" + tf.convertToString(TelehashPackage.Literals.ENDPOINT, switchHandler.getAddress())) .with("_hop", 1); switchHandler.send(telexOut); } } logger.debug("END .see HANDLER"); }
public void execute() { logger.debug("BEGIN .see HANDLER"); for (InetSocketAddress seeAddr : telex.getSee()) { if (seeAddr.equals(switchHandler.getAddress())) { continue; } // they're making themselves visible now, awesome if (seeAddr.equals(recvLine.getAddress()) && !recvLine.isVisible()) { logger.debug("VISIBLE " + recvLine.getAddress()); recvLine.setVisible(true); recvLine.getNeighbors().addAll( switchHandler.nearTo(recvLine.getEnd(), switchHandler.getAddress())); switchHandler.nearTo(recvLine.getEnd(), recvLine.getAddress()); // injects this switch as hints into its neighbors, fully seeded now } Hash seeHash = Hash.of(seeAddr); if (switchHandler.getLine(seeHash) != null) { continue; } // XXX todo: if we're dialing we'd want to reach out to any of these closer to that $tap_end // also check to see if we want them in a bucket if (bucketWant(seeAddr, seeHash)) { // send direct (should open our outgoing to them) Telex telexOut = tf.createTelex().withTo(seeAddr) .withEnd(switchHandler.getAddressHash()); switchHandler.send(telexOut); // send pop signal back to the switch who .see'd us in case the new one is behind a nat telexOut = (Telex) tf.createTelex().withTo(recvLine) .withEnd(seeHash) .with("+pop", "th:" + tf.convertToString(TelehashPackage.Literals.ENDPOINT, switchHandler.getAddress())) .with("_hop", 1); switchHandler.send(telexOut); } } logger.debug("END .see HANDLER"); }
diff --git a/src/main/java/net/pterodactylus/sone/core/SoneDownloader.java b/src/main/java/net/pterodactylus/sone/core/SoneDownloader.java index cffc8d93..53eef168 100644 --- a/src/main/java/net/pterodactylus/sone/core/SoneDownloader.java +++ b/src/main/java/net/pterodactylus/sone/core/SoneDownloader.java @@ -1,544 +1,536 @@ /* * Sone - SoneDownloader.java - Copyright © 2010–2013 David Roden * * 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 3 of the License, or * (at your option) 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, see <http://www.gnu.org/licenses/>. */ package net.pterodactylus.sone.core; import java.io.InputStream; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import net.pterodactylus.sone.core.FreenetInterface.Fetched; import net.pterodactylus.sone.data.Album; import net.pterodactylus.sone.data.Client; import net.pterodactylus.sone.data.Image; import net.pterodactylus.sone.data.Post; import net.pterodactylus.sone.data.PostReply; import net.pterodactylus.sone.data.Profile; import net.pterodactylus.sone.data.Sone; import net.pterodactylus.sone.data.Sone.SoneStatus; import net.pterodactylus.sone.data.SoneImpl; import net.pterodactylus.sone.database.PostBuilder; import net.pterodactylus.sone.database.PostReplyBuilder; import net.pterodactylus.util.io.Closer; import net.pterodactylus.util.logging.Logging; import net.pterodactylus.util.number.Numbers; import net.pterodactylus.util.service.AbstractService; import net.pterodactylus.util.xml.SimpleXML; import net.pterodactylus.util.xml.XML; import org.w3c.dom.Document; import freenet.client.FetchResult; import freenet.keys.FreenetURI; import freenet.support.api.Bucket; /** * The Sone downloader is responsible for download Sones as they are updated. * * @author <a href="mailto:[email protected]">David ‘Bombe’ Roden</a> */ public class SoneDownloader extends AbstractService { /** The logger. */ private static final Logger logger = Logging.getLogger(SoneDownloader.class); /** The maximum protocol version. */ private static final int MAX_PROTOCOL_VERSION = 0; /** The core. */ private final Core core; /** The Freenet interface. */ private final FreenetInterface freenetInterface; /** The sones to update. */ private final Set<Sone> sones = new HashSet<Sone>(); /** * Creates a new Sone downloader. * * @param core * The core * @param freenetInterface * The Freenet interface */ public SoneDownloader(Core core, FreenetInterface freenetInterface) { super("Sone Downloader", false); this.core = core; this.freenetInterface = freenetInterface; } // // ACTIONS // /** * Adds the given Sone to the set of Sones that will be watched for updates. * * @param sone * The Sone to add */ public void addSone(Sone sone) { if (!sones.add(sone)) { freenetInterface.unregisterUsk(sone); } freenetInterface.registerUsk(sone, this); } /** * Removes the given Sone from the downloader. * * @param sone * The Sone to stop watching */ public void removeSone(Sone sone) { if (sones.remove(sone)) { freenetInterface.unregisterUsk(sone); } } /** * Fetches the updated Sone. This method is a callback method for * {@link FreenetInterface#registerUsk(Sone, SoneDownloader)}. * * @param sone * The Sone to fetch */ public void fetchSone(Sone sone) { fetchSone(sone, sone.getRequestUri().sskForUSK()); } /** * Fetches the updated Sone. This method can be used to fetch a Sone from a * specific URI. * * @param sone * The Sone to fetch * @param soneUri * The URI to fetch the Sone from */ public void fetchSone(Sone sone, FreenetURI soneUri) { fetchSone(sone, soneUri, false); } /** * Fetches the Sone from the given URI. * * @param sone * The Sone to fetch * @param soneUri * The URI of the Sone to fetch * @param fetchOnly * {@code true} to only fetch and parse the Sone, {@code false} * to {@link Core#updateSone(Sone) update} it in the core * @return The downloaded Sone, or {@code null} if the Sone could not be * downloaded */ public Sone fetchSone(Sone sone, FreenetURI soneUri, boolean fetchOnly) { logger.log(Level.FINE, String.format("Starting fetch for Sone “%s” from %s…", sone, soneUri)); FreenetURI requestUri = soneUri.setMetaString(new String[] { "sone.xml" }); sone.setStatus(SoneStatus.downloading); try { Fetched fetchResults = freenetInterface.fetchUri(requestUri); if (fetchResults == null) { /* TODO - mark Sone as bad. */ return null; } logger.log(Level.FINEST, String.format("Got %d bytes back.", fetchResults.getFetchResult().size())); Sone parsedSone = parseSone(sone, fetchResults.getFetchResult(), fetchResults.getFreenetUri()); if (parsedSone != null) { if (!fetchOnly) { parsedSone.setStatus((parsedSone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle); core.updateSone(parsedSone); addSone(parsedSone); } } return parsedSone; } finally { sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle); } } /** * Parses a Sone from a fetch result. * * @param originalSone * The sone to parse, or {@code null} if the Sone is yet unknown * @param fetchResult * The fetch result * @param requestUri * The requested URI * @return The parsed Sone, or {@code null} if the Sone could not be parsed */ public Sone parseSone(Sone originalSone, FetchResult fetchResult, FreenetURI requestUri) { logger.log(Level.FINEST, String.format("Parsing FetchResult (%d bytes, %s) for %s…", fetchResult.size(), fetchResult.getMimeType(), originalSone)); Bucket soneBucket = fetchResult.asBucket(); InputStream soneInputStream = null; try { soneInputStream = soneBucket.getInputStream(); Sone parsedSone = parseSone(originalSone, soneInputStream); if (parsedSone != null) { parsedSone.setLatestEdition(requestUri.getEdition()); if (requestUri.getKeyType().equals("USK")) { parsedSone.setRequestUri(requestUri.setMetaString(new String[0])); } else { parsedSone.setRequestUri(requestUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0])); } } return parsedSone; } catch (Exception e1) { logger.log(Level.WARNING, String.format("Could not parse Sone from %s!", requestUri), e1); } finally { Closer.close(soneInputStream); soneBucket.free(); } return null; } /** * Parses a Sone from the given input stream and creates a new Sone from the * parsed data. * * @param originalSone * The Sone to update * @param soneInputStream * The input stream to parse the Sone from * @return The parsed Sone * @throws SoneException * if a parse error occurs, or the protocol is invalid */ public Sone parseSone(Sone originalSone, InputStream soneInputStream) throws SoneException { /* TODO - impose a size limit? */ Document document; /* XML parsing is not thread-safe. */ synchronized (this) { document = XML.transformToDocument(soneInputStream); } if (document == null) { /* TODO - mark Sone as bad. */ logger.log(Level.WARNING, String.format("Could not parse XML for Sone %s!", originalSone)); return null; } Sone sone = new SoneImpl(originalSone.getId(), originalSone.isLocal()).setIdentity(originalSone.getIdentity()); SimpleXML soneXml; try { soneXml = SimpleXML.fromDocument(document); } catch (NullPointerException npe1) { /* for some reason, invalid XML can cause NPEs. */ logger.log(Level.WARNING, String.format("XML for Sone %s can not be parsed!", sone), npe1); return null; } Integer protocolVersion = null; String soneProtocolVersion = soneXml.getValue("protocol-version", null); if (soneProtocolVersion != null) { protocolVersion = Numbers.safeParseInteger(soneProtocolVersion); } if (protocolVersion == null) { logger.log(Level.INFO, "No protocol version found, assuming 0."); protocolVersion = 0; } if (protocolVersion < 0) { logger.log(Level.WARNING, String.format("Invalid protocol version: %d! Not parsing Sone.", protocolVersion)); return null; } /* check for valid versions. */ if (protocolVersion > MAX_PROTOCOL_VERSION) { logger.log(Level.WARNING, String.format("Unknown protocol version: %d! Not parsing Sone.", protocolVersion)); return null; } String soneTime = soneXml.getValue("time", null); if (soneTime == null) { /* TODO - mark Sone as bad. */ logger.log(Level.WARNING, String.format("Downloaded time for Sone %s was null!", sone)); return null; } try { sone.setTime(Long.parseLong(soneTime)); } catch (NumberFormatException nfe1) { /* TODO - mark Sone as bad. */ logger.log(Level.WARNING, String.format("Downloaded Sone %s with invalid time: %s", sone, soneTime)); return null; } SimpleXML clientXml = soneXml.getNode("client"); if (clientXml != null) { String clientName = clientXml.getValue("name", null); String clientVersion = clientXml.getValue("version", null); if ((clientName == null) || (clientVersion == null)) { logger.log(Level.WARNING, String.format("Download Sone %s with client XML but missing name or version!", sone)); return null; } sone.setClient(new Client(clientName, clientVersion)); } String soneRequestUri = soneXml.getValue("request-uri", null); if (soneRequestUri != null) { try { sone.setRequestUri(new FreenetURI(soneRequestUri)); } catch (MalformedURLException mue1) { /* TODO - mark Sone as bad. */ logger.log(Level.WARNING, String.format("Downloaded Sone %s has invalid request URI: %s", sone, soneRequestUri), mue1); return null; } } - String soneInsertUri = soneXml.getValue("insert-uri", null); - if ((soneInsertUri != null) && (sone.getInsertUri() == null)) { - try { - sone.setInsertUri(new FreenetURI(soneInsertUri)); - sone.setLatestEdition(Math.max(sone.getRequestUri().getEdition(), sone.getInsertUri().getEdition())); - } catch (MalformedURLException mue1) { - /* TODO - mark Sone as bad. */ - logger.log(Level.WARNING, String.format("Downloaded Sone %s has invalid insert URI: %s", sone, soneInsertUri), mue1); - return null; - } + if (originalSone.getInsertUri() != null) { + sone.setInsertUri(originalSone.getInsertUri()); } SimpleXML profileXml = soneXml.getNode("profile"); if (profileXml == null) { /* TODO - mark Sone as bad. */ logger.log(Level.WARNING, String.format("Downloaded Sone %s has no profile!", sone)); return null; } /* parse profile. */ String profileFirstName = profileXml.getValue("first-name", null); String profileMiddleName = profileXml.getValue("middle-name", null); String profileLastName = profileXml.getValue("last-name", null); Integer profileBirthDay = Numbers.safeParseInteger(profileXml.getValue("birth-day", null)); Integer profileBirthMonth = Numbers.safeParseInteger(profileXml.getValue("birth-month", null)); Integer profileBirthYear = Numbers.safeParseInteger(profileXml.getValue("birth-year", null)); Profile profile = new Profile(sone).setFirstName(profileFirstName).setMiddleName(profileMiddleName).setLastName(profileLastName); profile.setBirthDay(profileBirthDay).setBirthMonth(profileBirthMonth).setBirthYear(profileBirthYear); /* avatar is processed after images are loaded. */ String avatarId = profileXml.getValue("avatar", null); /* parse profile fields. */ SimpleXML profileFieldsXml = profileXml.getNode("fields"); if (profileFieldsXml != null) { for (SimpleXML fieldXml : profileFieldsXml.getNodes("field")) { String fieldName = fieldXml.getValue("field-name", null); String fieldValue = fieldXml.getValue("field-value", ""); if (fieldName == null) { logger.log(Level.WARNING, String.format("Downloaded profile field for Sone %s with missing data! Name: %s, Value: %s", sone, fieldName, fieldValue)); return null; } try { profile.addField(fieldName).setValue(fieldValue); } catch (IllegalArgumentException iae1) { logger.log(Level.WARNING, String.format("Duplicate field: %s", fieldName), iae1); return null; } } } /* parse posts. */ SimpleXML postsXml = soneXml.getNode("posts"); Set<Post> posts = new HashSet<Post>(); if (postsXml == null) { /* TODO - mark Sone as bad. */ logger.log(Level.WARNING, String.format("Downloaded Sone %s has no posts!", sone)); } else { for (SimpleXML postXml : postsXml.getNodes("post")) { String postId = postXml.getValue("id", null); String postRecipientId = postXml.getValue("recipient", null); String postTime = postXml.getValue("time", null); String postText = postXml.getValue("text", null); if ((postId == null) || (postTime == null) || (postText == null)) { /* TODO - mark Sone as bad. */ logger.log(Level.WARNING, String.format("Downloaded post for Sone %s with missing data! ID: %s, Time: %s, Text: %s", sone, postId, postTime, postText)); return null; } try { PostBuilder postBuilder = core.postBuilder(); /* TODO - parse time correctly. */ postBuilder.withId(postId).from(sone.getId()).withTime(Long.parseLong(postTime)).withText(postText); if ((postRecipientId != null) && (postRecipientId.length() == 43)) { postBuilder.to(postRecipientId); } posts.add(postBuilder.build()); } catch (NumberFormatException nfe1) { /* TODO - mark Sone as bad. */ logger.log(Level.WARNING, String.format("Downloaded post for Sone %s with invalid time: %s", sone, postTime)); return null; } } } /* parse replies. */ SimpleXML repliesXml = soneXml.getNode("replies"); Set<PostReply> replies = new HashSet<PostReply>(); if (repliesXml == null) { /* TODO - mark Sone as bad. */ logger.log(Level.WARNING, String.format("Downloaded Sone %s has no replies!", sone)); } else { for (SimpleXML replyXml : repliesXml.getNodes("reply")) { String replyId = replyXml.getValue("id", null); String replyPostId = replyXml.getValue("post-id", null); String replyTime = replyXml.getValue("time", null); String replyText = replyXml.getValue("text", null); if ((replyId == null) || (replyPostId == null) || (replyTime == null) || (replyText == null)) { /* TODO - mark Sone as bad. */ logger.log(Level.WARNING, String.format("Downloaded reply for Sone %s with missing data! ID: %s, Post: %s, Time: %s, Text: %s", sone, replyId, replyPostId, replyTime, replyText)); return null; } try { PostReplyBuilder postReplyBuilder = core.postReplyBuilder(); /* TODO - parse time correctly. */ postReplyBuilder.withId(replyId).from(sone.getId()).to(replyPostId).withTime(Long.parseLong(replyTime)).withText(replyText); replies.add(postReplyBuilder.build()); } catch (NumberFormatException nfe1) { /* TODO - mark Sone as bad. */ logger.log(Level.WARNING, String.format("Downloaded reply for Sone %s with invalid time: %s", sone, replyTime)); return null; } } } /* parse liked post IDs. */ SimpleXML likePostIdsXml = soneXml.getNode("post-likes"); Set<String> likedPostIds = new HashSet<String>(); if (likePostIdsXml == null) { /* TODO - mark Sone as bad. */ logger.log(Level.WARNING, String.format("Downloaded Sone %s has no post likes!", sone)); } else { for (SimpleXML likedPostIdXml : likePostIdsXml.getNodes("post-like")) { String postId = likedPostIdXml.getValue(); likedPostIds.add(postId); } } /* parse liked reply IDs. */ SimpleXML likeReplyIdsXml = soneXml.getNode("reply-likes"); Set<String> likedReplyIds = new HashSet<String>(); if (likeReplyIdsXml == null) { /* TODO - mark Sone as bad. */ logger.log(Level.WARNING, String.format("Downloaded Sone %s has no reply likes!", sone)); } else { for (SimpleXML likedReplyIdXml : likeReplyIdsXml.getNodes("reply-like")) { String replyId = likedReplyIdXml.getValue(); likedReplyIds.add(replyId); } } /* parse albums. */ SimpleXML albumsXml = soneXml.getNode("albums"); List<Album> topLevelAlbums = new ArrayList<Album>(); if (albumsXml != null) { for (SimpleXML albumXml : albumsXml.getNodes("album")) { String id = albumXml.getValue("id", null); String parentId = albumXml.getValue("parent", null); String title = albumXml.getValue("title", null); String description = albumXml.getValue("description", ""); String albumImageId = albumXml.getValue("album-image", null); if ((id == null) || (title == null) || (description == null)) { logger.log(Level.WARNING, String.format("Downloaded Sone %s contains invalid album!", sone)); return null; } Album parent = null; if (parentId != null) { parent = core.getAlbum(parentId, false); if (parent == null) { logger.log(Level.WARNING, String.format("Downloaded Sone %s has album with invalid parent!", sone)); return null; } } Album album = core.getAlbum(id).setSone(sone).modify().setTitle(title).setDescription(description).update(); if (parent != null) { parent.addAlbum(album); } else { topLevelAlbums.add(album); } SimpleXML imagesXml = albumXml.getNode("images"); if (imagesXml != null) { for (SimpleXML imageXml : imagesXml.getNodes("image")) { String imageId = imageXml.getValue("id", null); String imageCreationTimeString = imageXml.getValue("creation-time", null); String imageKey = imageXml.getValue("key", null); String imageTitle = imageXml.getValue("title", null); String imageDescription = imageXml.getValue("description", ""); String imageWidthString = imageXml.getValue("width", null); String imageHeightString = imageXml.getValue("height", null); if ((imageId == null) || (imageCreationTimeString == null) || (imageKey == null) || (imageTitle == null) || (imageWidthString == null) || (imageHeightString == null)) { logger.log(Level.WARNING, String.format("Downloaded Sone %s contains invalid images!", sone)); return null; } long creationTime = Numbers.safeParseLong(imageCreationTimeString, 0L); int imageWidth = Numbers.safeParseInteger(imageWidthString, 0); int imageHeight = Numbers.safeParseInteger(imageHeightString, 0); if ((imageWidth < 1) || (imageHeight < 1)) { logger.log(Level.WARNING, String.format("Downloaded Sone %s contains image %s with invalid dimensions (%s, %s)!", sone, imageId, imageWidthString, imageHeightString)); return null; } Image image = core.getImage(imageId).modify().setSone(sone).setKey(imageKey).setCreationTime(creationTime).update(); image = image.modify().setTitle(imageTitle).setDescription(imageDescription).update(); image = image.modify().setWidth(imageWidth).setHeight(imageHeight).update(); album.addImage(image); } } album.modify().setAlbumImage(albumImageId).update(); } } /* process avatar. */ if (avatarId != null) { profile.setAvatar(core.getImage(avatarId, false)); } /* okay, apparently everything was parsed correctly. Now import. */ /* atomic setter operation on the Sone. */ synchronized (sone) { sone.setProfile(profile); sone.setPosts(posts); sone.setReplies(replies); sone.setLikePostIds(likedPostIds); sone.setLikeReplyIds(likedReplyIds); for (Album album : topLevelAlbums) { sone.getRootAlbum().addAlbum(album); } } return sone; } // // SERVICE METHODS // /** * {@inheritDoc} */ @Override protected void serviceStop() { for (Sone sone : sones) { freenetInterface.unregisterUsk(sone); } } }
true
true
public Sone parseSone(Sone originalSone, InputStream soneInputStream) throws SoneException { /* TODO - impose a size limit? */ Document document; /* XML parsing is not thread-safe. */ synchronized (this) { document = XML.transformToDocument(soneInputStream); } if (document == null) { /* TODO - mark Sone as bad. */ logger.log(Level.WARNING, String.format("Could not parse XML for Sone %s!", originalSone)); return null; } Sone sone = new SoneImpl(originalSone.getId(), originalSone.isLocal()).setIdentity(originalSone.getIdentity()); SimpleXML soneXml; try { soneXml = SimpleXML.fromDocument(document); } catch (NullPointerException npe1) { /* for some reason, invalid XML can cause NPEs. */ logger.log(Level.WARNING, String.format("XML for Sone %s can not be parsed!", sone), npe1); return null; } Integer protocolVersion = null; String soneProtocolVersion = soneXml.getValue("protocol-version", null); if (soneProtocolVersion != null) { protocolVersion = Numbers.safeParseInteger(soneProtocolVersion); } if (protocolVersion == null) { logger.log(Level.INFO, "No protocol version found, assuming 0."); protocolVersion = 0; } if (protocolVersion < 0) { logger.log(Level.WARNING, String.format("Invalid protocol version: %d! Not parsing Sone.", protocolVersion)); return null; } /* check for valid versions. */ if (protocolVersion > MAX_PROTOCOL_VERSION) { logger.log(Level.WARNING, String.format("Unknown protocol version: %d! Not parsing Sone.", protocolVersion)); return null; } String soneTime = soneXml.getValue("time", null); if (soneTime == null) { /* TODO - mark Sone as bad. */ logger.log(Level.WARNING, String.format("Downloaded time for Sone %s was null!", sone)); return null; } try { sone.setTime(Long.parseLong(soneTime)); } catch (NumberFormatException nfe1) { /* TODO - mark Sone as bad. */ logger.log(Level.WARNING, String.format("Downloaded Sone %s with invalid time: %s", sone, soneTime)); return null; } SimpleXML clientXml = soneXml.getNode("client"); if (clientXml != null) { String clientName = clientXml.getValue("name", null); String clientVersion = clientXml.getValue("version", null); if ((clientName == null) || (clientVersion == null)) { logger.log(Level.WARNING, String.format("Download Sone %s with client XML but missing name or version!", sone)); return null; } sone.setClient(new Client(clientName, clientVersion)); } String soneRequestUri = soneXml.getValue("request-uri", null); if (soneRequestUri != null) { try { sone.setRequestUri(new FreenetURI(soneRequestUri)); } catch (MalformedURLException mue1) { /* TODO - mark Sone as bad. */ logger.log(Level.WARNING, String.format("Downloaded Sone %s has invalid request URI: %s", sone, soneRequestUri), mue1); return null; } } String soneInsertUri = soneXml.getValue("insert-uri", null); if ((soneInsertUri != null) && (sone.getInsertUri() == null)) { try { sone.setInsertUri(new FreenetURI(soneInsertUri)); sone.setLatestEdition(Math.max(sone.getRequestUri().getEdition(), sone.getInsertUri().getEdition())); } catch (MalformedURLException mue1) { /* TODO - mark Sone as bad. */ logger.log(Level.WARNING, String.format("Downloaded Sone %s has invalid insert URI: %s", sone, soneInsertUri), mue1); return null; } } SimpleXML profileXml = soneXml.getNode("profile"); if (profileXml == null) { /* TODO - mark Sone as bad. */ logger.log(Level.WARNING, String.format("Downloaded Sone %s has no profile!", sone)); return null; } /* parse profile. */ String profileFirstName = profileXml.getValue("first-name", null); String profileMiddleName = profileXml.getValue("middle-name", null); String profileLastName = profileXml.getValue("last-name", null); Integer profileBirthDay = Numbers.safeParseInteger(profileXml.getValue("birth-day", null)); Integer profileBirthMonth = Numbers.safeParseInteger(profileXml.getValue("birth-month", null)); Integer profileBirthYear = Numbers.safeParseInteger(profileXml.getValue("birth-year", null)); Profile profile = new Profile(sone).setFirstName(profileFirstName).setMiddleName(profileMiddleName).setLastName(profileLastName); profile.setBirthDay(profileBirthDay).setBirthMonth(profileBirthMonth).setBirthYear(profileBirthYear); /* avatar is processed after images are loaded. */ String avatarId = profileXml.getValue("avatar", null); /* parse profile fields. */ SimpleXML profileFieldsXml = profileXml.getNode("fields"); if (profileFieldsXml != null) { for (SimpleXML fieldXml : profileFieldsXml.getNodes("field")) { String fieldName = fieldXml.getValue("field-name", null); String fieldValue = fieldXml.getValue("field-value", ""); if (fieldName == null) { logger.log(Level.WARNING, String.format("Downloaded profile field for Sone %s with missing data! Name: %s, Value: %s", sone, fieldName, fieldValue)); return null; } try { profile.addField(fieldName).setValue(fieldValue); } catch (IllegalArgumentException iae1) { logger.log(Level.WARNING, String.format("Duplicate field: %s", fieldName), iae1); return null; } } } /* parse posts. */ SimpleXML postsXml = soneXml.getNode("posts"); Set<Post> posts = new HashSet<Post>(); if (postsXml == null) { /* TODO - mark Sone as bad. */ logger.log(Level.WARNING, String.format("Downloaded Sone %s has no posts!", sone)); } else { for (SimpleXML postXml : postsXml.getNodes("post")) { String postId = postXml.getValue("id", null); String postRecipientId = postXml.getValue("recipient", null); String postTime = postXml.getValue("time", null); String postText = postXml.getValue("text", null); if ((postId == null) || (postTime == null) || (postText == null)) { /* TODO - mark Sone as bad. */ logger.log(Level.WARNING, String.format("Downloaded post for Sone %s with missing data! ID: %s, Time: %s, Text: %s", sone, postId, postTime, postText)); return null; } try { PostBuilder postBuilder = core.postBuilder(); /* TODO - parse time correctly. */ postBuilder.withId(postId).from(sone.getId()).withTime(Long.parseLong(postTime)).withText(postText); if ((postRecipientId != null) && (postRecipientId.length() == 43)) { postBuilder.to(postRecipientId); } posts.add(postBuilder.build()); } catch (NumberFormatException nfe1) { /* TODO - mark Sone as bad. */ logger.log(Level.WARNING, String.format("Downloaded post for Sone %s with invalid time: %s", sone, postTime)); return null; } } } /* parse replies. */ SimpleXML repliesXml = soneXml.getNode("replies"); Set<PostReply> replies = new HashSet<PostReply>(); if (repliesXml == null) { /* TODO - mark Sone as bad. */ logger.log(Level.WARNING, String.format("Downloaded Sone %s has no replies!", sone)); } else { for (SimpleXML replyXml : repliesXml.getNodes("reply")) { String replyId = replyXml.getValue("id", null); String replyPostId = replyXml.getValue("post-id", null); String replyTime = replyXml.getValue("time", null); String replyText = replyXml.getValue("text", null); if ((replyId == null) || (replyPostId == null) || (replyTime == null) || (replyText == null)) { /* TODO - mark Sone as bad. */ logger.log(Level.WARNING, String.format("Downloaded reply for Sone %s with missing data! ID: %s, Post: %s, Time: %s, Text: %s", sone, replyId, replyPostId, replyTime, replyText)); return null; } try { PostReplyBuilder postReplyBuilder = core.postReplyBuilder(); /* TODO - parse time correctly. */ postReplyBuilder.withId(replyId).from(sone.getId()).to(replyPostId).withTime(Long.parseLong(replyTime)).withText(replyText); replies.add(postReplyBuilder.build()); } catch (NumberFormatException nfe1) { /* TODO - mark Sone as bad. */ logger.log(Level.WARNING, String.format("Downloaded reply for Sone %s with invalid time: %s", sone, replyTime)); return null; } } } /* parse liked post IDs. */ SimpleXML likePostIdsXml = soneXml.getNode("post-likes"); Set<String> likedPostIds = new HashSet<String>(); if (likePostIdsXml == null) { /* TODO - mark Sone as bad. */ logger.log(Level.WARNING, String.format("Downloaded Sone %s has no post likes!", sone)); } else { for (SimpleXML likedPostIdXml : likePostIdsXml.getNodes("post-like")) { String postId = likedPostIdXml.getValue(); likedPostIds.add(postId); } } /* parse liked reply IDs. */ SimpleXML likeReplyIdsXml = soneXml.getNode("reply-likes"); Set<String> likedReplyIds = new HashSet<String>(); if (likeReplyIdsXml == null) { /* TODO - mark Sone as bad. */ logger.log(Level.WARNING, String.format("Downloaded Sone %s has no reply likes!", sone)); } else { for (SimpleXML likedReplyIdXml : likeReplyIdsXml.getNodes("reply-like")) { String replyId = likedReplyIdXml.getValue(); likedReplyIds.add(replyId); } } /* parse albums. */ SimpleXML albumsXml = soneXml.getNode("albums"); List<Album> topLevelAlbums = new ArrayList<Album>(); if (albumsXml != null) { for (SimpleXML albumXml : albumsXml.getNodes("album")) { String id = albumXml.getValue("id", null); String parentId = albumXml.getValue("parent", null); String title = albumXml.getValue("title", null); String description = albumXml.getValue("description", ""); String albumImageId = albumXml.getValue("album-image", null); if ((id == null) || (title == null) || (description == null)) { logger.log(Level.WARNING, String.format("Downloaded Sone %s contains invalid album!", sone)); return null; } Album parent = null; if (parentId != null) { parent = core.getAlbum(parentId, false); if (parent == null) { logger.log(Level.WARNING, String.format("Downloaded Sone %s has album with invalid parent!", sone)); return null; } } Album album = core.getAlbum(id).setSone(sone).modify().setTitle(title).setDescription(description).update(); if (parent != null) { parent.addAlbum(album); } else { topLevelAlbums.add(album); } SimpleXML imagesXml = albumXml.getNode("images"); if (imagesXml != null) { for (SimpleXML imageXml : imagesXml.getNodes("image")) { String imageId = imageXml.getValue("id", null); String imageCreationTimeString = imageXml.getValue("creation-time", null); String imageKey = imageXml.getValue("key", null); String imageTitle = imageXml.getValue("title", null); String imageDescription = imageXml.getValue("description", ""); String imageWidthString = imageXml.getValue("width", null); String imageHeightString = imageXml.getValue("height", null); if ((imageId == null) || (imageCreationTimeString == null) || (imageKey == null) || (imageTitle == null) || (imageWidthString == null) || (imageHeightString == null)) { logger.log(Level.WARNING, String.format("Downloaded Sone %s contains invalid images!", sone)); return null; } long creationTime = Numbers.safeParseLong(imageCreationTimeString, 0L); int imageWidth = Numbers.safeParseInteger(imageWidthString, 0); int imageHeight = Numbers.safeParseInteger(imageHeightString, 0); if ((imageWidth < 1) || (imageHeight < 1)) { logger.log(Level.WARNING, String.format("Downloaded Sone %s contains image %s with invalid dimensions (%s, %s)!", sone, imageId, imageWidthString, imageHeightString)); return null; } Image image = core.getImage(imageId).modify().setSone(sone).setKey(imageKey).setCreationTime(creationTime).update(); image = image.modify().setTitle(imageTitle).setDescription(imageDescription).update(); image = image.modify().setWidth(imageWidth).setHeight(imageHeight).update(); album.addImage(image); } } album.modify().setAlbumImage(albumImageId).update(); } } /* process avatar. */ if (avatarId != null) { profile.setAvatar(core.getImage(avatarId, false)); } /* okay, apparently everything was parsed correctly. Now import. */ /* atomic setter operation on the Sone. */ synchronized (sone) { sone.setProfile(profile); sone.setPosts(posts); sone.setReplies(replies); sone.setLikePostIds(likedPostIds); sone.setLikeReplyIds(likedReplyIds); for (Album album : topLevelAlbums) { sone.getRootAlbum().addAlbum(album); } } return sone; }
public Sone parseSone(Sone originalSone, InputStream soneInputStream) throws SoneException { /* TODO - impose a size limit? */ Document document; /* XML parsing is not thread-safe. */ synchronized (this) { document = XML.transformToDocument(soneInputStream); } if (document == null) { /* TODO - mark Sone as bad. */ logger.log(Level.WARNING, String.format("Could not parse XML for Sone %s!", originalSone)); return null; } Sone sone = new SoneImpl(originalSone.getId(), originalSone.isLocal()).setIdentity(originalSone.getIdentity()); SimpleXML soneXml; try { soneXml = SimpleXML.fromDocument(document); } catch (NullPointerException npe1) { /* for some reason, invalid XML can cause NPEs. */ logger.log(Level.WARNING, String.format("XML for Sone %s can not be parsed!", sone), npe1); return null; } Integer protocolVersion = null; String soneProtocolVersion = soneXml.getValue("protocol-version", null); if (soneProtocolVersion != null) { protocolVersion = Numbers.safeParseInteger(soneProtocolVersion); } if (protocolVersion == null) { logger.log(Level.INFO, "No protocol version found, assuming 0."); protocolVersion = 0; } if (protocolVersion < 0) { logger.log(Level.WARNING, String.format("Invalid protocol version: %d! Not parsing Sone.", protocolVersion)); return null; } /* check for valid versions. */ if (protocolVersion > MAX_PROTOCOL_VERSION) { logger.log(Level.WARNING, String.format("Unknown protocol version: %d! Not parsing Sone.", protocolVersion)); return null; } String soneTime = soneXml.getValue("time", null); if (soneTime == null) { /* TODO - mark Sone as bad. */ logger.log(Level.WARNING, String.format("Downloaded time for Sone %s was null!", sone)); return null; } try { sone.setTime(Long.parseLong(soneTime)); } catch (NumberFormatException nfe1) { /* TODO - mark Sone as bad. */ logger.log(Level.WARNING, String.format("Downloaded Sone %s with invalid time: %s", sone, soneTime)); return null; } SimpleXML clientXml = soneXml.getNode("client"); if (clientXml != null) { String clientName = clientXml.getValue("name", null); String clientVersion = clientXml.getValue("version", null); if ((clientName == null) || (clientVersion == null)) { logger.log(Level.WARNING, String.format("Download Sone %s with client XML but missing name or version!", sone)); return null; } sone.setClient(new Client(clientName, clientVersion)); } String soneRequestUri = soneXml.getValue("request-uri", null); if (soneRequestUri != null) { try { sone.setRequestUri(new FreenetURI(soneRequestUri)); } catch (MalformedURLException mue1) { /* TODO - mark Sone as bad. */ logger.log(Level.WARNING, String.format("Downloaded Sone %s has invalid request URI: %s", sone, soneRequestUri), mue1); return null; } } if (originalSone.getInsertUri() != null) { sone.setInsertUri(originalSone.getInsertUri()); } SimpleXML profileXml = soneXml.getNode("profile"); if (profileXml == null) { /* TODO - mark Sone as bad. */ logger.log(Level.WARNING, String.format("Downloaded Sone %s has no profile!", sone)); return null; } /* parse profile. */ String profileFirstName = profileXml.getValue("first-name", null); String profileMiddleName = profileXml.getValue("middle-name", null); String profileLastName = profileXml.getValue("last-name", null); Integer profileBirthDay = Numbers.safeParseInteger(profileXml.getValue("birth-day", null)); Integer profileBirthMonth = Numbers.safeParseInteger(profileXml.getValue("birth-month", null)); Integer profileBirthYear = Numbers.safeParseInteger(profileXml.getValue("birth-year", null)); Profile profile = new Profile(sone).setFirstName(profileFirstName).setMiddleName(profileMiddleName).setLastName(profileLastName); profile.setBirthDay(profileBirthDay).setBirthMonth(profileBirthMonth).setBirthYear(profileBirthYear); /* avatar is processed after images are loaded. */ String avatarId = profileXml.getValue("avatar", null); /* parse profile fields. */ SimpleXML profileFieldsXml = profileXml.getNode("fields"); if (profileFieldsXml != null) { for (SimpleXML fieldXml : profileFieldsXml.getNodes("field")) { String fieldName = fieldXml.getValue("field-name", null); String fieldValue = fieldXml.getValue("field-value", ""); if (fieldName == null) { logger.log(Level.WARNING, String.format("Downloaded profile field for Sone %s with missing data! Name: %s, Value: %s", sone, fieldName, fieldValue)); return null; } try { profile.addField(fieldName).setValue(fieldValue); } catch (IllegalArgumentException iae1) { logger.log(Level.WARNING, String.format("Duplicate field: %s", fieldName), iae1); return null; } } } /* parse posts. */ SimpleXML postsXml = soneXml.getNode("posts"); Set<Post> posts = new HashSet<Post>(); if (postsXml == null) { /* TODO - mark Sone as bad. */ logger.log(Level.WARNING, String.format("Downloaded Sone %s has no posts!", sone)); } else { for (SimpleXML postXml : postsXml.getNodes("post")) { String postId = postXml.getValue("id", null); String postRecipientId = postXml.getValue("recipient", null); String postTime = postXml.getValue("time", null); String postText = postXml.getValue("text", null); if ((postId == null) || (postTime == null) || (postText == null)) { /* TODO - mark Sone as bad. */ logger.log(Level.WARNING, String.format("Downloaded post for Sone %s with missing data! ID: %s, Time: %s, Text: %s", sone, postId, postTime, postText)); return null; } try { PostBuilder postBuilder = core.postBuilder(); /* TODO - parse time correctly. */ postBuilder.withId(postId).from(sone.getId()).withTime(Long.parseLong(postTime)).withText(postText); if ((postRecipientId != null) && (postRecipientId.length() == 43)) { postBuilder.to(postRecipientId); } posts.add(postBuilder.build()); } catch (NumberFormatException nfe1) { /* TODO - mark Sone as bad. */ logger.log(Level.WARNING, String.format("Downloaded post for Sone %s with invalid time: %s", sone, postTime)); return null; } } } /* parse replies. */ SimpleXML repliesXml = soneXml.getNode("replies"); Set<PostReply> replies = new HashSet<PostReply>(); if (repliesXml == null) { /* TODO - mark Sone as bad. */ logger.log(Level.WARNING, String.format("Downloaded Sone %s has no replies!", sone)); } else { for (SimpleXML replyXml : repliesXml.getNodes("reply")) { String replyId = replyXml.getValue("id", null); String replyPostId = replyXml.getValue("post-id", null); String replyTime = replyXml.getValue("time", null); String replyText = replyXml.getValue("text", null); if ((replyId == null) || (replyPostId == null) || (replyTime == null) || (replyText == null)) { /* TODO - mark Sone as bad. */ logger.log(Level.WARNING, String.format("Downloaded reply for Sone %s with missing data! ID: %s, Post: %s, Time: %s, Text: %s", sone, replyId, replyPostId, replyTime, replyText)); return null; } try { PostReplyBuilder postReplyBuilder = core.postReplyBuilder(); /* TODO - parse time correctly. */ postReplyBuilder.withId(replyId).from(sone.getId()).to(replyPostId).withTime(Long.parseLong(replyTime)).withText(replyText); replies.add(postReplyBuilder.build()); } catch (NumberFormatException nfe1) { /* TODO - mark Sone as bad. */ logger.log(Level.WARNING, String.format("Downloaded reply for Sone %s with invalid time: %s", sone, replyTime)); return null; } } } /* parse liked post IDs. */ SimpleXML likePostIdsXml = soneXml.getNode("post-likes"); Set<String> likedPostIds = new HashSet<String>(); if (likePostIdsXml == null) { /* TODO - mark Sone as bad. */ logger.log(Level.WARNING, String.format("Downloaded Sone %s has no post likes!", sone)); } else { for (SimpleXML likedPostIdXml : likePostIdsXml.getNodes("post-like")) { String postId = likedPostIdXml.getValue(); likedPostIds.add(postId); } } /* parse liked reply IDs. */ SimpleXML likeReplyIdsXml = soneXml.getNode("reply-likes"); Set<String> likedReplyIds = new HashSet<String>(); if (likeReplyIdsXml == null) { /* TODO - mark Sone as bad. */ logger.log(Level.WARNING, String.format("Downloaded Sone %s has no reply likes!", sone)); } else { for (SimpleXML likedReplyIdXml : likeReplyIdsXml.getNodes("reply-like")) { String replyId = likedReplyIdXml.getValue(); likedReplyIds.add(replyId); } } /* parse albums. */ SimpleXML albumsXml = soneXml.getNode("albums"); List<Album> topLevelAlbums = new ArrayList<Album>(); if (albumsXml != null) { for (SimpleXML albumXml : albumsXml.getNodes("album")) { String id = albumXml.getValue("id", null); String parentId = albumXml.getValue("parent", null); String title = albumXml.getValue("title", null); String description = albumXml.getValue("description", ""); String albumImageId = albumXml.getValue("album-image", null); if ((id == null) || (title == null) || (description == null)) { logger.log(Level.WARNING, String.format("Downloaded Sone %s contains invalid album!", sone)); return null; } Album parent = null; if (parentId != null) { parent = core.getAlbum(parentId, false); if (parent == null) { logger.log(Level.WARNING, String.format("Downloaded Sone %s has album with invalid parent!", sone)); return null; } } Album album = core.getAlbum(id).setSone(sone).modify().setTitle(title).setDescription(description).update(); if (parent != null) { parent.addAlbum(album); } else { topLevelAlbums.add(album); } SimpleXML imagesXml = albumXml.getNode("images"); if (imagesXml != null) { for (SimpleXML imageXml : imagesXml.getNodes("image")) { String imageId = imageXml.getValue("id", null); String imageCreationTimeString = imageXml.getValue("creation-time", null); String imageKey = imageXml.getValue("key", null); String imageTitle = imageXml.getValue("title", null); String imageDescription = imageXml.getValue("description", ""); String imageWidthString = imageXml.getValue("width", null); String imageHeightString = imageXml.getValue("height", null); if ((imageId == null) || (imageCreationTimeString == null) || (imageKey == null) || (imageTitle == null) || (imageWidthString == null) || (imageHeightString == null)) { logger.log(Level.WARNING, String.format("Downloaded Sone %s contains invalid images!", sone)); return null; } long creationTime = Numbers.safeParseLong(imageCreationTimeString, 0L); int imageWidth = Numbers.safeParseInteger(imageWidthString, 0); int imageHeight = Numbers.safeParseInteger(imageHeightString, 0); if ((imageWidth < 1) || (imageHeight < 1)) { logger.log(Level.WARNING, String.format("Downloaded Sone %s contains image %s with invalid dimensions (%s, %s)!", sone, imageId, imageWidthString, imageHeightString)); return null; } Image image = core.getImage(imageId).modify().setSone(sone).setKey(imageKey).setCreationTime(creationTime).update(); image = image.modify().setTitle(imageTitle).setDescription(imageDescription).update(); image = image.modify().setWidth(imageWidth).setHeight(imageHeight).update(); album.addImage(image); } } album.modify().setAlbumImage(albumImageId).update(); } } /* process avatar. */ if (avatarId != null) { profile.setAvatar(core.getImage(avatarId, false)); } /* okay, apparently everything was parsed correctly. Now import. */ /* atomic setter operation on the Sone. */ synchronized (sone) { sone.setProfile(profile); sone.setPosts(posts); sone.setReplies(replies); sone.setLikePostIds(likedPostIds); sone.setLikeReplyIds(likedReplyIds); for (Album album : topLevelAlbums) { sone.getRootAlbum().addAlbum(album); } } return sone; }
diff --git a/android/src/fq/router2/utils/ConfigUtils.java b/android/src/fq/router2/utils/ConfigUtils.java index c0acf78..55e9ecd 100644 --- a/android/src/fq/router2/utils/ConfigUtils.java +++ b/android/src/fq/router2/utils/ConfigUtils.java @@ -1,21 +1,21 @@ package fq.router2.utils; import org.json.JSONObject; import java.io.File; public class ConfigUtils { public static int getHttpManagerPort() { - File configFile = new File("/data/data/fq.router2/fqsocks.json"); + File configFile = new File("/data/data/fq.router2/etc/fqsocks.json"); if (!configFile.exists()) { return 2515; } try { return new JSONObject(IOUtils.readFromFile(configFile)).getJSONObject("http_manager").getInt("port"); } catch (Exception e) { LogUtils.e("failed to parse config", e); return 2515; } } }
true
true
public static int getHttpManagerPort() { File configFile = new File("/data/data/fq.router2/fqsocks.json"); if (!configFile.exists()) { return 2515; } try { return new JSONObject(IOUtils.readFromFile(configFile)).getJSONObject("http_manager").getInt("port"); } catch (Exception e) { LogUtils.e("failed to parse config", e); return 2515; } }
public static int getHttpManagerPort() { File configFile = new File("/data/data/fq.router2/etc/fqsocks.json"); if (!configFile.exists()) { return 2515; } try { return new JSONObject(IOUtils.readFromFile(configFile)).getJSONObject("http_manager").getInt("port"); } catch (Exception e) { LogUtils.e("failed to parse config", e); return 2515; } }
diff --git a/src/com/sparkedia/valrix/AutoReplace/AutoPlayerListener.java b/src/com/sparkedia/valrix/AutoReplace/AutoPlayerListener.java index acaf4b8..aebf1a0 100644 --- a/src/com/sparkedia/valrix/AutoReplace/AutoPlayerListener.java +++ b/src/com/sparkedia/valrix/AutoReplace/AutoPlayerListener.java @@ -1,131 +1,131 @@ package com.sparkedia.valrix.AutoReplace; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerListener; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; public class AutoPlayerListener extends PlayerListener { public AutoReplace plugin; public AutoPlayerListener(AutoReplace plugin) { this.plugin = plugin; } public boolean legal(int ID) { switch (ID) { case 55: return true; case 63: return true; case 295: return true; case 321: return true; case 323: return true; case 324: return true; case 330: return true; case 331: return true; case 338: return true; case 355: return true; case 356: return true; default: return false; } } public boolean food(int ID) { switch (ID) { case 260: return true; case 282: return true; case 297: return true; case 319: return true; case 320: return true; case 322: return true; case 349: return true; case 350: return true; case 357: return true; default: return false; } } @SuppressWarnings("deprecation") public void onPlayerInteract(PlayerInteractEvent e) { if (e.getAction().toString().equals("RIGHT_CLICK_AIR") && food(e.getMaterial().getId())) { Player player = e.getPlayer(); PlayerInventory inv = player.getInventory(); ItemStack item = e.getItem(); int slot = inv.getHeldItemSlot(); ItemStack[] items = inv.getContents(); for (int i = 0; i < items.length; i++) { if (i != slot) { ItemStack obj = items[i]; if ((obj != null) && (obj.getTypeId() == item.getTypeId()) && (obj.getAmount() > 0)) { inv.getItemInHand().setAmount(obj.getAmount()+1); inv.clear(i); player.updateInventory(); break; } } } } else if (e.getAction().toString().equalsIgnoreCase("RIGHT_CLICK_BLOCK") && e.hasBlock() && e.hasItem() && !e.isBlockInHand() && legal(e.getItem().getTypeId())) { Player player = e.getPlayer(); PlayerInventory inv = player.getInventory(); ItemStack item = e.getItem(); int count = (player.getItemInHand().getAmount()-1); int slot = inv.getHeldItemSlot(); if (count < 1) { ItemStack[] items = inv.getContents(); for (int i = 0; i < items.length; i++) { if (i != slot) { ItemStack obj = items[i]; if ((obj != null) && (obj.getTypeId() == item.getTypeId()) && (obj.getAmount() > 0)) { inv.getItemInHand().setAmount(obj.getAmount()+1); inv.clear(i); player.updateInventory(); break; } } } } - } else if (e.getMaterial().getId() != 325 && e.getAction().toString().equalsIgnoreCase("RIGHT_CLICK_BLOCK")) { + } else if (e.getMaterial().getId() == 326 && e.getAction().toString().equalsIgnoreCase("RIGHT_CLICK_BLOCK")) { Player player = e.getPlayer(); PlayerInventory inv = player.getInventory(); int slot = inv.getHeldItemSlot(); ItemStack[] items = inv.getContents(); for (int i = 0; i < items.length; i++) { if (i != slot) { ItemStack obj = items[i]; if ((obj != null) && (obj.getTypeId() == 326)) { e.setCancelled(true); ItemStack b = new ItemStack(325); b.setAmount(1); inv.setItem(i, b); player.updateInventory(); e.getClickedBlock().getRelative(e.getBlockFace()).setType(Material.WATER); break; } } } } } }
true
true
public void onPlayerInteract(PlayerInteractEvent e) { if (e.getAction().toString().equals("RIGHT_CLICK_AIR") && food(e.getMaterial().getId())) { Player player = e.getPlayer(); PlayerInventory inv = player.getInventory(); ItemStack item = e.getItem(); int slot = inv.getHeldItemSlot(); ItemStack[] items = inv.getContents(); for (int i = 0; i < items.length; i++) { if (i != slot) { ItemStack obj = items[i]; if ((obj != null) && (obj.getTypeId() == item.getTypeId()) && (obj.getAmount() > 0)) { inv.getItemInHand().setAmount(obj.getAmount()+1); inv.clear(i); player.updateInventory(); break; } } } } else if (e.getAction().toString().equalsIgnoreCase("RIGHT_CLICK_BLOCK") && e.hasBlock() && e.hasItem() && !e.isBlockInHand() && legal(e.getItem().getTypeId())) { Player player = e.getPlayer(); PlayerInventory inv = player.getInventory(); ItemStack item = e.getItem(); int count = (player.getItemInHand().getAmount()-1); int slot = inv.getHeldItemSlot(); if (count < 1) { ItemStack[] items = inv.getContents(); for (int i = 0; i < items.length; i++) { if (i != slot) { ItemStack obj = items[i]; if ((obj != null) && (obj.getTypeId() == item.getTypeId()) && (obj.getAmount() > 0)) { inv.getItemInHand().setAmount(obj.getAmount()+1); inv.clear(i); player.updateInventory(); break; } } } } } else if (e.getMaterial().getId() != 325 && e.getAction().toString().equalsIgnoreCase("RIGHT_CLICK_BLOCK")) { Player player = e.getPlayer(); PlayerInventory inv = player.getInventory(); int slot = inv.getHeldItemSlot(); ItemStack[] items = inv.getContents(); for (int i = 0; i < items.length; i++) { if (i != slot) { ItemStack obj = items[i]; if ((obj != null) && (obj.getTypeId() == 326)) { e.setCancelled(true); ItemStack b = new ItemStack(325); b.setAmount(1); inv.setItem(i, b); player.updateInventory(); e.getClickedBlock().getRelative(e.getBlockFace()).setType(Material.WATER); break; } } } } }
public void onPlayerInteract(PlayerInteractEvent e) { if (e.getAction().toString().equals("RIGHT_CLICK_AIR") && food(e.getMaterial().getId())) { Player player = e.getPlayer(); PlayerInventory inv = player.getInventory(); ItemStack item = e.getItem(); int slot = inv.getHeldItemSlot(); ItemStack[] items = inv.getContents(); for (int i = 0; i < items.length; i++) { if (i != slot) { ItemStack obj = items[i]; if ((obj != null) && (obj.getTypeId() == item.getTypeId()) && (obj.getAmount() > 0)) { inv.getItemInHand().setAmount(obj.getAmount()+1); inv.clear(i); player.updateInventory(); break; } } } } else if (e.getAction().toString().equalsIgnoreCase("RIGHT_CLICK_BLOCK") && e.hasBlock() && e.hasItem() && !e.isBlockInHand() && legal(e.getItem().getTypeId())) { Player player = e.getPlayer(); PlayerInventory inv = player.getInventory(); ItemStack item = e.getItem(); int count = (player.getItemInHand().getAmount()-1); int slot = inv.getHeldItemSlot(); if (count < 1) { ItemStack[] items = inv.getContents(); for (int i = 0; i < items.length; i++) { if (i != slot) { ItemStack obj = items[i]; if ((obj != null) && (obj.getTypeId() == item.getTypeId()) && (obj.getAmount() > 0)) { inv.getItemInHand().setAmount(obj.getAmount()+1); inv.clear(i); player.updateInventory(); break; } } } } } else if (e.getMaterial().getId() == 326 && e.getAction().toString().equalsIgnoreCase("RIGHT_CLICK_BLOCK")) { Player player = e.getPlayer(); PlayerInventory inv = player.getInventory(); int slot = inv.getHeldItemSlot(); ItemStack[] items = inv.getContents(); for (int i = 0; i < items.length; i++) { if (i != slot) { ItemStack obj = items[i]; if ((obj != null) && (obj.getTypeId() == 326)) { e.setCancelled(true); ItemStack b = new ItemStack(325); b.setAmount(1); inv.setItem(i, b); player.updateInventory(); e.getClickedBlock().getRelative(e.getBlockFace()).setType(Material.WATER); break; } } } } }
diff --git a/jmbs_maven/Server/src/main/java/jmbs/server/ProjectDAO.java b/jmbs_maven/Server/src/main/java/jmbs/server/ProjectDAO.java index 7082114..6d9e3c9 100644 --- a/jmbs_maven/Server/src/main/java/jmbs/server/ProjectDAO.java +++ b/jmbs_maven/Server/src/main/java/jmbs/server/ProjectDAO.java @@ -1,263 +1,263 @@ /** * JMBS: Java Micro Blogging System * * Copyright (C) 2012 * * 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 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY. 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, see <http://www.gnu.org/licenses/>. * * @author Younes CHEIKH http://cyounes.com * @author Benjamin Babic http://bbabic.com * */ package jmbs.server; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import jmbs.common.Project; import jmbs.common.User; public class ProjectDAO extends DAO { private static final long serialVersionUID = -1449738022340494222L; public ProjectDAO(Connection c) { super(c); } public boolean closeProject(int idproject) { boolean ret; if (exists(idproject)) { // can be optimized set("UPDATE projects SET status = ? WHERE idproject = ?;"); setInt(1, Project.STATUS_CLOSED); setInt(2, idproject); ret = executeUpdate(); } else { System.err.println("Project you are trying to close does not exists."); ret = false; } return ret; } public Project createProject(String name, int iduser) { Project ret = null; boolean res; if (!this.exists(name)) { set("INSERT INTO projects (name,idowner,status,nbsuscribers) VALUES (?,?,?,?);", Statement.RETURN_GENERATED_KEYS); setString(1, name); setInt(2, iduser); setInt(3, 1); // is activate by default setInt(4, 0); // starts with 0 involved users res = executeUpdate(); if (res) {//TODO: change creator when youyou is ready to implement new interface try { ResultSet rs = getGeneratedKeys(); ret = new Project(name, rs.getInt("idproject"), new UserDAO(con).getUser(iduser), Project.STATUS_OPENED, 0, Project.DEFAULT_EDIT_OPTION, Project.DEFAULT_SUPRESS_OPTION, Project.DEFAULT_ACCES_OPTION); } catch (SQLException e) { } } } return ret; } public boolean exists(String name) { // xpost from /UserDAO. set("SELECT name FROM projects WHERE name=?;"); setString(1, name); ResultSet res = executeQuery(); boolean ret = false; try { res.getInt("idproject"); ret = true; } catch (SQLException e) { // project does not exist we can do something here if we really want to waste time ... } return ret; } public boolean exists(int idprj) { // xpost from /UserDAO. set("SELECT name FROM projects WHERE idproject=?;"); setInt(1, idprj); ResultSet res = executeQuery(); boolean ret = false; try { res.getString("name"); ret = true; } catch (SQLException e) { // project does not exist we can do something here if we really want to waste time ... } return ret; } protected Project getProject(ResultSet rs) throws SQLException { Project p; UserDAO udao = new UserDAO(con); User u = udao.getUser(rs.getInt("idowner")); p = new Project(rs.getString("name"), rs.getInt("idproject"), u, rs.getInt("status"), rs.getInt("nbsuscribers"), rs.getBoolean("iseditallowed"), rs.getBoolean("issupressionallowed"), rs.getBoolean("ispublic")); return p; } /** * find a project using his id. Returns null if there are no projects found * for that id * * @param id id of the project */ public Project findProject(int id) { Project p = null; set("SELECT * FROM projects WHERE idproject=? ;"); setInt(1, id); ResultSet res = executeQuery(); try { p = getProject(res); } catch (SQLException e) { System.out.println("Unable to find project with id=" + id + "."); } try { res.close(); } catch (SQLException e) { System.out.println("Database acess error !\n Unable to close connection !"); } return p; } public Project findProject(String name) { Project p = null; UserDAO udao = new UserDAO(con); set("SELECT * FROM projects WHERE name=? ;"); setString(1, name); ResultSet res = executeQuery(); try { p = getProject(res); } catch (SQLException e) { System.out.println("Unable to find any project with name containg " + name); } return p; } public ArrayList<Project> findProjects(String name) { ArrayList<Project> found = new ArrayList<Project>(); UserDAO udao = new UserDAO(con); set("SELECT * FROM projects WHERE name LIKE ? ;"); setString(1, "%" + name + "%"); ResultSet res = executeQuery(); try { do { found.add(getProject(res)); } while (res.next()); } catch (SQLException e) { System.out.println("Unable to find any project with name containg " + name); } return found; } /** * Lists all the users in the project without filling their Project array * * @return Collection of User */ public ArrayList<User> getUsers(int id) { ArrayList<User> u = new ArrayList<User>(); int userid; - set("SELECT participate.name,user.* FROM participate,user WHERE participate.idproject=? AND user.name=projects.name;"); + set("SELECT users.* FROM participate,users WHERE participate.idproject=? AND users.iduser=participate.iduser;"); setInt(1, id); ResultSet res = executeQuery(); try { do { userid = res.getInt("iduser"); u.add(new User(res.getString("name"), res.getString("forename"), res.getString("email"), userid, res.getString("picture"), res.getInt("authlvl"))); } while (res.next()); } catch (SQLException e) { System.out.println("Unable to find project with id=" + id + "."); } try { res.close(); } catch (SQLException e) { System.err.println("Database acess error !\n Unable to close connection !"); } return u; } public boolean isOwner(int iduser, int idproject) { set("SELECT idowner FROM projects WHERE idproject=?;"); setInt(1, idproject); ResultSet rs = executeQuery(); boolean b; try { b = (iduser == rs.getInt("idowner")); } catch (SQLException e) { b = false; } return b; } public boolean isActive(int projectId) { set("SELECT status FROM projects WHERE idproject=?;"); setInt(1, projectId); ResultSet rs = executeQuery(); boolean b; try { b = (rs.getInt("status") == 1); } catch (SQLException e) { b = false; } return b; } public boolean isUserInvolved(int idproject, int iduser) { boolean b; set("SELECT idproject FROM projects WHERE idproject=? AND iduser=?;"); setInt(1, idproject); setInt(2, iduser); ResultSet rs = executeQuery(); try { rs.getInt("idproject"); b = true; } catch (SQLException e) { b = false; } return b; } }
true
true
public ArrayList<User> getUsers(int id) { ArrayList<User> u = new ArrayList<User>(); int userid; set("SELECT participate.name,user.* FROM participate,user WHERE participate.idproject=? AND user.name=projects.name;"); setInt(1, id); ResultSet res = executeQuery(); try { do { userid = res.getInt("iduser"); u.add(new User(res.getString("name"), res.getString("forename"), res.getString("email"), userid, res.getString("picture"), res.getInt("authlvl"))); } while (res.next()); } catch (SQLException e) { System.out.println("Unable to find project with id=" + id + "."); } try { res.close(); } catch (SQLException e) { System.err.println("Database acess error !\n Unable to close connection !"); } return u; }
public ArrayList<User> getUsers(int id) { ArrayList<User> u = new ArrayList<User>(); int userid; set("SELECT users.* FROM participate,users WHERE participate.idproject=? AND users.iduser=participate.iduser;"); setInt(1, id); ResultSet res = executeQuery(); try { do { userid = res.getInt("iduser"); u.add(new User(res.getString("name"), res.getString("forename"), res.getString("email"), userid, res.getString("picture"), res.getInt("authlvl"))); } while (res.next()); } catch (SQLException e) { System.out.println("Unable to find project with id=" + id + "."); } try { res.close(); } catch (SQLException e) { System.err.println("Database acess error !\n Unable to close connection !"); } return u; }
diff --git a/srcj/com/sun/electric/tool/user/ui/EditWindow.java b/srcj/com/sun/electric/tool/user/ui/EditWindow.java index 3582aff6f..173fa3b47 100755 --- a/srcj/com/sun/electric/tool/user/ui/EditWindow.java +++ b/srcj/com/sun/electric/tool/user/ui/EditWindow.java @@ -1,3935 +1,3935 @@ /* -*- tab-width: 4 -*- * * Electric(tm) VLSI Design System * * File: EditWindow.java * * Copyright (c) 2003 Sun Microsystems and Static Free Software * * Electric(tm) 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 3 of the License, or * (at your option) any later version. * * Electric(tm) 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 Electric(tm); see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, Mass 02111-1307, USA. */ package com.sun.electric.tool.user.ui; import com.sun.electric.database.Snapshot; import com.sun.electric.database.change.DatabaseChangeEvent; import com.sun.electric.database.change.DatabaseChangeListener; import com.sun.electric.database.geometry.DBMath; import com.sun.electric.database.geometry.EPoint; import com.sun.electric.database.geometry.Orientation; import com.sun.electric.database.geometry.Poly; import com.sun.electric.database.hierarchy.Cell; import com.sun.electric.database.hierarchy.EDatabase; import com.sun.electric.database.hierarchy.Export; import com.sun.electric.database.hierarchy.Library; import com.sun.electric.database.hierarchy.Nodable; import com.sun.electric.database.hierarchy.View; import com.sun.electric.database.hierarchy.Cell.CellGroup; import com.sun.electric.database.id.CellId; import com.sun.electric.database.network.Netlist; import com.sun.electric.database.network.Network; import com.sun.electric.database.prototype.NodeProto; import com.sun.electric.database.text.Name; import com.sun.electric.database.text.TextUtils; import com.sun.electric.database.text.TextUtils.WhatToSearch; import com.sun.electric.database.topology.ArcInst; import com.sun.electric.database.topology.Geometric; import com.sun.electric.database.topology.NodeInst; import com.sun.electric.database.topology.PortInst; import com.sun.electric.database.topology.RTNode; import com.sun.electric.database.variable.CodeExpression; import com.sun.electric.database.variable.EditWindow_; import com.sun.electric.database.variable.ElectricObject; import com.sun.electric.database.variable.TextDescriptor; import com.sun.electric.database.variable.VarContext; import com.sun.electric.database.variable.Variable; import com.sun.electric.technology.Layer; import com.sun.electric.technology.PrimitiveNode; import com.sun.electric.technology.SizeOffset; import com.sun.electric.technology.Technology; import com.sun.electric.technology.technologies.Generic; import com.sun.electric.tool.Job; import com.sun.electric.tool.JobException; import com.sun.electric.tool.generator.layout.LayoutLib; import com.sun.electric.tool.io.output.PNG; import com.sun.electric.tool.user.ActivityLogger; import com.sun.electric.tool.user.Highlight2; import com.sun.electric.tool.user.HighlightListener; import com.sun.electric.tool.user.Highlighter; import com.sun.electric.tool.user.MessagesStream; import com.sun.electric.tool.user.User; import com.sun.electric.tool.user.UserInterfaceMain; import com.sun.electric.tool.user.dialogs.GetInfoText; import com.sun.electric.tool.user.dialogs.SelectObject; import com.sun.electric.tool.user.redisplay.AbstractDrawing; import com.sun.electric.tool.user.redisplay.PixelDrawing; import com.sun.electric.tool.user.redisplay.VectorCache; import com.sun.electric.tool.user.waveform.WaveformWindow; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Point; import java.awt.Polygon; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Toolkit; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.dnd.DnDConstants; import java.awt.dnd.DropTarget; import java.awt.dnd.DropTargetDragEvent; import java.awt.dnd.DropTargetDropEvent; import java.awt.dnd.DropTargetEvent; import java.awt.dnd.DropTargetListener; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.AdjustmentEvent; import java.awt.event.AdjustmentListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import java.awt.font.FontRenderContext; import java.awt.font.GlyphVector; import java.awt.font.LineMetrics; import java.awt.geom.AffineTransform; import java.awt.geom.Area; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.awt.print.PageFormat; import java.awt.print.PrinterJob; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.print.PrintService; import javax.print.attribute.standard.ColorSupported; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollBar; import javax.swing.SwingUtilities; import javax.swing.tree.MutableTreeNode; /** * This class defines an editing window for displaying circuitry. * It implements WindowContent, which means it can be in the main part of a window * (to the right of the explorer panel). */ public class EditWindow extends JPanel implements EditWindow_, WindowContent, MouseMotionListener, MouseListener, MouseWheelListener, KeyListener, HighlightListener, DatabaseChangeListener { /** the window scale */ private double scale; /** the requested window scale */ private double scaleRequested; /** the global text scale in this window */ private double globalTextScale; /** the window offset */ private double offx = 0, offy = 0; /** the requested window offset */ private double offxRequested, offyRequested; /** the size of the window (in pixels) */ private Dimension sz; /** the display cache for this window */ private AbstractDrawing drawing; /** the half-sizes of the window (in pixels) */ private int szHalfWidth, szHalfHeight; /** the cell that is in the window */ private Cell cell; /** the page number (for multipage schematics) */ private int pageNumber; /** list of edit-in-place text in this window */ private List<GetInfoText.EditInPlaceListener> inPlaceTextObjects = new ArrayList<GetInfoText.EditInPlaceListener>(); /** true if doing down-in-place display */ private boolean inPlaceDisplay; /** transform from screen to cell (down-in-place only) */ private AffineTransform intoCell = new AffineTransform(); /** transform from cell to screen (down-in-place only) */ private AffineTransform outofCell = new AffineTransform(); /** path to cell being edited (down-in-place only) */ private List<NodeInst> inPlaceDescent = new ArrayList<NodeInst>(); /** true if repaint was requested for this editwindow */volatile boolean repaintRequest; /** full instantiate bounds for next drawing */ private Rectangle2D fullInstantiateBounds; /** Cell's VarContext */ private VarContext cellVarContext; // /** Stack of selected PortInsts */ private PortInst[] selectedPorts; /** the window frame containing this editwindow */ private WindowFrame wf; /** the overall panel with disp area and sliders */ private JPanel overall; /** the bottom scrollbar on the edit window. */ private JScrollBar bottomScrollBar; /** the right scrollbar on the edit window. */ private JScrollBar rightScrollBar; /** true if showing grid in this window */ private boolean showGrid = false; /** X spacing of grid dots in this window */ private double gridXSpacing; /** Y spacing of grid dots in this window */ private double gridYSpacing; /** true if doing object-selection drag */ private boolean doingAreaDrag = false; /** starting screen point for drags in this window */ private Point startDrag = new Point(); /** ending screen point for drags in this window */ private Point endDrag = new Point(); /** true if drawing popup cloud */ private boolean showPopupCloud = false; // /** Strings to write to popup cloud */ private List<String> popupCloudText; // /** lower left corner of popup cloud */ private Point2D popupCloudPoint; /** Highlighter for this window */ private Highlighter highlighter; /** Mouse-over Highlighter for this window */ private Highlighter mouseOverHighlighter; /** Ruler Highlighter for this window */ private Highlighter rulerHighlighter; /** selectable text in this window */ private RTNode textInCell; /** navigate through saved views */ private EditWindowFocusBrowser viewBrowser; /** synchronization lock */ private static Object lock = new Object(); /** scheduled or running rendering job */ private static RenderJob runningNow = null; /** Logger of this package. */ private static Logger logger = Logger.getLogger("com.sun.electric.tool.user.ui"); /** Class name for logging. */ private static String CLASS_NAME = EditWindow.class.getName(); private static final int SCROLLBARRESOLUTION = 200; /** for drawing selection boxes */ private static final BasicStroke selectionLine = new BasicStroke( 1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[] {2}, 3); /** for outlining down-hierarchy in-place bounds */ private static final BasicStroke inPlaceMarker = new BasicStroke(2); private static EditWindowDropTarget editWindowDropTarget = new EditWindowDropTarget(); // ************************************* CONSTRUCTION ************************************* // constructor private EditWindow(Cell cell, WindowFrame wf, Dimension approxSZ) { this.cell = cell; this.pageNumber = 0; this.wf = wf; setDrawingAlgorithm(); this.gridXSpacing = User.getDefGridXSpacing(); this.gridYSpacing = User.getDefGridYSpacing(); inPlaceDisplay = false; viewBrowser = new EditWindowFocusBrowser(this); sz = approxSZ; if (sz == null) sz = new Dimension(500, 500); szHalfWidth = sz.width / 2; szHalfHeight = sz.height / 2; setSize(sz.width, sz.height); setPreferredSize(sz); scale = scaleRequested = 1; textInCell = null; globalTextScale = User.getGlobalTextScale(); // the total panel in the edit window overall = new JPanel(); overall.setLayout(new GridBagLayout()); // the horizontal scroll bar int thumbSize = SCROLLBARRESOLUTION / 20; bottomScrollBar = new JScrollBar(JScrollBar.HORIZONTAL, SCROLLBARRESOLUTION/2, thumbSize, 0, SCROLLBARRESOLUTION+thumbSize); bottomScrollBar.setBlockIncrement(SCROLLBARRESOLUTION / 5); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 1; gbc.fill = GridBagConstraints.HORIZONTAL; overall.add(bottomScrollBar, gbc); bottomScrollBar.addAdjustmentListener(new ScrollAdjustmentListener(this)); bottomScrollBar.setValue(bottomScrollBar.getMaximum()/2); // the vertical scroll bar in the edit window rightScrollBar = new JScrollBar(JScrollBar.VERTICAL, SCROLLBARRESOLUTION/2, thumbSize, 0, SCROLLBARRESOLUTION+thumbSize); rightScrollBar.setBlockIncrement(SCROLLBARRESOLUTION / 5); gbc = new GridBagConstraints(); gbc.gridx = 1; gbc.gridy = 0; gbc.fill = GridBagConstraints.VERTICAL; overall.add(rightScrollBar, gbc); rightScrollBar.addAdjustmentListener(new ScrollAdjustmentListener(this)); rightScrollBar.setValue(rightScrollBar.getMaximum()/2); // put this object's display up gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; gbc.fill = GridBagConstraints.BOTH; gbc.weightx = gbc.weighty = 1; overall.add(this, gbc); setOpaque(true); setLayout(null); // a drop target for the signal panel new DropTarget(this, DnDConstants.ACTION_LINK, editWindowDropTarget, true); //setAutoscrolls(true); installHighlighters(); if (wf != null) { // make a highlighter for this window UserInterfaceMain.addDatabaseChangeListener(this); Highlighter.addHighlightListener(this); setCell(cell, VarContext.globalContext, null); } } private void setDrawingAlgorithm() { drawing = AbstractDrawing.createDrawing(this, drawing, cell); LayerTab layerTab = getWindowFrame().getLayersTab(); if (layerTab != null) layerTab.setDisplayAlgorithm(drawing.hasOpacity()); } private void installHighlighters() { // see if this cell is displayed elsewhere highlighter = mouseOverHighlighter = rulerHighlighter = null; for(Iterator<WindowFrame> it = WindowFrame.getWindows(); it.hasNext(); ) { WindowFrame oWf = it.next(); if (oWf.getContent() instanceof EditWindow) { EditWindow oWnd = (EditWindow)oWf.getContent(); if (oWnd == this) continue; if (oWnd.getCell() == cell) { highlighter = oWnd.highlighter; mouseOverHighlighter = oWnd.mouseOverHighlighter; rulerHighlighter = oWnd.rulerHighlighter; break; } } } if (highlighter == null) { // not shown elsewhere: create highlighters highlighter = new Highlighter(Highlighter.SELECT_HIGHLIGHTER, wf); mouseOverHighlighter = new Highlighter(Highlighter.MOUSEOVER_HIGHLIGHTER, wf); rulerHighlighter = new Highlighter(Highlighter.RULER_HIGHLIGHTER, wf); } // add listeners --> BE SURE to remove listeners in finished() addKeyListener(this); addMouseListener(this); addMouseMotionListener(this); addMouseWheelListener(this); } private void uninstallHighlighters() { removeKeyListener(this); removeMouseListener(this); removeMouseMotionListener(this); removeMouseWheelListener(this); // see if the highlighters are used elsewhere boolean used = false; for(Iterator<WindowFrame> it = WindowFrame.getWindows(); it.hasNext(); ) { WindowFrame oWf = it.next(); if (oWf.getContent() instanceof EditWindow) { EditWindow oWnd = (EditWindow)oWf.getContent(); if (oWnd == this) continue; if (oWnd.getCell() == cell) { used = true; break; } } } if (!used) { highlighter.delete(); mouseOverHighlighter.delete(); rulerHighlighter.delete(); } } /** * Factory method to create a new EditWindow with a given cell, in a given WindowFrame. * @param cell the cell in this EditWindow. * @param wf the WindowFrame that this EditWindow lives in. * @param approxSZ the approximate size of this EditWindow (in pixels). * @return the new EditWindow. */ public static EditWindow CreateElectricDoc(Cell cell, WindowFrame wf, Dimension approxSZ) { EditWindow ui = new EditWindow(cell, wf, approxSZ); return ui; } // ************************************* EVENT LISTENERS ************************************* private int lastXPosition, lastYPosition; // the MouseListener events public void mousePressed(MouseEvent evt) { requestFocus(); MessagesStream.userCommandIssued(); lastXPosition = evt.getX(); lastYPosition = evt.getY(); WindowFrame.curMouseListener.mousePressed(evt); } public void mouseReleased(MouseEvent evt) { lastXPosition = evt.getX(); lastYPosition = evt.getY(); WindowFrame.curMouseListener.mouseReleased(evt); } public void mouseClicked(MouseEvent evt) { lastXPosition = evt.getX(); lastYPosition = evt.getY(); WindowFrame.curMouseListener.mouseClicked(evt); } public void mouseEntered(MouseEvent evt) { lastXPosition = evt.getX(); lastYPosition = evt.getY(); showCoordinates(evt); WindowFrame.curMouseListener.mouseEntered(evt); } public void mouseExited(MouseEvent evt) { lastXPosition = evt.getX(); lastYPosition = evt.getY(); WindowFrame.curMouseListener.mouseExited(evt); } // the MouseMotionListener events public void mouseMoved(MouseEvent evt) { lastXPosition = evt.getX(); lastYPosition = evt.getY(); showCoordinates(evt); WindowFrame.curMouseMotionListener.mouseMoved(evt); } public void mouseDragged(MouseEvent evt) { lastXPosition = evt.getX(); lastYPosition = evt.getY(); showCoordinates(evt); WindowFrame.curMouseMotionListener.mouseDragged(evt); } private void showCoordinates(MouseEvent evt) { EditWindow wnd = (EditWindow)evt.getSource(); if (wnd.getCell() == null) StatusBar.setCoordinates(null, wnd.wf); else { Point2D pt = wnd.screenToDatabase(evt.getX(), evt.getY()); EditWindow.gridAlign(pt); Technology tech = wnd.getCell().getTechnology(); if (User.isShowHierarchicalCursorCoordinates()) { // if the current VarContext is not the global one, user is "down hierarchy" String path = null; if (cellVarContext != VarContext.globalContext) { Point2D ptPath = new Point2D.Double(pt.getX(), pt.getY()); VarContext vc = cellVarContext; boolean validPath = true; boolean first = true; NodeInst ni = null; path = ""; while (vc != VarContext.globalContext) { Nodable no = vc.getNodable(); if (!(no instanceof NodeInst)) { validPath = false; break; } ni = (NodeInst)no; path = ni.getParent().getName() + "[" + ni.getName() + "]" + (first? "" : " / ") + path; if (first) first = false; AffineTransform trans = ni.translateOut(ni.rotateOut()); trans.transform(ptPath, ptPath); vc = vc.pop(); } if (validPath) { if (ni.getParent().isSchematic()) { path = "Location is " + ni.getParent() + " / " + path; } else { path = "Location in " + ni.getParent() + " / " + path + " is (" + TextUtils.formatDistance(ptPath.getX(), tech) + ", " + TextUtils.formatDistance(ptPath.getY(), tech) + ")"; } } else path = null; } StatusBar.setHierarchicalCoordinates(path, wnd.wf); } StatusBar.setCoordinates("(" + TextUtils.formatDistance(pt.getX(), tech) + ", " + TextUtils.formatDistance(pt.getY(), tech) + ")", wnd.wf); } } // the MouseWheelListener events public void mouseWheelMoved(MouseWheelEvent evt) { WindowFrame.curMouseWheelListener.mouseWheelMoved(evt); } // the KeyListener events public void keyPressed(KeyEvent evt) { MessagesStream.userCommandIssued(); WindowFrame.curKeyListener.keyPressed(evt); } public void keyReleased(KeyEvent evt) { WindowFrame.curKeyListener.keyReleased(evt); } public void keyTyped(KeyEvent evt) { WindowFrame.curKeyListener.keyTyped(evt); } public void highlightChanged(Highlighter which) { repaint(); } /** * Called when by a Highlighter when it loses focus. The argument * is the Highlighter that has gained focus (may be null). * @param highlighterGainedFocus the highlighter for the current window (may be null). */ public void highlighterLostFocus(Highlighter highlighterGainedFocus) {} public Point getLastMousePosition() { return new Point(lastXPosition, lastYPosition); } // ************************************* WHEN DROPPING A CELL NAME FROM THE EXPLORER TREE ************************************* /** * Method to figure out which cell in a cell group should be used when dragging the group * onto this EditWindow. * @param group the cell group dragged. * @return the Cell in the group to drag into this EditWindow. */ private Cell whichCellInGroup(CellGroup group) { if (cell == null) return null; for(Iterator<Cell> it = group.getCells(); it.hasNext(); ) { Cell c = it.next(); View cV = c.getView(); if (cV == View.DOC) continue; // skip document if (cV == View.ICON) { if (cell.getView() == View.SCHEMATIC || cell.getView() == View.ICON) return c; } else if (cV != View.SCHEMATIC) { if (cell.getView() != View.SCHEMATIC && cell.getView() != View.ICON) return c; } } return null; } /** * Method to set the highlight to show the outline of a node that will be placed in this EditWindow. * @param toDraw the object to draw (a NodeInst or a NodeProto). * @param oldx the X position (on the screen) of the outline. * @param oldy the Y position (on the screen) of the outline. */ public void showDraggedBox(Object toDraw, int oldx, int oldy) { // undraw it Highlighter highlighter = getHighlighter(); highlighter.clear(); // draw it Point2D drawnLoc = screenToDatabase(oldx, oldy); EditWindow.gridAlign(drawnLoc); NodeProto np = null; if (toDraw instanceof CellGroup) { // figure out which cell in the group should be dragged np = whichCellInGroup((CellGroup)toDraw); } if (toDraw instanceof NodeInst) { NodeInst ni = (NodeInst)toDraw; np = ni.getProto(); } if (toDraw instanceof NodeProto) { np = (NodeProto)toDraw; } int defAngle = 0; if (toDraw instanceof NodeInst) { NodeInst ni = (NodeInst)toDraw; defAngle = ni.getAngle(); } if (toDraw instanceof PrimitiveNode) { defAngle = User.getNewNodeRotation(); } if (np != null) { // zoom the window to fit the placed node (if appropriate) zoomWindowToFitCellInstance(np); Poly poly = null; Orientation orient = Orientation.fromJava(defAngle, defAngle >= 3600, false); if (np instanceof Cell) { Cell placeCell = (Cell)np; Rectangle2D cellBounds = placeCell.getBounds(); poly = new Poly(cellBounds); AffineTransform rotate = orient.pureRotate(); AffineTransform translate = new AffineTransform(); translate.setToTranslation(drawnLoc.getX(), drawnLoc.getY()); rotate.concatenate(translate); poly.transform(rotate); } else { SizeOffset so = np.getProtoSizeOffset(); double trueSizeX = np.getDefWidth() - so.getLowXOffset() - so.getHighXOffset(); double trueSizeY = np.getDefHeight() - so.getLowYOffset() - so.getHighYOffset(); double dX = (so.getHighXOffset() - so.getLowXOffset())/2; double dY = (so.getHighYOffset() - so.getLowYOffset())/2; poly = new Poly(drawnLoc.getX()-dX, drawnLoc.getY()-dY, trueSizeX, trueSizeY); AffineTransform trans = orient.rotateAbout(drawnLoc.getX(), drawnLoc.getY()); poly.transform(trans); } Point2D [] points = poly.getPoints(); for(int i=0; i<points.length; i++) { int last = i-1; if (i == 0) last = points.length - 1; highlighter.addLine(points[last], points[i], getCell()); } repaint(); } highlighter.finished(); } /** * Method to zoom this window to fit a placed node (if appropriate). * If the placed object is a cell instance that is larger than the window, * and the window is empty, zoom out to fit. * @param np the node being placed. */ public void zoomWindowToFitCellInstance(NodeProto np) { Cell parent = getCell(); if (parent == null) return; boolean empty = true; if (parent.getNumArcs() > 0) empty = false; if (parent.getNumNodes() > 1) empty = false; else { if (parent.getNumNodes() == 1) { NodeInst onlyNi = parent.getNode(0); if (onlyNi.getProto() != Generic.tech().cellCenterNode) empty = false; } } if (empty && np instanceof Cell) { // placing instance of cell into empty cell: see if scaling is necessary Rectangle2D cellBounds = ((Cell)np).getBounds(); Rectangle2D screenBounds = displayableBounds(); if (cellBounds.getWidth() > screenBounds.getWidth() || cellBounds.getHeight() > screenBounds.getHeight()) { double scaleX = cellBounds.getWidth() / (screenBounds.getWidth() * 0.9); double scaleY = cellBounds.getHeight() / (screenBounds.getHeight() * 0.9); double scale = Math.max(scaleX, scaleY); setScale(getScale() / scale); } } } /** * Class to define a custom data flavor that packages a NodeProto to create. */ public static class NodeProtoDataFlavor extends DataFlavor { private Cell cell; private Cell.CellGroup group; private ExplorerTree originalTree; NodeProtoDataFlavor(Cell cell, Cell.CellGroup group, ExplorerTree originalTree) { super(NodeProto.class, "electric/instance"); this.cell = cell; this.group = group; this.originalTree = originalTree; } public Object getFlavorObject() { if (cell != null) return cell; return group; } public ExplorerTree getOriginalTree() { return originalTree; } } /** * Class to define a custom transferable that packages a Cell or Group. */ public static class NodeProtoTransferable implements Transferable { private Cell cell; private Cell.CellGroup group; private NodeProtoDataFlavor df; public NodeProtoTransferable(Object obj, ExplorerTree tree) { if (obj instanceof Cell) { cell = (Cell)obj; group = cell.getCellGroup(); } else if (obj instanceof Cell.CellGroup) { group = (Cell.CellGroup)obj; } df = new NodeProtoDataFlavor(cell, group, tree); } public boolean isValid() { return group != null; } public DataFlavor[] getTransferDataFlavors() { DataFlavor [] it = new DataFlavor[1]; it[0] = df; return it; } public boolean isDataFlavorSupported(DataFlavor flavor) { if (flavor == df) return true; return false; } public Object getTransferData(DataFlavor flavor) { if (flavor != df) return null; if (cell != null) return cell; return group; } } /** * Class for catching drags into the edit window. * These drags come from the Explorer tree (when a cell name is dragged to place an instance). */ private static class EditWindowDropTarget implements DropTargetListener { public void dragEnter(DropTargetDragEvent e) { dragAction(e); } public void dragOver(DropTargetDragEvent e) { dragAction(e); } private Object getDraggedObject(DataFlavor [] flavors) { if (flavors.length > 0) { if (flavors[0] instanceof NodeProtoDataFlavor) { NodeProtoDataFlavor npdf = (NodeProtoDataFlavor)flavors[0]; Object obj = npdf.getFlavorObject(); return obj; } } return null; } private void dragAction(DropTargetDragEvent e) { Object obj = getDraggedObject(e.getCurrentDataFlavors()); if (obj != null) { e.acceptDrag(e.getDropAction()); // determine the window DropTarget dt = (DropTarget)e.getSource(); if (dt.getComponent() instanceof JPanel) { EditWindow wnd = (EditWindow)dt.getComponent(); wnd.showDraggedBox(obj, e.getLocation().x, e.getLocation().y); } return; } } public void dropActionChanged(DropTargetDragEvent e) { e.acceptDrag(e.getDropAction()); } public void dragExit(DropTargetEvent e) {} public void drop(DropTargetDropEvent dtde) { dtde.acceptDrop(DnDConstants.ACTION_LINK); Object obj = getDraggedObject(dtde.getCurrentDataFlavors()); if (obj == null) { dtde.dropComplete(false); return; } // determine the window DropTarget dt = (DropTarget)dtde.getSource(); if (!(dt.getComponent() instanceof JPanel)) { dtde.dropComplete(false); return; } EditWindow wnd = (EditWindow)dt.getComponent(); Point2D where = wnd.screenToDatabase(dtde.getLocation().x, dtde.getLocation().y); EditWindow.gridAlign(where); wnd.getHighlighter().clear(); NodeInst ni = null; NodeProto np = null; int defAngle = 0; if (obj instanceof CellGroup) { np = wnd.whichCellInGroup((CellGroup)obj); } else if (obj instanceof NodeProto) { np = (NodeProto)obj; if (np instanceof PrimitiveNode) defAngle = User.getNewNodeRotation(); } else if (obj instanceof NodeInst) { ni = (NodeInst)obj; np = ni.getProto(); } else if (obj instanceof Cell.CellGroup) { Cell.CellGroup gp = (Cell.CellGroup)obj; View view = wnd.getCell().getView(); if (view == View.SCHEMATIC) view = View.ICON; for (Iterator<Cell> itG = gp.getCells(); itG.hasNext();) { Cell c = itG.next(); if (c.getView() == view) { np = c; // found break; } } if (np == null) System.out.println("No " + view + " type found in the dragged group '" + gp.getName() + "'"); } else if (obj instanceof String) { String str = (String)obj; if (str.startsWith("LOADCELL ")) { String cellName = str.substring(9); np = Cell.findNodeProto(cellName); } } if (np != null) // doesn't make sense to call this job if nothing is selected new PaletteFrame.PlaceNewNode("Create Node", np, ni, defAngle, where, wnd.getCell(), null, false); } } // ************************************* INFORMATION ************************************* /** * Method to return the top-level JPanel for this EditWindow. * The actual EditWindow object is below the top level, surrounded by scroll bars. * @return the top-level JPanel for this EditWindow. */ public JPanel getPanel() { return overall; } /** * Method to return the location of this window on the user's screens. * @return the location of this window on the user's screens. */ public Point getScreenLocationOfCorner() { return overall.getLocationOnScreen(); } /** * Method to return the current EditWindow. * @return the current EditWindow (null if none). */ public static EditWindow getCurrent() { WindowFrame wf = WindowFrame.getCurrentWindowFrame(false); if (wf == null) return null; if (wf.getContent() instanceof EditWindow) return (EditWindow)wf.getContent(); return null; } /** * Method to return the current EditWindow. * @return the current EditWindow. * If there is none, an error message is displayed and it returns null. */ public static EditWindow needCurrent() { WindowFrame wf = WindowFrame.getCurrentWindowFrame(false); if (wf != null) { if (wf.getContent() instanceof EditWindow) return (EditWindow)wf.getContent(); } System.out.println("There is no current window for this operation"); return null; } // ************************************* EDITWINDOW METHODS ************************************* /** * Method to return the cell that is shown in this window. * @return the cell that is shown in this window. */ public Cell getCell() { return cell; } /** * Method to set the page number that is shown in this window. * Only applies to multi-page schematics. * @param pageNumber the page number that is shown in this window (0-based). */ public void setMultiPageNumber(int pageNumber) { if (this.pageNumber == pageNumber) return; this.pageNumber = pageNumber; setWindowTitle(); fillScreen(); } /** * Method to return the page number that is shown in this window. * Only applies to multi-page schematics. * @return the page number that is shown in this window (0-based). */ public int getMultiPageNumber() { return pageNumber; } /** * Method to tell whether this EditWindow is displaying a cell "in-place". * In-place display implies that the user has descended into a lower-level * cell while requesting that the upper-level remain displayed. * @return true if this EditWindow is displaying a cell "in-place". */ public boolean isInPlaceEdit() { return inPlaceDisplay; } /** * Method to return the top-level cell for "in-place" display. * In-place display implies that the user has descended into a lower-level * cell while requesting that the upper-level remain displayed. * The top-level cell is the original cell that is remaining displayed. * @return the top-level cell for "in-place" display. */ public Cell getInPlaceEditTopCell() { return inPlaceDisplay ? inPlaceDescent.get(0).getParent() : cell; } /** * Method to return a List of NodeInsts to the cell being in-place edited. * In-place display implies that the user has descended into a lower-level * cell while requesting that the upper-level remain displayed. * @return a List of NodeInsts to the cell being in-place edited. */ public List<NodeInst> getInPlaceEditNodePath() { return inPlaceDescent; } /** * Method to set the List of NodeInsts to the cell being in-place edited. * In-place display implies that the user has descended into a lower-level * cell while requesting that the upper-level remain displayed. * @param da DisplayAttributes of EditWindow. */ private void setInPlaceEditNodePath(WindowFrame.DisplayAttributes da) { inPlaceDescent = da.inPlaceDescent; intoCell = da.getIntoCellTransform(); outofCell = da.getOutofCellTransform(); inPlaceDisplay = !inPlaceDescent.isEmpty(); } /** * Method to return the transformation matrix from the displayed top-level cell to the current cell. * In-place display implies that the user has descended into a lower-level * cell while requesting that the upper-level remain displayed. * @return the transformation matrix from the displayed top-level cell to the current cell. */ public AffineTransform getInPlaceTransformIn() { return intoCell; } /** * Method to return the transformation matrix from the current cell to the displayed top-level cell. * In-place display implies that the user has descended into a lower-level * cell while requesting that the upper-level remain displayed. * @return the transformation matrix from the current cell to the displayed top-level cell. */ public AffineTransform getInPlaceTransformOut() { return outofCell; } /** * Get the highlighter for this WindowContent. * @return the highlighter. */ public Highlighter getHighlighter() { return highlighter; } /** * Get the mouse over highlighter for this EditWindow. * @return the mouse over highlighter. */ public Highlighter getMouseOverHighlighter() { return mouseOverHighlighter; } /** * Get the ruler highlighter for this EditWindow (for measurement). * @return the ruler highlighter. */ public Highlighter getRulerHighlighter() { return rulerHighlighter; } /** * Get the RTree with all text in this Cell. * @return the RTree with all text in this Cell. */ public RTNode getTextInCell() { return textInCell; } /** * Set the RTree with all text in this Cell. * @param tic the RTree with all text in this Cell. */ public void setTextInCell(RTNode tic) { textInCell = tic; } /** * Method to return the WindowFrame in which this EditWindow resides. * @return the WindowFrame in which this EditWindow resides. */ public WindowFrame getWindowFrame() { return wf; } /** * Method to set the cell that is shown in the window to "cell". */ public void setCell(Cell cell, VarContext context, WindowFrame.DisplayAttributes displayAttributes) { // by default record history and fillscreen // However, when navigating through history, don't want to record new history objects. if (context == null) context = VarContext.globalContext; boolean fillTheScreen = false; if (displayAttributes == null) { displayAttributes = new WindowFrame.DisplayAttributes(getScale(), getOffset().getX(), getOffset().getY(), new ArrayList<NodeInst>()); fillTheScreen = true; } // recalculate the screen size sz = getSize(); szHalfWidth = sz.width / 2; szHalfHeight = sz.height / 2; showCell(cell, context, fillTheScreen, displayAttributes); } /** * Method to show a cell with ports, display factors, etc. */ private void showCell(Cell cell, VarContext context, boolean fillTheScreen, WindowFrame.DisplayAttributes displayAttributes) { // record current history before switching to new cell wf.saveCurrentCellHistoryState(); // remove highlighters from the window uninstallHighlighters(); // set new values this.cell = cell; textInCell = null; setInPlaceEditNodePath(displayAttributes); this.pageNumber = 0; cellVarContext = context; if (cell != null) { Library lib = cell.getLibrary(); Job.getUserInterface().setCurrentCell(lib, cell); } setDrawingAlgorithm(); // add new highlighters from the window installHighlighters(); viewBrowser.clear(); setWindowTitle(); if (wf != null) { if (cell != null) { if (wf == WindowFrame.getCurrentWindowFrame(false)) { // if auto-switching technology, do it WindowFrame.autoTechnologySwitch(cell, wf); } } } if (fillTheScreen) fillScreen(); else { setScale(displayAttributes.scale); setOffset(new Point2D.Double(displayAttributes.offX, displayAttributes.offY)); } if (cell != null && User.isCheckCellDates()) cell.checkCellDates(); // clear list of cross-probed levels for this EditWindow clearCrossProbeLevels(); // update cell information in the status bar StatusBar.updateStatusBar(); } /** * Method to set the window title. */ public void setWindowTitle() { if (wf == null) return; wf.setTitle(wf.composeTitle(cell, "", pageNumber)); } /** * Method to find an EditWindow that is displaying a given cell. * @param cell the Cell to find. * @return the EditWindow showing that cell, or null if none found. */ public static EditWindow findWindow(Cell cell) { for(Iterator<WindowFrame> it = WindowFrame.getWindows(); it.hasNext(); ) { WindowFrame wf = it.next(); WindowContent content = wf.getContent(); if (!(content instanceof EditWindow)) continue; if (content.getCell() == cell) return (EditWindow)content; } return null; } /** * Method to bring to the front a WindowFrame associated to a given Cell. * If no WindowFrame is found, a new WindowFrame will be created and displayed * @param c the Cell in the window to raise. * @param varC the Context of that window. * @return the EditWindow of the cell that was found or created. */ public static EditWindow showEditWindowForCell(Cell c, VarContext varC) { for(Iterator<WindowFrame> it2 = WindowFrame.getWindows(); it2.hasNext(); ) { WindowFrame wf = it2.next(); WindowContent content = wf.getContent(); if (c != content.getCell()) continue; if (!(content instanceof EditWindow)) continue; EditWindow wnd = (EditWindow)content; if (varC != null) // it has to be an EditWindow class { // VarContexts must match if (!varC.equals(wnd.getVarContext())) continue; } WindowFrame.showFrame(wf); return wnd; } // If no window is found, then create one WindowFrame wf = WindowFrame.createEditWindow(c); EditWindow wnd = (EditWindow)wf.getContent(); wnd.setCell(c, varC, null); return wnd; } public List<MutableTreeNode> loadExplorerTrees() { return wf.loadDefaultExplorerTree(); } /** * Method to get rid of this EditWindow. Called by WindowFrame when * that windowFrame gets closed. */ public void finished() { //wf = null; // clear reference //offscreen = null; // need to clear this ref, because it points to this // remove myself from listener list uninstallHighlighters(); UserInterfaceMain.removeDatabaseChangeListener(this); Highlighter.removeHighlightListener(this); } // ************************************* SCROLLING ************************************* /** * Method to return the scroll bar resolution. * This is the extent of the JScrollBar. * @return the scroll bar resolution. */ public static int getScrollBarResolution() { return SCROLLBARRESOLUTION; } /** * This class handles changes to the edit window scroll bars. */ private static class ScrollAdjustmentListener implements AdjustmentListener { /** A weak reference to the WindowFrame */ EditWindow wnd; ScrollAdjustmentListener(EditWindow wnd) { super(); this.wnd = wnd; // this.wf = new WeakReference(wf); } public void adjustmentValueChanged(AdjustmentEvent e) { if (e.getSource() == wnd.getBottomScrollBar() && wnd.getCell() != null) wnd.bottomScrollChanged(e.getValue()); if (e.getSource() == wnd.getRightScrollBar() && wnd.getCell() != null) wnd.rightScrollChanged(e.getValue()); } } /** * Method to return the horizontal scroll bar at the bottom of the edit window. * @return the horizontal scroll bar at the bottom of the edit window. */ public JScrollBar getBottomScrollBar() { return bottomScrollBar; } /** * Method to return the vertical scroll bar at the right side of the edit window. * @return the vertical scroll bar at the right side of the edit window. */ public JScrollBar getRightScrollBar() { return rightScrollBar; } // ************************************* REPAINT ************************************* /** * Method to repaint this EditWindow. * Composites the image (taken from the PixelDrawing object) * with the grid, highlight, and any dragging rectangle. */ public void paintComponent(Graphics graphics) { // to enable keys to be received if (wf == null) return; // if (wf == WindowFrame.getCurrentWindowFrame()) // requestFocusInWindow(); Graphics2D g = (Graphics2D)graphics; if (cell == null) { g.setColor(new Color(User.getColor(User.ColorPrefType.BACKGROUND))); g.fillRect(0, 0, getWidth(), getHeight()); String msg = "No cell in this window"; Font f = new Font(User.getDefaultFont(), Font.BOLD, 18); g.setFont(f); g.setColor(new Color(User.getColor(User.ColorPrefType.TEXT))); g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g.drawString(msg, (getWidth() - g.getFontMetrics(f).stringWidth(msg))/2, getHeight()/2); return; } logger.entering(CLASS_NAME, "paintComponent", this); if (!drawing.paintComponent(g, getSize())) { fullRepaint(); g.setColor(new Color(User.getColor(User.ColorPrefType.BACKGROUND))); g.fillRect(0, 0, getWidth(), getHeight()); logger.exiting(CLASS_NAME, "paintComponent", "resize and repaint"); return; } logger.logp(Level.FINER, CLASS_NAME, "paintComponent", "offscreen is drawn"); sz = getSize(); szHalfWidth = sz.width / 2; szHalfHeight = sz.height / 2; if (scale != drawing.da.scale || offx != drawing.da.offX || offy != drawing.da.offY) textInCell = null; scale = drawing.da.scale; offx = drawing.da.offX; offy = drawing.da.offY; setScrollPosition(); // redraw scroll bars // set the default text size (for highlighting, etc) Font f = new Font(User.getDefaultFont(), Font.PLAIN, (int)(10*globalTextScale)); g.setFont(f); // add cross-probed level display showCrossProbeLevels(g); if (Job.getDebug()) { // add in highlighting if (Job.acquireExamineLock(false)) { try { // add in the frame if present drawCellFrame(g); //long start = System.currentTimeMillis(); rulerHighlighter.showHighlights(this, g); mouseOverHighlighter.showHighlights(this, g); highlighter.showHighlights(this, g); //long end = System.currentTimeMillis(); //System.out.println("drawing highlights took "+TextUtils.getElapsedTime(end-start)); Job.releaseExamineLock(); } catch (Error e) { Job.releaseExamineLock(); throw e; } } } else { // unsafe try { // add in the frame if present drawCellFrame(g); //long start = System.currentTimeMillis(); rulerHighlighter.showHighlights(this, g); mouseOverHighlighter.showHighlights(this, g); highlighter.showHighlights(this, g); //long end = System.currentTimeMillis(); //System.out.println("drawing highlights took "+TextUtils.getElapsedTime(end-start)); } catch (Exception e) { } } // add in drag area if (doingAreaDrag) showDragBox(g); // add in popup cloud if (showPopupCloud) drawPopupCloud(g); // add in shadow if doing in-place editing if (inPlaceDisplay) { Rectangle2D bounds = cell.getBounds(); Point i1 = databaseToScreen(bounds.getMinX(), bounds.getMinY()); Point i2 = databaseToScreen(bounds.getMinX(), bounds.getMaxY()); Point i3 = databaseToScreen(bounds.getMaxX(), bounds.getMaxY()); Point i4 = databaseToScreen(bounds.getMaxX(), bounds.getMinY()); // shade everything else except for the cell being edited if (User.isDimUpperLevelWhenDownInPlace()) { Polygon innerPoly = new Polygon(); innerPoly.addPoint(i1.x, i1.y); innerPoly.addPoint(i2.x, i2.y); innerPoly.addPoint(i3.x, i3.y); innerPoly.addPoint(i4.x, i4.y); Area outerArea = new Area(new Rectangle(0, 0, sz.width, sz.height)); Area innerArea = new Area(innerPoly); outerArea.subtract(innerArea); g.setColor(new Color(128, 128, 128, 128)); g.fill(outerArea); } // draw a red box around the cell being edited g.setStroke(inPlaceMarker); g.setColor(new Color(User.getColor(User.ColorPrefType.DOWNINPLACEBORDER))); int lX = Math.min(Math.min(i1.x, i2.x), Math.min(i3.x, i4.x)); int hX = Math.max(Math.max(i1.x, i2.x), Math.max(i3.x, i4.x)); int lY = Math.min(Math.min(i1.y, i2.y), Math.min(i3.y, i4.y)); int hY = Math.max(Math.max(i1.y, i2.y), Math.max(i3.y, i4.y)); g.drawLine(lX-1, lY-1, lX-1, hY+1); g.drawLine(lX-1, hY+1, hX+1, hY+1); g.drawLine(hX+1, hY+1, hX+1, lY-1); g.drawLine(hX+1, lY-1, lX-1, lY-1); } logger.logp(Level.FINER, CLASS_NAME, "paintComponent", "overlays are drawn"); // see if anything else is queued if (scale != scaleRequested || offx != offxRequested || offy != offyRequested || !getSize().equals(sz)) { textInCell = null; fullRepaint(); } logger.exiting(CLASS_NAME, "paintComponent"); } /** * Method to store a new "in-place" text editing object on this EditWindow. * @param tl the Listener that is now sitting on top of this EditWindow. */ public void addInPlaceTextObject(GetInfoText.EditInPlaceListener tl) { inPlaceTextObjects.add(tl); add(tl.getTextComponent()); } /** * Method to return the current "in-place" text editing object on this EditWindow. * @return the current "in-place" text editing object on this EditWindow. */ public GetInfoText.EditInPlaceListener getInPlaceTextObject() { if (inPlaceTextObjects.size() == 0) return null; return inPlaceTextObjects.get(inPlaceTextObjects.size()-1); } /** * Method to remove a "in-place" text editing object from this EditWindow. * @param tl the Listener that is no longer sitting on top of this EditWindow. */ public void removeInPlaceTextObject(GetInfoText.EditInPlaceListener tl) { inPlaceTextObjects.remove(tl); remove(tl.getTextComponent()); } /** * Method to remove all in-place text objects in this window. * Called when the window pans or zooms and the text objects are no longer in the proper place. */ public void removeAllInPlaceTextObjects() { List<GetInfoText.EditInPlaceListener> allTextObjects = new ArrayList<GetInfoText.EditInPlaceListener>(); for(GetInfoText.EditInPlaceListener eip : inPlaceTextObjects) allTextObjects.add(eip); for(GetInfoText.EditInPlaceListener tl : allTextObjects) { tl.closeEditInPlace(); } } /** * Method requests that every EditWindow be redrawn, including a change of display algorithm. */ public static void displayAlgorithmChanged() { for(Iterator<WindowFrame> it = WindowFrame.getWindows(); it.hasNext(); ) { WindowFrame wf = it.next(); WindowContent content = wf.getContent(); if (!(content instanceof EditWindow)) continue; EditWindow wnd = (EditWindow)content; wnd.setDrawingAlgorithm(); wnd.fullRepaint(); } } /** * Method requests that every EditWindow be redrawn, including a rerendering of its contents. */ public static void repaintAllContents() { for(Iterator<WindowFrame> it = WindowFrame.getWindows(); it.hasNext(); ) { WindowFrame wf = it.next(); WindowContent content = wf.getContent(); if (!(content instanceof EditWindow)) continue; EditWindow wnd = (EditWindow)content; wnd.fullRepaint(); } } /** * Method requests that every EditWindow be redrawn, without rerendering the offscreen contents. */ public static void repaintAll() { for(Iterator<WindowFrame> it = WindowFrame.getWindows(); it.hasNext(); ) { WindowFrame wf = it.next(); WindowContent content = wf.getContent(); if (!(content instanceof EditWindow)) continue; EditWindow wnd = (EditWindow)content; wnd.repaint(); } } /** * Method requests that this EditWindow be redrawn, including a rerendering of the contents. */ public void fullRepaint() { repaintContents(null, false); } /** * Method requests that this EditWindow be redrawn, including a rerendering of the contents. * @param bounds the area to redraw (null to draw everything). * @param fullInstantiate true to display to the bottom of the hierarchy (for peeking). */ public void repaintContents(Rectangle2D bounds, boolean fullInstantiate) { // start rendering thread if (wf == null) return; if (cell == null) { repaint(); return; } if (runningNow != null && repaintRequest && !fullInstantiate) return; logger.entering(CLASS_NAME, "repaintContents", bounds); // do the redraw in a separate thread if (fullInstantiate) { fullInstantiateBounds = bounds.getBounds2D(); DBMath.transformRect(fullInstantiateBounds, outofCell); } invokeRenderJob(this); logger.exiting(CLASS_NAME, "repaintContents"); } public static void invokeRenderJob() { invokeRenderJob(null); } private static void invokeRenderJob(EditWindow wnd) { logger.entering(CLASS_NAME, "invokeRenderJob", wnd); synchronized(lock) { if (wnd != null) { wnd.drawing.abortRendering(); wnd.repaintRequest = true; } if (runningNow != null) { runningNow.hasTasks = true; logger.exiting(CLASS_NAME, "invokeRenderJob running now"); return; } runningNow = new RenderJob(); } runningNow.startJob(); logger.exiting(CLASS_NAME, "invokeRenderJob starting job"); } private final static String RENDER_JOB_CLASS_NAME = CLASS_NAME + ".RenderJob"; /** * This class queues requests to rerender a window. */ private static class RenderJob extends Job { private static Snapshot oldSnapshot = EDatabase.clientDatabase().getInitialSnapshot(); volatile boolean hasTasks; protected RenderJob() { super("Display", User.getUserTool(), Job.Type.EXAMINE, null, null, Job.Priority.USER); } public boolean doIt() throws JobException { logger.entering(RENDER_JOB_CLASS_NAME, "doIt"); try { for (;;) { hasTasks = false; Snapshot snapshot = EDatabase.clientDatabase().backup(); if (snapshot != oldSnapshot) { endBatch(oldSnapshot, snapshot); oldSnapshot = snapshot; } EditWindow wnd = null; for (Iterator<WindowFrame> it = WindowFrame.getWindows(); it.hasNext();) { WindowFrame wf = it.next(); WindowContent wc = wf.getContent(); if (wc instanceof EditWindow && ((EditWindow) wc).repaintRequest) { wnd = (EditWindow) wc; break; } } if (wnd == null) { break; } wnd.repaintRequest = false; render(wnd); } } finally { RenderJob j = null; synchronized (lock) { if (hasTasks) { runningNow = j = new RenderJob(); } else { runningNow = null; } } if (j != null) { assert j == runningNow; j.startJob(); } } logger.exiting(RENDER_JOB_CLASS_NAME, "doIt"); return true; } private void render(EditWindow wnd) throws JobException { logger.entering(RENDER_JOB_CLASS_NAME, "render"); // do the hard work of re-rendering the image Rectangle2D bounds = null; boolean fullInstantiate = false; if (wnd.fullInstantiateBounds != null) { fullInstantiate = true; bounds = wnd.fullInstantiateBounds; wnd.fullInstantiateBounds = null; } else if (bounds == null) { // see if a real bounds is defined in the cell bounds = User.getChangedInWindow(wnd); } if (bounds != null) { User.clearChangedInWindow(wnd); } WindowFrame.DisplayAttributes da = new WindowFrame.DisplayAttributes(wnd.scaleRequested, wnd.offxRequested, wnd.offyRequested, wnd.inPlaceDescent); wnd.drawing.render(wnd.getSize(), da, fullInstantiate, bounds); wnd.repaint(); logger.exiting(RENDER_JOB_CLASS_NAME, "render"); } } /** * Method to automatically set the opacity of each layer in a Technology. * At the current time, this method is not used. * @param tech the Technology to set. */ public static void setDefaultOpacity(Technology tech) { for(Iterator<Layer> it = tech.getLayers(); it.hasNext(); ) { Layer layer = it.next(); Layer.Function fun = layer.getFunction(); int extra = layer.getFunctionExtras(); double opacity = 0.4; if (fun.isMetal()) { opacity = 0.75 - fun.getLevel() * 0.05; } else if (fun.isContact()) { if ((extra&Layer.Function.CONMETAL) != 0) opacity = 0.7; else opacity = 1; } else if (fun == Layer.Function.OVERGLASS) { opacity = 0.2; } else if (fun == Layer.Function.POLY1 || fun == Layer.Function.POLY2 || fun == Layer.Function.POLY3 || fun == Layer.Function.GATE || fun == Layer.Function.DIFF || fun == Layer.Function.DIFFP || fun == Layer.Function.DIFFN || fun == Layer.Function.WELL || fun == Layer.Function.WELLP || fun == Layer.Function.WELLN || fun == Layer.Function.IMPLANT || fun == Layer.Function.IMPLANTN || fun == Layer.Function.IMPLANTP) { // lowest level layers should all be opaque opacity = 1.0; } else if (fun == Layer.Function.ART) { if (layer.getName().equals("Glyph")) opacity = 0; // essential bounds } if (layer.getGraphics().getOpacity() != opacity) layer.getGraphics().setOpacity(opacity); } } /** * Returns alpha blending order for this EditWindow. * Alpha blending order specifies pixel color by such a way: * Color col = backgroudColor; * for (LayerColor layerColor: blendingOrder) { * if (This pixel covers a piece of layer layerColor.layer) { * alpha = layerColor.color.getAlpha(); * col = layerColor.color.getRGB()*alpha + col*(1 - alpha) * } * } * return col; * @param layersAvailable layers available in this EditWindow * @return alpha blending order. */ public List<AbstractDrawing.LayerColor> getBlendingOrder(Set<Layer> layersAvailable, boolean patternedDisplay, boolean alphaBlendingOvercolor) { List<AbstractDrawing.LayerColor> layerColors = new ArrayList<AbstractDrawing.LayerColor>(); List<Layer> sortedLayers = new ArrayList<Layer>(layersAvailable); Collections.sort(sortedLayers, Technology.LAYERS_BY_HEIGHT_LIFT_CONTACTS); float[] backgroundComps = (new Color(User.getColor(User.ColorPrefType.BACKGROUND))).getRGBColorComponents(null); float bRed = backgroundComps[0]; float bGreen = backgroundComps[1]; float bBlue = backgroundComps[2]; for(Layer layer : sortedLayers) { if (!layer.isVisible()) continue; if (layer == Generic.tech().glyphLay && !patternedDisplay) continue; Color color = new Color(layer.getGraphics().getRGB()); float[] compArray = color.getRGBComponents(null); float red = compArray[0]; float green = compArray[1]; float blue = compArray[2]; float opacity = (float)layer.getGraphics().getOpacity(); if (opacity <= 0) continue; float inverseAlpha = 1 - opacity; if (alphaBlendingOvercolor) { red -= bRed*inverseAlpha; green -= bGreen*inverseAlpha; blue -= bBlue*inverseAlpha; } else { red *= opacity; green *= opacity; blue *= opacity; } layerColors.add(new AbstractDrawing.LayerColor(layer, red, green, blue, inverseAlpha)); } final LayerTab layerTab = getWindowFrame().getLayersTab(); final boolean showOpacity = !User.isLegacyComposite(); if (layerTab != null) SwingUtilities.invokeLater(new Runnable() { public void run() { layerTab.setDisplayAlgorithm(showOpacity); }}); return layerColors; } public void testJogl() { drawing.testJogl(); } void opacityChanged() { drawing.opacityChanged(); } // ************************************* SIMULATION CROSSPROBE LEVEL DISPLAY ************************************* private static class CrossProbe { boolean isLine; Point2D start, end; Rectangle2D box; Color color; }; private List<CrossProbe> crossProbeObjects = new ArrayList<CrossProbe>(); /** * Method to clear the list of cross-probed levels in this EditWindow. * Cross-probed levels are displays of the current simulation value * at a point in the display, and come from the Waveform Window. */ public void clearCrossProbeLevels() { crossProbeObjects.clear(); } /** * Method to tell whether there is any cross-probed data in this EditWindow. * Cross-probed levels are displays of the current simulation value * at a point in the display, and come from the Waveform Window. * @return true if there are any cross-probed data displays in this EditWindow. */ public boolean hasCrossProbeData() { if (crossProbeObjects.size() > 0) return true; return false; } /** * Method to add a line to the list of cross-probed levels in this EditWindow. * Cross-probed levels are displays of the current simulation value * at a point in the display, and come from the Waveform Window. * @param start the starting point of the line. * @param end the ending point of the line. * @param color the color of the line. */ public void addCrossProbeLine(Point2D start, Point2D end, Color color) { CrossProbe cp = new CrossProbe(); cp.isLine = true; cp.start = start; cp.end = end; cp.color = color; crossProbeObjects.add(cp); } /** * Method to add a box to the list of cross-probed levels in this EditWindow. * Cross-probed levels are displays of the current simulation value * at a point in the display, and come from the Waveform Window. * @param box the bounds of the box. * @param color the color of the box. */ public void addCrossProbeBox(Rectangle2D box, Color color) { CrossProbe cp = new CrossProbe(); cp.isLine = false; cp.box = box; cp.color = color; crossProbeObjects.add(cp); } private void showCrossProbeLevels(Graphics g) { for(CrossProbe cp : crossProbeObjects) { g.setColor(cp.color); if (cp.isLine) { // draw a line Point pS = databaseToScreen(cp.start); Point pE = databaseToScreen(cp.end); g.drawLine(pS.x, pS.y, pE.x, pE.y); } else { // draw a box Point pS = databaseToScreen(cp.box.getMinX(), cp.box.getMinY()); Point pE = databaseToScreen(cp.box.getMaxX(), cp.box.getMaxY()); int lX = Math.min(pS.x, pE.x); int lY = Math.min(pS.y, pE.y); int wid = Math.abs(pS.x - pE.x); int hei = Math.abs(pS.y - pE.y); g.fillRect(lX, lY, wid, hei); } } } // ************************************* DRAG BOX ************************************* public boolean isDoingAreaDrag() { return doingAreaDrag; } public void setDoingAreaDrag() { doingAreaDrag = true; } public void clearDoingAreaDrag() { doingAreaDrag = false; } public Point getStartDrag() { return startDrag; } public void setStartDrag(int x, int y) { startDrag.setLocation(x, y); } public Point getEndDrag() { return endDrag; } public void setEndDrag(int x, int y) { endDrag.setLocation(x, y); } private void showDragBox(Graphics g) { int lX = (int)Math.min(startDrag.getX(), endDrag.getX()); int hX = (int)Math.max(startDrag.getX(), endDrag.getX()); int lY = (int)Math.min(startDrag.getY(), endDrag.getY()); int hY = (int)Math.max(startDrag.getY(), endDrag.getY()); Graphics2D g2 = (Graphics2D)g; g2.setStroke(selectionLine); g.setColor(new Color(User.getColor(User.ColorPrefType.HIGHLIGHT))); g.drawLine(lX, lY, lX, hY); g.drawLine(lX, hY, hX, hY); g.drawLine(hX, hY, hX, lY); g.drawLine(hX, lY, lX, lY); } // ************************************* CELL FRAME ************************************* /** * Method to render the cell frame directly to the Graphics. */ private void drawCellFrame(Graphics g) { DisplayedFrame df = new DisplayedFrame(cell, g, this); df.renderFrame(); } /** * Class for rendering a cell frame. * Extends Cell.FrameDescription and provides hooks for drawing to a Graphics. */ private static class DisplayedFrame extends Cell.FrameDescription { private Graphics g; private EditWindow wnd; private Color lineColor, textColor; /** * Constructor for cell frame rendering. * @param cell the Cell that is having a frame drawn. * @param g the Graphics to which to draw the frame. * @param wnd the EditWindow in which this is being drawn. */ public DisplayedFrame(Cell cell, Graphics g, EditWindow wnd) { super(cell, wnd.pageNumber); this.g = g; this.wnd = wnd; lineColor = new Color(User.getColor(User.ColorPrefType.INSTANCE)); textColor = new Color(User.getColor(User.ColorPrefType.TEXT)); } /** * Method to draw a line in a frame. * @param from the starting point of the line (in database units). * @param to the ending point of the line (in database units). */ public void showFrameLine(Point2D from, Point2D to) { g.setColor(lineColor); Point f = wnd.databaseToScreen(from); Point t = wnd.databaseToScreen(to); g.drawLine(f.x, f.y, t.x, t.y); } /** * Method to draw text in a frame. * @param ctr the anchor point of the text. * @param size the size of the text (in database units). * @param maxWid the maximum width of the text (ignored if zero). * @param maxHei the maximum height of the text (ignored if zero). * @param string the text to be displayed. */ public void showFrameText(Point2D ctr, double size, double maxWid, double maxHei, String string) { // convert text size to screen points Point2D sizeVector = wnd.deltaDatabaseToScreen(size, size); int initialHeight = (int)Math.abs(sizeVector.getY()); // get the font Font font = new Font(User.getDefaultFont(), Font.PLAIN, initialHeight); g.setFont(font); g.setColor(textColor); FontRenderContext frc = new FontRenderContext(null, true, true); // convert the message to glyphs GlyphVector gv = font.createGlyphVector(frc, string); LineMetrics lm = font.getLineMetrics(string, frc); Rectangle rect = gv.getOutline(0, lm.getAscent()-lm.getLeading()).getBounds(); double width = rect.width; double height = lm.getHeight(); Point2D databaseSize = wnd.deltaScreenToDatabase((int)width, (int)height); double dbWidth = Math.abs(databaseSize.getX()); double dbHeight = Math.abs(databaseSize.getY()); if (maxWid > 0 && maxHei > 0 && (dbWidth > maxWid || dbHeight > maxHei)) { double scale = Math.min(maxWid / dbWidth, maxHei / dbHeight); font = new Font(User.getDefaultFont(), Font.PLAIN, (int)(initialHeight*scale)); if (font != null) { gv = font.createGlyphVector(frc, string); lm = font.getLineMetrics(string, frc); rect = gv.getOutline(0, lm.getAscent()-lm.getLeading()).getBounds(); width = rect.width; height = lm.getHeight(); } } // render the text Graphics2D g2 = (Graphics2D)g; Point p = wnd.databaseToScreen(ctr); g2.drawGlyphVector(gv, (float)(p.x - width/2), (float)(p.y + height/2 - lm.getDescent())); } } // ************************************* GRID ************************************* /** * Method to set the display of a grid in this window. * @param showGrid true to show the grid. */ public void setGrid(boolean showGrid) { this.showGrid = showGrid; fullRepaint(); } /** * Method to return the state of grid display in this window. * @return true if the grid is displayed in this window. */ public boolean isGrid() { return showGrid; } /** * Method to return the distance between grid dots in the X direction. * @return the distance between grid dots in the X direction. */ public double getGridXSpacing() { return gridXSpacing; } /** * Method to set the distance between grid dots in the X direction. * @param spacing the distance between grid dots in the X direction. */ public void setGridXSpacing(double spacing) { gridXSpacing = spacing; } /** * Method to return the distance between grid dots in the Y direction. * @return the distance between grid dots in the Y direction. */ public double getGridYSpacing() { return gridYSpacing; } /** * Method to set the distance between grid dots in the Y direction. * @param spacing the distance between grid dots in the Y direction. */ public void setGridYSpacing(double spacing) { gridYSpacing = spacing; } /** * Method to return a rectangle in database coordinates that covers the viewable extent of this window. * @return a rectangle that describes the viewable extent of this window (database coordinates). */ public Rectangle2D displayableBounds() { Point2D low = screenToDatabase(0, 0); Point2D high = screenToDatabase(sz.width-1, sz.height-1); double lowX = Math.min(low.getX(), high.getX()); double lowY = Math.min(low.getY(), high.getY()); double sizeX = Math.abs(high.getX()-low.getX()); double sizeY = Math.abs(high.getY()-low.getY()); Rectangle2D bounds = new Rectangle2D.Double(lowX, lowY, sizeX, sizeY); return bounds; } // *************************** SEARCHING FOR TEXT *************************** /** Information about String search */ private StringSearch textSearch = new StringSearch(); private static class StringSearch implements Serializable { /** list of all found strings in the cell */ private List<StringsInCell> foundInCell; /** the currently reported string index */ private int currentFindPosition; private static Pattern getPattern(String search, boolean caseSensitive) { int flags = caseSensitive ? 0 : Pattern.CASE_INSENSITIVE+Pattern.UNICODE_CASE; Pattern p = null; try { p = Pattern.compile(search, flags); } catch (Exception e) { System.out.println("Error in regular expression '" + search + "'"); System.out.println(e.getMessage()); } return p; } private void searchTextNodes(Cell cell, String search, boolean caseSensitive, boolean regExp, Set whatToSearch, CodeExpression.Code codeRestr, TextDescriptor.Unit unitRestr, Pattern pattern, Set<Geometric> examineThis) { boolean doTemp = whatToSearch.contains(TextUtils.WhatToSearch.TEMP_NAMES); TextUtils.WhatToSearch what = get(whatToSearch, TextUtils.WhatToSearch.NODE_NAME); TextUtils.WhatToSearch whatVar = get(whatToSearch, TextUtils.WhatToSearch.NODE_VAR); for(Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); ) { NodeInst ni = it.next(); if (examineThis != null && !examineThis.contains(ni)) continue; if (what != null) { Name name = ni.getNameKey(); if (doTemp || !name.isTempname()) { findAllMatches(ni, NodeInst.NODE_NAME, 0, name.toString(), search, caseSensitive, regExp, pattern, codeRestr, unitRestr); } } if (whatVar != null) addVariableTextToList(ni, search, caseSensitive,regExp, pattern, codeRestr, unitRestr); } } private void searchTextArcs(Cell cell, String search, boolean caseSensitive, boolean regExp, Set whatToSearch, CodeExpression.Code codeRestr, TextDescriptor.Unit unitRestr, Pattern pattern, Set<Geometric> examineThis) { boolean doTemp = whatToSearch.contains(TextUtils.WhatToSearch.TEMP_NAMES); TextUtils.WhatToSearch what = get(whatToSearch, TextUtils.WhatToSearch.ARC_NAME); TextUtils.WhatToSearch whatVar = get(whatToSearch, TextUtils.WhatToSearch.ARC_VAR); for(Iterator<ArcInst> it = cell.getArcs(); it.hasNext(); ) { ArcInst ai = it.next(); if (examineThis != null && !examineThis.contains(ai)) continue; if (what != null) { Name name = ai.getNameKey(); if (doTemp || !name.isTempname()) { findAllMatches(ai, ArcInst.ARC_NAME, 0, name.toString(), search, caseSensitive, regExp, pattern, codeRestr, unitRestr); } } if (whatVar != null) addVariableTextToList(ai, search, caseSensitive, regExp, pattern, codeRestr, unitRestr); } } private void searchTextExports(Cell cell, String search, boolean caseSensitive, boolean regExp, Set whatToSearch, CodeExpression.Code codeRestr, TextDescriptor.Unit unitRestr, Pattern pattern, Set<Geometric> examineThis) { WhatToSearch what = get(whatToSearch, TextUtils.WhatToSearch.EXPORT_NAME); TextUtils.WhatToSearch whatVar = get(whatToSearch, TextUtils.WhatToSearch.EXPORT_VAR); for(Iterator<Export> it = cell.getExports(); it.hasNext(); ) { Export pp = it.next(); if (examineThis != null && !examineThis.contains(pp.getOriginalPort().getNodeInst())) continue; if (what != null) { Name name = pp.getNameKey(); findAllMatches(pp, Export.EXPORT_NAME, 0, name.toString(), search, caseSensitive, regExp, pattern, codeRestr, unitRestr); } if (whatVar != null) addVariableTextToList(pp, search, caseSensitive, regExp, pattern, codeRestr, unitRestr); } } private void searchTextCellVars(Cell cell, String search, boolean caseSensitive, boolean regExp, Set whatToSearch, CodeExpression.Code codeRestr, TextDescriptor.Unit unitRestr, Pattern pattern, Rectangle2D highBounds) { WhatToSearch whatVar = get(whatToSearch, TextUtils.WhatToSearch.CELL_VAR); if (whatVar != null) { for(Iterator<Variable> it = cell.getParametersAndVariables(); it.hasNext(); ) { Variable var = it.next(); if (!var.isDisplay()) continue; if (highBounds != null) { if (var.getXOff() < highBounds.getMinX() || var.getXOff() > highBounds.getMaxX() || var.getYOff() < highBounds.getMinY() || var.getYOff() > highBounds.getMaxY()) continue; } findAllMatches(cell, var.getKey(), -1, var.getPureValue(-1), search, caseSensitive, regExp, pattern, codeRestr, unitRestr); } } } /** * Method to change a string to another. * @param index the entry in the array of replacements to change. * @param rep the new string. * @param cell the Cell in which these strings reside. */ private void changeOneText(int index, String rep, Cell cell) { if (index < 0 || index >= foundInCell.size()) return; StringsInCell sic = foundInCell.get(index); String oldString = sic.theLine; String newString; if (sic.regExpSearch != null) { Pattern p = Pattern.compile(sic.regExpSearch); Matcher m = p.matcher(oldString); boolean found = m.find(sic.startPosition); LayoutLib.error(!found, "regExp find before replace failed"); try { StringBuffer ns = new StringBuffer(); m.appendReplacement(ns, rep); m.appendTail(ns); newString = ns.toString(); } catch (Exception e) { System.out.println("Regular expression replace failed"); newString = oldString; } } else { newString = oldString.substring(0, sic.startPosition) + rep + oldString.substring(sic.endPosition); } printChange(sic, newString); if (sic.object == null) { // cell variable name name if (cell.isParam(sic.key)) cell.getCellGroup().updateParamText((Variable.AttrKey)sic.key, newString); else cell.updateVarText(sic.key, newString); } else { if (sic.key == NodeInst.NODE_NAME) { // node name NodeInst ni = (NodeInst)sic.object; ni.setName(newString); } else if (sic.key == ArcInst.ARC_NAME) { // arc name ArcInst ai = (ArcInst)sic.object; ai.setName(newString); } else if (sic.key == Export.EXPORT_NAME) { // export name Export pp = (Export)sic.object; pp.rename(newString); } else { // text on a variable ElectricObject base = (ElectricObject)sic.object; Variable var = base.getParameterOrVariable(sic.key); Object obj = var.getObject(); if (obj instanceof String || obj instanceof CodeExpression) { base.updateVarText(sic.key, newString); } else if (obj instanceof String[]) { String [] oldLines = (String [])obj; String [] newLines = new String[oldLines.length]; for(int i=0; i<oldLines.length; i++) { if (i == sic.lineInVariable) newLines[i] = newString; else newLines[i] = oldLines[i]; } base.updateVar(sic.key, newLines); } } } // because the replacement changes things, must update other search strings that point to the same place int delta = newString.length() - oldString.length(); for(StringsInCell oSIC : foundInCell) { if (oSIC == sic) continue; if (oSIC.object != sic.object) continue; if (oSIC.key != sic.key) continue; if (oSIC.lineInVariable != sic.lineInVariable) continue; // part of the same string: update it oSIC.theLine = newString; if (oSIC.startPosition > sic.startPosition) { oSIC.startPosition += delta; oSIC.endPosition += delta; } } } private void replaceAllText(String replace, Cell cell) { if (foundInCell.size() == 0) { Toolkit.getDefaultToolkit().beep(); } else { for(int i = 0; i < foundInCell.size(); i++) changeOneText(i, replace, cell); System.out.println("Replaced " + foundInCell.size() + " times"); } } /** * Method to initialize for a new text * @param search the string to locate. * @param caseSensitive true to match only where the case is the same. * @param regExp true if the search string is a regular expression. * @param whatToSearch a collection of text types to consider. * @param codeRestr a restriction on types of Code to consider (null to consider all Code values). * @param unitRestr a restriction on types of Units to consider (null to consider all Unit values). * @param highlightedOnly true to search only in the highlighted area. * @param wnd the window in which search is being done (used if "highlightedOnly" is true). */ public void initTextSearch(Cell cell, String search, boolean caseSensitive, boolean regExp, Set<TextUtils.WhatToSearch> whatToSearch, CodeExpression.Code codeRestr, TextDescriptor.Unit unitRestr, boolean highlightedOnly, EditWindow wnd) { foundInCell = new ArrayList<StringsInCell>(); if (cell == null) { System.out.println("No current Cell"); return; } Pattern pattern = null; if (regExp) { pattern = getPattern(search, caseSensitive); if (pattern == null) return; // errror } // see if searching the highlighted area only Set<Geometric> examineThis = null; Rectangle2D highBounds = null; if (highlightedOnly) { examineThis = new HashSet<Geometric>(); List<Geometric> highs = wnd.getHighlightedEObjs(true, true); highBounds = wnd.getHighlightedArea(); for(Geometric g : highs) examineThis.add(g); Rectangle2D selection = wnd.getHighlightedArea(); if (selection != null) { List<Highlight2> inArea = Highlighter.findAllInArea(wnd.getHighlighter(), cell, false, false, false, false, true, true, selection, wnd); for(Highlight2 h : inArea) { ElectricObject eo = h.getElectricObject(); if (eo instanceof PortInst) eo = ((PortInst)eo).getNodeInst(); if (eo instanceof Geometric) examineThis.add((Geometric)eo); } } } // initialize the search searchTextNodes(cell, search, caseSensitive, regExp, whatToSearch, codeRestr, unitRestr, pattern, examineThis); searchTextArcs(cell, search, caseSensitive, regExp, whatToSearch, codeRestr, unitRestr, pattern, examineThis); searchTextExports(cell, search, caseSensitive, regExp, whatToSearch, codeRestr, unitRestr, pattern, examineThis); searchTextCellVars(cell, search, caseSensitive, regExp, whatToSearch, codeRestr, unitRestr, pattern, highBounds); if (foundInCell.size() == 0) System.out.println("Nothing found"); currentFindPosition = -1; } /** * Method to find the next occurrence of a string. * @param reverse true to find in the reverse direction. * @return true if something was found. */ private boolean findNextText(Cell cell, Highlighter highlighter, boolean reverse) { int curPos = currentFindPosition; currentFindPosition = -1; for(int i=0; i<foundInCell.size(); i++) { if (reverse) { curPos--; if (curPos < 0) curPos = foundInCell.size()-1; } else { curPos++; if (curPos >= foundInCell.size()) curPos = 0; } if (!foundInCell.get(curPos).replaced) { currentFindPosition = curPos; break; } } if (currentFindPosition < 0) return false; StringsInCell sic = foundInCell.get(currentFindPosition); highlighter.clear(); printFind(sic); if (sic.object == null) { highlighter.addText(cell, cell, sic.key); } else { ElectricObject eObj = (ElectricObject)sic.object; Variable.Key key = sic.key; if (key == null) { if (eObj instanceof Export) key = Export.EXPORT_NAME; else if (eObj instanceof ArcInst) key = ArcInst.ARC_NAME; else if (eObj instanceof NodeInst) key = NodeInst.NODE_NAME; assert(key != null); } highlighter.addText(eObj, cell, key); } highlighter.finished(); return true; } /** * Method to find all strings on a given database string, and add matches to the list. * @param object the Object on which the string resides. * @param key the Variable.key on which the string resides. * @param lineInVariable the line number in arrayed variables. * @param theLine the actual string from the database. * @param search the string to find. * @param caseSensitive true to do a case-sensitive */ private void findAllMatches(ElectricObject object, Variable.Key key, int lineInVariable, String theLine, String search, boolean caseSensitive, boolean regExp, Pattern p, CodeExpression.Code codeRestr, TextDescriptor.Unit unitRestr) { if (codeRestr != null || unitRestr != null) { Variable var = object.getVar(key); if (var != null) { if (codeRestr != null && var.getCode() != codeRestr) return; if (unitRestr != null && var.getUnit() != unitRestr) return; } } Matcher m = (p != null) ? p.matcher(theLine) : null; // p != null -> regExp for(int startPos = 0; ; ) { int endPos; if (regExp) { boolean found = m.find(); if (!found) break; startPos = m.start(); endPos = m.end(); } else { startPos = TextUtils.findStringInString(theLine, search, startPos, caseSensitive, false); if (startPos < 0) break; endPos = startPos + search.length(); } String regExpSearch = regExp ? search : null; foundInCell.add(new StringsInCell(object instanceof Cell ? null : object, key, lineInVariable, theLine, startPos, endPos, regExpSearch)); startPos = endPos; } } /** * Method to all all displayable variable strings to the list of strings in the Cell. * @param eObj the ElectricObject on which variables should be examined. * @param search the string to find on the text. * @param caseSensitive true to do a case-sensitive. * @param regExp true to use regular-expression parsing. * @param p the pattern to find. * @param codeRestr a restriction on types of Code to consider (null to consider all Code values). * @param unitRestr a restriction on types of Units to consider (null to consider all Unit values). */ private void addVariableTextToList(ElectricObject eObj, String search, boolean caseSensitive, boolean regExp, Pattern p, CodeExpression.Code codeRestr, TextDescriptor.Unit unitRestr) { for(Iterator<Variable> it = eObj.getParametersAndVariables(); it.hasNext(); ) { Variable var = it.next(); if (!var.isDisplay()) continue; Object obj = var.getObject(); if (obj instanceof String || obj instanceof CodeExpression) { findAllMatches(eObj, var.getKey(), -1, obj.toString(), search, caseSensitive, regExp, p, codeRestr, unitRestr); } else if (obj instanceof String[]) { String [] strings = (String [])obj; for(int i=0; i<strings.length; i++) { findAllMatches(eObj, var.getKey(), i, strings[i], search, caseSensitive, regExp, p, codeRestr, unitRestr); } } } } } /** * Class to define a string found in a cell. */ private static class StringsInCell implements Serializable { /** the object that the string resides on */ final Object object; /** the Variable that the string resides on */ final Variable.Key key; /** the original string. */ String theLine; /** the line number in arrayed variables */ final int lineInVariable; /** the starting character position */ int startPosition; /** the ending character position */ int endPosition; /** the Regular Expression searched for */ final String regExpSearch; /** true if the replacement has been done */ boolean replaced; StringsInCell(Object object, Variable.Key key, int lineInVariable, String theLine, int startPosition, int endPosition, String regExpSearch) { this.object = object; assert(key!=null); this.key = key; this.lineInVariable = lineInVariable; this.theLine = theLine; this.startPosition = startPosition; this.endPosition = endPosition; this.regExpSearch = regExpSearch; this.replaced = false; } public String toString() { return "StringsInCell obj="+object+" var="+key+ /*" name="+name+*/" line="+lineInVariable+" start="+startPosition+" end="+endPosition+" msg="+theLine; } } private static TextUtils.WhatToSearch get(Set whatToSearch, TextUtils.WhatToSearch what) { if (whatToSearch.contains(what)) return what; return null; } /** * Method to initialize for a new text * @param search the string to locate. * @param caseSensitive true to match only where the case is the same. * @param regExp true if the search string is a regular expression. * @param whatToSearch a collection of text types to consider. * @param codeRestr a restriction on types of Code to consider (null to consider all Code values). * @param unitRestr a restriction on types of Units to consider (null to consider all Unit values). * @param highlightedOnly true to search only in the highlighted area. */ public void initTextSearch(String search, boolean caseSensitive, boolean regExp, Set<TextUtils.WhatToSearch> whatToSearch, CodeExpression.Code codeRestr, TextDescriptor.Unit unitRestr, boolean highlightedOnly) { textSearch.initTextSearch(cell, search, caseSensitive, regExp, whatToSearch, codeRestr, unitRestr, highlightedOnly, this); } private static String repeatChar(char c, int num) { StringBuffer sb = new StringBuffer(); for (int i=0; i<num; i++) sb.append(c); return sb.toString(); } private static void printFind(StringsInCell sic) { String foundHdr = "Found "+sic.key+": "; String foundStr = sic.theLine; String highlightHdr = repeatChar(' ', foundHdr.length()+sic.startPosition); String highlight = repeatChar('^', sic.endPosition-sic.startPosition); System.out.println(foundHdr+foundStr+"\n"+ highlightHdr+highlight); } /** * Method to find the next occurrence of a string. * @param reverse true to find in the reverse direction. * @return true if something was found. */ public boolean findNextText(boolean reverse) { return textSearch.findNextText(cell, highlighter, reverse); } /** * Method to replace the text that was just selected with findNextText(). * @param replace the new text to replace. */ public void replaceText(String replace) { int pos = textSearch.currentFindPosition; if (pos < 0 || pos >= textSearch.foundInCell.size()) return; StringsInCell sic = textSearch.foundInCell.get(pos); if (sic.replaced) return; // mark this replacement done sic.replaced = true; new ReplaceTextJob(this, replace); } /** * Method to replace all selected text. * @param replace the new text to replace everywhere. */ public void replaceAllText(String replace) { // remove replacements already done for(int i = textSearch.foundInCell.size()-1; i >= 0; i--) { StringsInCell sic = textSearch.foundInCell.get(i); if (sic.replaced) textSearch.foundInCell.remove(i); } // mark all of these changes as done for(StringsInCell sic : textSearch.foundInCell) sic.replaced = true; // replace everything new ReplaceAllTextJob(this, replace); } /** * Class to change text in a new thread. */ private static class ReplaceTextJob extends Job { private String replace; private Cell cell; private StringSearch search; private ReplaceTextJob(EditWindow wnd, String replace) { super("Replace Text", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER); this.search = wnd.textSearch; this.cell = wnd.cell; this.replace = replace; startJob(); } public boolean doIt() throws JobException { search.changeOneText(search.currentFindPosition, replace, cell); fieldVariableChanged("search"); return true; } } /** * Class to change text in a new thread. */ private static class ReplaceAllTextJob extends Job { private StringSearch search; private String replace; private Cell cell; public ReplaceAllTextJob(EditWindow wnd, String replace) { super("Replace All Text", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER); this.search = wnd.textSearch; this.replace = replace; this.cell = wnd.cell; startJob(); } public boolean doIt() throws JobException { search.replaceAllText(replace, cell); fieldVariableChanged("search"); return true; } } private static void printChange(StringsInCell sic, String newString) { String foundHdr = "Change "+sic.key+": "; String foundStr = sic.theLine; String replaceHdr = " -> "; String replaceStr = newString; String highlightHdr = repeatChar(' ', foundHdr.length()+sic.startPosition); String highlightStr = repeatChar('^', sic.endPosition-sic.startPosition); System.out.println(foundHdr + foundStr + replaceHdr+replaceStr + "\n" + highlightHdr + highlightStr); } // ************************************* POPUP CLOUD ************************************* public boolean getShowPopupCloud() { return showPopupCloud; } public void setShowPopupCloud(List<String> text, Point2D point) { showPopupCloud = true; // popupCloudText = text; // popupCloudPoint = point; } public void clearShowPopupCloud() { showPopupCloud = false; } private void drawPopupCloud(Graphics2D g) { // JKG NOTE: disabled for now // must decide whether or not this is useful /* if (popupCloudText == null || popupCloudText.size() == 0) return; // draw cloud float yspacing = 5; float x = (float)popupCloudPoint.getX() + 25; float y = (float)popupCloudPoint.getY() + 10 + yspacing; for (int i=0; i<popupCloudText.size(); i++) { GlyphVector glyph = getFont().createGlyphVector(g.getFontRenderContext(), popupCloudText.get(i)); g.drawGlyphVector(glyph, x, y); y += glyph.getVisualBounds().getHeight() + yspacing; } */ } // ************************************* WINDOW ZOOM AND PAN ************************************* /** * Method to return the size of this EditWindow. * @return a Dimension with the size of this EditWindow. */ public Dimension getScreenSize() { return sz; } /** * Method to return the scale factor for this window. * @return the scale factor for this window. */ public double getScale() { return scale; } /** * Method to return the text scale factor for this window. * @return the text scale factor for this window. */ public double getGlobalTextScale() { return globalTextScale; } /** * Method to set the text scale factor for this window. * @param gts the text scale factor for this window. */ public void setGlobalTextScale(double gts) { globalTextScale = gts; } /** * Method to set the scale factor for this window. * @param scale the scale factor for this window. */ public void setScale(double scale) { if (scale <= 0) throw new IllegalArgumentException("Negative window scale"); scaleRequested = scale; removeAllInPlaceTextObjects(); } /** * Method to return the offset factor for this window. * @return the offset factor for this window. */ public Point2D getOffset() { return new Point2D.Double(offx, offy); } /** * Method to return the offset factor for this window. * If new offsets are queued, this gets the ultimate offset value. * @return the offset factor for this window. */ public Point2D getScheduledOffset() { return new Point2D.Double(offxRequested, offyRequested); } /** * Method to set the offset factor for this window. * @param off the offset factor for this window. */ public void setOffset(Point2D off) { offxRequested = off.getX(); offyRequested = off.getY(); removeAllInPlaceTextObjects(); } private void setScreenBounds(Rectangle2D bounds) { double width = bounds.getWidth(); double height = bounds.getHeight(); if (width == 0) width = 2; if (height == 0) height = 2; double scalex = sz.width/width * 0.9; double scaley = sz.height/height * 0.9; setScale(Math.min(scalex, scaley)); setOffset(new Point2D.Double(bounds.getCenterX(), bounds.getCenterY())); } public Rectangle2D getDisplayedBounds() { double width = sz.width/scale; double height = sz.height/scale; return new Rectangle2D.Double(offx - width/2, offy - height/2, width, height); } private static final double scrollPagePercent = 0.2; // ignore programmatic scroll changes. Only respond to user scroll changes private boolean ignoreScrollChange = false; private static final int scrollRangeMult = 100; // when zoomed in, this prevents rounding from causing problems /** * New version of setScrollPosition. Attempts to provides means of scrolling * out of cell bounds. */ public void setScrollPosition() { if (!SwingUtilities.isEventDispatchThread()) { SwingUtilities.invokeLater(new Runnable() { public void run() { setScrollPositionUnsafe(); } }); } else setScrollPositionUnsafe(); } /** * New version of setScrollPosition. Attempts to provides means of scrolling * out of cell bounds. This is the Swing unsafe version */ private void setScrollPositionUnsafe() { if (bottomScrollBar == null || rightScrollBar == null) return; bottomScrollBar.setEnabled(cell != null); rightScrollBar.setEnabled(cell != null); if (cell == null) return; Rectangle2D cellBounds = getInPlaceEditTopCell().getBounds(); Rectangle2D viewBounds = displayableBounds(); // scroll bar is being repositioned: ignore the change events it generates ignoreScrollChange = true; double width = (viewBounds.getWidth() < cellBounds.getWidth()) ? viewBounds.getWidth() : cellBounds.getWidth(); double height = (viewBounds.getHeight() < cellBounds.getHeight()) ? viewBounds.getHeight() : cellBounds.getHeight(); Point2D dbPt = new Point2D.Double(offx, offy); double oX = dbPt.getX(); double oY = dbPt.getY(); if (!bottomScrollBar.getValueIsAdjusting()) { int value = (int)((oX-0.5*width)*scrollRangeMult); int extent = (int)(width*scrollRangeMult); int min = (int)((cellBounds.getX() - scrollPagePercent*cellBounds.getWidth())*scrollRangeMult); int max = (int)(((cellBounds.getX()+cellBounds.getWidth()) + scrollPagePercent*cellBounds.getWidth())*scrollRangeMult); bottomScrollBar.getModel().setRangeProperties(value, extent, min, max, false); bottomScrollBar.setUnitIncrement((int)(0.05*viewBounds.getWidth()*scrollRangeMult)); bottomScrollBar.setBlockIncrement((int)(scrollPagePercent*viewBounds.getWidth()*scrollRangeMult)); } if (!rightScrollBar.getValueIsAdjusting()) { int value = (int)((-oY-0.5*height)*scrollRangeMult); int extent = (int)(height*scrollRangeMult); int min = (int)((-((cellBounds.getY()+cellBounds.getHeight()) + scrollPagePercent*cellBounds.getHeight()))*scrollRangeMult); int max = (int)((-(cellBounds.getY() - scrollPagePercent*cellBounds.getHeight()))*scrollRangeMult); rightScrollBar.getModel().setRangeProperties(value, extent, min, max, false); rightScrollBar.setUnitIncrement((int)(0.05*viewBounds.getHeight()*scrollRangeMult)); rightScrollBar.setBlockIncrement((int)(scrollPagePercent*viewBounds.getHeight()*scrollRangeMult)); } ignoreScrollChange = false; } public void bottomScrollChanged(int value) { if (cell == null) return; if (ignoreScrollChange) return; Point2D dbPt = new Point2D.Double(offx, offy); double oY = dbPt.getY(); double val = (double)value/(double)scrollRangeMult; Rectangle2D cellBounds = getInPlaceEditTopCell().getBounds(); Rectangle2D viewBounds = displayableBounds(); double width = (viewBounds.getWidth() < cellBounds.getWidth()) ? viewBounds.getWidth() : cellBounds.getWidth(); double newoffx = val+0.5*width; // new offset Point2D offset = new Point2D.Double(newoffx, oY); setOffset(offset); getSavedFocusBrowser().updateCurrentFocus(); fullRepaint(); } public void rightScrollChanged(int value) { if (cell == null) return; if (ignoreScrollChange) return; Point2D dbPt = new Point2D.Double(offx, offy); double oX = dbPt.getX(); double val = (double)value/(double)scrollRangeMult; Rectangle2D cellBounds = getInPlaceEditTopCell().getBounds(); Rectangle2D viewBounds = displayableBounds(); double height = (viewBounds.getHeight() < cellBounds.getHeight()) ? viewBounds.getHeight() : cellBounds.getHeight(); double newoffy = -(val+0.5*height); Point2D offset = new Point2D.Double(oX, newoffy); setOffset(offset); getSavedFocusBrowser().updateCurrentFocus(); fullRepaint(); } /** * Method to focus the screen so that an area fills it. * @param bounds the area to make fill the screen. */ public void focusScreen(Rectangle2D bounds) { if (bounds == null) return; if (inPlaceDisplay) { Point2D llPt = new Point2D.Double(bounds.getMinX(), bounds.getMinY()); Point2D urPt = new Point2D.Double(bounds.getMaxX(), bounds.getMaxY()); outofCell.transform(llPt, llPt); outofCell.transform(urPt, urPt); double lX = Math.min(llPt.getX(), urPt.getX()); double hX = Math.max(llPt.getX(), urPt.getX()); double lY = Math.min(llPt.getY(), urPt.getY()); double hY = Math.max(llPt.getY(), urPt.getY()); bounds = new Rectangle2D.Double(lX, lY, hX-lX, hY-lY); } setScreenBounds(bounds); setScrollPosition(); getSavedFocusBrowser().saveCurrentFocus(); fullRepaint(); } /** * Method to compute the bounds of the cell in this EditWindow. * Bounds includes factors such as frame size and large text. * @return the bounds of the cell in this EditWindow. */ public Rectangle2D getBoundsInWindow() { Rectangle2D cellBounds = cell.getBounds(); Dimension d = new Dimension(); int frameFactor = Cell.FrameDescription.getCellFrameInfo(cell, d); Rectangle2D frameBounds = new Rectangle2D.Double(-d.getWidth()/2, -d.getHeight()/2, d.getWidth(), d.getHeight()); if (frameFactor == 0) { cellBounds = frameBounds; if (cell.isMultiPage()) { double offY = pageNumber * Cell.FrameDescription.MULTIPAGESEPARATION; cellBounds.setRect(cellBounds.getMinX(), cellBounds.getMinY() + offY, cellBounds.getWidth(), cellBounds.getHeight()); } } else { if (cellBounds.getWidth() == 0 && cellBounds.getHeight() == 0) { int defaultCellSize = 60; cellBounds = new Rectangle2D.Double(cellBounds.getCenterX()-defaultCellSize/2, cellBounds.getCenterY()-defaultCellSize/2, defaultCellSize, defaultCellSize); } // make sure text fits if (wf != null && runningNow != null) { // System.out.println("Warning: screen extent computation is inaccurate"); } else { double oldScale = getScale(); Point2D oldOffset = getOffset(); setScreenBounds(cellBounds); if (scale != scaleRequested) textInCell = null; scale = scaleRequested; Rectangle2D relativeTextBounds = cell.getRelativeTextBounds(this); if (relativeTextBounds != null) { Rectangle2D newCellBounds = new Rectangle2D.Double(); Rectangle2D.union(relativeTextBounds, cellBounds, newCellBounds); // do it twice more to get closer to the actual text size for(int i=0; i<2; i++) { setScreenBounds(newCellBounds); if (scale != scaleRequested) textInCell = null; scale = scaleRequested; relativeTextBounds = cell.getRelativeTextBounds(this); if (relativeTextBounds != null) Rectangle2D.union(relativeTextBounds, cellBounds, newCellBounds); } cellBounds = newCellBounds; } setScale(oldScale); setOffset(oldOffset); } // make sure title box fits (if there is just a title box) if (frameFactor == 1) { Rectangle2D.union(frameBounds, cellBounds, frameBounds); cellBounds = frameBounds; } } return cellBounds; } // Highlighting methods for the EditWindow_ interface public void addElectricObject(ElectricObject eObj, Cell cell) { highlighter.addElectricObject(eObj, cell); } public Rectangle2D getHighlightedArea() { return highlighter.getHighlightedArea(this); } public void addHighlightArea(Rectangle2D rect, Cell cell) { highlighter.addArea(rect, cell); } public void addHighlightLine(Point2D pt1, Point2D pt2, Cell cell, boolean thick) { highlighter.addLine(pt1, pt2, cell, thick); } public void addHighlightMessage(Cell cell, String message, Point2D loc) { highlighter.addMessage(cell, message, loc); } public void addHighlightText(ElectricObject eObj, Cell cell, Variable.Key varKey) { highlighter.addText(eObj, cell, varKey); } public ElectricObject getOneElectricObject(Class clz) { return highlighter.getOneElectricObject(clz); } public List<Geometric> getHighlightedEObjs(boolean wantNodes, boolean wantArcs) { return highlighter.getHighlightedEObjs(wantNodes, wantArcs); } public Set<Network> getHighlightedNetworks() { return highlighter.getHighlightedNetworks(); } public Point2D getHighlightOffset() { return highlighter.getHighlightOffset(); } public void setHighlightOffset(int dX, int dY) { highlighter.setHighlightOffset(dX, dY); } public List<Highlight2> saveHighlightList() { List<Highlight2> saveList = new ArrayList<Highlight2>(); for(Highlight2 h : highlighter.getHighlights()) saveList.add(h); return saveList; } public void restoreHighlightList(List<Highlight2> list) { highlighter.setHighlightListGeneral(list); } public void clearHighlighting() { highlighter.clear(); } public void finishedHighlighting() { highlighter.finished(); } /** * Method to pan and zoom the screen so that the entire cell is displayed. */ public void fillScreen() { if (cell != null) { if (!cell.getView().isTextView()) { Rectangle2D cellBounds = getBoundsInWindow(); focusScreen(cellBounds); return; } } getSavedFocusBrowser().saveCurrentFocus(); repaint(); } public void zoomOutContents() { double scale = getScale(); setScale(scale / 2); getSavedFocusBrowser().saveCurrentFocus(); fullRepaint(); } public void zoomInContents() { double scale = getScale(); setScale(scale * 2); getSavedFocusBrowser().saveCurrentFocus(); fullRepaint(); } public void focusOnHighlighted() { // focus on highlighting Rectangle2D bounds = highlighter.getHighlightedArea(this); focusScreen(bounds); } /** * Get the Saved View Browser for this Edit Window */ public EditWindowFocusBrowser getSavedFocusBrowser() { return viewBrowser; } // ************************************* HIERARCHY TRAVERSAL ************************************* /** * Get the window's VarContext * @return the current VarContext */ public VarContext getVarContext() { return cellVarContext; } /** * Push into an instance (go down the hierarchy) * @param keepFocus true to keep the zoom and scale in the new window. * @param newWindow true to create a new window for the cell. * @param inPlace true to descend "in-place" showing the higher levels. */ public void downHierarchy(boolean keepFocus, boolean newWindow, boolean inPlace) { // get highlighted Highlight2 h = highlighter.getOneHighlight(); if (h == null) return; ElectricObject eobj = h.getElectricObject(); NodeInst ni = null; PortInst pi = null; // see if a nodeinst was highlighted (true if text on nodeinst was highlighted) if (eobj instanceof NodeInst) ni = (NodeInst)eobj; // see if portinst was highlighted if (eobj instanceof PortInst) { pi = (PortInst)eobj; ni = pi.getNodeInst(); } if (ni == null) { System.out.println("Must select a Node to descend into"); return; } if (!ni.isCellInstance()) { System.out.println("Can only descend into cell instances"); return; } Cell cell = (Cell)ni.getProto(); Cell schCell = cell.getEquivalent(); // special case: if cell is icon of current cell, descend into icon if (this.cell == schCell) schCell = cell; if (schCell == null) schCell = cell; // when editing in-place, always descend to the icon if (inPlace) schCell = cell; // determine display factors for new cell double offX = offx; double offY = offy; if (keepFocus) { offX -= ni.getAnchorCenterX(); offY -= ni.getAnchorCenterY(); } // handle in-place display List<NodeInst> newInPlaceDescent = new ArrayList<NodeInst>(); if (inPlace) { newInPlaceDescent.addAll(inPlaceDescent); newInPlaceDescent.add(ni); } WindowFrame.DisplayAttributes da = new WindowFrame.DisplayAttributes(scale, offX, offY, newInPlaceDescent); // for stacked NodeInsts, must choose which one Nodable desiredNO = null; List<Nodable> possibleNodables = new ArrayList<Nodable>(); Netlist nl = ni.getParent().acquireUserNetlist(); if (nl == null) { System.out.println("Netlist is not ready"); return; } for(Iterator<Nodable> it = nl.getNodables(); it.hasNext(); ) { Nodable no = it.next(); if (no.getNodeInst() == ni) { possibleNodables.add(no); } } if (possibleNodables.size() > 1) { desiredNO = possibleNodables.get(0); // see if there are any waveform windows boolean promptUser = isArrayedContextMatter(desiredNO); if (promptUser) { String [] manyOptions = new String[possibleNodables.size()]; int i = 0; for(Nodable no : possibleNodables) manyOptions[i++] = no.getName(); String chosen = (String)JOptionPane.showInputDialog(TopLevel.getCurrentJFrame(), "Descend into which node?", "Choose a Node", JOptionPane.QUESTION_MESSAGE, null, manyOptions, manyOptions[0]); if (chosen == null) return; for(Nodable no : possibleNodables) { if (no.getName().equals(chosen)) { desiredNO = no; break; } } } } // do the descent boolean redisplay = true; if (inPlace) redisplay = false; if (keepFocus) redisplay = false; EditWindow newWND = this; if (newWindow) { WindowFrame newWF = WindowFrame.createEditWindow(schCell); newWND = (EditWindow)newWF.getContent(); } else SelectObject.selectObjectDialog(schCell, true); VarContext vc; if (desiredNO != null) { vc = cellVarContext.push(desiredNO); } else { vc = cellVarContext.push(ni); } newWND.showCell(schCell, vc, redisplay, da); newWND.getWindowFrame().addToHistory(schCell, vc, da); if (!redisplay) fullRepaint(); clearSubCellCache(); // if highlighted was a port inst, then highlight the corresponding export if (pi != null) { Export schExport = schCell.findExport(pi.getPortProto().getName()); if (schExport != null) { PortInst origPort = schExport.getOriginalPort(); newWND.highlighter.addElectricObject(origPort, schCell); newWND.highlighter.finished(); } } } /** * Returns true if, in terms of context, it matters which index * of the nodable we push into. * @param no the nodable * @return true if we need to ask the user which index to descent into, * false otherwise. */ public static boolean isArrayedContextMatter(Nodable no) { // matters if the user requested it if (User.isPromptForIndexWhenDescending()) return true; // matters if there is a waveform window open for(Iterator<WindowFrame> it = WindowFrame.getWindows(); it.hasNext(); ) { WindowFrame wf = it.next(); if (wf.getContent() instanceof WaveformWindow) return true; } // if getdrive is called for (Iterator<Variable> it = no.getDefinedParameters(); it.hasNext(); ) { Variable var = it.next(); Object obj = var.getObject(); if (obj instanceof CodeExpression) { String str = obj.toString(); if (str.matches(".*LE\\.getdrive.*")) return true; } } // does not matter return false; } /** * Pop out of an instance (go up the hierarchy) */ public void upHierarchy(boolean keepFocus) { if (cell == null) return; Cell oldCell = cell; // determine which export is selected so it can be shown in the upper level Export selectedExport = null; Set<Network> nets = highlighter.getHighlightedNetworks(); for(Network net : nets) { for(Iterator<Export> eIt = net.getExports(); eIt.hasNext(); ) { Export e = eIt.next(); selectedExport = e; break; } if (selectedExport != null) break; } try { Nodable no = cellVarContext.getNodable(); - if (no != null) + if (no != null && no.getNodeInst().isLinked()) { Cell parent = no.getParent(); // see if this was in history, if so, restore offset and scale // search backwards to get most recent entry // search history **before** calling setCell, otherwise we find // the history record for the cell we just switched to VarContext context = cellVarContext.pop(); int historyIndex = wf.findCellHistoryIndex(parent, context); if (historyIndex >= 0) { // found previous in cell history: show it WindowFrame.CellHistory foundHistory = wf.getCellHistoryList().get(historyIndex); foundHistory.setContext(context); if (selectedExport != null) foundHistory.setSelPort(no.getNodeInst().findPortInstFromProto(selectedExport)); if (keepFocus) { double newX = offx, newY = offy; if (!inPlaceDisplay) { Point2D curCtr = new Point2D.Double(offx, offy); AffineTransform up = no.getNodeInst().rotateOut(no.getNodeInst().translateOut()); up.transform(curCtr, curCtr); newX = curCtr.getX(); newY = curCtr.getY(); } List<NodeInst> oldInPlaceDescent = foundHistory.getDisplayAttributes().inPlaceDescent; foundHistory.setDisplayAttributes(new WindowFrame.DisplayAttributes(scale, newX, newY, oldInPlaceDescent)); } wf.setCellByHistory(historyIndex); } else { // no previous history: make one up List<NodeInst> newInPlaceDescent = new ArrayList<NodeInst>(inPlaceDescent); if (!newInPlaceDescent.isEmpty()) newInPlaceDescent.remove(newInPlaceDescent.size() - 1); double newX = offx, newY = offy; if (keepFocus) { NodeInst ni = no.getNodeInst(); Point2D curCtr = new Point2D.Double(offx, offy); AffineTransform up = ni.rotateOut(ni.translateOut()); up.transform(curCtr, curCtr); newX = curCtr.getX(); newY = curCtr.getY(); } WindowFrame.DisplayAttributes da = new WindowFrame.DisplayAttributes(scale, newX, newY, newInPlaceDescent); showCell(parent, context, true, da); wf.addToHistory(parent, context, da); // highlight node we came from PortInst pi = null; if (selectedExport != null) pi = no.getNodeInst().findPortInstFromProto(selectedExport); if (pi != null) highlighter.addElectricObject(pi, parent); else highlighter.addElectricObject(no.getNodeInst(), parent); } clearSubCellCache(); // highlight portinst selected at the time, if any SelectObject.selectObjectDialog(parent, true); return; } // no parent - if icon, go to sch view if (cell.isIcon()) { Cell schCell = cell.getEquivalent(); if (schCell != null) { setCell(schCell, VarContext.globalContext, null); SelectObject.selectObjectDialog(schCell, true); return; } } // find all possible parents in all libraries Set<Cell> found = new HashSet<Cell>(); for(Iterator<NodeInst> it = cell.getInstancesOf(); it.hasNext(); ) { NodeInst ni = it.next(); Cell parent = ni.getParent(); if (parent.getLibrary().isHidden()) continue; found.add(parent); } if (cell.isSchematic()) { for(Iterator<Cell> cIt = cell.getCellGroup().getCells(); cIt.hasNext(); ) { Cell iconView = cIt.next(); if (iconView.getView() != View.ICON) continue; for(Iterator<NodeInst> it = iconView.getInstancesOf(); it.hasNext(); ) { NodeInst ni = it.next(); if (ni.isIconOfParent()) continue; Cell parent = ni.getParent(); if (parent.getLibrary().isHidden()) continue; found.add(parent); } } } // see what was found if (found.size() == 0) { // no parent cell System.out.println("Not in any cells"); } else if (found.size() == 1) { // just one parent cell: show it Cell parent = found.iterator().next(); // find the instance in the parent NodeInst theOne = null; for (Iterator<NodeInst> it = parent.getNodes(); it.hasNext(); ) { NodeInst ni = it.next(); if (ni.isCellInstance()) { Cell nodeCell = (Cell)ni.getProto(); if (nodeCell == oldCell || nodeCell.isIconOf(oldCell)) { theOne = ni; break; } } } double newX = offx, newY = offy; if (keepFocus) { Point2D curCtr = new Point2D.Double(offx, offy); AffineTransform up = theOne.rotateOut(theOne.translateOut()); up.transform(curCtr, curCtr); newX = curCtr.getX(); newY = curCtr.getY(); } WindowFrame.DisplayAttributes da = new WindowFrame.DisplayAttributes(getScale(), newX, newY, new ArrayList<NodeInst>()); setCell(parent, VarContext.globalContext, da); if (!keepFocus) fillScreen(); // highlight instance if (theOne != null) { if (selectedExport != null) highlighter.addElectricObject(theOne.findPortInstFromProto(selectedExport), parent); else highlighter.addElectricObject(theOne, parent); highlighter.finished(); } SelectObject.selectObjectDialog(parent, true); } else { // prompt the user to choose a parent cell // BUG #436: The following code creates and displays a popup menu // with a list of cell names caused by an ambiguous "Up Hierarchy" command. // The popup does not allow the up/down arrows to scroll through it. // Unfortunately, this is a known bug in Java's JPopupMenu object. // I also tried: JPopupMenu.setDefaultLightWeightPopupEnabled(false); JPopupMenu parents = new JPopupMenu("parents"); for(Cell parent : found) { String cellName = parent.describe(false); JMenuItem menuItem = new JMenuItem(cellName); menuItem.addActionListener(new UpHierarchyPopupListener(keepFocus)); parents.add(menuItem); } parents.show(overall, 0, 0); } } catch (NullPointerException e) { ActivityLogger.logException(e); } } private class UpHierarchyPopupListener implements ActionListener { private boolean keepFocus; UpHierarchyPopupListener(boolean k) { keepFocus = k; } /** * Respond to an action performed, in this case change the current cell * when the user clicks on an entry in the upHierarchy popup menu. */ public void actionPerformed(ActionEvent e) { JMenuItem source = (JMenuItem)e.getSource(); // extract library and cell from string Cell cell = (Cell)Cell.findNodeProto(source.getText()); if (cell == null) return; Cell currentCell = getCell(); // find one of these nodes in the upper cell NodeInst theOne = null; for (Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); ) { NodeInst ni = it.next(); if (ni.isCellInstance()) { Cell nodeCell = (Cell)ni.getProto(); if (nodeCell == currentCell) { theOne = ni; break; } if (nodeCell.isIconOf(currentCell)) { theOne = ni; break; } } } double newX = offx, newY = offy; if (keepFocus) { Point2D curCtr = new Point2D.Double(offx, offy); AffineTransform up = theOne.rotateOut(theOne.translateOut()); up.transform(curCtr, curCtr); newX = curCtr.getX(); newY = curCtr.getY(); } WindowFrame.DisplayAttributes da = new WindowFrame.DisplayAttributes(getScale(), newX, newY, new ArrayList<NodeInst>()); setCell(cell, VarContext.globalContext, da); if (!keepFocus) fillScreen(); // Highlight an instance of cell we came from in current cell highlighter.clear(); if (theOne != null) highlighter.addElectricObject(theOne, cell); highlighter.finished(); } } /** * Method to clear the cache of expanded subcells. * This is used by layer visibility which, when changed, causes everything to be redrawn. */ public static void clearSubCellCache() { AbstractDrawing.clearSubCellCache(); } /** * Handles database changes of a Job. * @param oldSnapshot database snapshot before Job. * @param newSnapshot database snapshot after Job and constraint propagation. * @param undoRedo true if Job was Undo/Redo job. */ private static void endBatch(Snapshot oldSnapshot, Snapshot newSnapshot) { // Mark cells for redraw Set<CellId> topCells = new HashSet<CellId>(); for(Iterator<WindowFrame> wit = WindowFrame.getWindows(); wit.hasNext(); ) { WindowFrame wf = wit.next(); WindowContent content = wf.getContent(); if (!(content instanceof EditWindow)) continue; Cell winCell = content.getCell(); if (winCell == null) continue; if (!winCell.isLinked()) continue; topCells.add(winCell.getId()); } Set<CellId> changedVisibility = VectorCache.theCache.forceRedrawAfterChange(topCells); for (CellId cellId: changedVisibility) { Cell cell = VectorCache.theCache.database.getCell(cellId); EditWindow.forceRedraw(cell); } for(Iterator<WindowFrame> wit = WindowFrame.getWindows(); wit.hasNext(); ) { WindowFrame wf = wit.next(); WindowContent content = wf.getContent(); if (!(content instanceof EditWindow)) continue; Cell winCell = content.getCell(); if (winCell == null) continue; EditWindow wnd = (EditWindow)content; if (changedVisibility.contains(winCell.getId())) wnd.fullRepaint(); } } /** * Method to recurse flag all windows showing a cell to redraw. * @param cell the Cell that changed. */ public static void expansionChanged(Cell cell) { if (User.getDisplayAlgorithm() != 0) return; Set<Cell> marked = new HashSet<Cell>(); markCellForRedrawRecursively(cell, marked); for(Iterator<WindowFrame> wit = WindowFrame.getWindows(); wit.hasNext(); ) { WindowFrame wf = wit.next(); WindowContent content = wf.getContent(); if (!(content instanceof EditWindow)) continue; Cell winCell = content.getCell(); if (marked.contains(winCell)) { EditWindow wnd = (EditWindow)content; wnd.fullRepaint(); } } } private static void markCellForRedrawRecursively(Cell cell, Set<Cell> marked) { if (marked.contains(cell)) return; marked.add(cell); // recurse up the hierarchy so that all windows showing the cell get redrawn for(Iterator<NodeInst> it = cell.getInstancesOf(); it.hasNext(); ) { NodeInst ni = it.next(); if (ni.isExpanded()) markCellForRedrawRecursively(ni.getParent(), marked); } } private static void forceRedraw(Cell cell) { AbstractDrawing.forceRedraw(cell); } // ************************************* COORDINATES ************************************* /** * Method to convert a screen coordinate to database coordinates. * @param screenX the X coordinate (on the screen in this EditWindow). * @param screenY the Y coordinate (on the screen in this EditWindow). * @return the coordinate of that point in database units. */ public Point2D screenToDatabase(int screenX, int screenY) { double dbX = (screenX - szHalfWidth) / scale + offx; double dbY = (szHalfHeight - screenY) / scale + offy; Point2D dbPt = new Point2D.Double(dbX, dbY); // if doing in-place display, transform into the proper cell if (inPlaceDisplay) intoCell.transform(dbPt, dbPt); return dbPt; } /** * Method to convert a rectangle in screen units to a rectangle in * database units. * @param screenRect the rectangle to convert * @return the same rectangle in database units */ public Rectangle2D screenToDatabase(Rectangle2D screenRect) { Point2D anchor = screenToDatabase((int)screenRect.getX(), (int)screenRect.getY()); Point2D size = deltaScreenToDatabase((int)screenRect.getWidth(), (int)screenRect.getHeight()); // note that lower left corner in screen units is upper left corner in db units, so // compensate for that here return new Rectangle2D.Double(anchor.getX(), anchor.getY()+size.getY(), size.getX(), -size.getY()); } /** * Method to convert a screen distance to a database distance. * @param screenDX the X coordinate change (on the screen in this EditWindow). * @param screenDY the Y coordinate change (on the screen in this EditWindow). * @return the distance in database units. */ public Point2D deltaScreenToDatabase(int screenDX, int screenDY) { Point2D origin = screenToDatabase(0, 0); Point2D pt = screenToDatabase(screenDX, screenDY); return new Point2D.Double(pt.getX() - origin.getX(), pt.getY() - origin.getY()); } /** * Method to convert a database coordinate to screen coordinates. * @param dbX the X coordinate (in database units). * @param dbY the Y coordinate (in database units). * @param result the Point in which to store the screen coordinates. */ public void databaseToScreen(double dbX, double dbY, Point result) { // if doing in-place display, transform out of the proper cell if (inPlaceDisplay) { Point2D dbPt = new Point2D.Double(dbX, dbY); outofCell.transform(dbPt, dbPt); dbX = dbPt.getX(); dbY = dbPt.getY(); } double scrX = szHalfWidth + (dbX - offx) * scale; double scrY = szHalfHeight - (dbY - offy) * scale; result.x = (int)(scrX >= 0 ? scrX + 0.5 : scrX - 0.5); result.y = (int)(scrY >= 0 ? scrY + 0.5 : scrY - 0.5); } /** * Method to convert a database coordinate to screen coordinates. * @param dbX the X coordinate (in database units). * @param dbY the Y coordinate (in database units). * @return the coordinate on the screen. */ public Point databaseToScreen(double dbX, double dbY) { Point result = new Point(); databaseToScreen(dbX, dbY, result); return result; } /** * Method to convert a database coordinate to screen coordinates. * @param db the coordinate (in database units). * @return the coordinate on the screen. */ public Point databaseToScreen(Point2D db) { return databaseToScreen(db.getX(), db.getY()); } /** * Method to convert a database rectangle to screen coordinates. * @param db the rectangle (in database units). * @return the rectangle on the screen. */ public Rectangle databaseToScreen(Rectangle2D db) { Point llPt = databaseToScreen(db.getMinX(), db.getMinY()); Point urPt = databaseToScreen(db.getMaxX(), db.getMaxY()); int screenLX = llPt.x; int screenHX = urPt.x; int screenLY = llPt.y; int screenHY = urPt.y; if (screenHX < screenLX) { int swap = screenHX; screenHX = screenLX; screenLX = swap; } if (screenHY < screenLY) { int swap = screenHY; screenHY = screenLY; screenLY = swap; } return new Rectangle(screenLX, screenLY, screenHX-screenLX+1, screenHY-screenLY+1); } /** * Method to convert a database distance to a screen distance. * @param dbDX the X change (in database units). * @param dbDY the Y change (in database units). * @return the distance on the screen. */ public Point deltaDatabaseToScreen(double dbDX, double dbDY) { Point origin = databaseToScreen(0, 0); Point pt = databaseToScreen(dbDX, dbDY); return new Point(pt.x - origin.x, pt.y - origin.y); } /** * Method to snap a point to the nearest database-space grid unit. * @param pt the point to be snapped. */ public static void gridAlign(Point2D pt) { DBMath.gridAlign(pt, User.getAlignmentToGrid()); } /** * Method to snap a point to the nearest database-space grid unit. * @param pt the point to be snapped. * @param direction -1 if X and Y coordinates, 0 if only X and 1 if only Y */ public static void gridAlignSize(Point2D pt, int direction) { DBMath.gridAlign(pt, User.getAlignmentToGrid(), direction); } // ************************************* TEXT ************************************* /** * Method to find the size in database units for text of a given point size in this EditWindow. * The scale of this EditWindow is used to determine the acutal unit size. * @param pointSize the size of the text in points. * @return the database size (in grid units) of the text. */ public double getTextUnitSize(double pointSize) { return pointSize / scale; } /** * Method to find the size in points (actual screen units) for text of a given database size in this EditWindow. * The scale of this EditWindow is used to determine the acutal screen size. * @param dbSize the size of the text in database grid-units. * @return the screen size (in points) of the text. */ public double getTextScreenSize(double dbSize) { return dbSize * scale; } public static int getDefaultFontSize() { return TextDescriptor.getDefaultFontSize(); } /** * Method to get a Font to use for a given TextDescriptor in this EditWindow. * @param descript the TextDescriptor. * @return the Font to use (returns null if the text is too small to display). */ public Font getFont(TextDescriptor descript) { return descript != null ? descript.getFont(this, PixelDrawing.MINIMUMTEXTSIZE) : TextDescriptor.getDefaultFont(); } /** * Method to get the height of text given a TextDescriptor in this EditWindow. * @param descript the TextDescriptor. * @return the height of the text. */ public double getFontHeight(TextDescriptor descript) { double size = getDefaultFontSize(); if (descript != null) size = descript.getTrueSize(this); return size; } /** * Method to convert a string and descriptor to a GlyphVector. * @param text the string to convert. * @param font the Font to use. * @return a GlyphVector describing the text. */ public GlyphVector getGlyphs(String text, Font font) { // make a glyph vector for the desired text return TextDescriptor.getGlyphs(text, font); } public void databaseChanged(DatabaseChangeEvent e) { if (cell != null && e.objectChanged(cell)) setWindowTitle(); // if cell was deleted, set cell to null if (cell != null && !cell.isLinked()) { showCell(null, VarContext.globalContext, true, null); wf.cellHistoryGoBack(); } // recalculate text positions textInCell = null; } /** * Method to export directly PNG file. * @param ep printable object. * @param filePath */ public void writeImage(ElectricPrinter ep, String filePath) { BufferedImage img = getPrintImage(ep); PNG.writeImage(img, filePath); } /** * Method to intialize for printing. * @param ep the ElectricPrinter object. * @param pageFormat information about the print job. * @return Always true. */ public boolean initializePrinting(ElectricPrinter ep, PageFormat pageFormat) { int scaleFactor = ep.getDesiredDPI() / 72; if (scaleFactor > 2) scaleFactor = 2; else if (scaleFactor <= 0) scaleFactor = 1; int pageWid = (int)pageFormat.getImageableWidth() * scaleFactor; int pageHei = (int)pageFormat.getImageableHeight() * scaleFactor; setSize(pageWid, pageHei); validate(); repaint(); return true; } /** * Method to print window using offscreen canvas. * @param ep printable object. * @return the image to print (null on error). */ public BufferedImage getPrintImage(ElectricPrinter ep) { if (getCell() == null) return null; int scaleFactor = ep.getDesiredDPI() / 72; if (scaleFactor > 2) scaleFactor = 2; else if (scaleFactor <= 0) scaleFactor = 1; int wid = (int)ep.getPageFormat().getImageableWidth() * scaleFactor; int hei = (int)ep.getPageFormat().getImageableHeight() * scaleFactor; BufferedImage img = ep.getBufferedImage(); if (img == null) { // change window size PixelDrawing offscreen = new PixelDrawing(new Dimension(wid, hei)); // prepare for printing PrinterJob pj = ep.getPrintJob(); if (pj == null) { System.out.println("Can't get PrintJob in getPrintImage()"); return null; } PrintService ps = pj.getPrintService(); if (ps == null) { System.out.println("Can't get PrintService in getPrintImage()"); return null; } ColorSupported cs = ps.getAttribute(ColorSupported.class); int printMode = 1; if (cs == null || cs.getValue() == 0) printMode = 2; offscreen.setPrintingMode(printMode); offscreen.setBackgroundColor(Color.WHITE); int oldBackgroundColor = User.getColor(User.ColorPrefType.BACKGROUND); User.setColor(User.ColorPrefType.BACKGROUND, 0xFFFFFF); // initialize drawing Rectangle2D cellBounds = ep.getRenderArea(); if (cellBounds == null) cellBounds = getBoundsInWindow(); cellBounds = new Rectangle2D.Double(cellBounds.getMinX()-1, cellBounds.getMinY()-1, cellBounds.getWidth()+2, cellBounds.getHeight()+2); double width = cellBounds.getWidth(); double height = cellBounds.getHeight(); if (width == 0) width = 2; if (height == 0) height = 2; double scalex = wid/width; double scaley = hei/height; double scale = Math.min(scalex, scaley); EPoint offset = new EPoint(cellBounds.getCenterX(), cellBounds.getCenterY()); offscreen.printImage(scale, offset, getCell(), getVarContext()); img = offscreen.getBufferedImage(); ep.setBufferedImage(img); // restore display state offscreen.setPrintingMode(0); User.setColor(User.ColorPrefType.BACKGROUND, oldBackgroundColor); } // copy the image to the page if graphics is not null Graphics2D g2d = (Graphics2D)ep.getGraphics(); if (g2d != null) { AffineTransform saveAT = g2d.getTransform(); int ix = (int)ep.getPageFormat().getImageableX() * scaleFactor; int iy = (int)ep.getPageFormat().getImageableY() * scaleFactor; g2d.scale(1.0 / scaleFactor, 1.0 / scaleFactor); g2d.drawImage(img, ix, iy, null); // save window factors Point2D saveOffset = getOffset(); double saveScale = scale; int saveHalfWid = szHalfWidth; int saveHalfHei = szHalfHeight; // compute proper window factors to center the frame Rectangle2D cellBounds = getBoundsInWindow(); double width = cellBounds.getWidth(); double height = cellBounds.getHeight(); if (width == 0) width = 2; if (height == 0) height = 2; scale = scaleRequested = Math.min(wid/width, hei/height); offx = offy = offxRequested = offyRequested = 0; szHalfWidth = ix + wid / 2; szHalfHeight = iy + hei / 2; // draw the frame g2d.setColor(Color.BLACK); drawCellFrame(g2d); // restore window factors scale = scaleRequested = saveScale; szHalfWidth = saveHalfWid; szHalfHeight = saveHalfHei; offx = offxRequested = saveOffset.getX(); offy = offyRequested = saveOffset.getY(); g2d.setTransform(saveAT); } return img; } /** * Method to pan along X or Y according to fixed amount of ticks * @param direction 0 is X and 1 is Y * @param panningAmounts * @param ticks */ public void panXOrY(int direction, double[] panningAmounts, int ticks) { Cell cell = getCell(); if (cell == null) return; Dimension dim = getSize(); double panningAmount = panningAmounts[User.getPanningDistance()]; double value = (direction == 0) ? dim.width : dim.height; int mult = (int)(value * panningAmount / getScale()); if (mult == 0) mult = 1; Point2D wndOffset = getOffset(); Point2D newOffset = (direction == 0) ? new Point2D.Double(wndOffset.getX() - mult*ticks, wndOffset.getY()) : new Point2D.Double(wndOffset.getX(), wndOffset.getY() - mult*ticks); setOffset(newOffset); getSavedFocusBrowser().updateCurrentFocus(); fullRepaint(); } /** * Method to shift the window so that the current cursor location becomes the center. */ public void centerCursor() { Point pt = getLastMousePosition(); Point2D center = screenToDatabase(pt.x, pt.y); setOffset(center); getSavedFocusBrowser().updateCurrentFocus(); fullRepaint(); } }
true
true
public void upHierarchy(boolean keepFocus) { if (cell == null) return; Cell oldCell = cell; // determine which export is selected so it can be shown in the upper level Export selectedExport = null; Set<Network> nets = highlighter.getHighlightedNetworks(); for(Network net : nets) { for(Iterator<Export> eIt = net.getExports(); eIt.hasNext(); ) { Export e = eIt.next(); selectedExport = e; break; } if (selectedExport != null) break; } try { Nodable no = cellVarContext.getNodable(); if (no != null) { Cell parent = no.getParent(); // see if this was in history, if so, restore offset and scale // search backwards to get most recent entry // search history **before** calling setCell, otherwise we find // the history record for the cell we just switched to VarContext context = cellVarContext.pop(); int historyIndex = wf.findCellHistoryIndex(parent, context); if (historyIndex >= 0) { // found previous in cell history: show it WindowFrame.CellHistory foundHistory = wf.getCellHistoryList().get(historyIndex); foundHistory.setContext(context); if (selectedExport != null) foundHistory.setSelPort(no.getNodeInst().findPortInstFromProto(selectedExport)); if (keepFocus) { double newX = offx, newY = offy; if (!inPlaceDisplay) { Point2D curCtr = new Point2D.Double(offx, offy); AffineTransform up = no.getNodeInst().rotateOut(no.getNodeInst().translateOut()); up.transform(curCtr, curCtr); newX = curCtr.getX(); newY = curCtr.getY(); } List<NodeInst> oldInPlaceDescent = foundHistory.getDisplayAttributes().inPlaceDescent; foundHistory.setDisplayAttributes(new WindowFrame.DisplayAttributes(scale, newX, newY, oldInPlaceDescent)); } wf.setCellByHistory(historyIndex); } else { // no previous history: make one up List<NodeInst> newInPlaceDescent = new ArrayList<NodeInst>(inPlaceDescent); if (!newInPlaceDescent.isEmpty()) newInPlaceDescent.remove(newInPlaceDescent.size() - 1); double newX = offx, newY = offy; if (keepFocus) { NodeInst ni = no.getNodeInst(); Point2D curCtr = new Point2D.Double(offx, offy); AffineTransform up = ni.rotateOut(ni.translateOut()); up.transform(curCtr, curCtr); newX = curCtr.getX(); newY = curCtr.getY(); } WindowFrame.DisplayAttributes da = new WindowFrame.DisplayAttributes(scale, newX, newY, newInPlaceDescent); showCell(parent, context, true, da); wf.addToHistory(parent, context, da); // highlight node we came from PortInst pi = null; if (selectedExport != null) pi = no.getNodeInst().findPortInstFromProto(selectedExport); if (pi != null) highlighter.addElectricObject(pi, parent); else highlighter.addElectricObject(no.getNodeInst(), parent); } clearSubCellCache(); // highlight portinst selected at the time, if any SelectObject.selectObjectDialog(parent, true); return; } // no parent - if icon, go to sch view if (cell.isIcon()) { Cell schCell = cell.getEquivalent(); if (schCell != null) { setCell(schCell, VarContext.globalContext, null); SelectObject.selectObjectDialog(schCell, true); return; } } // find all possible parents in all libraries Set<Cell> found = new HashSet<Cell>(); for(Iterator<NodeInst> it = cell.getInstancesOf(); it.hasNext(); ) { NodeInst ni = it.next(); Cell parent = ni.getParent(); if (parent.getLibrary().isHidden()) continue; found.add(parent); } if (cell.isSchematic()) { for(Iterator<Cell> cIt = cell.getCellGroup().getCells(); cIt.hasNext(); ) { Cell iconView = cIt.next(); if (iconView.getView() != View.ICON) continue; for(Iterator<NodeInst> it = iconView.getInstancesOf(); it.hasNext(); ) { NodeInst ni = it.next(); if (ni.isIconOfParent()) continue; Cell parent = ni.getParent(); if (parent.getLibrary().isHidden()) continue; found.add(parent); } } } // see what was found if (found.size() == 0) { // no parent cell System.out.println("Not in any cells"); } else if (found.size() == 1) { // just one parent cell: show it Cell parent = found.iterator().next(); // find the instance in the parent NodeInst theOne = null; for (Iterator<NodeInst> it = parent.getNodes(); it.hasNext(); ) { NodeInst ni = it.next(); if (ni.isCellInstance()) { Cell nodeCell = (Cell)ni.getProto(); if (nodeCell == oldCell || nodeCell.isIconOf(oldCell)) { theOne = ni; break; } } } double newX = offx, newY = offy; if (keepFocus) { Point2D curCtr = new Point2D.Double(offx, offy); AffineTransform up = theOne.rotateOut(theOne.translateOut()); up.transform(curCtr, curCtr); newX = curCtr.getX(); newY = curCtr.getY(); } WindowFrame.DisplayAttributes da = new WindowFrame.DisplayAttributes(getScale(), newX, newY, new ArrayList<NodeInst>()); setCell(parent, VarContext.globalContext, da); if (!keepFocus) fillScreen(); // highlight instance if (theOne != null) { if (selectedExport != null) highlighter.addElectricObject(theOne.findPortInstFromProto(selectedExport), parent); else highlighter.addElectricObject(theOne, parent); highlighter.finished(); } SelectObject.selectObjectDialog(parent, true); } else { // prompt the user to choose a parent cell // BUG #436: The following code creates and displays a popup menu // with a list of cell names caused by an ambiguous "Up Hierarchy" command. // The popup does not allow the up/down arrows to scroll through it. // Unfortunately, this is a known bug in Java's JPopupMenu object. // I also tried: JPopupMenu.setDefaultLightWeightPopupEnabled(false); JPopupMenu parents = new JPopupMenu("parents"); for(Cell parent : found) { String cellName = parent.describe(false); JMenuItem menuItem = new JMenuItem(cellName); menuItem.addActionListener(new UpHierarchyPopupListener(keepFocus)); parents.add(menuItem); } parents.show(overall, 0, 0); } } catch (NullPointerException e) { ActivityLogger.logException(e); } }
public void upHierarchy(boolean keepFocus) { if (cell == null) return; Cell oldCell = cell; // determine which export is selected so it can be shown in the upper level Export selectedExport = null; Set<Network> nets = highlighter.getHighlightedNetworks(); for(Network net : nets) { for(Iterator<Export> eIt = net.getExports(); eIt.hasNext(); ) { Export e = eIt.next(); selectedExport = e; break; } if (selectedExport != null) break; } try { Nodable no = cellVarContext.getNodable(); if (no != null && no.getNodeInst().isLinked()) { Cell parent = no.getParent(); // see if this was in history, if so, restore offset and scale // search backwards to get most recent entry // search history **before** calling setCell, otherwise we find // the history record for the cell we just switched to VarContext context = cellVarContext.pop(); int historyIndex = wf.findCellHistoryIndex(parent, context); if (historyIndex >= 0) { // found previous in cell history: show it WindowFrame.CellHistory foundHistory = wf.getCellHistoryList().get(historyIndex); foundHistory.setContext(context); if (selectedExport != null) foundHistory.setSelPort(no.getNodeInst().findPortInstFromProto(selectedExport)); if (keepFocus) { double newX = offx, newY = offy; if (!inPlaceDisplay) { Point2D curCtr = new Point2D.Double(offx, offy); AffineTransform up = no.getNodeInst().rotateOut(no.getNodeInst().translateOut()); up.transform(curCtr, curCtr); newX = curCtr.getX(); newY = curCtr.getY(); } List<NodeInst> oldInPlaceDescent = foundHistory.getDisplayAttributes().inPlaceDescent; foundHistory.setDisplayAttributes(new WindowFrame.DisplayAttributes(scale, newX, newY, oldInPlaceDescent)); } wf.setCellByHistory(historyIndex); } else { // no previous history: make one up List<NodeInst> newInPlaceDescent = new ArrayList<NodeInst>(inPlaceDescent); if (!newInPlaceDescent.isEmpty()) newInPlaceDescent.remove(newInPlaceDescent.size() - 1); double newX = offx, newY = offy; if (keepFocus) { NodeInst ni = no.getNodeInst(); Point2D curCtr = new Point2D.Double(offx, offy); AffineTransform up = ni.rotateOut(ni.translateOut()); up.transform(curCtr, curCtr); newX = curCtr.getX(); newY = curCtr.getY(); } WindowFrame.DisplayAttributes da = new WindowFrame.DisplayAttributes(scale, newX, newY, newInPlaceDescent); showCell(parent, context, true, da); wf.addToHistory(parent, context, da); // highlight node we came from PortInst pi = null; if (selectedExport != null) pi = no.getNodeInst().findPortInstFromProto(selectedExport); if (pi != null) highlighter.addElectricObject(pi, parent); else highlighter.addElectricObject(no.getNodeInst(), parent); } clearSubCellCache(); // highlight portinst selected at the time, if any SelectObject.selectObjectDialog(parent, true); return; } // no parent - if icon, go to sch view if (cell.isIcon()) { Cell schCell = cell.getEquivalent(); if (schCell != null) { setCell(schCell, VarContext.globalContext, null); SelectObject.selectObjectDialog(schCell, true); return; } } // find all possible parents in all libraries Set<Cell> found = new HashSet<Cell>(); for(Iterator<NodeInst> it = cell.getInstancesOf(); it.hasNext(); ) { NodeInst ni = it.next(); Cell parent = ni.getParent(); if (parent.getLibrary().isHidden()) continue; found.add(parent); } if (cell.isSchematic()) { for(Iterator<Cell> cIt = cell.getCellGroup().getCells(); cIt.hasNext(); ) { Cell iconView = cIt.next(); if (iconView.getView() != View.ICON) continue; for(Iterator<NodeInst> it = iconView.getInstancesOf(); it.hasNext(); ) { NodeInst ni = it.next(); if (ni.isIconOfParent()) continue; Cell parent = ni.getParent(); if (parent.getLibrary().isHidden()) continue; found.add(parent); } } } // see what was found if (found.size() == 0) { // no parent cell System.out.println("Not in any cells"); } else if (found.size() == 1) { // just one parent cell: show it Cell parent = found.iterator().next(); // find the instance in the parent NodeInst theOne = null; for (Iterator<NodeInst> it = parent.getNodes(); it.hasNext(); ) { NodeInst ni = it.next(); if (ni.isCellInstance()) { Cell nodeCell = (Cell)ni.getProto(); if (nodeCell == oldCell || nodeCell.isIconOf(oldCell)) { theOne = ni; break; } } } double newX = offx, newY = offy; if (keepFocus) { Point2D curCtr = new Point2D.Double(offx, offy); AffineTransform up = theOne.rotateOut(theOne.translateOut()); up.transform(curCtr, curCtr); newX = curCtr.getX(); newY = curCtr.getY(); } WindowFrame.DisplayAttributes da = new WindowFrame.DisplayAttributes(getScale(), newX, newY, new ArrayList<NodeInst>()); setCell(parent, VarContext.globalContext, da); if (!keepFocus) fillScreen(); // highlight instance if (theOne != null) { if (selectedExport != null) highlighter.addElectricObject(theOne.findPortInstFromProto(selectedExport), parent); else highlighter.addElectricObject(theOne, parent); highlighter.finished(); } SelectObject.selectObjectDialog(parent, true); } else { // prompt the user to choose a parent cell // BUG #436: The following code creates and displays a popup menu // with a list of cell names caused by an ambiguous "Up Hierarchy" command. // The popup does not allow the up/down arrows to scroll through it. // Unfortunately, this is a known bug in Java's JPopupMenu object. // I also tried: JPopupMenu.setDefaultLightWeightPopupEnabled(false); JPopupMenu parents = new JPopupMenu("parents"); for(Cell parent : found) { String cellName = parent.describe(false); JMenuItem menuItem = new JMenuItem(cellName); menuItem.addActionListener(new UpHierarchyPopupListener(keepFocus)); parents.add(menuItem); } parents.show(overall, 0, 0); } } catch (NullPointerException e) { ActivityLogger.logException(e); } }
diff --git a/workspace/jPad/src/edu/iastate/se339/text/WordTokenizerDecorator.java b/workspace/jPad/src/edu/iastate/se339/text/WordTokenizerDecorator.java index 5ca2241..f029c5a 100644 --- a/workspace/jPad/src/edu/iastate/se339/text/WordTokenizerDecorator.java +++ b/workspace/jPad/src/edu/iastate/se339/text/WordTokenizerDecorator.java @@ -1,35 +1,38 @@ package edu.iastate.se339.text; import java.util.StringTokenizer; public class WordTokenizerDecorator extends AbstractDecorator{ private String delimiter; private int wordsPerLine; public WordTokenizerDecorator(AbstractRepresentation component, String delimiter, int wordsPerLine){ super(component); this.delimiter = delimiter; this.wordsPerLine = wordsPerLine; } public WordTokenizerDecorator(AbstractRepresentation component) { this(component, " ", 4); } @Override public String toString() { String in = component.toString(); StringTokenizer tok = new StringTokenizer(in, delimiter); StringBuilder sb = new StringBuilder(); int i = 0; while(tok.hasMoreTokens()){ sb.append(tok.nextToken()); if(++i % wordsPerLine == 0){ sb.append("\n"); } + else{ + sb.append(delimiter); + } } return sb.toString(); } }
true
true
public String toString() { String in = component.toString(); StringTokenizer tok = new StringTokenizer(in, delimiter); StringBuilder sb = new StringBuilder(); int i = 0; while(tok.hasMoreTokens()){ sb.append(tok.nextToken()); if(++i % wordsPerLine == 0){ sb.append("\n"); } } return sb.toString(); }
public String toString() { String in = component.toString(); StringTokenizer tok = new StringTokenizer(in, delimiter); StringBuilder sb = new StringBuilder(); int i = 0; while(tok.hasMoreTokens()){ sb.append(tok.nextToken()); if(++i % wordsPerLine == 0){ sb.append("\n"); } else{ sb.append(delimiter); } } return sb.toString(); }
diff --git a/portal-util/util/src/java/org/sakaiproject/portal/util/ErrorReporter.java b/portal-util/util/src/java/org/sakaiproject/portal/util/ErrorReporter.java index de916db2..bc327009 100644 --- a/portal-util/util/src/java/org/sakaiproject/portal/util/ErrorReporter.java +++ b/portal-util/util/src/java/org/sakaiproject/portal/util/ErrorReporter.java @@ -1,721 +1,726 @@ /********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2006 The Sakai Foundation. * * Licensed under the Educational Community License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ package org.sakaiproject.portal.util; import java.io.IOException; import java.io.PrintWriter; import java.security.MessageDigest; import java.util.Enumeration; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.sakaiproject.component.cover.ServerConfigurationService; import org.sakaiproject.email.cover.EmailService; import org.sakaiproject.event.api.UsageSession; import org.sakaiproject.event.cover.UsageSessionService; import org.sakaiproject.time.api.Time; import org.sakaiproject.time.cover.TimeService; import org.sakaiproject.tool.api.Placement; import org.sakaiproject.tool.cover.SessionManager; import org.sakaiproject.tool.cover.ToolManager; import org.sakaiproject.user.api.User; import org.sakaiproject.user.cover.UserDirectoryService; import org.sakaiproject.util.FormattedText; import org.sakaiproject.util.ResourceLoader; /** * <p> * ErrorReporter helps with end-user formatted error reporting, user feedback * collection, logging and emailing for uncaught throwable based errors. * </p> */ public class ErrorReporter { /** Our log (commons). */ private static Log M_log = LogFactory.getLog(ErrorReporter.class); /** messages. */ private static ResourceLoader rb = new ResourceLoader("portal-util"); public ErrorReporter() { } /** Following two methods borrowed from RWikiObjectImpl.java * */ private static MessageDigest shatemplate = null; public static String computeSha1(String content) { String digest = ""; try { if (shatemplate == null) { shatemplate = MessageDigest.getInstance("SHA"); } MessageDigest shadigest = (MessageDigest) shatemplate.clone(); byte[] bytedigest = shadigest.digest(content.getBytes("UTF8")); digest = byteArrayToHexStr(bytedigest); } catch (Exception ex) { System.err.println("Unable to create SHA hash of content"); ex.printStackTrace(); } return digest; } private static String byteArrayToHexStr(byte[] data) { String output = ""; String tempStr = ""; int tempInt = 0; for (int cnt = 0; cnt < data.length; cnt++) { // Deposit a byte into the 8 lsb of an int. tempInt = data[cnt] & 0xFF; // Get hex representation of the int as a // string. tempStr = Integer.toHexString(tempInt); // Append a leading 0 if necessary so that // each hex string will contain two // characters. if (tempStr.length() == 1) tempStr = "0" + tempStr; // Concatenate the two characters to the // output string. output = output + tempStr; }// end for loop return output.toUpperCase(); }// end byteArrayToHexStr /** * Format the full stack trace. * * @param t * The throwable. * @return A display of the full stack trace for the throwable. */ protected String getStackTrace(Throwable t) { StackTraceElement[] st = t.getStackTrace(); StringBuilder buf = new StringBuilder(); if (st != null) { for (int i = 0; i < st.length; i++) { buf.append("\n at " + st[i].getClassName() + "." + st[i].getMethodName() + "(" + ((st[i].isNativeMethod()) ? "Native Method" : (st[i] .getFileName() + ":" + st[i].getLineNumber())) + ")"); } buf.append("\n"); } return buf.toString(); } /** * Format a one-level stack trace, just showing the place where the * exception occurred (the first entry in the stack trace). * * @param t * The throwable. * @return A display of the first stack trace entry for the throwable. */ protected String getOneTrace(Throwable t) { StackTraceElement[] st = t.getStackTrace(); StringBuilder buf = new StringBuilder(); if (st != null && st.length > 0) { buf.append("\n at " + st[1].getClassName() + "." + st[1].getMethodName() + "(" + ((st[1].isNativeMethod()) ? "Native Method" : (st[1].getFileName() + ":" + st[1].getLineNumber())) + ")\n"); } return buf.toString(); } /** * Compute the cause of a throwable, checking for the special * ServletException case, and the points-to-self case. * * @param t * The throwable. * @return The cause of the throwable, or null if there is none. */ protected Throwable getCause(Throwable t) { Throwable rv = null; // ServletException is non-standard if (t instanceof ServletException) { rv = ((ServletException) t).getRootCause(); } // try for the standard cause if (rv == null) rv = t.getCause(); // clear it if the cause is pointing at the throwable if ((rv != null) && (rv == t)) rv = null; return rv; } /** * Format a throwable for display: list the various throwables drilling down * the cause, and full stacktrack for the final cause. * * @param t * The throwable. * @return The string display of the throwable. */ protected String throwableDisplay(Throwable t) { StringBuilder buf = new StringBuilder(); buf.append(t.toString() + ((getCause(t) == null) ? (getStackTrace(t)) : getOneTrace(t))); while (getCause(t) != null) { t = getCause(t); buf.append("caused by: "); buf.append(t.toString() + ((getCause(t) == null) ? (getStackTrace(t)) : getOneTrace(t))); } return buf.toString(); } /** * Log and email the error report details. * * @param usageSessionId * The end-user's usage session id. * @param userId * The end-user's user id. * @param time * The time of the error. * @param problem * The stacktrace of the error. * @param problemdigest * The sha1 digest of the stacktrace. * @param requestURI * The request URI. * @param userReport * The end user comments. * @param object * @param placementDisplay */ protected void logAndMail(String usageSessionId, String userId, String time, String problem, String problemdigest, String requestURI, String userReport) { logAndMail(usageSessionId, userId, time, problem, problemdigest, requestURI, "", "", userReport); } protected void logAndMail(String usageSessionId, String userId, String time, String problem, String problemdigest, String requestURI, String requestDisplay, String placementDisplay, String userReport) { // log M_log.warn(rb.getString("bugreport.bugreport") + " " + rb.getString("bugreport.user") + ": " + userId + " " + rb.getString("bugreport.usagesession") + ": " + usageSessionId + " " + rb.getString("bugreport.time") + ": " + time + " " + rb.getString("bugreport.usercomment") + ": " + userReport + " " + rb.getString("bugreport.stacktrace") + "\n" + problem + "\n" + placementDisplay + "\n" + requestDisplay); // mail String emailAddr = ServerConfigurationService.getString("portal.error.email"); if (emailAddr != null) { String uSessionInfo = ""; UsageSession usageSession = UsageSessionService.getSession(); if (usageSession != null) { uSessionInfo = rb.getString("bugreport.useragent") + ": " + usageSession.getUserAgent() + "\n" + rb.getString("bugreport.browserid") + ": " + usageSession.getBrowserId() + "\n" + rb.getString("bugreport.ip") + ": " + usageSession.getIpAddress() + "\n"; } String pathInfo = ""; if (requestURI != null) { pathInfo = rb.getString("bugreport.path") + ": " + requestURI + "\n"; } User user = null; String userName = null; String userMail = null; String userEid = null; if (userId != null) { try { user = UserDirectoryService.getUser(userId); userName = user.getDisplayName(); userMail = user.getEmail(); userEid = user.getEid(); } catch (Exception e) { // nothing } } String subject = rb.getString("bugreport.bugreport") + ": " + problemdigest + " / " + usageSessionId; String userComment = ""; if (userReport != null) { userComment = rb.getString("bugreport.usercomment") + ":\n\n" + userReport + "\n\n\n"; subject = subject + " " + rb.getString("bugreport.commentflag"); } String from = "\"" + ServerConfigurationService.getString("ui.service", "Sakai") + "\"<no-reply@" + ServerConfigurationService.getServerName() + ">"; String body = rb.getString("bugreport.user") + ": " + userEid + " (" + userName + ")\n" + rb.getString("bugreport.email") + ": " + userMail + "\n" + rb.getString("bugreport.usagesession") + ": " + usageSessionId + "\n" + rb.getString("bugreport.digest") + ": " + problemdigest + "\n" + rb.getString("bugreport.version-sakai") + ": " + ServerConfigurationService.getString("version.sakai") + "\n" + rb.getString("bugreport.version-service") + ": " + ServerConfigurationService.getString("version.service") + "\n" + rb.getString("bugreport.appserver") + ": " + ServerConfigurationService.getServerId() + "\n" + uSessionInfo + pathInfo + rb.getString("bugreport.time") + ": " + time + "\n\n\n" + userComment + rb.getString("bugreport.stacktrace") + ":\n\n" + problem + "\n\n" + placementDisplay + "\n\n" + requestDisplay; EmailService.send(from, emailAddr, subject, body, emailAddr, null, null); } } /** * Handle the inital report of an error, from an uncaught throwable, with a * user display. * * @param req * The request. * @param res * The response. * @param t * The uncaught throwable. */ public void report(HttpServletRequest req, HttpServletResponse res, Throwable t) { String headInclude = (String) req.getAttribute("sakai.html.head"); String bodyOnload = (String) req.getAttribute("sakai.html.body.onload"); Time reportTime = TimeService.newTime(); String time = reportTime.toStringLocalDate() + " " + reportTime.toStringLocalTime24(); String usageSessionId = UsageSessionService.getSessionId(); String userId = SessionManager.getCurrentSessionUserId(); String requestDisplay = requestDisplay(req); String placementDisplay = placementDisplay(); String problem = throwableDisplay(t); String problemdigest = computeSha1(problem); String postAddr = ServerConfigurationService.getPortalUrl() + "/error-report"; String requestURI = req.getRequestURI(); if (bodyOnload == null) { bodyOnload = ""; } else { bodyOnload = " onload=\"" + bodyOnload + "\""; } try { // headers res.setContentType("text/html; charset=UTF-8"); res.addDateHeader("Expires", System.currentTimeMillis() - (1000L * 60L * 60L * 24L * 365L)); res.addDateHeader("Last-Modified", System.currentTimeMillis()); res .addHeader("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0"); res.addHeader("Pragma", "no-cache"); - PrintWriter out = res.getWriter(); + PrintWriter out = null; + try { + out = res.getWriter(); + } catch (Exception ex ) { + out = new PrintWriter(res.getOutputStream()); + } out .println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">"); out .println("<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xml:lang=\"en\">"); if (headInclude != null) { out.println("<head>"); out.println(headInclude); out.println("</head>"); } out.println("<body" + bodyOnload + ">"); out.println("<div class=\"portletBody\">"); out.println("<h3>" + rb.getString("bugreport.error") + "</h3>"); out.println("<p>" + rb.getString("bugreport.statement") + "<br /><br /></p>"); out.println("<h4>" + rb.getString("bugreport.sendtitle") + "</h4>"); out.println("<p>" + rb.getString("bugreport.sendinstructions") + "</p>"); out.println("<form action=\"" + postAddr + "\" method=\"POST\">"); out.println("<input type=\"hidden\" name=\"problem\" value=\""); out.println(FormattedText.escapeHtml(problem, false)); out.println("\">"); out.println("<input type=\"hidden\" name=\"problemRequest\" value=\""); out.println(FormattedText.escapeHtml(requestDisplay, false)); out.println("\">"); out.println("<input type=\"hidden\" name=\"problemPlacement\" value=\""); out.println(FormattedText.escapeHtml(placementDisplay, false)); out.println("\">"); out.println("<input type=\"hidden\" name=\"problemdigest\" value=\"" + FormattedText.escapeHtml(problemdigest, false) + "\">"); out.println("<input type=\"hidden\" name=\"session\" value=\"" + FormattedText.escapeHtml(usageSessionId, false) + "\">"); out.println("<input type=\"hidden\" name=\"user\" value=\"" + FormattedText.escapeHtml(userId, false) + "\">"); out.println("<input type=\"hidden\" name=\"time\" value=\"" + FormattedText.escapeHtml(time, false) + "\">"); out .println("<table class=\"itemSummary\" cellspacing=\"5\" cellpadding=\"5\">"); out.println("<tbody>"); out.println("<tr>"); out .println("<td><textarea rows=\"10\" cols=\"60\" name=\"comment\"></textarea></td>"); out.println("</tr>"); out.println("</tbody>"); out.println("</table>"); out.println("<div class=\"act\">"); out.println("<input type=\"submit\" value=\"" + rb.getString("bugreport.sendsubmit") + "\">"); out.println("</div>"); out.println("</form><br />"); out.println("<h4>" + rb.getString("bugreport.recoverytitle") + "</h4>"); out.println("<p>" + rb.getString("bugreport.recoveryinstructions") + ""); out.println("<ul><li>" + rb.getString("bugreport.recoveryinstructions1") + "</li>"); out.println("<li>" + rb.getString("bugreport.recoveryinstructions2") + "</li>"); out.println("<li>" + rb.getString("bugreport.recoveryinstructions3") + "</li></ul><br /><br /></p>"); out.println("<h4>" + rb.getString("bugreport.detailstitle") + "</h4>"); out.println("<p>" + rb.getString("bugreport.detailsnote") + "</p>"); out.println("<p><pre>"); out.println(FormattedText.escapeHtml(problem, false)); out.println(); out.println(rb.getString("bugreport.user") + ": " + FormattedText.escapeHtml(userId, false) + "\n"); out.println(rb.getString("bugreport.usagesession") + ": " + FormattedText.escapeHtml(usageSessionId, false) + "\n"); out.println(rb.getString("bugreport.time") + ": " + FormattedText.escapeHtml(time, false) + "\n"); out.println("</pre></p>"); out.println("</body>"); out.println("</html>"); // log and send the preliminary email logAndMail(usageSessionId, userId, time, problem, problemdigest, requestURI, requestDisplay, placementDisplay, null); } catch (Throwable any) { M_log.warn(rb.getString("bugreport.troublereporting"), any); } } private String placementDisplay() { StringBuilder sb = new StringBuilder(); try { Placement p = ToolManager.getCurrentPlacement(); if (p != null) { sb.append(rb.getString("bugreport.placement")).append("\n"); sb.append(rb.getString("bugreport.placement.id")).append(p.getToolId()) .append("\n"); sb.append(rb.getString("bugreport.placement.context")).append( p.getContext()).append("\n"); sb.append(rb.getString("bugreport.placement.title")).append(p.getTitle()) .append("\n"); } else { sb.append(rb.getString("bugreport.placement")).append("\n"); sb.append(rb.getString("bugreport.placement.none")).append("\n"); } } catch (Exception ex) { M_log.error("Failed to generate placement display", ex); sb.append("Error " + ex.getMessage()); } return sb.toString(); } private String requestDisplay(HttpServletRequest request) { StringBuilder sb = new StringBuilder(); try { sb.append(rb.getString("bugreport.request")).append("\n"); sb.append(rb.getString("bugreport.request.authtype")).append( request.getAuthType()).append("\n"); sb.append(rb.getString("bugreport.request.charencoding")).append( request.getCharacterEncoding()).append("\n"); sb.append(rb.getString("bugreport.request.contentlength")).append( request.getContentLength()).append("\n"); sb.append(rb.getString("bugreport.request.contenttype")).append( request.getContentType()).append("\n"); sb.append(rb.getString("bugreport.request.contextpath")).append( request.getContextPath()).append("\n"); sb.append(rb.getString("bugreport.request.localaddr")).append( request.getLocalAddr()).append("\n"); sb.append(rb.getString("bugreport.request.localname")).append( request.getLocalName()).append("\n"); sb.append(rb.getString("bugreport.request.localport")).append( request.getLocalPort()).append("\n"); sb.append(rb.getString("bugreport.request.method")).append( request.getMethod()).append("\n"); sb.append(rb.getString("bugreport.request.pathinfo")).append( request.getPathInfo()).append("\n"); sb.append(rb.getString("bugreport.request.protocol")).append( request.getProtocol()).append("\n"); sb.append(rb.getString("bugreport.request.querystring")).append( request.getQueryString()).append("\n"); sb.append(rb.getString("bugreport.request.remoteaddr")).append( request.getRemoteAddr()).append("\n"); sb.append(rb.getString("bugreport.request.remotehost")).append( request.getRemoteHost()).append("\n"); sb.append(rb.getString("bugreport.request.remoteport")).append( request.getRemotePort()).append("\n"); sb.append(rb.getString("bugreport.request.remoteuser")).append( request.getRemoteUser()).append("\n"); sb.append(rb.getString("bugreport.request.requestedsession")).append( request.getRequestedSessionId()).append("\n"); sb.append(rb.getString("bugreport.request.requesturl")).append( request.getRequestURL()).append("\n"); sb.append(rb.getString("bugreport.request.scheme")).append( request.getScheme()).append("\n"); sb.append(rb.getString("bugreport.request.servername")).append( request.getServerName()).append("\n"); sb.append(rb.getString("bugreport.request.headers")).append("\n"); for (Enumeration e = request.getHeaderNames(); e.hasMoreElements();) { String headerName = (String) e.nextElement(); for (Enumeration he = request.getHeaders(headerName); he .hasMoreElements();) { String headerValue = (String) he.nextElement(); sb.append(rb.getString("bugreport.request.header")) .append(headerName).append(":").append(headerValue).append( "\n"); } } sb.append(rb.getString("bugreport.request.parameters")).append("\n"); for (Enumeration e = request.getParameterNames(); e.hasMoreElements();) { String parameterName = (String) e.nextElement(); String[] paramvalues = request.getParameterValues(parameterName); for (int i = 0; i < paramvalues.length; i++) { sb.append(rb.getString("bugreport.request.parameter")).append( parameterName).append(":").append(i).append(":").append( paramvalues[i]).append("\n"); } } sb.append(rb.getString("bugreport.request.attributes")).append("\n"); for (Enumeration e = request.getAttributeNames(); e.hasMoreElements();) { String attributeName = (String) e.nextElement(); Object attribute = request.getAttribute(attributeName); sb.append(rb.getString("bugreport.request.attribute")).append( attributeName).append(":").append(attribute).append("\n"); } HttpSession session = request.getSession(false); if (session != null) { sb.append(rb.getString("bugreport.session")).append("\n"); sb.append(rb.getString("bugreport.session.creation")).append( session.getCreationTime()).append("\n"); sb.append(rb.getString("bugreport.session.lastaccess")).append( session.getLastAccessedTime()).append("\n"); sb.append(rb.getString("bugreport.session.maxinactive")).append( session.getMaxInactiveInterval()).append("\n"); sb.append(rb.getString("bugreport.session.attributes")).append("\n"); for (Enumeration e = session.getAttributeNames(); e.hasMoreElements();) { String attributeName = (String) e.nextElement(); Object attribute = session.getAttribute(attributeName); sb.append(rb.getString("bugreport.session.attribute")).append( attributeName).append(":").append(attribute).append("\n"); } } } catch (Exception ex) { M_log.error("Failed to generate request display", ex); sb.append("Error " + ex.getMessage()); } return sb.toString(); } /** * Accept the user feedback post. * * @param req * The request. * @param res * The response. */ public void postResponse(HttpServletRequest req, HttpServletResponse res) { String session = req.getParameter("session"); String user = req.getParameter("user"); String time = req.getParameter("time"); String comment = req.getParameter("comment"); String problem = req.getParameter("problem"); String problemdigest = req.getParameter("problemdigest"); String problemRequest = req.getParameter("problemRequest"); String problemPlacement = req.getParameter("problemPlacement"); // log and send the followup email logAndMail(session, user, time, problem, problemdigest, null, problemRequest, problemPlacement, comment); // always redirect from a post try { res.sendRedirect(res.encodeRedirectURL(ServerConfigurationService .getPortalUrl() + "/error-reported")); } catch (IOException e) { M_log.warn(rb.getString("bugreport.troubleredirecting"), e); } } /** * Accept the user feedback post. * * @param req * The request. * @param res * The response. */ public void thanksResponse(HttpServletRequest req, HttpServletResponse res) { String headInclude = (String) req.getAttribute("sakai.html.head"); String bodyOnload = (String) req.getAttribute("sakai.html.body.onload"); if (bodyOnload == null) { bodyOnload = ""; } else { bodyOnload = " onload=\"" + bodyOnload + "\""; } try { // headers res.setContentType("text/html; charset=UTF-8"); res.addDateHeader("Expires", System.currentTimeMillis() - (1000L * 60L * 60L * 24L * 365L)); res.addDateHeader("Last-Modified", System.currentTimeMillis()); res .addHeader("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0"); res.addHeader("Pragma", "no-cache"); PrintWriter out = res.getWriter(); out .println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">"); out .println("<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xml:lang=\"en\">"); if (headInclude != null) { out.println("<head>"); out.println(headInclude); out.println("</head>"); } out.println("<body" + bodyOnload + ">"); out.println("<div class=\"portletBody\">"); out.println("<h3>" + rb.getString("bugreport.error") + "</h3>"); out.println("<p>" + rb.getString("bugreport.statement") + "<br /><br /></p>"); out.println("<h4>" + rb.getString("bugreport.senttitle") + "</h4>"); out.println("<p>" + rb.getString("bugreport.sentnote") + "<br /><br /></p>"); out.println("<h4>" + rb.getString("bugreport.recoverytitle") + "</h4>"); out.println("<p>" + rb.getString("bugreport.recoveryinstructions") + ""); out.println("<ul><li>" + rb.getString("bugreport.recoveryinstructions1") + "</li>"); out.println("<li>" + rb.getString("bugreport.recoveryinstructions2") + "</li>"); out.println("<li>" + rb.getString("bugreport.recoveryinstructions3") + "</li></ul><br /><br /></p>"); out.println("</body>"); out.println("</html>"); } catch (Throwable any) { M_log.warn(rb.getString("bugreport.troublethanks"), any); } } }
true
true
public void report(HttpServletRequest req, HttpServletResponse res, Throwable t) { String headInclude = (String) req.getAttribute("sakai.html.head"); String bodyOnload = (String) req.getAttribute("sakai.html.body.onload"); Time reportTime = TimeService.newTime(); String time = reportTime.toStringLocalDate() + " " + reportTime.toStringLocalTime24(); String usageSessionId = UsageSessionService.getSessionId(); String userId = SessionManager.getCurrentSessionUserId(); String requestDisplay = requestDisplay(req); String placementDisplay = placementDisplay(); String problem = throwableDisplay(t); String problemdigest = computeSha1(problem); String postAddr = ServerConfigurationService.getPortalUrl() + "/error-report"; String requestURI = req.getRequestURI(); if (bodyOnload == null) { bodyOnload = ""; } else { bodyOnload = " onload=\"" + bodyOnload + "\""; } try { // headers res.setContentType("text/html; charset=UTF-8"); res.addDateHeader("Expires", System.currentTimeMillis() - (1000L * 60L * 60L * 24L * 365L)); res.addDateHeader("Last-Modified", System.currentTimeMillis()); res .addHeader("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0"); res.addHeader("Pragma", "no-cache"); PrintWriter out = res.getWriter(); out .println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">"); out .println("<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xml:lang=\"en\">"); if (headInclude != null) { out.println("<head>"); out.println(headInclude); out.println("</head>"); } out.println("<body" + bodyOnload + ">"); out.println("<div class=\"portletBody\">"); out.println("<h3>" + rb.getString("bugreport.error") + "</h3>"); out.println("<p>" + rb.getString("bugreport.statement") + "<br /><br /></p>"); out.println("<h4>" + rb.getString("bugreport.sendtitle") + "</h4>"); out.println("<p>" + rb.getString("bugreport.sendinstructions") + "</p>"); out.println("<form action=\"" + postAddr + "\" method=\"POST\">"); out.println("<input type=\"hidden\" name=\"problem\" value=\""); out.println(FormattedText.escapeHtml(problem, false)); out.println("\">"); out.println("<input type=\"hidden\" name=\"problemRequest\" value=\""); out.println(FormattedText.escapeHtml(requestDisplay, false)); out.println("\">"); out.println("<input type=\"hidden\" name=\"problemPlacement\" value=\""); out.println(FormattedText.escapeHtml(placementDisplay, false)); out.println("\">"); out.println("<input type=\"hidden\" name=\"problemdigest\" value=\"" + FormattedText.escapeHtml(problemdigest, false) + "\">"); out.println("<input type=\"hidden\" name=\"session\" value=\"" + FormattedText.escapeHtml(usageSessionId, false) + "\">"); out.println("<input type=\"hidden\" name=\"user\" value=\"" + FormattedText.escapeHtml(userId, false) + "\">"); out.println("<input type=\"hidden\" name=\"time\" value=\"" + FormattedText.escapeHtml(time, false) + "\">"); out .println("<table class=\"itemSummary\" cellspacing=\"5\" cellpadding=\"5\">"); out.println("<tbody>"); out.println("<tr>"); out .println("<td><textarea rows=\"10\" cols=\"60\" name=\"comment\"></textarea></td>"); out.println("</tr>"); out.println("</tbody>"); out.println("</table>"); out.println("<div class=\"act\">"); out.println("<input type=\"submit\" value=\"" + rb.getString("bugreport.sendsubmit") + "\">"); out.println("</div>"); out.println("</form><br />"); out.println("<h4>" + rb.getString("bugreport.recoverytitle") + "</h4>"); out.println("<p>" + rb.getString("bugreport.recoveryinstructions") + ""); out.println("<ul><li>" + rb.getString("bugreport.recoveryinstructions1") + "</li>"); out.println("<li>" + rb.getString("bugreport.recoveryinstructions2") + "</li>"); out.println("<li>" + rb.getString("bugreport.recoveryinstructions3") + "</li></ul><br /><br /></p>"); out.println("<h4>" + rb.getString("bugreport.detailstitle") + "</h4>"); out.println("<p>" + rb.getString("bugreport.detailsnote") + "</p>"); out.println("<p><pre>"); out.println(FormattedText.escapeHtml(problem, false)); out.println(); out.println(rb.getString("bugreport.user") + ": " + FormattedText.escapeHtml(userId, false) + "\n"); out.println(rb.getString("bugreport.usagesession") + ": " + FormattedText.escapeHtml(usageSessionId, false) + "\n"); out.println(rb.getString("bugreport.time") + ": " + FormattedText.escapeHtml(time, false) + "\n"); out.println("</pre></p>"); out.println("</body>"); out.println("</html>"); // log and send the preliminary email logAndMail(usageSessionId, userId, time, problem, problemdigest, requestURI, requestDisplay, placementDisplay, null); } catch (Throwable any) { M_log.warn(rb.getString("bugreport.troublereporting"), any); } }
public void report(HttpServletRequest req, HttpServletResponse res, Throwable t) { String headInclude = (String) req.getAttribute("sakai.html.head"); String bodyOnload = (String) req.getAttribute("sakai.html.body.onload"); Time reportTime = TimeService.newTime(); String time = reportTime.toStringLocalDate() + " " + reportTime.toStringLocalTime24(); String usageSessionId = UsageSessionService.getSessionId(); String userId = SessionManager.getCurrentSessionUserId(); String requestDisplay = requestDisplay(req); String placementDisplay = placementDisplay(); String problem = throwableDisplay(t); String problemdigest = computeSha1(problem); String postAddr = ServerConfigurationService.getPortalUrl() + "/error-report"; String requestURI = req.getRequestURI(); if (bodyOnload == null) { bodyOnload = ""; } else { bodyOnload = " onload=\"" + bodyOnload + "\""; } try { // headers res.setContentType("text/html; charset=UTF-8"); res.addDateHeader("Expires", System.currentTimeMillis() - (1000L * 60L * 60L * 24L * 365L)); res.addDateHeader("Last-Modified", System.currentTimeMillis()); res .addHeader("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0"); res.addHeader("Pragma", "no-cache"); PrintWriter out = null; try { out = res.getWriter(); } catch (Exception ex ) { out = new PrintWriter(res.getOutputStream()); } out .println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">"); out .println("<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xml:lang=\"en\">"); if (headInclude != null) { out.println("<head>"); out.println(headInclude); out.println("</head>"); } out.println("<body" + bodyOnload + ">"); out.println("<div class=\"portletBody\">"); out.println("<h3>" + rb.getString("bugreport.error") + "</h3>"); out.println("<p>" + rb.getString("bugreport.statement") + "<br /><br /></p>"); out.println("<h4>" + rb.getString("bugreport.sendtitle") + "</h4>"); out.println("<p>" + rb.getString("bugreport.sendinstructions") + "</p>"); out.println("<form action=\"" + postAddr + "\" method=\"POST\">"); out.println("<input type=\"hidden\" name=\"problem\" value=\""); out.println(FormattedText.escapeHtml(problem, false)); out.println("\">"); out.println("<input type=\"hidden\" name=\"problemRequest\" value=\""); out.println(FormattedText.escapeHtml(requestDisplay, false)); out.println("\">"); out.println("<input type=\"hidden\" name=\"problemPlacement\" value=\""); out.println(FormattedText.escapeHtml(placementDisplay, false)); out.println("\">"); out.println("<input type=\"hidden\" name=\"problemdigest\" value=\"" + FormattedText.escapeHtml(problemdigest, false) + "\">"); out.println("<input type=\"hidden\" name=\"session\" value=\"" + FormattedText.escapeHtml(usageSessionId, false) + "\">"); out.println("<input type=\"hidden\" name=\"user\" value=\"" + FormattedText.escapeHtml(userId, false) + "\">"); out.println("<input type=\"hidden\" name=\"time\" value=\"" + FormattedText.escapeHtml(time, false) + "\">"); out .println("<table class=\"itemSummary\" cellspacing=\"5\" cellpadding=\"5\">"); out.println("<tbody>"); out.println("<tr>"); out .println("<td><textarea rows=\"10\" cols=\"60\" name=\"comment\"></textarea></td>"); out.println("</tr>"); out.println("</tbody>"); out.println("</table>"); out.println("<div class=\"act\">"); out.println("<input type=\"submit\" value=\"" + rb.getString("bugreport.sendsubmit") + "\">"); out.println("</div>"); out.println("</form><br />"); out.println("<h4>" + rb.getString("bugreport.recoverytitle") + "</h4>"); out.println("<p>" + rb.getString("bugreport.recoveryinstructions") + ""); out.println("<ul><li>" + rb.getString("bugreport.recoveryinstructions1") + "</li>"); out.println("<li>" + rb.getString("bugreport.recoveryinstructions2") + "</li>"); out.println("<li>" + rb.getString("bugreport.recoveryinstructions3") + "</li></ul><br /><br /></p>"); out.println("<h4>" + rb.getString("bugreport.detailstitle") + "</h4>"); out.println("<p>" + rb.getString("bugreport.detailsnote") + "</p>"); out.println("<p><pre>"); out.println(FormattedText.escapeHtml(problem, false)); out.println(); out.println(rb.getString("bugreport.user") + ": " + FormattedText.escapeHtml(userId, false) + "\n"); out.println(rb.getString("bugreport.usagesession") + ": " + FormattedText.escapeHtml(usageSessionId, false) + "\n"); out.println(rb.getString("bugreport.time") + ": " + FormattedText.escapeHtml(time, false) + "\n"); out.println("</pre></p>"); out.println("</body>"); out.println("</html>"); // log and send the preliminary email logAndMail(usageSessionId, userId, time, problem, problemdigest, requestURI, requestDisplay, placementDisplay, null); } catch (Throwable any) { M_log.warn(rb.getString("bugreport.troublereporting"), any); } }
diff --git a/src/main/java/com/google/gerrit/client/data/SparseFileContent.java b/src/main/java/com/google/gerrit/client/data/SparseFileContent.java index d22612744..358692dc2 100644 --- a/src/main/java/com/google/gerrit/client/data/SparseFileContent.java +++ b/src/main/java/com/google/gerrit/client/data/SparseFileContent.java @@ -1,153 +1,153 @@ // Copyright (C) 2009 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.client.data; import java.util.ArrayList; import java.util.List; public class SparseFileContent { protected List<Range> ranges; protected int size; protected boolean missingNewlineAtEnd; private transient int currentRangeIdx; public SparseFileContent() { ranges = new ArrayList<Range>(); } public int size() { return size; } public void setSize(final int s) { size = s; } public boolean isMissingNewlineAtEnd() { return missingNewlineAtEnd; } public void setMissingNewlineAtEnd(final boolean missing) { missingNewlineAtEnd = missing; } public String get(final int idx) { final String line = getLine(idx); if (line == null) { throw new ArrayIndexOutOfBoundsException(idx); } return line; } public boolean contains(final int idx) { return getLine(idx) != null; } private String getLine(final int idx) { // Most requests are sequential in nature, fetching the next // line from the current range, or the next range. // int high = ranges.size(); if (currentRangeIdx < high) { Range cur = ranges.get(currentRangeIdx); if (cur.contains(idx)) { return cur.get(idx); } if (++currentRangeIdx < high) { final Range next = ranges.get(currentRangeIdx); if (next.contains(idx)) { return next.get(idx); } } } // Binary search for the range, since we know its a sorted list. // int low = 0; do { final int mid = (low + high) / 2; final Range cur = ranges.get(mid); if (cur.contains(idx)) { currentRangeIdx = mid; return cur.get(idx); } - if (cur.base < idx) + if (idx < cur.base) high = mid; else low = mid + 1; } while (low < high); return null; } public void addLine(final int i, final String content) { final Range r; if (!ranges.isEmpty() && i == last().end()) { r = last(); } else { r = new Range(i); ranges.add(r); } r.lines.add(content); } private Range last() { return ranges.get(ranges.size() - 1); } @Override public String toString() { final StringBuilder b = new StringBuilder(); b.append("SparseFileContent[\n"); for (Range r : ranges) { b.append(" "); b.append(r.toString()); b.append('\n'); } b.append("]"); return b.toString(); } static class Range { protected int base; protected List<String> lines; private Range(final int b) { base = b; lines = new ArrayList<String>(); } protected Range() { } private String get(final int i) { return lines.get(i - base); } private int end() { return base + lines.size(); } private boolean contains(final int i) { return base <= i && i < end(); } @Override public String toString() { return "Range[" + base + "," + end() + ")"; } } }
true
true
private String getLine(final int idx) { // Most requests are sequential in nature, fetching the next // line from the current range, or the next range. // int high = ranges.size(); if (currentRangeIdx < high) { Range cur = ranges.get(currentRangeIdx); if (cur.contains(idx)) { return cur.get(idx); } if (++currentRangeIdx < high) { final Range next = ranges.get(currentRangeIdx); if (next.contains(idx)) { return next.get(idx); } } } // Binary search for the range, since we know its a sorted list. // int low = 0; do { final int mid = (low + high) / 2; final Range cur = ranges.get(mid); if (cur.contains(idx)) { currentRangeIdx = mid; return cur.get(idx); } if (cur.base < idx) high = mid; else low = mid + 1; } while (low < high); return null; }
private String getLine(final int idx) { // Most requests are sequential in nature, fetching the next // line from the current range, or the next range. // int high = ranges.size(); if (currentRangeIdx < high) { Range cur = ranges.get(currentRangeIdx); if (cur.contains(idx)) { return cur.get(idx); } if (++currentRangeIdx < high) { final Range next = ranges.get(currentRangeIdx); if (next.contains(idx)) { return next.get(idx); } } } // Binary search for the range, since we know its a sorted list. // int low = 0; do { final int mid = (low + high) / 2; final Range cur = ranges.get(mid); if (cur.contains(idx)) { currentRangeIdx = mid; return cur.get(idx); } if (idx < cur.base) high = mid; else low = mid + 1; } while (low < high); return null; }
diff --git a/src/org/openstreetmap/josm/plugins/notes/gui/NotesQueueListCellRenderer.java b/src/org/openstreetmap/josm/plugins/notes/gui/NotesQueueListCellRenderer.java index d5ccb7d..6645b4a 100644 --- a/src/org/openstreetmap/josm/plugins/notes/gui/NotesQueueListCellRenderer.java +++ b/src/org/openstreetmap/josm/plugins/notes/gui/NotesQueueListCellRenderer.java @@ -1,88 +1,88 @@ /* Copyright (c) 2013, Ian Dees * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the project nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package org.openstreetmap.josm.plugins.notes.gui; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import javax.swing.Icon; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.ListCellRenderer; import javax.swing.UIManager; import org.openstreetmap.josm.plugins.notes.NotesPlugin; import org.openstreetmap.josm.plugins.notes.gui.action.AddCommentAction; import org.openstreetmap.josm.plugins.notes.gui.action.CloseNoteAction; import org.openstreetmap.josm.plugins.notes.gui.action.NewNoteAction; public class NotesQueueListCellRenderer implements ListCellRenderer { private Color background = Color.WHITE; private Color altBackground = new Color(250, 250, 220); public Component getListCellRendererComponent(JList list, Object action, int index, boolean isSelected, boolean cellHasFocus) { JLabel label = new JLabel(); label.setOpaque(true); if(isSelected) { label.setForeground(UIManager.getColor("List.selectionForeground")); label.setBackground(UIManager.getColor("List.selectionBackground")); } else { label.setForeground(UIManager.getColor("List.foreground")); label.setBackground(index % 2 == 0 ? background : altBackground); } Icon icon = null; if(action instanceof NewNoteAction) { - icon = NotesPlugin.loadIcon("icon_error_add16.png"); + icon = NotesPlugin.loadIcon("new_note16.png"); } else if(action instanceof AddCommentAction) { icon = NotesPlugin.loadIcon("add_comment16.png"); } else if(action instanceof CloseNoteAction) { - icon = NotesPlugin.loadIcon("icon_valid16.png"); + icon = NotesPlugin.loadIcon("closed_note16.png"); } label.setIcon(icon); String text = action.toString(); if(text.indexOf("<hr />") > 0) { text = text.substring(0, text.indexOf("<hr />")); } label.setText("<html>" + text + "</html>"); Dimension d = label.getPreferredSize(); d.height += 10; label.setPreferredSize(d); return label; } }
false
true
public Component getListCellRendererComponent(JList list, Object action, int index, boolean isSelected, boolean cellHasFocus) { JLabel label = new JLabel(); label.setOpaque(true); if(isSelected) { label.setForeground(UIManager.getColor("List.selectionForeground")); label.setBackground(UIManager.getColor("List.selectionBackground")); } else { label.setForeground(UIManager.getColor("List.foreground")); label.setBackground(index % 2 == 0 ? background : altBackground); } Icon icon = null; if(action instanceof NewNoteAction) { icon = NotesPlugin.loadIcon("icon_error_add16.png"); } else if(action instanceof AddCommentAction) { icon = NotesPlugin.loadIcon("add_comment16.png"); } else if(action instanceof CloseNoteAction) { icon = NotesPlugin.loadIcon("icon_valid16.png"); } label.setIcon(icon); String text = action.toString(); if(text.indexOf("<hr />") > 0) { text = text.substring(0, text.indexOf("<hr />")); } label.setText("<html>" + text + "</html>"); Dimension d = label.getPreferredSize(); d.height += 10; label.setPreferredSize(d); return label; }
public Component getListCellRendererComponent(JList list, Object action, int index, boolean isSelected, boolean cellHasFocus) { JLabel label = new JLabel(); label.setOpaque(true); if(isSelected) { label.setForeground(UIManager.getColor("List.selectionForeground")); label.setBackground(UIManager.getColor("List.selectionBackground")); } else { label.setForeground(UIManager.getColor("List.foreground")); label.setBackground(index % 2 == 0 ? background : altBackground); } Icon icon = null; if(action instanceof NewNoteAction) { icon = NotesPlugin.loadIcon("new_note16.png"); } else if(action instanceof AddCommentAction) { icon = NotesPlugin.loadIcon("add_comment16.png"); } else if(action instanceof CloseNoteAction) { icon = NotesPlugin.loadIcon("closed_note16.png"); } label.setIcon(icon); String text = action.toString(); if(text.indexOf("<hr />") > 0) { text = text.substring(0, text.indexOf("<hr />")); } label.setText("<html>" + text + "</html>"); Dimension d = label.getPreferredSize(); d.height += 10; label.setPreferredSize(d); return label; }
diff --git a/fe/src/main/java/com/cloudera/impala/common/JniUtil.java b/fe/src/main/java/com/cloudera/impala/common/JniUtil.java index 4d73f3df..a830828c 100644 --- a/fe/src/main/java/com/cloudera/impala/common/JniUtil.java +++ b/fe/src/main/java/com/cloudera/impala/common/JniUtil.java @@ -1,49 +1,49 @@ // Copyright 2012 Cloudera Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.cloudera.impala.common; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; /** * Utility class with methods intended for JNI clients */ public class JniUtil { /** * Returns a formatted string containing the simple exception name and the * exception message without the full stack trace. Includes the * the chain of causes each in a separate line. * Writes the full stack trace to the log. */ public static String throwableToString(Throwable t) { Writer output = new StringWriter(); try { output.write(String.format("%s: %s", t.getClass().getSimpleName(), t.getMessage())); // Follow the chain of exception causes and print them as well. Throwable cause = t; while ((cause = cause.getCause()) != null) { - output.write(String.format("CAUSED BY: %s: %s", cause.getClass().getSimpleName(), - cause.getMessage())); + output.write(String.format("\nCAUSED BY: %s: %s", + cause.getClass().getSimpleName(), cause.getMessage())); } } catch (IOException e) { throw new Error(e); } return output.toString(); } }
true
true
public static String throwableToString(Throwable t) { Writer output = new StringWriter(); try { output.write(String.format("%s: %s", t.getClass().getSimpleName(), t.getMessage())); // Follow the chain of exception causes and print them as well. Throwable cause = t; while ((cause = cause.getCause()) != null) { output.write(String.format("CAUSED BY: %s: %s", cause.getClass().getSimpleName(), cause.getMessage())); } } catch (IOException e) { throw new Error(e); } return output.toString(); }
public static String throwableToString(Throwable t) { Writer output = new StringWriter(); try { output.write(String.format("%s: %s", t.getClass().getSimpleName(), t.getMessage())); // Follow the chain of exception causes and print them as well. Throwable cause = t; while ((cause = cause.getCause()) != null) { output.write(String.format("\nCAUSED BY: %s: %s", cause.getClass().getSimpleName(), cause.getMessage())); } } catch (IOException e) { throw new Error(e); } return output.toString(); }
diff --git a/src/org/geometerplus/android/fbreader/preferences/ZLStringListPreference.java b/src/org/geometerplus/android/fbreader/preferences/ZLStringListPreference.java index 87e2fc5d..eb913fcb 100644 --- a/src/org/geometerplus/android/fbreader/preferences/ZLStringListPreference.java +++ b/src/org/geometerplus/android/fbreader/preferences/ZLStringListPreference.java @@ -1,72 +1,81 @@ /* * Copyright (C) 2009-2011 Geometer Plus <[email protected]> * * 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 * (at your option) 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., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ package org.geometerplus.android.fbreader.preferences; import android.content.Context; import android.preference.ListPreference; import org.geometerplus.zlibrary.core.resources.ZLResource; abstract class ZLStringListPreference extends ListPreference implements ZLPreference { private final ZLResource myResource; ZLStringListPreference(Context context, ZLResource rootResource, String resourceKey) { super(context); myResource = rootResource.getResource(resourceKey); setTitle(myResource.getValue()); } protected final void setList(String[] values) { String[] texts = new String[values.length]; for (int i = 0; i < values.length; ++i) { final ZLResource resource = myResource.getResource(values[i]); texts[i] = resource.hasValue() ? resource.getValue() : values[i]; } setLists(values, texts); } protected final void setLists(String[] values, String[] texts) { assert(values.length == texts.length); setEntries(texts); setEntryValues(values); } protected final boolean setInitialValue(String value) { - if (value == null || "".equals(value)) { + if (value == null) { return false; } - final int index = findIndexOfValue(value); + // throws NPE in some cases (?) + //final int index = findIndexOfValue(value); + int index = -1; + final CharSequence[] entryValues = getEntryValues(); + for (int i = 0; i < entryValues.length; ++i) { + if (value.equals(entryValues[i])) { + index = i; + break; + } + } if (index >= 0) { setValueIndex(index); setSummary(getEntry()); return true; } return false; } @Override protected void onDialogClosed(boolean result) { super.onDialogClosed(result); if (result) { setSummary(getEntry()); } } }
false
true
protected final boolean setInitialValue(String value) { if (value == null || "".equals(value)) { return false; } final int index = findIndexOfValue(value); if (index >= 0) { setValueIndex(index); setSummary(getEntry()); return true; } return false; }
protected final boolean setInitialValue(String value) { if (value == null) { return false; } // throws NPE in some cases (?) //final int index = findIndexOfValue(value); int index = -1; final CharSequence[] entryValues = getEntryValues(); for (int i = 0; i < entryValues.length; ++i) { if (value.equals(entryValues[i])) { index = i; break; } } if (index >= 0) { setValueIndex(index); setSummary(getEntry()); return true; } return false; }
diff --git a/camera-app/src/main/java/com/sneakysquid/nova/app/TakePhoto.java b/camera-app/src/main/java/com/sneakysquid/nova/app/TakePhoto.java index 46036a5..eb1b454 100644 --- a/camera-app/src/main/java/com/sneakysquid/nova/app/TakePhoto.java +++ b/camera-app/src/main/java/com/sneakysquid/nova/app/TakePhoto.java @@ -1,142 +1,142 @@ package com.sneakysquid.nova.app; import android.app.Activity; import android.hardware.Camera; import com.sneakysquid.nova.link.NovaFlashCallback; import com.sneakysquid.nova.link.NovaFlashCommand; import com.sneakysquid.nova.link.NovaLink; import com.sneakysquid.nova.link.NovaLinkStatus; import static com.sneakysquid.nova.util.Debug.assertOnUiThread; import static com.sneakysquid.nova.util.Debug.debug; /** * Runnable task that implements the asynchronous flow of steps required to take a photo. * <p/> * These are (each step can take some time): * <ul> * <li>Begin auto-focusing camera</li> * <li>Wait for focus, then trigger flash</li> * <li>Wait for flash ack, then take picture</li> * <li>Wait for JPEG, then trigger external PictureCallback</li> * </ul> * * @author Joe Walnes */ public class TakePhoto implements Runnable, Camera.AutoFocusCallback, NovaFlashCallback, Camera.ShutterCallback, Camera.PictureCallback { private final Activity activity; private final Camera camera; private final NovaLink novaLink; private final NovaFlashCommand flashCmd; private final Callback result; public interface Callback { void onPhotoTaken(byte[] jpeg); } public TakePhoto(Activity activity, Camera camera, NovaLink novaLink, NovaFlashCommand flashCmd, Callback result) { this.activity = activity; this.camera = camera; this.novaLink = novaLink; this.flashCmd = flashCmd; this.result = result; } @Override public void run() { takePhoto(); } private void takePhoto() { debug("takePhoto()"); assertOnUiThread(); // Step 1: Auto-focus camera.autoFocus(this); // -> callback: onAutoFocus() } @Override public void onAutoFocus(boolean success, Camera camera) { debug("onAutoFocus(%s)", success); assertOnUiThread(); // TODO: Handle success==false // Step 1: Auto-focus DONE. triggerFlash(); } @SuppressWarnings("ConstantConditions") private void triggerFlash() { debug("triggerFlash(%s)", flashCmd); assertOnUiThread(); if (flashCmd == null || flashCmd.isPointless() || novaLink.getStatus() != NovaLinkStatus.Ready) { // Flash not needed, or not possible. Skip to step 3 and just take the photo. - takePhoto(); + takePicture(); } else { // Step 2: Trigger flash novaLink.flash(flashCmd, this); // -> callback: onNovaFlashAcknowledged } } @Override public void onNovaFlashAcknowledged(boolean success) { debug("onNovaFlashAcknowledged(%s)", success); assertOnUiThread(); // Step 2: Trigger flash DONE // TODO: Handle success==false takePicture(); } private void takePicture() { debug("takePicture()"); assertOnUiThread(); // Step 3: Take picture camera.takePicture(this, null, this); // -> callback: onShutter(), and onPictureTaken() } @Override public void onShutter() { debug("onShutter()"); assertOnUiThread(); // TODO: Shutter finished. Deactivate flash ASAP } @Override public void onPictureTaken(byte[] data, Camera camera) { debug("onPictureTaken()"); assertOnUiThread(); // Step 3: Take picture DONE // Step 4: Call result result.onPhotoTaken(data); } private void delay(final int millis, final Runnable task) { new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(millis); } catch (InterruptedException e) { } activity.runOnUiThread(task); } }).start(); } }
true
true
private void triggerFlash() { debug("triggerFlash(%s)", flashCmd); assertOnUiThread(); if (flashCmd == null || flashCmd.isPointless() || novaLink.getStatus() != NovaLinkStatus.Ready) { // Flash not needed, or not possible. Skip to step 3 and just take the photo. takePhoto(); } else { // Step 2: Trigger flash novaLink.flash(flashCmd, this); // -> callback: onNovaFlashAcknowledged } }
private void triggerFlash() { debug("triggerFlash(%s)", flashCmd); assertOnUiThread(); if (flashCmd == null || flashCmd.isPointless() || novaLink.getStatus() != NovaLinkStatus.Ready) { // Flash not needed, or not possible. Skip to step 3 and just take the photo. takePicture(); } else { // Step 2: Trigger flash novaLink.flash(flashCmd, this); // -> callback: onNovaFlashAcknowledged } }
diff --git a/src/com/android/launcher2/LauncherModel.java b/src/com/android/launcher2/LauncherModel.java index a19eb4c3..a521d67a 100644 --- a/src/com/android/launcher2/LauncherModel.java +++ b/src/com/android/launcher2/LauncherModel.java @@ -1,1480 +1,1484 @@ /* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.launcher2; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProviderInfo; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.ContentProviderClient; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Intent; import android.content.Intent.ShortcutIconResource; import android.content.Context; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ProviderInfo; import android.content.pm.ResolveInfo; import android.content.res.Resources; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Parcelable; import android.os.RemoteException; import android.util.Log; import android.os.Process; import android.os.SystemClock; import java.lang.ref.WeakReference; import java.net.URISyntaxException; import java.text.Collator; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.Collections; import java.util.HashMap; import java.util.List; import com.android.launcher.R; /** * Maintains in-memory state of the Launcher. It is expected that there should be only one * LauncherModel object held in a static. Also provide APIs for updating the database state * for the Launcher. */ public class LauncherModel extends BroadcastReceiver { static final boolean DEBUG_LOADERS = false; static final String TAG = "Launcher.Model"; private int mBatchSize; // 0 is all apps at once private int mAllAppsLoadDelay; // milliseconds between batches private final LauncherApplication mApp; private final Object mLock = new Object(); private DeferredHandler mHandler = new DeferredHandler(); private Loader mLoader = new Loader(); private boolean mBeforeFirstLoad = true; // only access this from main thread private WeakReference<Callbacks> mCallbacks; private AllAppsList mAllAppsList; private IconCache mIconCache; private Bitmap mDefaultIcon; public interface Callbacks { public int getCurrentWorkspaceScreen(); public void startBinding(); public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end); public void bindFolders(HashMap<Long,FolderInfo> folders); public void finishBindingItems(); public void bindAppWidget(LauncherAppWidgetInfo info); public void bindAllApplications(ArrayList<ApplicationInfo> apps); public void bindAppsAdded(ArrayList<ApplicationInfo> apps); public void bindAppsUpdated(ArrayList<ApplicationInfo> apps); public void bindAppsRemoved(ArrayList<ApplicationInfo> apps); } LauncherModel(LauncherApplication app, IconCache iconCache) { mApp = app; mAllAppsList = new AllAppsList(iconCache); mIconCache = iconCache; mDefaultIcon = Utilities.createIconBitmap( app.getPackageManager().getDefaultActivityIcon(), app); mAllAppsLoadDelay = app.getResources().getInteger(R.integer.config_allAppsBatchLoadDelay); mBatchSize = app.getResources().getInteger(R.integer.config_allAppsBatchSize); } public Bitmap getFallbackIcon() { return Bitmap.createBitmap(mDefaultIcon); } /** * Adds an item to the DB if it was not created previously, or move it to a new * <container, screen, cellX, cellY> */ static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container, int screen, int cellX, int cellY) { if (item.container == ItemInfo.NO_ID) { // From all apps addItemToDatabase(context, item, container, screen, cellX, cellY, false); } else { // From somewhere else moveItemInDatabase(context, item, container, screen, cellX, cellY); } } /** * Move an item in the DB to a new <container, screen, cellX, cellY> */ static void moveItemInDatabase(Context context, ItemInfo item, long container, int screen, int cellX, int cellY) { item.container = container; item.screen = screen; item.cellX = cellX; item.cellY = cellY; final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); values.put(LauncherSettings.Favorites.CONTAINER, item.container); values.put(LauncherSettings.Favorites.CELLX, item.cellX); values.put(LauncherSettings.Favorites.CELLY, item.cellY); values.put(LauncherSettings.Favorites.SCREEN, item.screen); cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null); } /** * Returns true if the shortcuts already exists in the database. * we identify a shortcut by its title and intent. */ static boolean shortcutExists(Context context, String title, Intent intent) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { "title", "intent" }, "title=? and intent=?", new String[] { title, intent.toUri(0) }, null); boolean result = false; try { result = c.moveToFirst(); } finally { c.close(); } return result; } /** * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList. */ FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null, "_id=? and (itemType=? or itemType=?)", new String[] { String.valueOf(id), String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER), String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER) }, null); try { if (c.moveToFirst()) { final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE); final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); FolderInfo folderInfo = null; switch (c.getInt(itemTypeIndex)) { case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER: folderInfo = findOrMakeUserFolder(folderList, id); break; case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER: folderInfo = findOrMakeLiveFolder(folderList, id); break; } folderInfo.title = c.getString(titleIndex); folderInfo.id = id; folderInfo.container = c.getInt(containerIndex); folderInfo.screen = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); return folderInfo; } } finally { c.close(); } return null; } /** * Add an item to the database in a specified container. Sets the container, screen, cellX and * cellY fields of the item. Also assigns an ID to the item. */ static void addItemToDatabase(Context context, ItemInfo item, long container, int screen, int cellX, int cellY, boolean notify) { item.container = container; item.screen = screen; item.cellX = cellX; item.cellY = cellY; final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); item.onAddToDatabase(values); Uri result = cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI : LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values); if (result != null) { item.id = Integer.parseInt(result.getPathSegments().get(1)); } } /** * Update an item to the database in a specified container. */ static void updateItemInDatabase(Context context, ItemInfo item) { final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); item.onAddToDatabase(values); cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null); } /** * Removes the specified item from the database * @param context * @param item */ static void deleteItemFromDatabase(Context context, ItemInfo item) { final ContentResolver cr = context.getContentResolver(); cr.delete(LauncherSettings.Favorites.getContentUri(item.id, false), null, null); } /** * Remove the contents of the specified folder from the database */ static void deleteUserFolderContentsFromDatabase(Context context, UserFolderInfo info) { final ContentResolver cr = context.getContentResolver(); cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null); cr.delete(LauncherSettings.Favorites.CONTENT_URI, LauncherSettings.Favorites.CONTAINER + "=" + info.id, null); } /** * Set this as the current Launcher activity object for the loader. */ public void initialize(Callbacks callbacks) { synchronized (mLock) { mCallbacks = new WeakReference<Callbacks>(callbacks); } } public void startLoader(Context context, boolean isLaunching) { mLoader.startLoader(context, isLaunching); } public void stopLoader() { mLoader.stopLoader(); } /** * We pick up most of the changes to all apps. */ public void setAllAppsDirty() { mLoader.setAllAppsDirty(); } public void setWorkspaceDirty() { mLoader.setWorkspaceDirty(); } /** * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and * ACTION_PACKAGE_CHANGED. */ public void onReceive(Context context, Intent intent) { // Use the app as the context. context = mApp; ArrayList<ApplicationInfo> added = null; ArrayList<ApplicationInfo> removed = null; ArrayList<ApplicationInfo> modified = null; synchronized (mLock) { if (mBeforeFirstLoad) { // If we haven't even loaded yet, don't bother, since we'll just pick // up the changes. return; } final String action = intent.getAction(); if (Intent.ACTION_PACKAGE_CHANGED.equals(action) || Intent.ACTION_PACKAGE_REMOVED.equals(action) || Intent.ACTION_PACKAGE_ADDED.equals(action)) { final String packageName = intent.getData().getSchemeSpecificPart(); final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); if (packageName == null || packageName.length() == 0) { // they sent us a bad intent return; } if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) { mAllAppsList.updatePackage(context, packageName); } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) { if (!replacing) { mAllAppsList.removePackage(packageName); } // else, we are replacing the package, so a PACKAGE_ADDED will be sent // later, we will update the package at this time } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) { if (!replacing) { mAllAppsList.addPackage(context, packageName); } else { mAllAppsList.updatePackage(context, packageName); } } if (mAllAppsList.added.size() > 0) { added = mAllAppsList.added; mAllAppsList.added = new ArrayList<ApplicationInfo>(); } if (mAllAppsList.removed.size() > 0) { removed = mAllAppsList.removed; mAllAppsList.removed = new ArrayList<ApplicationInfo>(); for (ApplicationInfo info: removed) { mIconCache.remove(info.intent.getComponent()); } } if (mAllAppsList.modified.size() > 0) { modified = mAllAppsList.modified; mAllAppsList.modified = new ArrayList<ApplicationInfo>(); } final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == null) { Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading."); return; } if (added != null) { final ArrayList<ApplicationInfo> addedFinal = added; mHandler.post(new Runnable() { public void run() { callbacks.bindAppsAdded(addedFinal); } }); } if (modified != null) { final ArrayList<ApplicationInfo> modifiedFinal = modified; mHandler.post(new Runnable() { public void run() { callbacks.bindAppsUpdated(modifiedFinal); } }); } if (removed != null) { final ArrayList<ApplicationInfo> removedFinal = removed; mHandler.post(new Runnable() { public void run() { callbacks.bindAppsRemoved(removedFinal); } }); } } else { if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) { String packages[] = intent.getStringArrayExtra( Intent.EXTRA_CHANGED_PACKAGE_LIST); if (packages == null || packages.length == 0) { return; } setAllAppsDirty(); setWorkspaceDirty(); startLoader(context, false); } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) { String packages[] = intent.getStringArrayExtra( Intent.EXTRA_CHANGED_PACKAGE_LIST); if (packages == null || packages.length == 0) { return; } setAllAppsDirty(); setWorkspaceDirty(); startLoader(context, false); } } } } public class Loader { private static final int ITEMS_CHUNK = 6; private LoaderThread mLoaderThread; private int mLastWorkspaceSeq = 0; private int mWorkspaceSeq = 1; private int mLastAllAppsSeq = 0; private int mAllAppsSeq = 1; final ArrayList<ItemInfo> mItems = new ArrayList<ItemInfo>(); final ArrayList<LauncherAppWidgetInfo> mAppWidgets = new ArrayList<LauncherAppWidgetInfo>(); final HashMap<Long, FolderInfo> mFolders = new HashMap<Long, FolderInfo>(); /** * Call this from the ui thread so the handler is initialized on the correct thread. */ public Loader() { } public void startLoader(Context context, boolean isLaunching) { synchronized (mLock) { if (DEBUG_LOADERS) { Log.d(TAG, "startLoader isLaunching=" + isLaunching); } // Don't bother to start the thread if we know it's not going to do anything if (mCallbacks != null && mCallbacks.get() != null) { LoaderThread oldThread = mLoaderThread; if (oldThread != null) { if (oldThread.isLaunching()) { // don't downgrade isLaunching if we're already running isLaunching = true; } oldThread.stopLocked(); } mLoaderThread = new LoaderThread(context, oldThread, isLaunching); mLoaderThread.start(); } } } public void stopLoader() { synchronized (mLock) { if (mLoaderThread != null) { mLoaderThread.stopLocked(); } } } public void setWorkspaceDirty() { synchronized (mLock) { mWorkspaceSeq++; } } public void setAllAppsDirty() { synchronized (mLock) { mAllAppsSeq++; } } /** * Runnable for the thread that loads the contents of the launcher: * - workspace icons * - widgets * - all apps icons */ private class LoaderThread extends Thread { private Context mContext; private Thread mWaitThread; private boolean mIsLaunching; private boolean mStopped; private boolean mWorkspaceDoneBinding; LoaderThread(Context context, Thread waitThread, boolean isLaunching) { mContext = context; mWaitThread = waitThread; mIsLaunching = isLaunching; } boolean isLaunching() { return mIsLaunching; } /** * If another LoaderThread was supplied, we need to wait for that to finish before * we start our processing. This keeps the ordering of the setting and clearing * of the dirty flags correct by making sure we don't start processing stuff until * they've had a chance to re-set them. We do this waiting the worker thread, not * the ui thread to avoid ANRs. */ private void waitForOtherThread() { if (mWaitThread != null) { boolean done = false; while (!done) { try { mWaitThread.join(); done = true; } catch (InterruptedException ex) { // Ignore } } mWaitThread = null; } } public void run() { waitForOtherThread(); // Elevate priority when Home launches for the first time to avoid // starving at boot time. Staring at a blank home is not cool. synchronized (mLock) { android.os.Process.setThreadPriority(mIsLaunching ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND); } // Load the workspace only if it's dirty. int workspaceSeq; boolean workspaceDirty; synchronized (mLock) { workspaceSeq = mWorkspaceSeq; workspaceDirty = mWorkspaceSeq != mLastWorkspaceSeq; } if (workspaceDirty) { loadWorkspace(); } synchronized (mLock) { // If we're not stopped, and nobody has incremented mWorkspaceSeq. if (mStopped) { return; } if (workspaceSeq == mWorkspaceSeq) { mLastWorkspaceSeq = mWorkspaceSeq; } } // Bind the workspace bindWorkspace(); // Wait until the either we're stopped or the other threads are done. // This way we don't start loading all apps until the workspace has settled // down. synchronized (LoaderThread.this) { mHandler.postIdle(new Runnable() { public void run() { synchronized (LoaderThread.this) { mWorkspaceDoneBinding = true; if (DEBUG_LOADERS) { Log.d(TAG, "done with workspace"); } LoaderThread.this.notify(); } } }); if (DEBUG_LOADERS) { Log.d(TAG, "waiting to be done with workspace"); } while (!mStopped && !mWorkspaceDoneBinding) { try { this.wait(); } catch (InterruptedException ex) { // Ignore } } if (DEBUG_LOADERS) { Log.d(TAG, "done waiting to be done with workspace"); } } // Whew! Hard work done. synchronized (mLock) { if (mIsLaunching) { android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); } } // Load all apps if they're dirty int allAppsSeq; boolean allAppsDirty; synchronized (mLock) { allAppsSeq = mAllAppsSeq; allAppsDirty = mAllAppsSeq != mLastAllAppsSeq; if (DEBUG_LOADERS) { Log.d(TAG, "mAllAppsSeq=" + mAllAppsSeq + " mLastAllAppsSeq=" + mLastAllAppsSeq + " allAppsDirty"); } } if (allAppsDirty) { loadAndBindAllApps(); } synchronized (mLock) { // If we're not stopped, and nobody has incremented mAllAppsSeq. if (mStopped) { return; } if (allAppsSeq == mAllAppsSeq) { mLastAllAppsSeq = mAllAppsSeq; } } // Clear out this reference, otherwise we end up holding it until all of the // callback runnables are done. mContext = null; synchronized (mLock) { // Setting the reference is atomic, but we can't do it inside the other critical // sections. mLoaderThread = null; } } public void stopLocked() { synchronized (LoaderThread.this) { mStopped = true; this.notify(); } } /** * Gets the callbacks object. If we've been stopped, or if the launcher object * has somehow been garbage collected, return null instead. Pass in the Callbacks * object that was around when the deferred message was scheduled, and if there's * a new Callbacks object around then also return null. This will save us from * calling onto it with data that will be ignored. */ Callbacks tryGetCallbacks(Callbacks oldCallbacks) { synchronized (mLock) { if (mStopped) { return null; } if (mCallbacks == null) { return null; } final Callbacks callbacks = mCallbacks.get(); if (callbacks != oldCallbacks) { return null; } if (callbacks == null) { Log.w(TAG, "no mCallbacks"); return null; } return callbacks; } } private void loadWorkspace() { long t = SystemClock.uptimeMillis(); final Context context = mContext; final ContentResolver contentResolver = context.getContentResolver(); final PackageManager manager = context.getPackageManager(); final AppWidgetManager widgets = AppWidgetManager.getInstance(context); final boolean isSafeMode = manager.isSafeMode(); mItems.clear(); mAppWidgets.clear(); mFolders.clear(); final ArrayList<Long> itemsToRemove = new ArrayList<Long>(); final Cursor c = contentResolver.query( LauncherSettings.Favorites.CONTENT_URI, null, null, null, null); try { final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID); final int intentIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.INTENT); final int titleIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.TITLE); final int iconTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_TYPE); final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON); final int iconPackageIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_PACKAGE); final int iconResourceIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_RESOURCE); final int containerIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.CONTAINER); final int itemTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ITEM_TYPE); final int appWidgetIdIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.APPWIDGET_ID); final int screenIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLY); final int spanXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.SPANX); final int spanYIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SPANY); final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI); final int displayModeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.DISPLAY_MODE); ShortcutInfo info; String intentDescription; LauncherAppWidgetInfo appWidgetInfo; int container; long id; Intent intent; while (!mStopped && c.moveToNext()) { try { int itemType = c.getInt(itemTypeIndex); switch (itemType) { case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: intentDescription = c.getString(intentIndex); try { intent = Intent.parseUri(intentDescription, 0); } catch (URISyntaxException e) { continue; } if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) { info = getShortcutInfo(manager, intent, context, c, iconIndex, titleIndex); } else { info = getShortcutInfo(c, context, iconTypeIndex, iconPackageIndex, iconResourceIndex, iconIndex, titleIndex); } if (info != null) { updateSavedIcon(context, info, c, iconIndex); info.intent = intent; info.id = c.getLong(idIndex); container = c.getInt(containerIndex); info.container = container; info.screen = c.getInt(screenIndex); info.cellX = c.getInt(cellXIndex); info.cellY = c.getInt(cellYIndex); switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: mItems.add(info); break; default: // Item is in a user folder UserFolderInfo folderInfo = findOrMakeUserFolder(mFolders, container); folderInfo.add(info); break; } } else { // Failed to load the shortcut, probably because the // activity manager couldn't resolve it (maybe the app // was uninstalled), or the db row was somehow screwed up. // Delete it. id = c.getLong(idIndex); Log.e(TAG, "Error loading shortcut " + id + ", removing it"); contentResolver.delete(LauncherSettings.Favorites.getContentUri( id, false), null, null); } break; case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER: id = c.getLong(idIndex); UserFolderInfo folderInfo = findOrMakeUserFolder(mFolders, id); folderInfo.title = c.getString(titleIndex); folderInfo.id = id; container = c.getInt(containerIndex); folderInfo.container = container; folderInfo.screen = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: mItems.add(folderInfo); break; } mFolders.put(folderInfo.id, folderInfo); break; case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER: id = c.getLong(idIndex); Uri uri = Uri.parse(c.getString(uriIndex)); // Make sure the live folder exists final ProviderInfo providerInfo = context.getPackageManager().resolveContentProvider( uri.getAuthority(), 0); if (providerInfo == null && !isSafeMode) { itemsToRemove.add(id); } else { LiveFolderInfo liveFolderInfo = findOrMakeLiveFolder(mFolders, id); intentDescription = c.getString(intentIndex); intent = null; if (intentDescription != null) { try { intent = Intent.parseUri(intentDescription, 0); } catch (URISyntaxException e) { // Ignore, a live folder might not have a base intent } } liveFolderInfo.title = c.getString(titleIndex); liveFolderInfo.id = id; liveFolderInfo.uri = uri; container = c.getInt(containerIndex); liveFolderInfo.container = container; liveFolderInfo.screen = c.getInt(screenIndex); liveFolderInfo.cellX = c.getInt(cellXIndex); liveFolderInfo.cellY = c.getInt(cellYIndex); liveFolderInfo.baseIntent = intent; liveFolderInfo.displayMode = c.getInt(displayModeIndex); loadLiveFolderIcon(context, c, iconTypeIndex, iconPackageIndex, iconResourceIndex, liveFolderInfo); switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: mItems.add(liveFolderInfo); break; } mFolders.put(liveFolderInfo.id, liveFolderInfo); } break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: // Read all Launcher-specific widget details int appWidgetId = c.getInt(appWidgetIdIndex); id = c.getLong(idIndex); final AppWidgetProviderInfo provider = widgets.getAppWidgetInfo(appWidgetId); if (!isSafeMode && (provider == null || provider.provider == null || provider.provider.getPackageName() == null)) { Log.e(TAG, "Deleting widget that isn't installed anymore: id=" + id + " appWidgetId=" + appWidgetId); itemsToRemove.add(id); } else { appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId); appWidgetInfo.id = id; appWidgetInfo.screen = c.getInt(screenIndex); appWidgetInfo.cellX = c.getInt(cellXIndex); appWidgetInfo.cellY = c.getInt(cellYIndex); appWidgetInfo.spanX = c.getInt(spanXIndex); appWidgetInfo.spanY = c.getInt(spanYIndex); container = c.getInt(containerIndex); if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) { Log.e(TAG, "Widget found where container " + "!= CONTAINER_DESKTOP -- ignoring!"); continue; } appWidgetInfo.container = c.getInt(containerIndex); mAppWidgets.add(appWidgetInfo); } break; } } catch (Exception e) { Log.w(TAG, "Desktop items loading interrupted:", e); } } } finally { c.close(); } if (itemsToRemove.size() > 0) { ContentProviderClient client = contentResolver.acquireContentProviderClient( LauncherSettings.Favorites.CONTENT_URI); // Remove dead items for (long id : itemsToRemove) { if (DEBUG_LOADERS) { Log.d(TAG, "Removed id = " + id); } // Don't notify content observers try { client.delete(LauncherSettings.Favorites.getContentUri(id, false), null, null); } catch (RemoteException e) { Log.w(TAG, "Could not remove id = " + id); } } } if (DEBUG_LOADERS) { Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); } } /** * Read everything out of our database. */ private void bindWorkspace() { final long t = SystemClock.uptimeMillis(); // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderThread running with no launcher"); return; } int N; // Tell the workspace that we're about to start firing items at it mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.startBinding(); } } }); // Add the items to the workspace. N = mItems.size(); for (int i=0; i<N; i+=ITEMS_CHUNK) { final int start = i; final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i); mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindItems(mItems, start, start+chunkSize); } } }); } mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindFolders(mFolders); } } }); // Wait until the queue goes empty. mHandler.postIdle(new Runnable() { public void run() { if (DEBUG_LOADERS) { Log.d(TAG, "Going to start binding widgets soon."); } } }); // Bind the widgets, one at a time. // WARNING: this is calling into the workspace from the background thread, // but since getCurrentScreen() just returns the int, we should be okay. This // is just a hint for the order, and if it's wrong, we'll be okay. // TODO: instead, we should have that push the current screen into here. final int currentScreen = oldCallbacks.getCurrentWorkspaceScreen(); N = mAppWidgets.size(); // once for the current screen for (int i=0; i<N; i++) { final LauncherAppWidgetInfo widget = mAppWidgets.get(i); if (widget.screen == currentScreen) { mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAppWidget(widget); } } }); } } // once for the other screens for (int i=0; i<N; i++) { final LauncherAppWidgetInfo widget = mAppWidgets.get(i); if (widget.screen != currentScreen) { mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAppWidget(widget); } } }); } } // Tell the workspace that we're done. mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.finishBindingItems(); } } }); // If we're profiling, this is the last thing in the queue. mHandler.post(new Runnable() { public void run() { if (DEBUG_LOADERS) { Log.d(TAG, "bound workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); } if (Launcher.PROFILE_ROTATE) { android.os.Debug.stopMethodTracing(); } } }); } private void loadAndBindAllApps() { final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderThread running with no launcher (loadAndBindAllApps)"); return; } final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); final PackageManager packageManager = mContext.getPackageManager(); List<ResolveInfo> apps = null; int N = Integer.MAX_VALUE; int startIndex; int i=0; int batchSize = -1; while (i < N && !mStopped) { synchronized (mLock) { if (i == 0) { // This needs to happen inside the same lock block as when we // prepare the first batch for bindAllApplications. Otherwise // the package changed receiver can come in and double-add // (or miss one?). mAllAppsList.clear(); final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; apps = packageManager.queryIntentActivities(mainIntent, 0); if (DEBUG_LOADERS) { Log.d(TAG, "queryIntentActivities took " + (SystemClock.uptimeMillis()-qiaTime) + "ms"); } if (apps == null) { return; } N = apps.size(); if (DEBUG_LOADERS) { Log.d(TAG, "queryIntentActivities got " + N + " apps"); } if (N == 0) { // There are no apps?!? return; } if (mBatchSize == 0) { batchSize = N; } else { batchSize = mBatchSize; } final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; Collections.sort(apps, new ResolveInfo.DisplayNameComparator(packageManager)); if (DEBUG_LOADERS) { Log.d(TAG, "sort took " + (SystemClock.uptimeMillis()-qiaTime) + "ms"); } } final long t2 = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; startIndex = i; for (int j=0; i<N && j<batchSize; j++) { // This builds the icon bitmaps. mAllAppsList.add(new ApplicationInfo(apps.get(i), mIconCache)); i++; } final boolean first = i <= batchSize; final ArrayList<ApplicationInfo> added = mAllAppsList.added; mAllAppsList.added = new ArrayList<ApplicationInfo>(); mHandler.post(new Runnable() { public void run() { final long t = SystemClock.uptimeMillis(); final Callbacks callbacks = tryGetCallbacks(oldCallbacks); - if (first) { - mBeforeFirstLoad = false; - callbacks.bindAllApplications(added); + if (callbacks != null) { + if (first) { + mBeforeFirstLoad = false; + callbacks.bindAllApplications(added); + } else { + callbacks.bindAppsAdded(added); + } + if (DEBUG_LOADERS) { + Log.d(TAG, "bound " + added.size() + " apps in " + + (SystemClock.uptimeMillis() - t) + "ms"); + } } else { - callbacks.bindAppsAdded(added); - } - if (DEBUG_LOADERS) { - Log.d(TAG, "bound " + added.size() + " apps in " - + (SystemClock.uptimeMillis() - t) + "ms"); + Log.i(TAG, "not binding apps: no Launcher activity"); } } }); if (DEBUG_LOADERS) { Log.d(TAG, "batch of " + (i-startIndex) + " icons processed in " + (SystemClock.uptimeMillis()-t2) + "ms"); } } if (mAllAppsLoadDelay > 0 && i < N) { try { if (DEBUG_LOADERS) { Log.d(TAG, "sleeping for " + mAllAppsLoadDelay + "ms"); } Thread.sleep(mAllAppsLoadDelay); } catch (InterruptedException exc) { } } } if (DEBUG_LOADERS) { Log.d(TAG, "cached all " + N + " apps in " + (SystemClock.uptimeMillis()-t) + "ms" + (mAllAppsLoadDelay > 0 ? " (including delay)" : "")); } } public void dumpState() { Log.d(TAG, "mLoader.mLoaderThread.mContext=" + mContext); Log.d(TAG, "mLoader.mLoaderThread.mWaitThread=" + mWaitThread); Log.d(TAG, "mLoader.mLoaderThread.mIsLaunching=" + mIsLaunching); Log.d(TAG, "mLoader.mLoaderThread.mStopped=" + mStopped); Log.d(TAG, "mLoader.mLoaderThread.mWorkspaceDoneBinding=" + mWorkspaceDoneBinding); } } public void dumpState() { Log.d(TAG, "mLoader.mLastWorkspaceSeq=" + mLoader.mLastWorkspaceSeq); Log.d(TAG, "mLoader.mWorkspaceSeq=" + mLoader.mWorkspaceSeq); Log.d(TAG, "mLoader.mLastAllAppsSeq=" + mLoader.mLastAllAppsSeq); Log.d(TAG, "mLoader.mAllAppsSeq=" + mLoader.mAllAppsSeq); Log.d(TAG, "mLoader.mItems size=" + mLoader.mItems.size()); if (mLoaderThread != null) { mLoaderThread.dumpState(); } else { Log.d(TAG, "mLoader.mLoaderThread=null"); } } } /** * This is called from the code that adds shortcuts from the intent receiver. This * doesn't have a Cursor, but */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) { return getShortcutInfo(manager, intent, context, null, -1, -1); } /** * Make an ShortcutInfo object for a shortcut that is an application. * * If c is not null, then it will be used to fill in missing data like the title and icon. */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context, Cursor c, int iconIndex, int titleIndex) { Bitmap icon = null; final ShortcutInfo info = new ShortcutInfo(); ComponentName componentName = intent.getComponent(); if (componentName == null) { return null; } // TODO: See if the PackageManager knows about this case. If it doesn't // then return null & delete this. // the resource -- This may implicitly give us back the fallback icon, // but don't worry about that. All we're doing with usingFallbackIcon is // to avoid saving lots of copies of that in the database, and most apps // have icons anyway. final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0); if (resolveInfo != null) { icon = mIconCache.getIcon(componentName, resolveInfo); } // the db if (icon == null) { if (c != null) { icon = getIconFromCursor(c, iconIndex); } } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } info.setIcon(icon); // from the resource if (resolveInfo != null) { info.title = resolveInfo.activityInfo.loadLabel(manager); } // from the db if (info.title == null) { if (c != null) { info.title = c.getString(titleIndex); } } // fall back to the class name of the activity if (info.title == null) { info.title = componentName.getClassName(); } info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION; return info; } /** * Make an ShortcutInfo object for a shortcut that isn't an application. */ private ShortcutInfo getShortcutInfo(Cursor c, Context context, int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex, int titleIndex) { Bitmap icon = null; final ShortcutInfo info = new ShortcutInfo(); info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT; // TODO: If there's an explicit component and we can't install that, delete it. info.title = c.getString(titleIndex); int iconType = c.getInt(iconTypeIndex); switch (iconType) { case LauncherSettings.Favorites.ICON_TYPE_RESOURCE: String packageName = c.getString(iconPackageIndex); String resourceName = c.getString(iconResourceIndex); PackageManager packageManager = context.getPackageManager(); info.customIcon = false; // the resource try { Resources resources = packageManager.getResourcesForApplication(packageName); if (resources != null) { final int id = resources.getIdentifier(resourceName, null, null); icon = Utilities.createIconBitmap(resources.getDrawable(id), context); } } catch (Exception e) { // drop this. we have other places to look for icons } // the db if (icon == null) { icon = getIconFromCursor(c, iconIndex); } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } break; case LauncherSettings.Favorites.ICON_TYPE_BITMAP: icon = getIconFromCursor(c, iconIndex); if (icon == null) { icon = getFallbackIcon(); info.customIcon = false; info.usingFallbackIcon = true; } else { info.customIcon = true; } break; default: icon = getFallbackIcon(); info.usingFallbackIcon = true; info.customIcon = false; break; } info.setIcon(icon); return info; } Bitmap getIconFromCursor(Cursor c, int iconIndex) { if (false) { Log.d(TAG, "getIconFromCursor app=" + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE))); } byte[] data = c.getBlob(iconIndex); try { return BitmapFactory.decodeByteArray(data, 0, data.length); } catch (Exception e) { return null; } } ShortcutInfo addShortcut(Context context, Intent data, CellLayout.CellInfo cellInfo, boolean notify) { final ShortcutInfo info = infoFromShortcutIntent(context, data); addItemToDatabase(context, info, LauncherSettings.Favorites.CONTAINER_DESKTOP, cellInfo.screen, cellInfo.cellX, cellInfo.cellY, notify); return info; } private ShortcutInfo infoFromShortcutIntent(Context context, Intent data) { Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT); String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME); Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON); Bitmap icon = null; boolean filtered = false; boolean customIcon = false; ShortcutIconResource iconResource = null; if (bitmap != null && bitmap instanceof Bitmap) { icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context); filtered = true; customIcon = true; } else { Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE); if (extra != null && extra instanceof ShortcutIconResource) { try { iconResource = (ShortcutIconResource) extra; final PackageManager packageManager = context.getPackageManager(); Resources resources = packageManager.getResourcesForApplication( iconResource.packageName); final int id = resources.getIdentifier(iconResource.resourceName, null, null); icon = Utilities.createIconBitmap(resources.getDrawable(id), context); } catch (Exception e) { Log.w(TAG, "Could not load shortcut icon: " + extra); } } } final ShortcutInfo info = new ShortcutInfo(); if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } info.setIcon(icon); info.title = name; info.intent = intent; info.customIcon = customIcon; info.iconResource = iconResource; return info; } private static void loadLiveFolderIcon(Context context, Cursor c, int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, LiveFolderInfo liveFolderInfo) { int iconType = c.getInt(iconTypeIndex); switch (iconType) { case LauncherSettings.Favorites.ICON_TYPE_RESOURCE: String packageName = c.getString(iconPackageIndex); String resourceName = c.getString(iconResourceIndex); PackageManager packageManager = context.getPackageManager(); try { Resources resources = packageManager.getResourcesForApplication(packageName); final int id = resources.getIdentifier(resourceName, null, null); liveFolderInfo.icon = Utilities.createIconBitmap(resources.getDrawable(id), context); } catch (Exception e) { liveFolderInfo.icon = Utilities.createIconBitmap( context.getResources().getDrawable(R.drawable.ic_launcher_folder), context); } liveFolderInfo.iconResource = new Intent.ShortcutIconResource(); liveFolderInfo.iconResource.packageName = packageName; liveFolderInfo.iconResource.resourceName = resourceName; break; default: liveFolderInfo.icon = Utilities.createIconBitmap( context.getResources().getDrawable(R.drawable.ic_launcher_folder), context); } } void updateSavedIcon(Context context, ShortcutInfo info, Cursor c, int iconIndex) { // If this icon doesn't have a custom icon, check to see // what's stored in the DB, and if it doesn't match what // we're going to show, store what we are going to show back // into the DB. We do this so when we're loading, if the // package manager can't find an icon (for example because // the app is on SD) then we can use that instead. if (info.onExternalStorage && !info.customIcon && !info.usingFallbackIcon) { boolean needSave; byte[] data = c.getBlob(iconIndex); try { if (data != null) { Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length); Bitmap loaded = info.getIcon(mIconCache); needSave = !saved.sameAs(loaded); } else { needSave = true; } } catch (Exception e) { needSave = true; } if (needSave) { Log.d(TAG, "going to save icon bitmap for info=" + info); // This is slower than is ideal, but this only happens either // after the froyo OTA or when the app is updated with a new // icon. updateItemInDatabase(context, info); } } } /** * Return an existing UserFolderInfo object if we have encountered this ID previously, * or make a new one. */ private static UserFolderInfo findOrMakeUserFolder(HashMap<Long, FolderInfo> folders, long id) { // See if a placeholder was created for us already FolderInfo folderInfo = folders.get(id); if (folderInfo == null || !(folderInfo instanceof UserFolderInfo)) { // No placeholder -- create a new instance folderInfo = new UserFolderInfo(); folders.put(id, folderInfo); } return (UserFolderInfo) folderInfo; } /** * Return an existing UserFolderInfo object if we have encountered this ID previously, or make a * new one. */ private static LiveFolderInfo findOrMakeLiveFolder(HashMap<Long, FolderInfo> folders, long id) { // See if a placeholder was created for us already FolderInfo folderInfo = folders.get(id); if (folderInfo == null || !(folderInfo instanceof LiveFolderInfo)) { // No placeholder -- create a new instance folderInfo = new LiveFolderInfo(); folders.put(id, folderInfo); } return (LiveFolderInfo) folderInfo; } private static String getLabel(PackageManager manager, ActivityInfo activityInfo) { String label = activityInfo.loadLabel(manager).toString(); if (label == null) { label = manager.getApplicationLabel(activityInfo.applicationInfo).toString(); if (label == null) { label = activityInfo.name; } } return label; } private static final Collator sCollator = Collator.getInstance(); public static final Comparator<ApplicationInfo> APP_NAME_COMPARATOR = new Comparator<ApplicationInfo>() { public final int compare(ApplicationInfo a, ApplicationInfo b) { return sCollator.compare(a.title.toString(), b.title.toString()); } }; public void dumpState() { Log.d(TAG, "mBeforeFirstLoad=" + mBeforeFirstLoad); Log.d(TAG, "mCallbacks=" + mCallbacks); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mAllAppsList.data); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mAllAppsList.added); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mAllAppsList.removed); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mAllAppsList.modified); mLoader.dumpState(); } }
false
true
static boolean shortcutExists(Context context, String title, Intent intent) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { "title", "intent" }, "title=? and intent=?", new String[] { title, intent.toUri(0) }, null); boolean result = false; try { result = c.moveToFirst(); } finally { c.close(); } return result; } /** * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList. */ FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null, "_id=? and (itemType=? or itemType=?)", new String[] { String.valueOf(id), String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER), String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER) }, null); try { if (c.moveToFirst()) { final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE); final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); FolderInfo folderInfo = null; switch (c.getInt(itemTypeIndex)) { case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER: folderInfo = findOrMakeUserFolder(folderList, id); break; case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER: folderInfo = findOrMakeLiveFolder(folderList, id); break; } folderInfo.title = c.getString(titleIndex); folderInfo.id = id; folderInfo.container = c.getInt(containerIndex); folderInfo.screen = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); return folderInfo; } } finally { c.close(); } return null; } /** * Add an item to the database in a specified container. Sets the container, screen, cellX and * cellY fields of the item. Also assigns an ID to the item. */ static void addItemToDatabase(Context context, ItemInfo item, long container, int screen, int cellX, int cellY, boolean notify) { item.container = container; item.screen = screen; item.cellX = cellX; item.cellY = cellY; final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); item.onAddToDatabase(values); Uri result = cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI : LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values); if (result != null) { item.id = Integer.parseInt(result.getPathSegments().get(1)); } } /** * Update an item to the database in a specified container. */ static void updateItemInDatabase(Context context, ItemInfo item) { final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); item.onAddToDatabase(values); cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null); } /** * Removes the specified item from the database * @param context * @param item */ static void deleteItemFromDatabase(Context context, ItemInfo item) { final ContentResolver cr = context.getContentResolver(); cr.delete(LauncherSettings.Favorites.getContentUri(item.id, false), null, null); } /** * Remove the contents of the specified folder from the database */ static void deleteUserFolderContentsFromDatabase(Context context, UserFolderInfo info) { final ContentResolver cr = context.getContentResolver(); cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null); cr.delete(LauncherSettings.Favorites.CONTENT_URI, LauncherSettings.Favorites.CONTAINER + "=" + info.id, null); } /** * Set this as the current Launcher activity object for the loader. */ public void initialize(Callbacks callbacks) { synchronized (mLock) { mCallbacks = new WeakReference<Callbacks>(callbacks); } } public void startLoader(Context context, boolean isLaunching) { mLoader.startLoader(context, isLaunching); } public void stopLoader() { mLoader.stopLoader(); } /** * We pick up most of the changes to all apps. */ public void setAllAppsDirty() { mLoader.setAllAppsDirty(); } public void setWorkspaceDirty() { mLoader.setWorkspaceDirty(); } /** * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and * ACTION_PACKAGE_CHANGED. */ public void onReceive(Context context, Intent intent) { // Use the app as the context. context = mApp; ArrayList<ApplicationInfo> added = null; ArrayList<ApplicationInfo> removed = null; ArrayList<ApplicationInfo> modified = null; synchronized (mLock) { if (mBeforeFirstLoad) { // If we haven't even loaded yet, don't bother, since we'll just pick // up the changes. return; } final String action = intent.getAction(); if (Intent.ACTION_PACKAGE_CHANGED.equals(action) || Intent.ACTION_PACKAGE_REMOVED.equals(action) || Intent.ACTION_PACKAGE_ADDED.equals(action)) { final String packageName = intent.getData().getSchemeSpecificPart(); final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); if (packageName == null || packageName.length() == 0) { // they sent us a bad intent return; } if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) { mAllAppsList.updatePackage(context, packageName); } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) { if (!replacing) { mAllAppsList.removePackage(packageName); } // else, we are replacing the package, so a PACKAGE_ADDED will be sent // later, we will update the package at this time } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) { if (!replacing) { mAllAppsList.addPackage(context, packageName); } else { mAllAppsList.updatePackage(context, packageName); } } if (mAllAppsList.added.size() > 0) { added = mAllAppsList.added; mAllAppsList.added = new ArrayList<ApplicationInfo>(); } if (mAllAppsList.removed.size() > 0) { removed = mAllAppsList.removed; mAllAppsList.removed = new ArrayList<ApplicationInfo>(); for (ApplicationInfo info: removed) { mIconCache.remove(info.intent.getComponent()); } } if (mAllAppsList.modified.size() > 0) { modified = mAllAppsList.modified; mAllAppsList.modified = new ArrayList<ApplicationInfo>(); } final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == null) { Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading."); return; } if (added != null) { final ArrayList<ApplicationInfo> addedFinal = added; mHandler.post(new Runnable() { public void run() { callbacks.bindAppsAdded(addedFinal); } }); } if (modified != null) { final ArrayList<ApplicationInfo> modifiedFinal = modified; mHandler.post(new Runnable() { public void run() { callbacks.bindAppsUpdated(modifiedFinal); } }); } if (removed != null) { final ArrayList<ApplicationInfo> removedFinal = removed; mHandler.post(new Runnable() { public void run() { callbacks.bindAppsRemoved(removedFinal); } }); } } else { if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) { String packages[] = intent.getStringArrayExtra( Intent.EXTRA_CHANGED_PACKAGE_LIST); if (packages == null || packages.length == 0) { return; } setAllAppsDirty(); setWorkspaceDirty(); startLoader(context, false); } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) { String packages[] = intent.getStringArrayExtra( Intent.EXTRA_CHANGED_PACKAGE_LIST); if (packages == null || packages.length == 0) { return; } setAllAppsDirty(); setWorkspaceDirty(); startLoader(context, false); } } } } public class Loader { private static final int ITEMS_CHUNK = 6; private LoaderThread mLoaderThread; private int mLastWorkspaceSeq = 0; private int mWorkspaceSeq = 1; private int mLastAllAppsSeq = 0; private int mAllAppsSeq = 1; final ArrayList<ItemInfo> mItems = new ArrayList<ItemInfo>(); final ArrayList<LauncherAppWidgetInfo> mAppWidgets = new ArrayList<LauncherAppWidgetInfo>(); final HashMap<Long, FolderInfo> mFolders = new HashMap<Long, FolderInfo>(); /** * Call this from the ui thread so the handler is initialized on the correct thread. */ public Loader() { } public void startLoader(Context context, boolean isLaunching) { synchronized (mLock) { if (DEBUG_LOADERS) { Log.d(TAG, "startLoader isLaunching=" + isLaunching); } // Don't bother to start the thread if we know it's not going to do anything if (mCallbacks != null && mCallbacks.get() != null) { LoaderThread oldThread = mLoaderThread; if (oldThread != null) { if (oldThread.isLaunching()) { // don't downgrade isLaunching if we're already running isLaunching = true; } oldThread.stopLocked(); } mLoaderThread = new LoaderThread(context, oldThread, isLaunching); mLoaderThread.start(); } } } public void stopLoader() { synchronized (mLock) { if (mLoaderThread != null) { mLoaderThread.stopLocked(); } } } public void setWorkspaceDirty() { synchronized (mLock) { mWorkspaceSeq++; } } public void setAllAppsDirty() { synchronized (mLock) { mAllAppsSeq++; } } /** * Runnable for the thread that loads the contents of the launcher: * - workspace icons * - widgets * - all apps icons */ private class LoaderThread extends Thread { private Context mContext; private Thread mWaitThread; private boolean mIsLaunching; private boolean mStopped; private boolean mWorkspaceDoneBinding; LoaderThread(Context context, Thread waitThread, boolean isLaunching) { mContext = context; mWaitThread = waitThread; mIsLaunching = isLaunching; } boolean isLaunching() { return mIsLaunching; } /** * If another LoaderThread was supplied, we need to wait for that to finish before * we start our processing. This keeps the ordering of the setting and clearing * of the dirty flags correct by making sure we don't start processing stuff until * they've had a chance to re-set them. We do this waiting the worker thread, not * the ui thread to avoid ANRs. */ private void waitForOtherThread() { if (mWaitThread != null) { boolean done = false; while (!done) { try { mWaitThread.join(); done = true; } catch (InterruptedException ex) { // Ignore } } mWaitThread = null; } } public void run() { waitForOtherThread(); // Elevate priority when Home launches for the first time to avoid // starving at boot time. Staring at a blank home is not cool. synchronized (mLock) { android.os.Process.setThreadPriority(mIsLaunching ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND); } // Load the workspace only if it's dirty. int workspaceSeq; boolean workspaceDirty; synchronized (mLock) { workspaceSeq = mWorkspaceSeq; workspaceDirty = mWorkspaceSeq != mLastWorkspaceSeq; } if (workspaceDirty) { loadWorkspace(); } synchronized (mLock) { // If we're not stopped, and nobody has incremented mWorkspaceSeq. if (mStopped) { return; } if (workspaceSeq == mWorkspaceSeq) { mLastWorkspaceSeq = mWorkspaceSeq; } } // Bind the workspace bindWorkspace(); // Wait until the either we're stopped or the other threads are done. // This way we don't start loading all apps until the workspace has settled // down. synchronized (LoaderThread.this) { mHandler.postIdle(new Runnable() { public void run() { synchronized (LoaderThread.this) { mWorkspaceDoneBinding = true; if (DEBUG_LOADERS) { Log.d(TAG, "done with workspace"); } LoaderThread.this.notify(); } } }); if (DEBUG_LOADERS) { Log.d(TAG, "waiting to be done with workspace"); } while (!mStopped && !mWorkspaceDoneBinding) { try { this.wait(); } catch (InterruptedException ex) { // Ignore } } if (DEBUG_LOADERS) { Log.d(TAG, "done waiting to be done with workspace"); } } // Whew! Hard work done. synchronized (mLock) { if (mIsLaunching) { android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); } } // Load all apps if they're dirty int allAppsSeq; boolean allAppsDirty; synchronized (mLock) { allAppsSeq = mAllAppsSeq; allAppsDirty = mAllAppsSeq != mLastAllAppsSeq; if (DEBUG_LOADERS) { Log.d(TAG, "mAllAppsSeq=" + mAllAppsSeq + " mLastAllAppsSeq=" + mLastAllAppsSeq + " allAppsDirty"); } } if (allAppsDirty) { loadAndBindAllApps(); } synchronized (mLock) { // If we're not stopped, and nobody has incremented mAllAppsSeq. if (mStopped) { return; } if (allAppsSeq == mAllAppsSeq) { mLastAllAppsSeq = mAllAppsSeq; } } // Clear out this reference, otherwise we end up holding it until all of the // callback runnables are done. mContext = null; synchronized (mLock) { // Setting the reference is atomic, but we can't do it inside the other critical // sections. mLoaderThread = null; } } public void stopLocked() { synchronized (LoaderThread.this) { mStopped = true; this.notify(); } } /** * Gets the callbacks object. If we've been stopped, or if the launcher object * has somehow been garbage collected, return null instead. Pass in the Callbacks * object that was around when the deferred message was scheduled, and if there's * a new Callbacks object around then also return null. This will save us from * calling onto it with data that will be ignored. */ Callbacks tryGetCallbacks(Callbacks oldCallbacks) { synchronized (mLock) { if (mStopped) { return null; } if (mCallbacks == null) { return null; } final Callbacks callbacks = mCallbacks.get(); if (callbacks != oldCallbacks) { return null; } if (callbacks == null) { Log.w(TAG, "no mCallbacks"); return null; } return callbacks; } } private void loadWorkspace() { long t = SystemClock.uptimeMillis(); final Context context = mContext; final ContentResolver contentResolver = context.getContentResolver(); final PackageManager manager = context.getPackageManager(); final AppWidgetManager widgets = AppWidgetManager.getInstance(context); final boolean isSafeMode = manager.isSafeMode(); mItems.clear(); mAppWidgets.clear(); mFolders.clear(); final ArrayList<Long> itemsToRemove = new ArrayList<Long>(); final Cursor c = contentResolver.query( LauncherSettings.Favorites.CONTENT_URI, null, null, null, null); try { final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID); final int intentIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.INTENT); final int titleIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.TITLE); final int iconTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_TYPE); final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON); final int iconPackageIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_PACKAGE); final int iconResourceIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_RESOURCE); final int containerIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.CONTAINER); final int itemTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ITEM_TYPE); final int appWidgetIdIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.APPWIDGET_ID); final int screenIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLY); final int spanXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.SPANX); final int spanYIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SPANY); final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI); final int displayModeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.DISPLAY_MODE); ShortcutInfo info; String intentDescription; LauncherAppWidgetInfo appWidgetInfo; int container; long id; Intent intent; while (!mStopped && c.moveToNext()) { try { int itemType = c.getInt(itemTypeIndex); switch (itemType) { case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: intentDescription = c.getString(intentIndex); try { intent = Intent.parseUri(intentDescription, 0); } catch (URISyntaxException e) { continue; } if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) { info = getShortcutInfo(manager, intent, context, c, iconIndex, titleIndex); } else { info = getShortcutInfo(c, context, iconTypeIndex, iconPackageIndex, iconResourceIndex, iconIndex, titleIndex); } if (info != null) { updateSavedIcon(context, info, c, iconIndex); info.intent = intent; info.id = c.getLong(idIndex); container = c.getInt(containerIndex); info.container = container; info.screen = c.getInt(screenIndex); info.cellX = c.getInt(cellXIndex); info.cellY = c.getInt(cellYIndex); switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: mItems.add(info); break; default: // Item is in a user folder UserFolderInfo folderInfo = findOrMakeUserFolder(mFolders, container); folderInfo.add(info); break; } } else { // Failed to load the shortcut, probably because the // activity manager couldn't resolve it (maybe the app // was uninstalled), or the db row was somehow screwed up. // Delete it. id = c.getLong(idIndex); Log.e(TAG, "Error loading shortcut " + id + ", removing it"); contentResolver.delete(LauncherSettings.Favorites.getContentUri( id, false), null, null); } break; case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER: id = c.getLong(idIndex); UserFolderInfo folderInfo = findOrMakeUserFolder(mFolders, id); folderInfo.title = c.getString(titleIndex); folderInfo.id = id; container = c.getInt(containerIndex); folderInfo.container = container; folderInfo.screen = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: mItems.add(folderInfo); break; } mFolders.put(folderInfo.id, folderInfo); break; case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER: id = c.getLong(idIndex); Uri uri = Uri.parse(c.getString(uriIndex)); // Make sure the live folder exists final ProviderInfo providerInfo = context.getPackageManager().resolveContentProvider( uri.getAuthority(), 0); if (providerInfo == null && !isSafeMode) { itemsToRemove.add(id); } else { LiveFolderInfo liveFolderInfo = findOrMakeLiveFolder(mFolders, id); intentDescription = c.getString(intentIndex); intent = null; if (intentDescription != null) { try { intent = Intent.parseUri(intentDescription, 0); } catch (URISyntaxException e) { // Ignore, a live folder might not have a base intent } } liveFolderInfo.title = c.getString(titleIndex); liveFolderInfo.id = id; liveFolderInfo.uri = uri; container = c.getInt(containerIndex); liveFolderInfo.container = container; liveFolderInfo.screen = c.getInt(screenIndex); liveFolderInfo.cellX = c.getInt(cellXIndex); liveFolderInfo.cellY = c.getInt(cellYIndex); liveFolderInfo.baseIntent = intent; liveFolderInfo.displayMode = c.getInt(displayModeIndex); loadLiveFolderIcon(context, c, iconTypeIndex, iconPackageIndex, iconResourceIndex, liveFolderInfo); switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: mItems.add(liveFolderInfo); break; } mFolders.put(liveFolderInfo.id, liveFolderInfo); } break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: // Read all Launcher-specific widget details int appWidgetId = c.getInt(appWidgetIdIndex); id = c.getLong(idIndex); final AppWidgetProviderInfo provider = widgets.getAppWidgetInfo(appWidgetId); if (!isSafeMode && (provider == null || provider.provider == null || provider.provider.getPackageName() == null)) { Log.e(TAG, "Deleting widget that isn't installed anymore: id=" + id + " appWidgetId=" + appWidgetId); itemsToRemove.add(id); } else { appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId); appWidgetInfo.id = id; appWidgetInfo.screen = c.getInt(screenIndex); appWidgetInfo.cellX = c.getInt(cellXIndex); appWidgetInfo.cellY = c.getInt(cellYIndex); appWidgetInfo.spanX = c.getInt(spanXIndex); appWidgetInfo.spanY = c.getInt(spanYIndex); container = c.getInt(containerIndex); if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) { Log.e(TAG, "Widget found where container " + "!= CONTAINER_DESKTOP -- ignoring!"); continue; } appWidgetInfo.container = c.getInt(containerIndex); mAppWidgets.add(appWidgetInfo); } break; } } catch (Exception e) { Log.w(TAG, "Desktop items loading interrupted:", e); } } } finally { c.close(); } if (itemsToRemove.size() > 0) { ContentProviderClient client = contentResolver.acquireContentProviderClient( LauncherSettings.Favorites.CONTENT_URI); // Remove dead items for (long id : itemsToRemove) { if (DEBUG_LOADERS) { Log.d(TAG, "Removed id = " + id); } // Don't notify content observers try { client.delete(LauncherSettings.Favorites.getContentUri(id, false), null, null); } catch (RemoteException e) { Log.w(TAG, "Could not remove id = " + id); } } } if (DEBUG_LOADERS) { Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); } } /** * Read everything out of our database. */ private void bindWorkspace() { final long t = SystemClock.uptimeMillis(); // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderThread running with no launcher"); return; } int N; // Tell the workspace that we're about to start firing items at it mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.startBinding(); } } }); // Add the items to the workspace. N = mItems.size(); for (int i=0; i<N; i+=ITEMS_CHUNK) { final int start = i; final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i); mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindItems(mItems, start, start+chunkSize); } } }); } mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindFolders(mFolders); } } }); // Wait until the queue goes empty. mHandler.postIdle(new Runnable() { public void run() { if (DEBUG_LOADERS) { Log.d(TAG, "Going to start binding widgets soon."); } } }); // Bind the widgets, one at a time. // WARNING: this is calling into the workspace from the background thread, // but since getCurrentScreen() just returns the int, we should be okay. This // is just a hint for the order, and if it's wrong, we'll be okay. // TODO: instead, we should have that push the current screen into here. final int currentScreen = oldCallbacks.getCurrentWorkspaceScreen(); N = mAppWidgets.size(); // once for the current screen for (int i=0; i<N; i++) { final LauncherAppWidgetInfo widget = mAppWidgets.get(i); if (widget.screen == currentScreen) { mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAppWidget(widget); } } }); } } // once for the other screens for (int i=0; i<N; i++) { final LauncherAppWidgetInfo widget = mAppWidgets.get(i); if (widget.screen != currentScreen) { mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAppWidget(widget); } } }); } } // Tell the workspace that we're done. mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.finishBindingItems(); } } }); // If we're profiling, this is the last thing in the queue. mHandler.post(new Runnable() { public void run() { if (DEBUG_LOADERS) { Log.d(TAG, "bound workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); } if (Launcher.PROFILE_ROTATE) { android.os.Debug.stopMethodTracing(); } } }); } private void loadAndBindAllApps() { final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderThread running with no launcher (loadAndBindAllApps)"); return; } final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); final PackageManager packageManager = mContext.getPackageManager(); List<ResolveInfo> apps = null; int N = Integer.MAX_VALUE; int startIndex; int i=0; int batchSize = -1; while (i < N && !mStopped) { synchronized (mLock) { if (i == 0) { // This needs to happen inside the same lock block as when we // prepare the first batch for bindAllApplications. Otherwise // the package changed receiver can come in and double-add // (or miss one?). mAllAppsList.clear(); final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; apps = packageManager.queryIntentActivities(mainIntent, 0); if (DEBUG_LOADERS) { Log.d(TAG, "queryIntentActivities took " + (SystemClock.uptimeMillis()-qiaTime) + "ms"); } if (apps == null) { return; } N = apps.size(); if (DEBUG_LOADERS) { Log.d(TAG, "queryIntentActivities got " + N + " apps"); } if (N == 0) { // There are no apps?!? return; } if (mBatchSize == 0) { batchSize = N; } else { batchSize = mBatchSize; } final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; Collections.sort(apps, new ResolveInfo.DisplayNameComparator(packageManager)); if (DEBUG_LOADERS) { Log.d(TAG, "sort took " + (SystemClock.uptimeMillis()-qiaTime) + "ms"); } } final long t2 = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; startIndex = i; for (int j=0; i<N && j<batchSize; j++) { // This builds the icon bitmaps. mAllAppsList.add(new ApplicationInfo(apps.get(i), mIconCache)); i++; } final boolean first = i <= batchSize; final ArrayList<ApplicationInfo> added = mAllAppsList.added; mAllAppsList.added = new ArrayList<ApplicationInfo>(); mHandler.post(new Runnable() { public void run() { final long t = SystemClock.uptimeMillis(); final Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (first) { mBeforeFirstLoad = false; callbacks.bindAllApplications(added); } else { callbacks.bindAppsAdded(added); } if (DEBUG_LOADERS) { Log.d(TAG, "bound " + added.size() + " apps in " + (SystemClock.uptimeMillis() - t) + "ms"); } } }); if (DEBUG_LOADERS) { Log.d(TAG, "batch of " + (i-startIndex) + " icons processed in " + (SystemClock.uptimeMillis()-t2) + "ms"); } } if (mAllAppsLoadDelay > 0 && i < N) { try { if (DEBUG_LOADERS) { Log.d(TAG, "sleeping for " + mAllAppsLoadDelay + "ms"); } Thread.sleep(mAllAppsLoadDelay); } catch (InterruptedException exc) { } } } if (DEBUG_LOADERS) { Log.d(TAG, "cached all " + N + " apps in " + (SystemClock.uptimeMillis()-t) + "ms" + (mAllAppsLoadDelay > 0 ? " (including delay)" : "")); } } public void dumpState() { Log.d(TAG, "mLoader.mLoaderThread.mContext=" + mContext); Log.d(TAG, "mLoader.mLoaderThread.mWaitThread=" + mWaitThread); Log.d(TAG, "mLoader.mLoaderThread.mIsLaunching=" + mIsLaunching); Log.d(TAG, "mLoader.mLoaderThread.mStopped=" + mStopped); Log.d(TAG, "mLoader.mLoaderThread.mWorkspaceDoneBinding=" + mWorkspaceDoneBinding); } } public void dumpState() { Log.d(TAG, "mLoader.mLastWorkspaceSeq=" + mLoader.mLastWorkspaceSeq); Log.d(TAG, "mLoader.mWorkspaceSeq=" + mLoader.mWorkspaceSeq); Log.d(TAG, "mLoader.mLastAllAppsSeq=" + mLoader.mLastAllAppsSeq); Log.d(TAG, "mLoader.mAllAppsSeq=" + mLoader.mAllAppsSeq); Log.d(TAG, "mLoader.mItems size=" + mLoader.mItems.size()); if (mLoaderThread != null) { mLoaderThread.dumpState(); } else { Log.d(TAG, "mLoader.mLoaderThread=null"); } } } /** * This is called from the code that adds shortcuts from the intent receiver. This * doesn't have a Cursor, but */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) { return getShortcutInfo(manager, intent, context, null, -1, -1); } /** * Make an ShortcutInfo object for a shortcut that is an application. * * If c is not null, then it will be used to fill in missing data like the title and icon. */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context, Cursor c, int iconIndex, int titleIndex) { Bitmap icon = null; final ShortcutInfo info = new ShortcutInfo(); ComponentName componentName = intent.getComponent(); if (componentName == null) { return null; } // TODO: See if the PackageManager knows about this case. If it doesn't // then return null & delete this. // the resource -- This may implicitly give us back the fallback icon, // but don't worry about that. All we're doing with usingFallbackIcon is // to avoid saving lots of copies of that in the database, and most apps // have icons anyway. final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0); if (resolveInfo != null) { icon = mIconCache.getIcon(componentName, resolveInfo); } // the db if (icon == null) { if (c != null) { icon = getIconFromCursor(c, iconIndex); } } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } info.setIcon(icon); // from the resource if (resolveInfo != null) { info.title = resolveInfo.activityInfo.loadLabel(manager); } // from the db if (info.title == null) { if (c != null) { info.title = c.getString(titleIndex); } } // fall back to the class name of the activity if (info.title == null) { info.title = componentName.getClassName(); } info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION; return info; } /** * Make an ShortcutInfo object for a shortcut that isn't an application. */ private ShortcutInfo getShortcutInfo(Cursor c, Context context, int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex, int titleIndex) { Bitmap icon = null; final ShortcutInfo info = new ShortcutInfo(); info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT; // TODO: If there's an explicit component and we can't install that, delete it. info.title = c.getString(titleIndex); int iconType = c.getInt(iconTypeIndex); switch (iconType) { case LauncherSettings.Favorites.ICON_TYPE_RESOURCE: String packageName = c.getString(iconPackageIndex); String resourceName = c.getString(iconResourceIndex); PackageManager packageManager = context.getPackageManager(); info.customIcon = false; // the resource try { Resources resources = packageManager.getResourcesForApplication(packageName); if (resources != null) { final int id = resources.getIdentifier(resourceName, null, null); icon = Utilities.createIconBitmap(resources.getDrawable(id), context); } } catch (Exception e) { // drop this. we have other places to look for icons } // the db if (icon == null) { icon = getIconFromCursor(c, iconIndex); } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } break; case LauncherSettings.Favorites.ICON_TYPE_BITMAP: icon = getIconFromCursor(c, iconIndex); if (icon == null) { icon = getFallbackIcon(); info.customIcon = false; info.usingFallbackIcon = true; } else { info.customIcon = true; } break; default: icon = getFallbackIcon(); info.usingFallbackIcon = true; info.customIcon = false; break; } info.setIcon(icon); return info; } Bitmap getIconFromCursor(Cursor c, int iconIndex) { if (false) { Log.d(TAG, "getIconFromCursor app=" + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE))); } byte[] data = c.getBlob(iconIndex); try { return BitmapFactory.decodeByteArray(data, 0, data.length); } catch (Exception e) { return null; } } ShortcutInfo addShortcut(Context context, Intent data, CellLayout.CellInfo cellInfo, boolean notify) { final ShortcutInfo info = infoFromShortcutIntent(context, data); addItemToDatabase(context, info, LauncherSettings.Favorites.CONTAINER_DESKTOP, cellInfo.screen, cellInfo.cellX, cellInfo.cellY, notify); return info; } private ShortcutInfo infoFromShortcutIntent(Context context, Intent data) { Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT); String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME); Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON); Bitmap icon = null; boolean filtered = false; boolean customIcon = false; ShortcutIconResource iconResource = null; if (bitmap != null && bitmap instanceof Bitmap) { icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context); filtered = true; customIcon = true; } else { Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE); if (extra != null && extra instanceof ShortcutIconResource) { try { iconResource = (ShortcutIconResource) extra; final PackageManager packageManager = context.getPackageManager(); Resources resources = packageManager.getResourcesForApplication( iconResource.packageName); final int id = resources.getIdentifier(iconResource.resourceName, null, null); icon = Utilities.createIconBitmap(resources.getDrawable(id), context); } catch (Exception e) { Log.w(TAG, "Could not load shortcut icon: " + extra); } } } final ShortcutInfo info = new ShortcutInfo(); if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } info.setIcon(icon); info.title = name; info.intent = intent; info.customIcon = customIcon; info.iconResource = iconResource; return info; } private static void loadLiveFolderIcon(Context context, Cursor c, int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, LiveFolderInfo liveFolderInfo) { int iconType = c.getInt(iconTypeIndex); switch (iconType) { case LauncherSettings.Favorites.ICON_TYPE_RESOURCE: String packageName = c.getString(iconPackageIndex); String resourceName = c.getString(iconResourceIndex); PackageManager packageManager = context.getPackageManager(); try { Resources resources = packageManager.getResourcesForApplication(packageName); final int id = resources.getIdentifier(resourceName, null, null); liveFolderInfo.icon = Utilities.createIconBitmap(resources.getDrawable(id), context); } catch (Exception e) { liveFolderInfo.icon = Utilities.createIconBitmap( context.getResources().getDrawable(R.drawable.ic_launcher_folder), context); } liveFolderInfo.iconResource = new Intent.ShortcutIconResource(); liveFolderInfo.iconResource.packageName = packageName; liveFolderInfo.iconResource.resourceName = resourceName; break; default: liveFolderInfo.icon = Utilities.createIconBitmap( context.getResources().getDrawable(R.drawable.ic_launcher_folder), context); } } void updateSavedIcon(Context context, ShortcutInfo info, Cursor c, int iconIndex) { // If this icon doesn't have a custom icon, check to see // what's stored in the DB, and if it doesn't match what // we're going to show, store what we are going to show back // into the DB. We do this so when we're loading, if the // package manager can't find an icon (for example because // the app is on SD) then we can use that instead. if (info.onExternalStorage && !info.customIcon && !info.usingFallbackIcon) { boolean needSave; byte[] data = c.getBlob(iconIndex); try { if (data != null) { Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length); Bitmap loaded = info.getIcon(mIconCache); needSave = !saved.sameAs(loaded); } else { needSave = true; } } catch (Exception e) { needSave = true; } if (needSave) { Log.d(TAG, "going to save icon bitmap for info=" + info); // This is slower than is ideal, but this only happens either // after the froyo OTA or when the app is updated with a new // icon. updateItemInDatabase(context, info); } } } /** * Return an existing UserFolderInfo object if we have encountered this ID previously, * or make a new one. */ private static UserFolderInfo findOrMakeUserFolder(HashMap<Long, FolderInfo> folders, long id) { // See if a placeholder was created for us already FolderInfo folderInfo = folders.get(id); if (folderInfo == null || !(folderInfo instanceof UserFolderInfo)) { // No placeholder -- create a new instance folderInfo = new UserFolderInfo(); folders.put(id, folderInfo); } return (UserFolderInfo) folderInfo; } /** * Return an existing UserFolderInfo object if we have encountered this ID previously, or make a * new one. */ private static LiveFolderInfo findOrMakeLiveFolder(HashMap<Long, FolderInfo> folders, long id) { // See if a placeholder was created for us already FolderInfo folderInfo = folders.get(id); if (folderInfo == null || !(folderInfo instanceof LiveFolderInfo)) { // No placeholder -- create a new instance folderInfo = new LiveFolderInfo(); folders.put(id, folderInfo); } return (LiveFolderInfo) folderInfo; } private static String getLabel(PackageManager manager, ActivityInfo activityInfo) { String label = activityInfo.loadLabel(manager).toString(); if (label == null) { label = manager.getApplicationLabel(activityInfo.applicationInfo).toString(); if (label == null) { label = activityInfo.name; } } return label; } private static final Collator sCollator = Collator.getInstance(); public static final Comparator<ApplicationInfo> APP_NAME_COMPARATOR = new Comparator<ApplicationInfo>() { public final int compare(ApplicationInfo a, ApplicationInfo b) { return sCollator.compare(a.title.toString(), b.title.toString()); } }; public void dumpState() { Log.d(TAG, "mBeforeFirstLoad=" + mBeforeFirstLoad); Log.d(TAG, "mCallbacks=" + mCallbacks); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mAllAppsList.data); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mAllAppsList.added); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mAllAppsList.removed); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mAllAppsList.modified); mLoader.dumpState(); } }
static boolean shortcutExists(Context context, String title, Intent intent) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { "title", "intent" }, "title=? and intent=?", new String[] { title, intent.toUri(0) }, null); boolean result = false; try { result = c.moveToFirst(); } finally { c.close(); } return result; } /** * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList. */ FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null, "_id=? and (itemType=? or itemType=?)", new String[] { String.valueOf(id), String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER), String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER) }, null); try { if (c.moveToFirst()) { final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE); final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); FolderInfo folderInfo = null; switch (c.getInt(itemTypeIndex)) { case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER: folderInfo = findOrMakeUserFolder(folderList, id); break; case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER: folderInfo = findOrMakeLiveFolder(folderList, id); break; } folderInfo.title = c.getString(titleIndex); folderInfo.id = id; folderInfo.container = c.getInt(containerIndex); folderInfo.screen = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); return folderInfo; } } finally { c.close(); } return null; } /** * Add an item to the database in a specified container. Sets the container, screen, cellX and * cellY fields of the item. Also assigns an ID to the item. */ static void addItemToDatabase(Context context, ItemInfo item, long container, int screen, int cellX, int cellY, boolean notify) { item.container = container; item.screen = screen; item.cellX = cellX; item.cellY = cellY; final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); item.onAddToDatabase(values); Uri result = cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI : LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values); if (result != null) { item.id = Integer.parseInt(result.getPathSegments().get(1)); } } /** * Update an item to the database in a specified container. */ static void updateItemInDatabase(Context context, ItemInfo item) { final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); item.onAddToDatabase(values); cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null); } /** * Removes the specified item from the database * @param context * @param item */ static void deleteItemFromDatabase(Context context, ItemInfo item) { final ContentResolver cr = context.getContentResolver(); cr.delete(LauncherSettings.Favorites.getContentUri(item.id, false), null, null); } /** * Remove the contents of the specified folder from the database */ static void deleteUserFolderContentsFromDatabase(Context context, UserFolderInfo info) { final ContentResolver cr = context.getContentResolver(); cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null); cr.delete(LauncherSettings.Favorites.CONTENT_URI, LauncherSettings.Favorites.CONTAINER + "=" + info.id, null); } /** * Set this as the current Launcher activity object for the loader. */ public void initialize(Callbacks callbacks) { synchronized (mLock) { mCallbacks = new WeakReference<Callbacks>(callbacks); } } public void startLoader(Context context, boolean isLaunching) { mLoader.startLoader(context, isLaunching); } public void stopLoader() { mLoader.stopLoader(); } /** * We pick up most of the changes to all apps. */ public void setAllAppsDirty() { mLoader.setAllAppsDirty(); } public void setWorkspaceDirty() { mLoader.setWorkspaceDirty(); } /** * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and * ACTION_PACKAGE_CHANGED. */ public void onReceive(Context context, Intent intent) { // Use the app as the context. context = mApp; ArrayList<ApplicationInfo> added = null; ArrayList<ApplicationInfo> removed = null; ArrayList<ApplicationInfo> modified = null; synchronized (mLock) { if (mBeforeFirstLoad) { // If we haven't even loaded yet, don't bother, since we'll just pick // up the changes. return; } final String action = intent.getAction(); if (Intent.ACTION_PACKAGE_CHANGED.equals(action) || Intent.ACTION_PACKAGE_REMOVED.equals(action) || Intent.ACTION_PACKAGE_ADDED.equals(action)) { final String packageName = intent.getData().getSchemeSpecificPart(); final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); if (packageName == null || packageName.length() == 0) { // they sent us a bad intent return; } if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) { mAllAppsList.updatePackage(context, packageName); } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) { if (!replacing) { mAllAppsList.removePackage(packageName); } // else, we are replacing the package, so a PACKAGE_ADDED will be sent // later, we will update the package at this time } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) { if (!replacing) { mAllAppsList.addPackage(context, packageName); } else { mAllAppsList.updatePackage(context, packageName); } } if (mAllAppsList.added.size() > 0) { added = mAllAppsList.added; mAllAppsList.added = new ArrayList<ApplicationInfo>(); } if (mAllAppsList.removed.size() > 0) { removed = mAllAppsList.removed; mAllAppsList.removed = new ArrayList<ApplicationInfo>(); for (ApplicationInfo info: removed) { mIconCache.remove(info.intent.getComponent()); } } if (mAllAppsList.modified.size() > 0) { modified = mAllAppsList.modified; mAllAppsList.modified = new ArrayList<ApplicationInfo>(); } final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == null) { Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading."); return; } if (added != null) { final ArrayList<ApplicationInfo> addedFinal = added; mHandler.post(new Runnable() { public void run() { callbacks.bindAppsAdded(addedFinal); } }); } if (modified != null) { final ArrayList<ApplicationInfo> modifiedFinal = modified; mHandler.post(new Runnable() { public void run() { callbacks.bindAppsUpdated(modifiedFinal); } }); } if (removed != null) { final ArrayList<ApplicationInfo> removedFinal = removed; mHandler.post(new Runnable() { public void run() { callbacks.bindAppsRemoved(removedFinal); } }); } } else { if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) { String packages[] = intent.getStringArrayExtra( Intent.EXTRA_CHANGED_PACKAGE_LIST); if (packages == null || packages.length == 0) { return; } setAllAppsDirty(); setWorkspaceDirty(); startLoader(context, false); } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) { String packages[] = intent.getStringArrayExtra( Intent.EXTRA_CHANGED_PACKAGE_LIST); if (packages == null || packages.length == 0) { return; } setAllAppsDirty(); setWorkspaceDirty(); startLoader(context, false); } } } } public class Loader { private static final int ITEMS_CHUNK = 6; private LoaderThread mLoaderThread; private int mLastWorkspaceSeq = 0; private int mWorkspaceSeq = 1; private int mLastAllAppsSeq = 0; private int mAllAppsSeq = 1; final ArrayList<ItemInfo> mItems = new ArrayList<ItemInfo>(); final ArrayList<LauncherAppWidgetInfo> mAppWidgets = new ArrayList<LauncherAppWidgetInfo>(); final HashMap<Long, FolderInfo> mFolders = new HashMap<Long, FolderInfo>(); /** * Call this from the ui thread so the handler is initialized on the correct thread. */ public Loader() { } public void startLoader(Context context, boolean isLaunching) { synchronized (mLock) { if (DEBUG_LOADERS) { Log.d(TAG, "startLoader isLaunching=" + isLaunching); } // Don't bother to start the thread if we know it's not going to do anything if (mCallbacks != null && mCallbacks.get() != null) { LoaderThread oldThread = mLoaderThread; if (oldThread != null) { if (oldThread.isLaunching()) { // don't downgrade isLaunching if we're already running isLaunching = true; } oldThread.stopLocked(); } mLoaderThread = new LoaderThread(context, oldThread, isLaunching); mLoaderThread.start(); } } } public void stopLoader() { synchronized (mLock) { if (mLoaderThread != null) { mLoaderThread.stopLocked(); } } } public void setWorkspaceDirty() { synchronized (mLock) { mWorkspaceSeq++; } } public void setAllAppsDirty() { synchronized (mLock) { mAllAppsSeq++; } } /** * Runnable for the thread that loads the contents of the launcher: * - workspace icons * - widgets * - all apps icons */ private class LoaderThread extends Thread { private Context mContext; private Thread mWaitThread; private boolean mIsLaunching; private boolean mStopped; private boolean mWorkspaceDoneBinding; LoaderThread(Context context, Thread waitThread, boolean isLaunching) { mContext = context; mWaitThread = waitThread; mIsLaunching = isLaunching; } boolean isLaunching() { return mIsLaunching; } /** * If another LoaderThread was supplied, we need to wait for that to finish before * we start our processing. This keeps the ordering of the setting and clearing * of the dirty flags correct by making sure we don't start processing stuff until * they've had a chance to re-set them. We do this waiting the worker thread, not * the ui thread to avoid ANRs. */ private void waitForOtherThread() { if (mWaitThread != null) { boolean done = false; while (!done) { try { mWaitThread.join(); done = true; } catch (InterruptedException ex) { // Ignore } } mWaitThread = null; } } public void run() { waitForOtherThread(); // Elevate priority when Home launches for the first time to avoid // starving at boot time. Staring at a blank home is not cool. synchronized (mLock) { android.os.Process.setThreadPriority(mIsLaunching ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND); } // Load the workspace only if it's dirty. int workspaceSeq; boolean workspaceDirty; synchronized (mLock) { workspaceSeq = mWorkspaceSeq; workspaceDirty = mWorkspaceSeq != mLastWorkspaceSeq; } if (workspaceDirty) { loadWorkspace(); } synchronized (mLock) { // If we're not stopped, and nobody has incremented mWorkspaceSeq. if (mStopped) { return; } if (workspaceSeq == mWorkspaceSeq) { mLastWorkspaceSeq = mWorkspaceSeq; } } // Bind the workspace bindWorkspace(); // Wait until the either we're stopped or the other threads are done. // This way we don't start loading all apps until the workspace has settled // down. synchronized (LoaderThread.this) { mHandler.postIdle(new Runnable() { public void run() { synchronized (LoaderThread.this) { mWorkspaceDoneBinding = true; if (DEBUG_LOADERS) { Log.d(TAG, "done with workspace"); } LoaderThread.this.notify(); } } }); if (DEBUG_LOADERS) { Log.d(TAG, "waiting to be done with workspace"); } while (!mStopped && !mWorkspaceDoneBinding) { try { this.wait(); } catch (InterruptedException ex) { // Ignore } } if (DEBUG_LOADERS) { Log.d(TAG, "done waiting to be done with workspace"); } } // Whew! Hard work done. synchronized (mLock) { if (mIsLaunching) { android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); } } // Load all apps if they're dirty int allAppsSeq; boolean allAppsDirty; synchronized (mLock) { allAppsSeq = mAllAppsSeq; allAppsDirty = mAllAppsSeq != mLastAllAppsSeq; if (DEBUG_LOADERS) { Log.d(TAG, "mAllAppsSeq=" + mAllAppsSeq + " mLastAllAppsSeq=" + mLastAllAppsSeq + " allAppsDirty"); } } if (allAppsDirty) { loadAndBindAllApps(); } synchronized (mLock) { // If we're not stopped, and nobody has incremented mAllAppsSeq. if (mStopped) { return; } if (allAppsSeq == mAllAppsSeq) { mLastAllAppsSeq = mAllAppsSeq; } } // Clear out this reference, otherwise we end up holding it until all of the // callback runnables are done. mContext = null; synchronized (mLock) { // Setting the reference is atomic, but we can't do it inside the other critical // sections. mLoaderThread = null; } } public void stopLocked() { synchronized (LoaderThread.this) { mStopped = true; this.notify(); } } /** * Gets the callbacks object. If we've been stopped, or if the launcher object * has somehow been garbage collected, return null instead. Pass in the Callbacks * object that was around when the deferred message was scheduled, and if there's * a new Callbacks object around then also return null. This will save us from * calling onto it with data that will be ignored. */ Callbacks tryGetCallbacks(Callbacks oldCallbacks) { synchronized (mLock) { if (mStopped) { return null; } if (mCallbacks == null) { return null; } final Callbacks callbacks = mCallbacks.get(); if (callbacks != oldCallbacks) { return null; } if (callbacks == null) { Log.w(TAG, "no mCallbacks"); return null; } return callbacks; } } private void loadWorkspace() { long t = SystemClock.uptimeMillis(); final Context context = mContext; final ContentResolver contentResolver = context.getContentResolver(); final PackageManager manager = context.getPackageManager(); final AppWidgetManager widgets = AppWidgetManager.getInstance(context); final boolean isSafeMode = manager.isSafeMode(); mItems.clear(); mAppWidgets.clear(); mFolders.clear(); final ArrayList<Long> itemsToRemove = new ArrayList<Long>(); final Cursor c = contentResolver.query( LauncherSettings.Favorites.CONTENT_URI, null, null, null, null); try { final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID); final int intentIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.INTENT); final int titleIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.TITLE); final int iconTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_TYPE); final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON); final int iconPackageIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_PACKAGE); final int iconResourceIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_RESOURCE); final int containerIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.CONTAINER); final int itemTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ITEM_TYPE); final int appWidgetIdIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.APPWIDGET_ID); final int screenIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLY); final int spanXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.SPANX); final int spanYIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SPANY); final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI); final int displayModeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.DISPLAY_MODE); ShortcutInfo info; String intentDescription; LauncherAppWidgetInfo appWidgetInfo; int container; long id; Intent intent; while (!mStopped && c.moveToNext()) { try { int itemType = c.getInt(itemTypeIndex); switch (itemType) { case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: intentDescription = c.getString(intentIndex); try { intent = Intent.parseUri(intentDescription, 0); } catch (URISyntaxException e) { continue; } if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) { info = getShortcutInfo(manager, intent, context, c, iconIndex, titleIndex); } else { info = getShortcutInfo(c, context, iconTypeIndex, iconPackageIndex, iconResourceIndex, iconIndex, titleIndex); } if (info != null) { updateSavedIcon(context, info, c, iconIndex); info.intent = intent; info.id = c.getLong(idIndex); container = c.getInt(containerIndex); info.container = container; info.screen = c.getInt(screenIndex); info.cellX = c.getInt(cellXIndex); info.cellY = c.getInt(cellYIndex); switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: mItems.add(info); break; default: // Item is in a user folder UserFolderInfo folderInfo = findOrMakeUserFolder(mFolders, container); folderInfo.add(info); break; } } else { // Failed to load the shortcut, probably because the // activity manager couldn't resolve it (maybe the app // was uninstalled), or the db row was somehow screwed up. // Delete it. id = c.getLong(idIndex); Log.e(TAG, "Error loading shortcut " + id + ", removing it"); contentResolver.delete(LauncherSettings.Favorites.getContentUri( id, false), null, null); } break; case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER: id = c.getLong(idIndex); UserFolderInfo folderInfo = findOrMakeUserFolder(mFolders, id); folderInfo.title = c.getString(titleIndex); folderInfo.id = id; container = c.getInt(containerIndex); folderInfo.container = container; folderInfo.screen = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: mItems.add(folderInfo); break; } mFolders.put(folderInfo.id, folderInfo); break; case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER: id = c.getLong(idIndex); Uri uri = Uri.parse(c.getString(uriIndex)); // Make sure the live folder exists final ProviderInfo providerInfo = context.getPackageManager().resolveContentProvider( uri.getAuthority(), 0); if (providerInfo == null && !isSafeMode) { itemsToRemove.add(id); } else { LiveFolderInfo liveFolderInfo = findOrMakeLiveFolder(mFolders, id); intentDescription = c.getString(intentIndex); intent = null; if (intentDescription != null) { try { intent = Intent.parseUri(intentDescription, 0); } catch (URISyntaxException e) { // Ignore, a live folder might not have a base intent } } liveFolderInfo.title = c.getString(titleIndex); liveFolderInfo.id = id; liveFolderInfo.uri = uri; container = c.getInt(containerIndex); liveFolderInfo.container = container; liveFolderInfo.screen = c.getInt(screenIndex); liveFolderInfo.cellX = c.getInt(cellXIndex); liveFolderInfo.cellY = c.getInt(cellYIndex); liveFolderInfo.baseIntent = intent; liveFolderInfo.displayMode = c.getInt(displayModeIndex); loadLiveFolderIcon(context, c, iconTypeIndex, iconPackageIndex, iconResourceIndex, liveFolderInfo); switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: mItems.add(liveFolderInfo); break; } mFolders.put(liveFolderInfo.id, liveFolderInfo); } break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: // Read all Launcher-specific widget details int appWidgetId = c.getInt(appWidgetIdIndex); id = c.getLong(idIndex); final AppWidgetProviderInfo provider = widgets.getAppWidgetInfo(appWidgetId); if (!isSafeMode && (provider == null || provider.provider == null || provider.provider.getPackageName() == null)) { Log.e(TAG, "Deleting widget that isn't installed anymore: id=" + id + " appWidgetId=" + appWidgetId); itemsToRemove.add(id); } else { appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId); appWidgetInfo.id = id; appWidgetInfo.screen = c.getInt(screenIndex); appWidgetInfo.cellX = c.getInt(cellXIndex); appWidgetInfo.cellY = c.getInt(cellYIndex); appWidgetInfo.spanX = c.getInt(spanXIndex); appWidgetInfo.spanY = c.getInt(spanYIndex); container = c.getInt(containerIndex); if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) { Log.e(TAG, "Widget found where container " + "!= CONTAINER_DESKTOP -- ignoring!"); continue; } appWidgetInfo.container = c.getInt(containerIndex); mAppWidgets.add(appWidgetInfo); } break; } } catch (Exception e) { Log.w(TAG, "Desktop items loading interrupted:", e); } } } finally { c.close(); } if (itemsToRemove.size() > 0) { ContentProviderClient client = contentResolver.acquireContentProviderClient( LauncherSettings.Favorites.CONTENT_URI); // Remove dead items for (long id : itemsToRemove) { if (DEBUG_LOADERS) { Log.d(TAG, "Removed id = " + id); } // Don't notify content observers try { client.delete(LauncherSettings.Favorites.getContentUri(id, false), null, null); } catch (RemoteException e) { Log.w(TAG, "Could not remove id = " + id); } } } if (DEBUG_LOADERS) { Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); } } /** * Read everything out of our database. */ private void bindWorkspace() { final long t = SystemClock.uptimeMillis(); // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderThread running with no launcher"); return; } int N; // Tell the workspace that we're about to start firing items at it mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.startBinding(); } } }); // Add the items to the workspace. N = mItems.size(); for (int i=0; i<N; i+=ITEMS_CHUNK) { final int start = i; final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i); mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindItems(mItems, start, start+chunkSize); } } }); } mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindFolders(mFolders); } } }); // Wait until the queue goes empty. mHandler.postIdle(new Runnable() { public void run() { if (DEBUG_LOADERS) { Log.d(TAG, "Going to start binding widgets soon."); } } }); // Bind the widgets, one at a time. // WARNING: this is calling into the workspace from the background thread, // but since getCurrentScreen() just returns the int, we should be okay. This // is just a hint for the order, and if it's wrong, we'll be okay. // TODO: instead, we should have that push the current screen into here. final int currentScreen = oldCallbacks.getCurrentWorkspaceScreen(); N = mAppWidgets.size(); // once for the current screen for (int i=0; i<N; i++) { final LauncherAppWidgetInfo widget = mAppWidgets.get(i); if (widget.screen == currentScreen) { mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAppWidget(widget); } } }); } } // once for the other screens for (int i=0; i<N; i++) { final LauncherAppWidgetInfo widget = mAppWidgets.get(i); if (widget.screen != currentScreen) { mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAppWidget(widget); } } }); } } // Tell the workspace that we're done. mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.finishBindingItems(); } } }); // If we're profiling, this is the last thing in the queue. mHandler.post(new Runnable() { public void run() { if (DEBUG_LOADERS) { Log.d(TAG, "bound workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); } if (Launcher.PROFILE_ROTATE) { android.os.Debug.stopMethodTracing(); } } }); } private void loadAndBindAllApps() { final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderThread running with no launcher (loadAndBindAllApps)"); return; } final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); final PackageManager packageManager = mContext.getPackageManager(); List<ResolveInfo> apps = null; int N = Integer.MAX_VALUE; int startIndex; int i=0; int batchSize = -1; while (i < N && !mStopped) { synchronized (mLock) { if (i == 0) { // This needs to happen inside the same lock block as when we // prepare the first batch for bindAllApplications. Otherwise // the package changed receiver can come in and double-add // (or miss one?). mAllAppsList.clear(); final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; apps = packageManager.queryIntentActivities(mainIntent, 0); if (DEBUG_LOADERS) { Log.d(TAG, "queryIntentActivities took " + (SystemClock.uptimeMillis()-qiaTime) + "ms"); } if (apps == null) { return; } N = apps.size(); if (DEBUG_LOADERS) { Log.d(TAG, "queryIntentActivities got " + N + " apps"); } if (N == 0) { // There are no apps?!? return; } if (mBatchSize == 0) { batchSize = N; } else { batchSize = mBatchSize; } final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; Collections.sort(apps, new ResolveInfo.DisplayNameComparator(packageManager)); if (DEBUG_LOADERS) { Log.d(TAG, "sort took " + (SystemClock.uptimeMillis()-qiaTime) + "ms"); } } final long t2 = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; startIndex = i; for (int j=0; i<N && j<batchSize; j++) { // This builds the icon bitmaps. mAllAppsList.add(new ApplicationInfo(apps.get(i), mIconCache)); i++; } final boolean first = i <= batchSize; final ArrayList<ApplicationInfo> added = mAllAppsList.added; mAllAppsList.added = new ArrayList<ApplicationInfo>(); mHandler.post(new Runnable() { public void run() { final long t = SystemClock.uptimeMillis(); final Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { if (first) { mBeforeFirstLoad = false; callbacks.bindAllApplications(added); } else { callbacks.bindAppsAdded(added); } if (DEBUG_LOADERS) { Log.d(TAG, "bound " + added.size() + " apps in " + (SystemClock.uptimeMillis() - t) + "ms"); } } else { Log.i(TAG, "not binding apps: no Launcher activity"); } } }); if (DEBUG_LOADERS) { Log.d(TAG, "batch of " + (i-startIndex) + " icons processed in " + (SystemClock.uptimeMillis()-t2) + "ms"); } } if (mAllAppsLoadDelay > 0 && i < N) { try { if (DEBUG_LOADERS) { Log.d(TAG, "sleeping for " + mAllAppsLoadDelay + "ms"); } Thread.sleep(mAllAppsLoadDelay); } catch (InterruptedException exc) { } } } if (DEBUG_LOADERS) { Log.d(TAG, "cached all " + N + " apps in " + (SystemClock.uptimeMillis()-t) + "ms" + (mAllAppsLoadDelay > 0 ? " (including delay)" : "")); } } public void dumpState() { Log.d(TAG, "mLoader.mLoaderThread.mContext=" + mContext); Log.d(TAG, "mLoader.mLoaderThread.mWaitThread=" + mWaitThread); Log.d(TAG, "mLoader.mLoaderThread.mIsLaunching=" + mIsLaunching); Log.d(TAG, "mLoader.mLoaderThread.mStopped=" + mStopped); Log.d(TAG, "mLoader.mLoaderThread.mWorkspaceDoneBinding=" + mWorkspaceDoneBinding); } } public void dumpState() { Log.d(TAG, "mLoader.mLastWorkspaceSeq=" + mLoader.mLastWorkspaceSeq); Log.d(TAG, "mLoader.mWorkspaceSeq=" + mLoader.mWorkspaceSeq); Log.d(TAG, "mLoader.mLastAllAppsSeq=" + mLoader.mLastAllAppsSeq); Log.d(TAG, "mLoader.mAllAppsSeq=" + mLoader.mAllAppsSeq); Log.d(TAG, "mLoader.mItems size=" + mLoader.mItems.size()); if (mLoaderThread != null) { mLoaderThread.dumpState(); } else { Log.d(TAG, "mLoader.mLoaderThread=null"); } } } /** * This is called from the code that adds shortcuts from the intent receiver. This * doesn't have a Cursor, but */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) { return getShortcutInfo(manager, intent, context, null, -1, -1); } /** * Make an ShortcutInfo object for a shortcut that is an application. * * If c is not null, then it will be used to fill in missing data like the title and icon. */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context, Cursor c, int iconIndex, int titleIndex) { Bitmap icon = null; final ShortcutInfo info = new ShortcutInfo(); ComponentName componentName = intent.getComponent(); if (componentName == null) { return null; } // TODO: See if the PackageManager knows about this case. If it doesn't // then return null & delete this. // the resource -- This may implicitly give us back the fallback icon, // but don't worry about that. All we're doing with usingFallbackIcon is // to avoid saving lots of copies of that in the database, and most apps // have icons anyway. final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0); if (resolveInfo != null) { icon = mIconCache.getIcon(componentName, resolveInfo); } // the db if (icon == null) { if (c != null) { icon = getIconFromCursor(c, iconIndex); } } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } info.setIcon(icon); // from the resource if (resolveInfo != null) { info.title = resolveInfo.activityInfo.loadLabel(manager); } // from the db if (info.title == null) { if (c != null) { info.title = c.getString(titleIndex); } } // fall back to the class name of the activity if (info.title == null) { info.title = componentName.getClassName(); } info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION; return info; } /** * Make an ShortcutInfo object for a shortcut that isn't an application. */ private ShortcutInfo getShortcutInfo(Cursor c, Context context, int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex, int titleIndex) { Bitmap icon = null; final ShortcutInfo info = new ShortcutInfo(); info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT; // TODO: If there's an explicit component and we can't install that, delete it. info.title = c.getString(titleIndex); int iconType = c.getInt(iconTypeIndex); switch (iconType) { case LauncherSettings.Favorites.ICON_TYPE_RESOURCE: String packageName = c.getString(iconPackageIndex); String resourceName = c.getString(iconResourceIndex); PackageManager packageManager = context.getPackageManager(); info.customIcon = false; // the resource try { Resources resources = packageManager.getResourcesForApplication(packageName); if (resources != null) { final int id = resources.getIdentifier(resourceName, null, null); icon = Utilities.createIconBitmap(resources.getDrawable(id), context); } } catch (Exception e) { // drop this. we have other places to look for icons } // the db if (icon == null) { icon = getIconFromCursor(c, iconIndex); } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } break; case LauncherSettings.Favorites.ICON_TYPE_BITMAP: icon = getIconFromCursor(c, iconIndex); if (icon == null) { icon = getFallbackIcon(); info.customIcon = false; info.usingFallbackIcon = true; } else { info.customIcon = true; } break; default: icon = getFallbackIcon(); info.usingFallbackIcon = true; info.customIcon = false; break; } info.setIcon(icon); return info; } Bitmap getIconFromCursor(Cursor c, int iconIndex) { if (false) { Log.d(TAG, "getIconFromCursor app=" + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE))); } byte[] data = c.getBlob(iconIndex); try { return BitmapFactory.decodeByteArray(data, 0, data.length); } catch (Exception e) { return null; } } ShortcutInfo addShortcut(Context context, Intent data, CellLayout.CellInfo cellInfo, boolean notify) { final ShortcutInfo info = infoFromShortcutIntent(context, data); addItemToDatabase(context, info, LauncherSettings.Favorites.CONTAINER_DESKTOP, cellInfo.screen, cellInfo.cellX, cellInfo.cellY, notify); return info; } private ShortcutInfo infoFromShortcutIntent(Context context, Intent data) { Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT); String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME); Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON); Bitmap icon = null; boolean filtered = false; boolean customIcon = false; ShortcutIconResource iconResource = null; if (bitmap != null && bitmap instanceof Bitmap) { icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context); filtered = true; customIcon = true; } else { Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE); if (extra != null && extra instanceof ShortcutIconResource) { try { iconResource = (ShortcutIconResource) extra; final PackageManager packageManager = context.getPackageManager(); Resources resources = packageManager.getResourcesForApplication( iconResource.packageName); final int id = resources.getIdentifier(iconResource.resourceName, null, null); icon = Utilities.createIconBitmap(resources.getDrawable(id), context); } catch (Exception e) { Log.w(TAG, "Could not load shortcut icon: " + extra); } } } final ShortcutInfo info = new ShortcutInfo(); if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } info.setIcon(icon); info.title = name; info.intent = intent; info.customIcon = customIcon; info.iconResource = iconResource; return info; } private static void loadLiveFolderIcon(Context context, Cursor c, int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, LiveFolderInfo liveFolderInfo) { int iconType = c.getInt(iconTypeIndex); switch (iconType) { case LauncherSettings.Favorites.ICON_TYPE_RESOURCE: String packageName = c.getString(iconPackageIndex); String resourceName = c.getString(iconResourceIndex); PackageManager packageManager = context.getPackageManager(); try { Resources resources = packageManager.getResourcesForApplication(packageName); final int id = resources.getIdentifier(resourceName, null, null); liveFolderInfo.icon = Utilities.createIconBitmap(resources.getDrawable(id), context); } catch (Exception e) { liveFolderInfo.icon = Utilities.createIconBitmap( context.getResources().getDrawable(R.drawable.ic_launcher_folder), context); } liveFolderInfo.iconResource = new Intent.ShortcutIconResource(); liveFolderInfo.iconResource.packageName = packageName; liveFolderInfo.iconResource.resourceName = resourceName; break; default: liveFolderInfo.icon = Utilities.createIconBitmap( context.getResources().getDrawable(R.drawable.ic_launcher_folder), context); } } void updateSavedIcon(Context context, ShortcutInfo info, Cursor c, int iconIndex) { // If this icon doesn't have a custom icon, check to see // what's stored in the DB, and if it doesn't match what // we're going to show, store what we are going to show back // into the DB. We do this so when we're loading, if the // package manager can't find an icon (for example because // the app is on SD) then we can use that instead. if (info.onExternalStorage && !info.customIcon && !info.usingFallbackIcon) { boolean needSave; byte[] data = c.getBlob(iconIndex); try { if (data != null) { Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length); Bitmap loaded = info.getIcon(mIconCache); needSave = !saved.sameAs(loaded); } else { needSave = true; } } catch (Exception e) { needSave = true; } if (needSave) { Log.d(TAG, "going to save icon bitmap for info=" + info); // This is slower than is ideal, but this only happens either // after the froyo OTA or when the app is updated with a new // icon. updateItemInDatabase(context, info); } } } /** * Return an existing UserFolderInfo object if we have encountered this ID previously, * or make a new one. */ private static UserFolderInfo findOrMakeUserFolder(HashMap<Long, FolderInfo> folders, long id) { // See if a placeholder was created for us already FolderInfo folderInfo = folders.get(id); if (folderInfo == null || !(folderInfo instanceof UserFolderInfo)) { // No placeholder -- create a new instance folderInfo = new UserFolderInfo(); folders.put(id, folderInfo); } return (UserFolderInfo) folderInfo; } /** * Return an existing UserFolderInfo object if we have encountered this ID previously, or make a * new one. */ private static LiveFolderInfo findOrMakeLiveFolder(HashMap<Long, FolderInfo> folders, long id) { // See if a placeholder was created for us already FolderInfo folderInfo = folders.get(id); if (folderInfo == null || !(folderInfo instanceof LiveFolderInfo)) { // No placeholder -- create a new instance folderInfo = new LiveFolderInfo(); folders.put(id, folderInfo); } return (LiveFolderInfo) folderInfo; } private static String getLabel(PackageManager manager, ActivityInfo activityInfo) { String label = activityInfo.loadLabel(manager).toString(); if (label == null) { label = manager.getApplicationLabel(activityInfo.applicationInfo).toString(); if (label == null) { label = activityInfo.name; } } return label; } private static final Collator sCollator = Collator.getInstance(); public static final Comparator<ApplicationInfo> APP_NAME_COMPARATOR = new Comparator<ApplicationInfo>() { public final int compare(ApplicationInfo a, ApplicationInfo b) { return sCollator.compare(a.title.toString(), b.title.toString()); } }; public void dumpState() { Log.d(TAG, "mBeforeFirstLoad=" + mBeforeFirstLoad); Log.d(TAG, "mCallbacks=" + mCallbacks); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mAllAppsList.data); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mAllAppsList.added); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mAllAppsList.removed); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mAllAppsList.modified); mLoader.dumpState(); } }
diff --git a/GUI.java b/GUI.java index 6c0115b..18a3bc9 100644 --- a/GUI.java +++ b/GUI.java @@ -1,158 +1,158 @@ import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.UIManager.*; /** * @author Brian Mock */ public class GUI extends JFrame implements ActionListener { private JButton waveButton; private JButton wavierButton; private JButton saddleButton; private JButton defaultShaderButton; private JButton phongShaderButton; private JButton celShaderButton; private String theShader; private String theTitle = "Volume Integral Visualizer by Brian Mock"; // Method provided by Oracle.com Java tutorial private void attemptNimbusStyle() { try { for (LookAndFeelInfo info: UIManager.getInstalledLookAndFeels()) { if (info.getName().equals("Nimbus")) { UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (Exception e) { } } public GUI() { attemptNimbusStyle(); setTitle(theTitle); waveButton = new JButton("Wave" ); wavierButton = new JButton("Wavier"); saddleButton = new JButton("Saddle"); //=========================================| defaultShaderButton = new JButton("Plain" ); phongShaderButton = new JButton("Pretty"); celShaderButton = new JButton("Cel" ); theShader = null; disableShaderButton(defaultShaderButton); waveButton .setActionCommand("set_func_wave" ); wavierButton .setActionCommand("set_func_wavier" ); saddleButton .setActionCommand("set_func_saddle" ); //=======================================================| defaultShaderButton .setActionCommand("set_shader_none" ); phongShaderButton .setActionCommand("set_shader_phong"); celShaderButton .setActionCommand("set_shader_cel" ); Container cp = getContentPane(); cp.setLayout(new FlowLayout()); cp.add(defaultShaderButton); cp.add(phongShaderButton ); - cp.add(celShaderButton ); + //cp.add(celShaderButton ); //=========================| cp.add(makeVSep() ); cp.add(makeVSep() ); //=========================| cp.add(waveButton ); cp.add(wavierButton ); - //cp.add(saddleButton ); + cp.add(saddleButton ); pack(); defaultShaderButton .addActionListener(this); phongShaderButton .addActionListener(this); celShaderButton .addActionListener(this); //==========================================| waveButton .addActionListener(this); wavierButton .addActionListener(this); saddleButton .addActionListener(this); setDefaultCloseOperation(DISPOSE_ON_CLOSE); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { GUI gui = new GUI(); gui.setVisible(true); } }); } public JSeparator makeVSep() { return new JSeparator(JSeparator.VERTICAL); } public void actionPerformed(ActionEvent e) { Object src = e.getSource(); String cmd = e.getActionCommand(); if (cmd.equals("set_func_wave")) { Visualizer.launchWith(new WaveFunc(), theShader); } else if (cmd.equals("set_func_wavier")) { Visualizer.launchWith(new WavierFunc(), theShader); } else if (cmd.equals("set_func_saddle")) { Visualizer.launchWith(new SaddleFunc(), theShader); } else if (cmd.equals("set_shader_none")) { useShaderButton(src, null); } else if (cmd.equals("set_shader_phong")) { useShaderButton(src, "phong"); } else if (cmd.equals("set_shader_cel")) { useShaderButton(src, "cel"); } } private void useShaderButton(Object button, String shaderName) { JButton cButton = (JButton) button; enableShaderButtons(); disableShaderButton(cButton); theShader = shaderName; } private void enableShaderButtons() { JButton[] buttons = { celShaderButton, phongShaderButton, defaultShaderButton }; for (JButton button: buttons) { button.setEnabled(true); } } private void disableShaderButton(JButton button) { button.setEnabled(false); } }
false
true
GUI() { attemptNimbusStyle(); setTitle(theTitle); waveButton = new JButton("Wave" ); wavierButton = new JButton("Wavier"); saddleButton = new JButton("Saddle"); //=========================================| defaultShaderButton = new JButton("Plain" ); phongShaderButton = new JButton("Pretty"); celShaderButton = new JButton("Cel" ); theShader = null; disableShaderButton(defaultShaderButton); waveButton .setActionCommand("set_func_wave" ); wavierButton .setActionCommand("set_func_wavier" ); saddleButton .setActionCommand("set_func_saddle" ); //=======================================================| defaultShaderButton .setActionCommand("set_shader_none" ); phongShaderButton .setActionCommand("set_shader_phong"); celShaderButton .setActionCommand("set_shader_cel" ); Container cp = getContentPane(); cp.setLayout(new FlowLayout()); cp.add(defaultShaderButton); cp.add(phongShaderButton ); cp.add(celShaderButton ); //=========================| cp.add(makeVSep() ); cp.add(makeVSep() ); //=========================| cp.add(waveButton ); cp.add(wavierButton ); //cp.add(saddleButton ); pack(); defaultShaderButton .addActionListener(this); phongShaderButton .addActionListener(this); celShaderButton .addActionListener(this); //==========================================| waveButton .addActionListener(this); wavierButton .addActionListener(this); saddleButton .addActionListener(this); setDefaultCloseOperation(DISPOSE_ON_CLOSE); }
GUI() { attemptNimbusStyle(); setTitle(theTitle); waveButton = new JButton("Wave" ); wavierButton = new JButton("Wavier"); saddleButton = new JButton("Saddle"); //=========================================| defaultShaderButton = new JButton("Plain" ); phongShaderButton = new JButton("Pretty"); celShaderButton = new JButton("Cel" ); theShader = null; disableShaderButton(defaultShaderButton); waveButton .setActionCommand("set_func_wave" ); wavierButton .setActionCommand("set_func_wavier" ); saddleButton .setActionCommand("set_func_saddle" ); //=======================================================| defaultShaderButton .setActionCommand("set_shader_none" ); phongShaderButton .setActionCommand("set_shader_phong"); celShaderButton .setActionCommand("set_shader_cel" ); Container cp = getContentPane(); cp.setLayout(new FlowLayout()); cp.add(defaultShaderButton); cp.add(phongShaderButton ); //cp.add(celShaderButton ); //=========================| cp.add(makeVSep() ); cp.add(makeVSep() ); //=========================| cp.add(waveButton ); cp.add(wavierButton ); cp.add(saddleButton ); pack(); defaultShaderButton .addActionListener(this); phongShaderButton .addActionListener(this); celShaderButton .addActionListener(this); //==========================================| waveButton .addActionListener(this); wavierButton .addActionListener(this); saddleButton .addActionListener(this); setDefaultCloseOperation(DISPOSE_ON_CLOSE); }
diff --git a/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/outline/cssdialog/tabs/TabPropertySheetControl.java b/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/outline/cssdialog/tabs/TabPropertySheetControl.java index 66ebb2cc..135d95cf 100644 --- a/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/outline/cssdialog/tabs/TabPropertySheetControl.java +++ b/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/outline/cssdialog/tabs/TabPropertySheetControl.java @@ -1,136 +1,137 @@ /******************************************************************************* * Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Exadel, Inc. and Red Hat, Inc. - initial API and implementation ******************************************************************************/ package org.jboss.tools.jst.jsp.outline.cssdialog.tabs; import java.util.ArrayList; import java.util.Set; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.TreeEditor; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeColumn; import org.eclipse.swt.widgets.TreeItem; import org.jboss.tools.jst.jsp.messages.JstUIMessages; import org.jboss.tools.jst.jsp.outline.cssdialog.common.CSSConstants; import org.jboss.tools.jst.jsp.outline.cssdialog.common.StyleAttributes; /** * Class for creating Property sheet tab * * @author Evgeny Zheleznyakov */ public class TabPropertySheetControl extends BaseTabControl { final static private String[] COLUMNS = new String[] { JstUIMessages.PROPERTY_NAME_COLUMN, JstUIMessages.PROPERTY_VALUE_COLUMN }; final static private int COLUMNS_WIDTH = 200; private Tree tree; /** * Constructor for creating controls * * @param composite * The parent composite for tab * @param elementMap * @param comboMap * @param styleAttributes * the StyleAttributes object */ public TabPropertySheetControl(Composite parent, StyleAttributes styleAttributes, DataBindingContext bindingContext) { super(bindingContext, styleAttributes, parent, SWT.NONE); setLayout(new FillLayout()); tree = new Tree(this, SWT.FULL_SELECTION | SWT.SINGLE | SWT.HIDE_SELECTION); tree.setHeaderVisible(true); tree.setLinesVisible(true); // Create columns for (int i = 0; i < COLUMNS.length; i++) { TreeColumn column = new TreeColumn(tree, SWT.LEFT | SWT.COLOR_BLACK); column.setText(COLUMNS[i]); column.setWidth(COLUMNS_WIDTH); } Set<String> sections = CSSConstants.CSS_STYLES_MAP.keySet(); for (String sectionKey : sections) { TreeItem sectionTreeItem = createTreeItem(tree, sectionKey); sectionTreeItem.setExpanded(true); ArrayList<String> attributeKeys = CSSConstants.CSS_STYLES_MAP .get(sectionKey); for (String attribute : attributeKeys) { TreeItem item = createBindedTreeItem(sectionTreeItem, attribute); item.setExpanded(true); } + sectionTreeItem.setExpanded(true); } final TreeEditor editor = new TreeEditor(tree); editor.horizontalAlignment = SWT.LEFT; editor.grabHorizontal = true; editor.minimumHeight = 0; editor.minimumWidth = 0; tree.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { // Clean up any previous editor control Control oldEditor = editor.getEditor(); if (oldEditor != null) oldEditor.dispose(); // Identify the selected row TreeItem item = (TreeItem) e.item; if (item == null) return; // The control that will be the editor must be a child of the // Tree Control newEditor = null; if (!CSSConstants.CSS_STYLES_MAP.containsKey((item .getText(NAME_ATTRIBUTE_COLUMN)))) { newEditor = createControl(tree, item .getText(NAME_ATTRIBUTE_COLUMN)); } if (newEditor != null) { newEditor.setFocus(); // Compute the width for the editor // Also, compute the column width, so that the dropdown fits Point size = newEditor .computeSize(SWT.DEFAULT, SWT.DEFAULT); editor.minimumWidth = size.x; editor.minimumHeight = size.y; if (tree.getColumn(VALUE_ATTRIBUTE_COLUMN).getWidth() < editor.minimumWidth) tree.getColumn(VALUE_ATTRIBUTE_COLUMN).setWidth( editor.minimumWidth); editor.setEditor(newEditor, item, VALUE_ATTRIBUTE_COLUMN); } } }); } }
true
true
public TabPropertySheetControl(Composite parent, StyleAttributes styleAttributes, DataBindingContext bindingContext) { super(bindingContext, styleAttributes, parent, SWT.NONE); setLayout(new FillLayout()); tree = new Tree(this, SWT.FULL_SELECTION | SWT.SINGLE | SWT.HIDE_SELECTION); tree.setHeaderVisible(true); tree.setLinesVisible(true); // Create columns for (int i = 0; i < COLUMNS.length; i++) { TreeColumn column = new TreeColumn(tree, SWT.LEFT | SWT.COLOR_BLACK); column.setText(COLUMNS[i]); column.setWidth(COLUMNS_WIDTH); } Set<String> sections = CSSConstants.CSS_STYLES_MAP.keySet(); for (String sectionKey : sections) { TreeItem sectionTreeItem = createTreeItem(tree, sectionKey); sectionTreeItem.setExpanded(true); ArrayList<String> attributeKeys = CSSConstants.CSS_STYLES_MAP .get(sectionKey); for (String attribute : attributeKeys) { TreeItem item = createBindedTreeItem(sectionTreeItem, attribute); item.setExpanded(true); } } final TreeEditor editor = new TreeEditor(tree); editor.horizontalAlignment = SWT.LEFT; editor.grabHorizontal = true; editor.minimumHeight = 0; editor.minimumWidth = 0; tree.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { // Clean up any previous editor control Control oldEditor = editor.getEditor(); if (oldEditor != null) oldEditor.dispose(); // Identify the selected row TreeItem item = (TreeItem) e.item; if (item == null) return; // The control that will be the editor must be a child of the // Tree Control newEditor = null; if (!CSSConstants.CSS_STYLES_MAP.containsKey((item .getText(NAME_ATTRIBUTE_COLUMN)))) { newEditor = createControl(tree, item .getText(NAME_ATTRIBUTE_COLUMN)); } if (newEditor != null) { newEditor.setFocus(); // Compute the width for the editor // Also, compute the column width, so that the dropdown fits Point size = newEditor .computeSize(SWT.DEFAULT, SWT.DEFAULT); editor.minimumWidth = size.x; editor.minimumHeight = size.y; if (tree.getColumn(VALUE_ATTRIBUTE_COLUMN).getWidth() < editor.minimumWidth) tree.getColumn(VALUE_ATTRIBUTE_COLUMN).setWidth( editor.minimumWidth); editor.setEditor(newEditor, item, VALUE_ATTRIBUTE_COLUMN); } } }); }
public TabPropertySheetControl(Composite parent, StyleAttributes styleAttributes, DataBindingContext bindingContext) { super(bindingContext, styleAttributes, parent, SWT.NONE); setLayout(new FillLayout()); tree = new Tree(this, SWT.FULL_SELECTION | SWT.SINGLE | SWT.HIDE_SELECTION); tree.setHeaderVisible(true); tree.setLinesVisible(true); // Create columns for (int i = 0; i < COLUMNS.length; i++) { TreeColumn column = new TreeColumn(tree, SWT.LEFT | SWT.COLOR_BLACK); column.setText(COLUMNS[i]); column.setWidth(COLUMNS_WIDTH); } Set<String> sections = CSSConstants.CSS_STYLES_MAP.keySet(); for (String sectionKey : sections) { TreeItem sectionTreeItem = createTreeItem(tree, sectionKey); sectionTreeItem.setExpanded(true); ArrayList<String> attributeKeys = CSSConstants.CSS_STYLES_MAP .get(sectionKey); for (String attribute : attributeKeys) { TreeItem item = createBindedTreeItem(sectionTreeItem, attribute); item.setExpanded(true); } sectionTreeItem.setExpanded(true); } final TreeEditor editor = new TreeEditor(tree); editor.horizontalAlignment = SWT.LEFT; editor.grabHorizontal = true; editor.minimumHeight = 0; editor.minimumWidth = 0; tree.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { // Clean up any previous editor control Control oldEditor = editor.getEditor(); if (oldEditor != null) oldEditor.dispose(); // Identify the selected row TreeItem item = (TreeItem) e.item; if (item == null) return; // The control that will be the editor must be a child of the // Tree Control newEditor = null; if (!CSSConstants.CSS_STYLES_MAP.containsKey((item .getText(NAME_ATTRIBUTE_COLUMN)))) { newEditor = createControl(tree, item .getText(NAME_ATTRIBUTE_COLUMN)); } if (newEditor != null) { newEditor.setFocus(); // Compute the width for the editor // Also, compute the column width, so that the dropdown fits Point size = newEditor .computeSize(SWT.DEFAULT, SWT.DEFAULT); editor.minimumWidth = size.x; editor.minimumHeight = size.y; if (tree.getColumn(VALUE_ATTRIBUTE_COLUMN).getWidth() < editor.minimumWidth) tree.getColumn(VALUE_ATTRIBUTE_COLUMN).setWidth( editor.minimumWidth); editor.setEditor(newEditor, item, VALUE_ATTRIBUTE_COLUMN); } } }); }
diff --git a/src/com/oresomecraft/BattleMaps/maps/Apollo.java b/src/com/oresomecraft/BattleMaps/maps/Apollo.java index 4ae8f00..c64479b 100755 --- a/src/com/oresomecraft/BattleMaps/maps/Apollo.java +++ b/src/com/oresomecraft/BattleMaps/maps/Apollo.java @@ -1,121 +1,121 @@ package com.oresomecraft.BattleMaps.maps; import org.bukkit.*; import org.bukkit.enchantments.*; import org.bukkit.event.*; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.inventory.*; import org.bukkit.potion.*; import com.oresomecraft.BattleMaps.*; import com.oresomecraft.OresomeBattles.api.*; public class Apollo extends BattleMap implements IBattleMap, Listener { public Apollo() { super.initiate(this, name, fullName, creators, modes); setAllowBuild(false); } // Map details String name = "apollo"; String fullName = "Apollo"; String creators = "RokMelon and Invinsible_Jelly"; Gamemode[] modes = {Gamemode.TDM, Gamemode.FFA, Gamemode.INFECTION}; public void readyTDMSpawns() { Location redSpawn = new Location(w, -11, 150, 72, 89, 0); Location blueSpawn = new Location(w, -33, 150, 50, -1, 0); redSpawns.add(redSpawn); redSpawns.add(new Location(w, -55, 150, 72, -111, 0)); redSpawns.add(new Location(w, -20, 133, 27, 48, 0)); redSpawns.add(new Location(w, -81, 133, 88, -133, 0)); redSpawns.add(new Location(w, -40, 110, 55, -89, 0)); redSpawns.add(new Location(w, -53, 93, 54, -43, 0)); redSpawns.add(new Location(w, -68, 122, 38, -45, 0)); redSpawns.add(new Location(w, -53, 133, 57, -53, 0)); redSpawns.add(new Location(w, -62, 136, 80, -131, 0)); blueSpawns.add(blueSpawn); blueSpawns.add(new Location(w, -33, 150, 94, 179, 0)); blueSpawns.add(new Location(w, -19, 133, 88, 137, 0)); blueSpawns.add(new Location(w, -82, 133, 25, -44, 0)); blueSpawns.add(new Location(w, -57, 109, 72, -2, 0)); blueSpawns.add(new Location(w, -53, 93, 54, -43, 0)); blueSpawns.add(new Location(w, -68, 122, 38, -45, 0)); blueSpawns.add(new Location(w, -53, 133, 57, -53, 0)); blueSpawns.add(new Location(w, -62, 136, 80, -131, 0)); } public void readyFFASpawns() { FFASpawns.add(new Location(w, -11, 150, 72, 89, 0)); FFASpawns.add(new Location(w, -33, 150, 50, -1, 0)); FFASpawns.add(new Location(w, -55, 150, 72, -111, 0)); FFASpawns.add(new Location(w, -20, 133, 27, 48, 0)); FFASpawns.add(new Location(w, -81, 133, 88, -133, 0)); FFASpawns.add(new Location(w, -40, 110, 55, -89, 0)); FFASpawns.add(new Location(w, -53, 93, 54, -43, 0)); FFASpawns.add(new Location(w, -68, 122, 38, -45, 0)); FFASpawns.add(new Location(w, -53, 133, 57, -53, 0)); FFASpawns.add(new Location(w, -62, 136, 80, -131, 0)); FFASpawns.add(new Location(w, -33, 150, 94, 179, 0)); FFASpawns.add(new Location(w, -19, 133, 88, 137, 0)); FFASpawns.add(new Location(w, -82, 133, 25, -44, 0)); FFASpawns.add(new Location(w, -57, 109, 72, -2, 0)); } public void applyInventory(final BattlePlayer p) { Inventory i = p.getInventory(); ItemStack HEALTH_POTION = new ItemStack(Material.POTION, 1, (short) 16373); ItemStack STEAK = new ItemStack(Material.COOKED_BEEF, 1); ItemStack BOW = new ItemStack(Material.BOW, 1); ItemStack ARROWS = new ItemStack(Material.ARROW, 64); ItemStack IRON_HELMET = new ItemStack(Material.IRON_HELMET, 1); ItemStack IRON_CHESTPLATE = new ItemStack(Material.IRON_CHESTPLATE, 1); ItemStack IRON_PANTS = new ItemStack(Material.IRON_LEGGINGS, 1); ItemStack IRON_BOOTS = new ItemStack(Material.IRON_BOOTS, 1); ItemStack IRON_SWORD = new ItemStack(Material.IRON_SWORD, 1); ItemStack EXP = new ItemStack(Material.EXP_BOTTLE, 5); ItemStack ENDER_PEARL = new ItemStack(Material.ENDER_PEARL, 3); IRON_BOOTS.addUnsafeEnchantment(Enchantment.PROTECTION_FALL, 4); p.getInventory().setBoots(IRON_BOOTS); p.getInventory().setLeggings(IRON_PANTS); p.getInventory().setChestplate(IRON_CHESTPLATE); p.getInventory().setHelmet(IRON_HELMET); i.setItem(0, IRON_SWORD); i.setItem(1, BOW); i.setItem(2, STEAK); i.setItem(3, HEALTH_POTION); - i.setItem(8, ARROWS); + i.setItem(9, ARROWS); i.setItem(4, EXP); i.setItem(8, ENDER_PEARL); Bukkit.getScheduler().runTask(plugin, new Runnable() { public void run() { p.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, 1000 * 20, 2)); } }); } // Top left corner. public int x1 = -8; public int y1 = 164; public int z1 = 16; //Bottom right corner. public int x2 = -85; public int y2 = 62; public int z2 = 99; @EventHandler public void onMove(PlayerMoveEvent event) { // Theoretically disable fall damage if (event.getPlayer().getWorld().getName().equals(name)) event.getPlayer().setFallDistance(0); } }
true
true
public void applyInventory(final BattlePlayer p) { Inventory i = p.getInventory(); ItemStack HEALTH_POTION = new ItemStack(Material.POTION, 1, (short) 16373); ItemStack STEAK = new ItemStack(Material.COOKED_BEEF, 1); ItemStack BOW = new ItemStack(Material.BOW, 1); ItemStack ARROWS = new ItemStack(Material.ARROW, 64); ItemStack IRON_HELMET = new ItemStack(Material.IRON_HELMET, 1); ItemStack IRON_CHESTPLATE = new ItemStack(Material.IRON_CHESTPLATE, 1); ItemStack IRON_PANTS = new ItemStack(Material.IRON_LEGGINGS, 1); ItemStack IRON_BOOTS = new ItemStack(Material.IRON_BOOTS, 1); ItemStack IRON_SWORD = new ItemStack(Material.IRON_SWORD, 1); ItemStack EXP = new ItemStack(Material.EXP_BOTTLE, 5); ItemStack ENDER_PEARL = new ItemStack(Material.ENDER_PEARL, 3); IRON_BOOTS.addUnsafeEnchantment(Enchantment.PROTECTION_FALL, 4); p.getInventory().setBoots(IRON_BOOTS); p.getInventory().setLeggings(IRON_PANTS); p.getInventory().setChestplate(IRON_CHESTPLATE); p.getInventory().setHelmet(IRON_HELMET); i.setItem(0, IRON_SWORD); i.setItem(1, BOW); i.setItem(2, STEAK); i.setItem(3, HEALTH_POTION); i.setItem(8, ARROWS); i.setItem(4, EXP); i.setItem(8, ENDER_PEARL); Bukkit.getScheduler().runTask(plugin, new Runnable() { public void run() { p.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, 1000 * 20, 2)); } }); }
public void applyInventory(final BattlePlayer p) { Inventory i = p.getInventory(); ItemStack HEALTH_POTION = new ItemStack(Material.POTION, 1, (short) 16373); ItemStack STEAK = new ItemStack(Material.COOKED_BEEF, 1); ItemStack BOW = new ItemStack(Material.BOW, 1); ItemStack ARROWS = new ItemStack(Material.ARROW, 64); ItemStack IRON_HELMET = new ItemStack(Material.IRON_HELMET, 1); ItemStack IRON_CHESTPLATE = new ItemStack(Material.IRON_CHESTPLATE, 1); ItemStack IRON_PANTS = new ItemStack(Material.IRON_LEGGINGS, 1); ItemStack IRON_BOOTS = new ItemStack(Material.IRON_BOOTS, 1); ItemStack IRON_SWORD = new ItemStack(Material.IRON_SWORD, 1); ItemStack EXP = new ItemStack(Material.EXP_BOTTLE, 5); ItemStack ENDER_PEARL = new ItemStack(Material.ENDER_PEARL, 3); IRON_BOOTS.addUnsafeEnchantment(Enchantment.PROTECTION_FALL, 4); p.getInventory().setBoots(IRON_BOOTS); p.getInventory().setLeggings(IRON_PANTS); p.getInventory().setChestplate(IRON_CHESTPLATE); p.getInventory().setHelmet(IRON_HELMET); i.setItem(0, IRON_SWORD); i.setItem(1, BOW); i.setItem(2, STEAK); i.setItem(3, HEALTH_POTION); i.setItem(9, ARROWS); i.setItem(4, EXP); i.setItem(8, ENDER_PEARL); Bukkit.getScheduler().runTask(plugin, new Runnable() { public void run() { p.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, 1000 * 20, 2)); } }); }
diff --git a/hazelcast/src/main/java/com/hazelcast/map/record/ObjectRecord.java b/hazelcast/src/main/java/com/hazelcast/map/record/ObjectRecord.java index 07692599c4..0dda92d6ed 100644 --- a/hazelcast/src/main/java/com/hazelcast/map/record/ObjectRecord.java +++ b/hazelcast/src/main/java/com/hazelcast/map/record/ObjectRecord.java @@ -1,88 +1,88 @@ /* * Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.map.record; import com.hazelcast.map.MapDataSerializerHook; import com.hazelcast.nio.ObjectDataInput; import com.hazelcast.nio.ObjectDataOutput; import com.hazelcast.nio.serialization.Data; import com.hazelcast.nio.serialization.IdentifiedDataSerializable; import java.io.IOException; public final class ObjectRecord extends AbstractRecord<Object> implements Record<Object>, IdentifiedDataSerializable { private volatile Object value; public ObjectRecord(Data keyData, Object value, boolean statisticsEnabled) { super(keyData, statisticsEnabled); this.value = value; } public ObjectRecord() { } // as there is no easy way to calculate the size of Object cost is not implemented for ObjectRecord @Override public long getCost() { long size = 0; // add statistics size if enabled. - size += ( statistics == null ? 0 : statistics.size() ); + //size += ( statistics == null ? 0 : statistics.size() ); // add size of version. - size += ( Long.SIZE/Byte.SIZE ); + //size += ( Long.SIZE/Byte.SIZE ); // add key size. - size += key.totalSize(); + //size += key.totalSize(); // todo add object size //size += ( value == null ? 0 : value.totalSize() ); return size; } public Object getValue() { return value; } public Object setValue(Object o) { Object old = value; value = o; return old; } @Override public void writeData(ObjectDataOutput out) throws IOException { super.writeData(out); out.writeObject(value); } @Override public void readData(ObjectDataInput in) throws IOException { super.readData(in); value = in.readObject(); } public int getFactoryId() { return MapDataSerializerHook.F_ID; } public int getId() { return MapDataSerializerHook.OBJECT_RECORD; } }
false
true
public long getCost() { long size = 0; // add statistics size if enabled. size += ( statistics == null ? 0 : statistics.size() ); // add size of version. size += ( Long.SIZE/Byte.SIZE ); // add key size. size += key.totalSize(); // todo add object size //size += ( value == null ? 0 : value.totalSize() ); return size; }
public long getCost() { long size = 0; // add statistics size if enabled. //size += ( statistics == null ? 0 : statistics.size() ); // add size of version. //size += ( Long.SIZE/Byte.SIZE ); // add key size. //size += key.totalSize(); // todo add object size //size += ( value == null ? 0 : value.totalSize() ); return size; }
diff --git a/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/edit/EditModelRegistry.java b/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/edit/EditModelRegistry.java index 38d40995..facd9cb9 100644 --- a/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/edit/EditModelRegistry.java +++ b/plugins/org.eclipse.wst.common.emfworkbench.integration/src/org/eclipse/wst/common/internal/emfworkbench/edit/EditModelRegistry.java @@ -1,371 +1,372 @@ /******************************************************************************* * Copyright (c) 2003, 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.wst.common.internal.emfworkbench.edit; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TreeSet; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.jem.util.RegistryReader; import org.eclipse.jem.util.logger.proxy.Logger; import org.eclipse.wst.common.internal.emfworkbench.EMFWorkbenchContext; import org.eclipse.wst.common.internal.emfworkbench.EMFWorkbenchEditResourceHandler; import org.eclipse.wst.common.internal.emfworkbench.integration.EMFWorkbenchEditPlugin; import org.eclipse.wst.common.internal.emfworkbench.integration.EditModel; import org.eclipse.wst.common.internal.emfworkbench.integration.IEditModelFactory; import org.eclipse.wst.common.project.facet.core.IFacetedProject; import org.eclipse.wst.common.project.facet.core.IProjectFacet; import org.eclipse.wst.common.project.facet.core.ProjectFacetsManager; /** * @author mdelder */ public class EditModelRegistry extends RegistryReader { private final static EditModelRegistry INSTANCE = new EditModelRegistry(); private final Map factoryConfigurations = new HashMap(); private static boolean initialized = false; public static final String EDIT_MODEL_ELEMENT = "editModel"; //$NON-NLS-1$ public static final String EDIT_MODEL_RESOURCE_EXTENSION = "resourceExtension"; //$NON-NLS-1$ public static final String EDIT_MODEL_RESOURCE_EXTENSION_NAME = "name"; //$NON-NLS-1$ public static final String EDIT_MODEL_ID_ATTR = "editModelID"; //$NON-NLS-1$ public static final String FACTORY_CLASS_ATTR = "factoryClass"; //$NON-NLS-1$ public static final String PARENT_MODEL_ATTR = "parentModelID"; //$NON-NLS-1$ public static final String LOAD_UNKNOWN_RESOURCES_ATTR = "loadUnknownResourcesAsReadOnly"; //$NON-NLS-1$ protected EditModelRegistry() { super(EMFWorkbenchEditPlugin.ID, EMFWorkbenchEditPlugin.EDIT_MODEL_FACTORIES_EXTENSION_POINT); } public static EditModelRegistry getInstance() { if(isInitialized()) return INSTANCE; synchronized(INSTANCE) { if(!isInitialized()) { INSTANCE.readRegistry(); initialized = true; } } return INSTANCE; } /* * (non-Javadoc) * * @see org.eclipse.wst.common.frameworks.internal.RegistryReader#readElement(org.eclipse.core.runtime.IConfigurationElement) */ public boolean readElement(IConfigurationElement element) { /* * The EditModel Extension Point defines Configuration elements named "editModel" with * attributes "editModelID" and "factoryClass" */ boolean result = false; if (element.getName().equals(EDIT_MODEL_ELEMENT)) { String editModelID = element.getAttribute(EDIT_MODEL_ID_ATTR); if (editModelID != null) { this.factoryConfigurations.put(editModelID, new EditModelInfo(editModelID, element)); result = true; } } return result; } public String getCacheID(String editModelID, Map params) { IEditModelFactory factory = getEditModelFactoryByKey(editModelID); return factory.getCacheID(editModelID, params); } public EditModel createEditModelForRead(String editModelID, EMFWorkbenchContext context, Map params) { return getEditModelFactoryByKey(editModelID).createEditModelForRead(editModelID, context, params); } public EditModel createEditModelForWrite(String editModelID, EMFWorkbenchContext context, Map params) { return getEditModelFactoryByKey(editModelID).createEditModelForWrite(editModelID, context, params); } public Collection getEditModelResources(String editModelID) { Collection resources = new TreeSet(); EditModelInfo nextEditModelInfo = getEditModelInfoById(editModelID); String parentModelID = null; Map visitedEditModels = new HashMap(); /* collect the resources from the parents */ while (nextEditModelInfo != null && (parentModelID = nextEditModelInfo.getParentModelID()) != null) { if (visitedEditModels.containsKey(parentModelID)) throw new IllegalStateException(EMFWorkbenchEditResourceHandler.getString(EMFWorkbenchEditResourceHandler.EditModelRegistry_ERROR_0, new Object[]{editModelID})); visitedEditModels.put(parentModelID, null); resources.addAll(getAllEditModelResources(parentModelID)); nextEditModelInfo = getEditModelInfoById(parentModelID); } /* Get the resources for the actual edit model id */ resources.addAll(getAllEditModelResources(editModelID)); return resources; } public Collection getEditModelExtensions(String editModelID) { Collection extensions = new TreeSet(); EditModelInfo nextEditModelInfo = getEditModelInfoById(editModelID); String parentModelID = null; Map visitedEditModels = new HashMap(); /* collect the resources from the parents */ while(nextEditModelInfo != null && (parentModelID = nextEditModelInfo.getParentModelID()) != null) { if(visitedEditModels.containsKey(parentModelID)) throw new IllegalStateException(EMFWorkbenchEditResourceHandler.getString(EMFWorkbenchEditResourceHandler.EditModelRegistry_ERROR_0,new Object [] {editModelID})); else visitedEditModels.put(parentModelID, null); extensions.addAll(getAllEditModelExtensions(parentModelID)); nextEditModelInfo = getEditModelInfoById(parentModelID); } /* Get the resources for the actual edit model id */ extensions.addAll(getAllEditModelExtensions(editModelID)); return extensions; } public IEditModelFactory findEditModelFactoryByKey(Object editModelID) { IEditModelFactory factory = null; EditModelInfo editMdlInfo = (EditModelInfo) factoryConfigurations.get(editModelID); if (editMdlInfo != null) factory = editMdlInfo.getEditModelFactory(); return factory; } public IEditModelFactory findEditModelFactoryByProject(IProject project) { IFacetedProject facetedProject = null; try { facetedProject = ProjectFacetsManager.create(project); } catch (Exception e) { return null; } if (facetedProject == null) return null; Iterator keys = factoryConfigurations.keySet().iterator(); while (keys.hasNext()) { Object key = keys.next(); if (key instanceof String) { try { IProjectFacet projectFacet = ProjectFacetsManager.getProjectFacet((String)key); if (projectFacet != null && facetedProject.hasProjectFacet(projectFacet)) return findEditModelFactoryByKey(key); } catch (Exception e) { continue; } } } return null; } protected Collection getAllEditModelResources(String editModelID) { Collection resources = new ArrayList(); resources.addAll(getLocalEditModelResources(editModelID)); resources.addAll(getExtendedEditModelResources(editModelID)); return resources; } protected Collection getAllEditModelExtensions(String editModelID) { Collection resources = new ArrayList(); resources.addAll(getLocalEditModelExtensions(editModelID)); return resources; } protected Collection getLocalEditModelResources(String editModelID) { EditModelInfo editMdlInfo = getEditModelInfoById(editModelID); return (editMdlInfo != null) ? editMdlInfo.getEditModelResources() : Collections.EMPTY_LIST; } protected Collection getLocalEditModelExtensions(String editModelID) { EditModelInfo editMdlInfo = getEditModelInfoById(editModelID); return (editMdlInfo != null) ? editMdlInfo.getEditModelExtensions() : Collections.EMPTY_LIST; } protected Collection getExtendedEditModelResources(String editModelID) { return EditModelExtensionRegistry.getInstance().getEditModelResources(editModelID); } /** * @param editModelKey * the editModelID of a given EditModelFactory defined in the Extension Point * @throws IllegalArgumentException * if a IEditModelFactory cannot be found for the given ID. * @return the EditModelFactory associated with a given EditModelID */ protected IEditModelFactory getEditModelFactoryByKey(Object editModelID) { IEditModelFactory factory = null; EditModelInfo editMdlInfo = getEditModelInfoById(editModelID); if (editMdlInfo != null) factory = editMdlInfo.getEditModelFactory(); else throw new IllegalArgumentException(EMFWorkbenchEditResourceHandler.getString(EMFWorkbenchEditResourceHandler.EditModelRegistry_ERROR_2, new Object[]{editModelID})); return factory; } /** * @param editModelID * @return */ protected EditModelInfo getEditModelInfoById(Object editModelID) { waitForInitializationIfNecessary(); return (EditModelInfo) factoryConfigurations.get(editModelID); } /** * If we are not initialized, block until the INSTANCE is released ( from getInstance()) */ private void waitForInitializationIfNecessary() { /* We only need to acquire the semaphore (INSTANCE), we do not need * to execute anything in this block. If the Registry is not initailized, * then it will block until the semaphore is released (from getInstance()), * and then release it and return immediately. */ if(!isInitialized()) synchronized(INSTANCE) { } } public class EditModelInfo { private String editModelID = null; private IConfigurationElement configurationElement = null; private IEditModelFactory factory = null; private List editModelResources = null; private List editModelExtensions = null; private String parentModelID = null; private String tostringCache = null; public EditModelInfo(String editModelID, IConfigurationElement configurationElement) { this.configurationElement = configurationElement; this.editModelID = editModelID; this.parentModelID = this.configurationElement.getAttribute(PARENT_MODEL_ATTR); } public List getEditModelResources() { /* this method is guarded */ initializeResources(); return editModelResources; } public IEditModelFactory getEditModelFactory() { // Do not block if the factory is not null if (this.factory == null) { synchronized (this) { // another thread could have already initialized the factory // while this thread was waiting to enter the sync block if(this.factory == null) { if (this.configurationElement != null) { try { this.factory = (IEditModelFactory) this.configurationElement.createExecutableExtension(FACTORY_CLASS_ATTR); Boolean value = Boolean.valueOf(this.configurationElement.getAttribute(LOAD_UNKNOWN_RESOURCES_ATTR)); this.factory.setLoadKnownResourcesAsReadOnly(value.booleanValue()); discardConfigurationElementIfNecessary(); } catch (CoreException e) { Logger.getLogger(EMFWorkbenchEditPlugin.ID).logError(e); } } else { Logger.getLogger().logError(EMFWorkbenchEditResourceHandler.EditModelRegistry_ERROR_1); } } } } return this.factory; } private synchronized void initializeResources() { if (editModelResources == null) { if (configurationElement != null) { editModelResources = new ArrayList(); IConfigurationElement[] resources = configurationElement.getChildren(EditModelResource.EDIT_MODEL_RESOURCE_ELEMENT); + IConfigurationElement[] resExtensions = configurationElement.getChildren(EDIT_MODEL_RESOURCE_EXTENSION); + // set the configurationElement to null- keeps code from reentering + discardConfigurationElementIfNecessary(); for (int j = 0; j < resources.length; j++) { editModelResources.add(new EditModelResource(resources[j])); } - IConfigurationElement[] resExtensions = configurationElement.getChildren(EDIT_MODEL_RESOURCE_EXTENSION); if (resExtensions == null || resExtensions.length == 0) { editModelExtensions = Collections.EMPTY_LIST; } else { editModelExtensions = new ArrayList(); for (int i = 0; i < resExtensions.length; i++) { String extension = resExtensions[i].getAttribute(EDIT_MODEL_RESOURCE_EXTENSION_NAME); editModelExtensions.add(extension); } } - discardConfigurationElementIfNecessary(); } else { editModelResources = Collections.EMPTY_LIST; editModelExtensions = Collections.EMPTY_LIST; } } } private void discardConfigurationElementIfNecessary() { if (this.editModelResources != null && this.factory != null) this.configurationElement = null; } public String toString() { if (tostringCache == null) tostringCache = "EditModelID: {" + this.editModelID + "}, Parent Model ID {" + this.parentModelID + "}, Configuration Element: [" + this.configurationElement + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$//$NON-NLS-4$ return tostringCache; } /** * @return Returns the parentModelID. */ public String getParentModelID() { return parentModelID; } public List getEditModelExtensions() { /* this method is guarded */ initializeResources(); return editModelExtensions; } } /** * @return Returns the initialized. */ protected static boolean isInitialized() { return initialized; } public String[] getRegisteredEditModelIDs() { return (String[]) factoryConfigurations.keySet().toArray(new String[factoryConfigurations.keySet().size()]); } }
false
true
private synchronized void initializeResources() { if (editModelResources == null) { if (configurationElement != null) { editModelResources = new ArrayList(); IConfigurationElement[] resources = configurationElement.getChildren(EditModelResource.EDIT_MODEL_RESOURCE_ELEMENT); for (int j = 0; j < resources.length; j++) { editModelResources.add(new EditModelResource(resources[j])); } IConfigurationElement[] resExtensions = configurationElement.getChildren(EDIT_MODEL_RESOURCE_EXTENSION); if (resExtensions == null || resExtensions.length == 0) { editModelExtensions = Collections.EMPTY_LIST; } else { editModelExtensions = new ArrayList(); for (int i = 0; i < resExtensions.length; i++) { String extension = resExtensions[i].getAttribute(EDIT_MODEL_RESOURCE_EXTENSION_NAME); editModelExtensions.add(extension); } } discardConfigurationElementIfNecessary(); } else { editModelResources = Collections.EMPTY_LIST; editModelExtensions = Collections.EMPTY_LIST; } } }
private synchronized void initializeResources() { if (editModelResources == null) { if (configurationElement != null) { editModelResources = new ArrayList(); IConfigurationElement[] resources = configurationElement.getChildren(EditModelResource.EDIT_MODEL_RESOURCE_ELEMENT); IConfigurationElement[] resExtensions = configurationElement.getChildren(EDIT_MODEL_RESOURCE_EXTENSION); // set the configurationElement to null- keeps code from reentering discardConfigurationElementIfNecessary(); for (int j = 0; j < resources.length; j++) { editModelResources.add(new EditModelResource(resources[j])); } if (resExtensions == null || resExtensions.length == 0) { editModelExtensions = Collections.EMPTY_LIST; } else { editModelExtensions = new ArrayList(); for (int i = 0; i < resExtensions.length; i++) { String extension = resExtensions[i].getAttribute(EDIT_MODEL_RESOURCE_EXTENSION_NAME); editModelExtensions.add(extension); } } } else { editModelResources = Collections.EMPTY_LIST; editModelExtensions = Collections.EMPTY_LIST; } } }
diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/filters/RequestModelsPrep.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/filters/RequestModelsPrep.java index c760a0b43..b2b1e293c 100644 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/filters/RequestModelsPrep.java +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/filters/RequestModelsPrep.java @@ -1,348 +1,346 @@ /* $This file is distributed under the terms of the license in /doc/license.txt$ */ package edu.cornell.mannlib.vitro.webapp.filters; import static edu.cornell.mannlib.vitro.webapp.servlet.setup.JenaDataSourceSetupBase.JENA_DB_MODEL; import static edu.cornell.mannlib.vitro.webapp.servlet.setup.JenaDataSourceSetupBase.JENA_INF_MODEL; import java.io.IOException; import java.util.List; import java.util.regex.Pattern; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.hp.hpl.jena.graph.BulkUpdateHandler; import com.hp.hpl.jena.graph.Graph; import com.hp.hpl.jena.ontology.OntModel; import com.hp.hpl.jena.ontology.OntModelSpec; import com.hp.hpl.jena.query.Dataset; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import edu.cornell.mannlib.vitro.webapp.auth.identifier.RequestIdentifiers; import edu.cornell.mannlib.vitro.webapp.auth.policy.ServletPolicyList; import edu.cornell.mannlib.vitro.webapp.config.ConfigurationProperties; import edu.cornell.mannlib.vitro.webapp.controller.VitroHttpServlet; import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; import edu.cornell.mannlib.vitro.webapp.dao.ModelAccess; import edu.cornell.mannlib.vitro.webapp.dao.ModelAccess.FactoryID; import edu.cornell.mannlib.vitro.webapp.dao.ModelAccess.ModelID; import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory; import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactoryConfig; import edu.cornell.mannlib.vitro.webapp.dao.filtering.WebappDaoFactoryFiltering; import edu.cornell.mannlib.vitro.webapp.dao.filtering.filters.HideFromDisplayByPolicyFilter; import edu.cornell.mannlib.vitro.webapp.dao.jena.OntModelSelector; import edu.cornell.mannlib.vitro.webapp.dao.jena.OntModelSelectorImpl; import edu.cornell.mannlib.vitro.webapp.dao.jena.RDFServiceDataset; import edu.cornell.mannlib.vitro.webapp.dao.jena.SpecialBulkUpdateHandlerGraph; import edu.cornell.mannlib.vitro.webapp.dao.jena.WebappDaoFactorySDB; import edu.cornell.mannlib.vitro.webapp.dao.jena.WebappDaoFactorySDB.SDBDatasetMode; import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFService; import edu.cornell.mannlib.vitro.webapp.rdfservice.filter.LanguageFilteringRDFService; import edu.cornell.mannlib.vitro.webapp.rdfservice.filter.LanguageFilteringUtils; import edu.cornell.mannlib.vitro.webapp.rdfservice.impl.RDFServiceUtils; /** * This sets up several objects in the Request scope for each incoming HTTP * request. This is done in a Filter so that controllers and JSPs get the same * setup. * * This code configures the WebappDaoFactory for each request. */ public class RequestModelsPrep implements Filter { private final static Log log = LogFactory.getLog(RequestModelsPrep.class); /** * The filter will be applied to all incoming urls, this is a list of URI * patterns to skip. These are matched against the requestURI sans query * parameters, e.g. "/vitro/index.jsp" "/vitro/themes/enhanced/css/edit.css" */ private final static Pattern[] skipPatterns = { Pattern.compile(".*\\.(gif|GIF|jpg|jpeg|png|PNG)$"), Pattern.compile(".*\\.css$"), Pattern.compile(".*\\.js$"), Pattern.compile("/.*/themes/.*/site_icons/.*"), Pattern.compile("/.*/images/.*") }; private ServletContext ctx; private ConfigurationProperties props; private String defaultNamespace; @Override public void init(FilterConfig fc) throws ServletException { ctx = fc.getServletContext(); props = ConfigurationProperties.getBean(ctx); defaultNamespace = props.getProperty("Vitro.defaultNamespace"); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse resp = (HttpServletResponse) response; // If we're not authorized for this request, skip the chain and // redirect. if (!ModelSwitcher.authorizedForSpecialModel(req)) { VitroHttpServlet.redirectUnauthorizedRequest(req, resp); return; } if (!thisRequestNeedsModels(req) || modelsAreAlreadySetUp(req)) { filterChain.doFilter(req, resp); } else { RDFService rdfService = RDFServiceUtils.getRDFServiceFactory(ctx) .getShortTermRDFService(); try { setUpTheRequestModels(rdfService, req); filterChain.doFilter(req, resp); } finally { rdfService.close(); } } } private boolean thisRequestNeedsModels(HttpServletRequest req) { String requestURI = req.getRequestURI(); for (Pattern skipPattern : skipPatterns) { if (skipPattern.matcher(requestURI).matches()) { log.debug("request matched skipPattern '" + skipPattern + "', skipping RequestModelsPrep"); return false; } } return true; } private boolean modelsAreAlreadySetUp(HttpServletRequest req) { String attributeName = RequestModelsPrep.class.getName() + "-setup"; if (req.getAttribute(attributeName) != null) { return true; } else { req.setAttribute(attributeName, Boolean.TRUE); return false; } } private void setUpTheRequestModels(RDFService rawRdfService, HttpServletRequest req) { VitroRequest vreq = new VitroRequest(req); setRdfServicesAndDatasets(rawRdfService, vreq); RDFService rdfService = vreq.getRDFService(); Dataset dataset = vreq.getDataset(); setRawModels(vreq, dataset); // We need access to some language-neutral items - either because we need to see all // contents regardless of language, or because we need to see the blank nodes that // are removed during language filtering. vreq.setLanguageNeutralUnionFullModel(ModelAccess.on(vreq).getOntModel(ModelID.UNION_FULL)); vreq.setLanguageNeutralWebappDaoFactory(new WebappDaoFactorySDB( rdfService, createLanguageNeutralOntModelSelector(vreq), createWadfConfig(vreq))); wrapModelsWithLanguageAwareness(vreq); setWebappDaoFactories(vreq, rdfService); } /** * Set language-neutral and language-aware versions of the RdfService and * Dataset. */ private void setRdfServicesAndDatasets(RDFService rawRdfService, VitroRequest vreq) { vreq.setUnfilteredRDFService(rawRdfService); vreq.setUnfilteredDataset(new RDFServiceDataset(rawRdfService)); RDFService rdfService = addLanguageAwareness(vreq, rawRdfService); vreq.setRDFService(rdfService); Dataset dataset = new RDFServiceDataset(rdfService); vreq.setDataset(dataset); } private void setRawModels(VitroRequest vreq, Dataset dataset) { // These are memory-mapped (fast), and read-mostly (low contention), so // just use the ones from the context. useModelFromContext(vreq, ModelID.APPLICATION_METADATA); useModelFromContext(vreq, ModelID.USER_ACCOUNTS); useModelFromContext(vreq, ModelID.DISPLAY); useModelFromContext(vreq, ModelID.DISPLAY_DISPLAY); useModelFromContext(vreq, ModelID.DISPLAY_TBOX); useModelFromContext(vreq, ModelID.BASE_TBOX); useModelFromContext(vreq, ModelID.INFERRED_TBOX); useModelFromContext(vreq, ModelID.UNION_TBOX); // Anything derived from the ABOX is not memory-mapped, so create // versions from the short-term RDF service. OntModel baseABoxModel = createNamedModelFromDataset(dataset, JENA_DB_MODEL); OntModel inferenceABoxModel = createNamedModelFromDataset(dataset, JENA_INF_MODEL); OntModel unionABoxModel = createCombinedBulkUpdatingModel( baseABoxModel, inferenceABoxModel); OntModel baseFullModel = createCombinedBulkUpdatingModel(baseABoxModel, ModelAccess.on(vreq).getOntModel(ModelID.BASE_TBOX)); OntModel inferenceFullModel = createCombinedModel(inferenceABoxModel, ModelAccess.on(vreq).getOntModel(ModelID.INFERRED_TBOX)); OntModel unionFullModel = ModelFactory.createOntologyModel( OntModelSpec.OWL_MEM, dataset.getDefaultModel()); ModelAccess.on(vreq).setOntModel(ModelID.BASE_ABOX, baseABoxModel); - ModelAccess.on(vreq).setOntModel(ModelID.INFERRED_ABOX, unionABoxModel); - ModelAccess.on(vreq) - .setOntModel(ModelID.UNION_ABOX, inferenceABoxModel); + ModelAccess.on(vreq).setOntModel(ModelID.INFERRED_ABOX, inferenceABoxModel); + ModelAccess.on(vreq).setOntModel(ModelID.UNION_ABOX, unionABoxModel); ModelAccess.on(vreq).setOntModel(ModelID.BASE_FULL, baseFullModel); - ModelAccess.on(vreq).setOntModel(ModelID.INFERRED_FULL, - inferenceFullModel); + ModelAccess.on(vreq).setOntModel(ModelID.INFERRED_FULL, inferenceFullModel); ModelAccess.on(vreq).setOntModel(ModelID.UNION_FULL, unionFullModel); } private void useModelFromContext(VitroRequest vreq, ModelID modelId) { OntModel contextModel = ModelAccess.on(ctx).getOntModel(modelId); ModelAccess.on(vreq).setOntModel(modelId, contextModel); } private OntModel createNamedModelFromDataset(Dataset dataset, String name) { return ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM, dataset.getNamedModel(name)); } private OntModel createCombinedModel(OntModel oneModel, OntModel otherModel) { return ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM, ModelFactory.createUnion(oneModel, otherModel)); } private OntModel createCombinedBulkUpdatingModel(OntModel baseModel, OntModel otherModel) { BulkUpdateHandler bulkUpdateHandler = baseModel.getGraph().getBulkUpdateHandler(); Graph unionGraph = ModelFactory.createUnion(baseModel, otherModel).getGraph(); Model unionModel = ModelFactory.createModelForGraph( new SpecialBulkUpdateHandlerGraph(unionGraph, bulkUpdateHandler)); return ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM, unionModel); } /** Create an OntModelSelector that will hold the un-language-filtered models. */ private OntModelSelector createLanguageNeutralOntModelSelector( VitroRequest vreq) { OntModelSelectorImpl oms = new OntModelSelectorImpl(); oms.setABoxModel(ModelAccess.on(vreq).getOntModel(ModelID.UNION_ABOX)); oms.setTBoxModel(ModelAccess.on(vreq).getOntModel(ModelID.UNION_TBOX)); oms.setFullModel(ModelAccess.on(vreq).getOntModel(ModelID.UNION_FULL)); oms.setApplicationMetadataModel(ModelAccess.on(vreq).getOntModel(ModelID.APPLICATION_METADATA)); oms.setDisplayModel(ModelAccess.on(vreq).getOntModel(ModelID.DISPLAY)); oms.setUserAccountsModel(ModelAccess.on(vreq).getOntModel(ModelID.USER_ACCOUNTS)); return oms; } private void wrapModelsWithLanguageAwareness(VitroRequest vreq) { wrapModelWithLanguageAwareness(vreq, ModelID.DISPLAY); wrapModelWithLanguageAwareness(vreq, ModelID.APPLICATION_METADATA); wrapModelWithLanguageAwareness(vreq, ModelID.BASE_TBOX); wrapModelWithLanguageAwareness(vreq, ModelID.UNION_TBOX); wrapModelWithLanguageAwareness(vreq, ModelID.UNION_FULL); wrapModelWithLanguageAwareness(vreq, ModelID.BASE_FULL); } private void wrapModelWithLanguageAwareness(HttpServletRequest req, ModelID id) { if (isLanguageAwarenessEnabled()) { OntModel unaware = ModelAccess.on(req).getOntModel(id); OntModel aware = LanguageFilteringUtils .wrapOntModelInALanguageFilter(unaware, req); ModelAccess.on(req).setOntModel(id, aware); } } private void setWebappDaoFactories(VitroRequest vreq, RDFService rdfService) { WebappDaoFactoryConfig config = createWadfConfig(vreq); WebappDaoFactory unfilteredWadf = new WebappDaoFactorySDB(rdfService, ModelAccess.on(vreq).getUnionOntModelSelector(), config); ModelAccess.on(vreq).setWebappDaoFactory(FactoryID.UNFILTERED_UNION, unfilteredWadf); WebappDaoFactory unfilteredAssertionsWadf = new WebappDaoFactorySDB( rdfService, ModelAccess.on(vreq).getBaseOntModelSelector(), config, SDBDatasetMode.ASSERTIONS_ONLY); ModelAccess.on(vreq).setWebappDaoFactory(FactoryID.BASE, unfilteredAssertionsWadf); ModelAccess.on(vreq).setWebappDaoFactory(FactoryID.UNFILTERED_BASE, unfilteredAssertionsWadf); WebappDaoFactory wadf = new WebappDaoFactorySDB(rdfService, ModelAccess .on(vreq).getUnionOntModelSelector(), config); // Do model switching and replace the WebappDaoFactory with // a different version if requested by parameters WebappDaoFactory switchedWadf = new ModelSwitcher() .checkForModelSwitching(vreq, wadf); // Switch the language-neutral one also. vreq.setLanguageNeutralWebappDaoFactory(new ModelSwitcher() .checkForModelSwitching(vreq, vreq.getLanguageNeutralWebappDaoFactory())); HideFromDisplayByPolicyFilter filter = new HideFromDisplayByPolicyFilter( RequestIdentifiers.getIdBundleForRequest(vreq), ServletPolicyList.getPolicies(ctx)); WebappDaoFactoryFiltering filteredWadf = new WebappDaoFactoryFiltering( switchedWadf, filter); ModelAccess.on(vreq).setWebappDaoFactory(FactoryID.UNION, filteredWadf); } private WebappDaoFactoryConfig createWadfConfig(HttpServletRequest req) { List<String> langs = getPreferredLanguages(req); WebappDaoFactoryConfig config = new WebappDaoFactoryConfig(); config.setDefaultNamespace(defaultNamespace); config.setPreferredLanguages(langs); config.setUnderlyingStoreReasoned(isStoreReasoned(req)); return config; } private List<String> getPreferredLanguages(HttpServletRequest req) { log.debug("Accept-Language: " + req.getHeader("Accept-Language")); return LanguageFilteringUtils.localesToLanguages(req.getLocales()); } /** * Language awareness is enabled unless they explicitly disable it. */ private Boolean isLanguageAwarenessEnabled() { return Boolean.valueOf(props.getProperty("RDFService.languageFilter", "true")); } private RDFService addLanguageAwareness(HttpServletRequest req, RDFService rawRDFService) { List<String> langs = getPreferredLanguages(req); if (isLanguageAwarenessEnabled()) { return new LanguageFilteringRDFService(rawRDFService, langs); } else { return rawRDFService; } } private boolean isStoreReasoned(ServletRequest req) { String isStoreReasoned = ConfigurationProperties.getBean(req).getProperty( "VitroConnection.DataSource.isStoreReasoned", "true"); return ("true".equals(isStoreReasoned)); } @Override public void destroy() { // Nothing to destroy } }
false
true
private void setRawModels(VitroRequest vreq, Dataset dataset) { // These are memory-mapped (fast), and read-mostly (low contention), so // just use the ones from the context. useModelFromContext(vreq, ModelID.APPLICATION_METADATA); useModelFromContext(vreq, ModelID.USER_ACCOUNTS); useModelFromContext(vreq, ModelID.DISPLAY); useModelFromContext(vreq, ModelID.DISPLAY_DISPLAY); useModelFromContext(vreq, ModelID.DISPLAY_TBOX); useModelFromContext(vreq, ModelID.BASE_TBOX); useModelFromContext(vreq, ModelID.INFERRED_TBOX); useModelFromContext(vreq, ModelID.UNION_TBOX); // Anything derived from the ABOX is not memory-mapped, so create // versions from the short-term RDF service. OntModel baseABoxModel = createNamedModelFromDataset(dataset, JENA_DB_MODEL); OntModel inferenceABoxModel = createNamedModelFromDataset(dataset, JENA_INF_MODEL); OntModel unionABoxModel = createCombinedBulkUpdatingModel( baseABoxModel, inferenceABoxModel); OntModel baseFullModel = createCombinedBulkUpdatingModel(baseABoxModel, ModelAccess.on(vreq).getOntModel(ModelID.BASE_TBOX)); OntModel inferenceFullModel = createCombinedModel(inferenceABoxModel, ModelAccess.on(vreq).getOntModel(ModelID.INFERRED_TBOX)); OntModel unionFullModel = ModelFactory.createOntologyModel( OntModelSpec.OWL_MEM, dataset.getDefaultModel()); ModelAccess.on(vreq).setOntModel(ModelID.BASE_ABOX, baseABoxModel); ModelAccess.on(vreq).setOntModel(ModelID.INFERRED_ABOX, unionABoxModel); ModelAccess.on(vreq) .setOntModel(ModelID.UNION_ABOX, inferenceABoxModel); ModelAccess.on(vreq).setOntModel(ModelID.BASE_FULL, baseFullModel); ModelAccess.on(vreq).setOntModel(ModelID.INFERRED_FULL, inferenceFullModel); ModelAccess.on(vreq).setOntModel(ModelID.UNION_FULL, unionFullModel); }
private void setRawModels(VitroRequest vreq, Dataset dataset) { // These are memory-mapped (fast), and read-mostly (low contention), so // just use the ones from the context. useModelFromContext(vreq, ModelID.APPLICATION_METADATA); useModelFromContext(vreq, ModelID.USER_ACCOUNTS); useModelFromContext(vreq, ModelID.DISPLAY); useModelFromContext(vreq, ModelID.DISPLAY_DISPLAY); useModelFromContext(vreq, ModelID.DISPLAY_TBOX); useModelFromContext(vreq, ModelID.BASE_TBOX); useModelFromContext(vreq, ModelID.INFERRED_TBOX); useModelFromContext(vreq, ModelID.UNION_TBOX); // Anything derived from the ABOX is not memory-mapped, so create // versions from the short-term RDF service. OntModel baseABoxModel = createNamedModelFromDataset(dataset, JENA_DB_MODEL); OntModel inferenceABoxModel = createNamedModelFromDataset(dataset, JENA_INF_MODEL); OntModel unionABoxModel = createCombinedBulkUpdatingModel( baseABoxModel, inferenceABoxModel); OntModel baseFullModel = createCombinedBulkUpdatingModel(baseABoxModel, ModelAccess.on(vreq).getOntModel(ModelID.BASE_TBOX)); OntModel inferenceFullModel = createCombinedModel(inferenceABoxModel, ModelAccess.on(vreq).getOntModel(ModelID.INFERRED_TBOX)); OntModel unionFullModel = ModelFactory.createOntologyModel( OntModelSpec.OWL_MEM, dataset.getDefaultModel()); ModelAccess.on(vreq).setOntModel(ModelID.BASE_ABOX, baseABoxModel); ModelAccess.on(vreq).setOntModel(ModelID.INFERRED_ABOX, inferenceABoxModel); ModelAccess.on(vreq).setOntModel(ModelID.UNION_ABOX, unionABoxModel); ModelAccess.on(vreq).setOntModel(ModelID.BASE_FULL, baseFullModel); ModelAccess.on(vreq).setOntModel(ModelID.INFERRED_FULL, inferenceFullModel); ModelAccess.on(vreq).setOntModel(ModelID.UNION_FULL, unionFullModel); }
diff --git a/flexodesktop/modules/flexoviewpointmodeler/src/dev/java/org/openflexo/vpm/fib/EditionPatternViewEDITOR.java b/flexodesktop/modules/flexoviewpointmodeler/src/dev/java/org/openflexo/vpm/fib/EditionPatternViewEDITOR.java index 9a124991b..f13f1dc3f 100644 --- a/flexodesktop/modules/flexoviewpointmodeler/src/dev/java/org/openflexo/vpm/fib/EditionPatternViewEDITOR.java +++ b/flexodesktop/modules/flexoviewpointmodeler/src/dev/java/org/openflexo/vpm/fib/EditionPatternViewEDITOR.java @@ -1,105 +1,105 @@ /* * (c) Copyright 2010-2011 AgileBirds * * This file is part of OpenFlexo. * * OpenFlexo 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 3 of the License, or * (at your option) any later version. * * OpenFlexo 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 OpenFlexo. If not, see <http://www.gnu.org/licenses/>. * */ package org.openflexo.vpm.fib; import java.io.File; import org.openflexo.fib.editor.FIBAbstractEditor; import org.openflexo.foundation.FlexoResourceCenter; import org.openflexo.foundation.ontology.OntologyLibrary; import org.openflexo.foundation.viewpoint.ViewPoint; import org.openflexo.foundation.viewpoint.ViewPointLibrary; import org.openflexo.module.FlexoResourceCenterService; import org.openflexo.module.ModuleLoader; import org.openflexo.vpm.CEDCst; public class EditionPatternViewEDITOR { public static void main(String[] args) { FIBAbstractEditor editor = new FIBAbstractEditor() { @Override public Object[] getData() { FlexoResourceCenter resourceCenter = getFlexoResourceCenterService().getFlexoResourceCenter(true); OntologyLibrary ontologyLibrary = resourceCenter.retrieveBaseOntologyLibrary(); ViewPointLibrary calcLibrary = resourceCenter.retrieveViewPointLibrary(); - Object[] returned = new Object[14]; + Object[] returned = new Object[13]; ViewPoint calc1 = calcLibrary .getOntologyCalc("http://www.agilebirds.com/openflexo/ViewPoints/Tests/BasicOrganizationTreeEditor.owl"); calc1.loadWhenUnloaded(); returned[0] = calc1.getEditionPattern("Employee"); returned[1] = calc1.getEditionPattern("BOTDepartment"); ViewPoint calc2 = calcLibrary .getOntologyCalc("http://www.agilebirds.com/openflexo/ViewPoints/ScopeDefinition/OrganizationalUnitDefinition.owl"); calc2.loadWhenUnloaded(); returned[2] = calc2.getEditionPattern("OrganizationalUnit"); returned[3] = calc2.getEditionPattern("OrganizationalUnitPosition"); returned[12] = calc2.getEditionPattern("PositionTask"); ViewPoint calc3 = calcLibrary.getOntologyCalc("http://www.agilebirds.com/openflexo/ViewPoints/Basic/BasicOntology.owl"); calc3.loadWhenUnloaded(); returned[4] = calc3.getEditionPattern("Concept"); returned[5] = calc3.getEditionPattern("IsARelationship"); returned[6] = calc3.getEditionPattern("HasRelationship"); ViewPoint calc4 = calcLibrary .getOntologyCalc("http://www.agilebirds.com/openflexo/ViewPoints/SKOS/SKOSThesaurusEditor.owl"); calc4.loadWhenUnloaded(); returned[7] = calc4.getEditionPattern("Concept"); ViewPoint calc5 = calcLibrary.getOntologyCalc("http://www.agilebirds.com/openflexo/ViewPoints/UML/UseCaseDiagram.owl"); calc5.loadWhenUnloaded(); returned[8] = calc5.getEditionPattern("Actor"); ViewPoint calc6 = calcLibrary .getOntologyCalc("http://www.agilebirds.com/openflexo/ViewPoints/ScopeDefinition/OrganizationalMap.owl"); calc6.loadWhenUnloaded(); returned[9] = calc6.getEditionPattern("ContainsPositionLink"); returned[10] = calc6.getEditionPattern("SubOrganizationUnitLink"); ViewPoint calc7 = calcLibrary.getOntologyCalc("http://www.agilebirds.com/openflexo/ViewPoints/UML/PackageDiagram.owl"); calc7.loadWhenUnloaded(); returned[11] = calc7.getEditionPattern("ImportPackage"); - ViewPoint calc9 = calcLibrary.getOntologyCalc("http://www.thalesgroup.com/ViewPoints/sepel-ng/MappingCapture.owl"); + /*ViewPoint calc9 = calcLibrary.getOntologyCalc("http://www.thalesgroup.com/ViewPoints/sepel-ng/MappingCapture.owl"); calc9.loadWhenUnloaded(); - returned[13] = calc9.getEditionPattern("ConceptMapping"); + returned[13] = calc9.getEditionPattern("ConceptMapping");*/ return returned; } @Override public File getFIBFile() { return CEDCst.EDITION_PATTERN_VIEW_FIB; } }; editor.launch(); } private static ModuleLoader getModuleLoader() { return ModuleLoader.instance(); } private static FlexoResourceCenterService getFlexoResourceCenterService() { return FlexoResourceCenterService.instance(); } }
false
true
public static void main(String[] args) { FIBAbstractEditor editor = new FIBAbstractEditor() { @Override public Object[] getData() { FlexoResourceCenter resourceCenter = getFlexoResourceCenterService().getFlexoResourceCenter(true); OntologyLibrary ontologyLibrary = resourceCenter.retrieveBaseOntologyLibrary(); ViewPointLibrary calcLibrary = resourceCenter.retrieveViewPointLibrary(); Object[] returned = new Object[14]; ViewPoint calc1 = calcLibrary .getOntologyCalc("http://www.agilebirds.com/openflexo/ViewPoints/Tests/BasicOrganizationTreeEditor.owl"); calc1.loadWhenUnloaded(); returned[0] = calc1.getEditionPattern("Employee"); returned[1] = calc1.getEditionPattern("BOTDepartment"); ViewPoint calc2 = calcLibrary .getOntologyCalc("http://www.agilebirds.com/openflexo/ViewPoints/ScopeDefinition/OrganizationalUnitDefinition.owl"); calc2.loadWhenUnloaded(); returned[2] = calc2.getEditionPattern("OrganizationalUnit"); returned[3] = calc2.getEditionPattern("OrganizationalUnitPosition"); returned[12] = calc2.getEditionPattern("PositionTask"); ViewPoint calc3 = calcLibrary.getOntologyCalc("http://www.agilebirds.com/openflexo/ViewPoints/Basic/BasicOntology.owl"); calc3.loadWhenUnloaded(); returned[4] = calc3.getEditionPattern("Concept"); returned[5] = calc3.getEditionPattern("IsARelationship"); returned[6] = calc3.getEditionPattern("HasRelationship"); ViewPoint calc4 = calcLibrary .getOntologyCalc("http://www.agilebirds.com/openflexo/ViewPoints/SKOS/SKOSThesaurusEditor.owl"); calc4.loadWhenUnloaded(); returned[7] = calc4.getEditionPattern("Concept"); ViewPoint calc5 = calcLibrary.getOntologyCalc("http://www.agilebirds.com/openflexo/ViewPoints/UML/UseCaseDiagram.owl"); calc5.loadWhenUnloaded(); returned[8] = calc5.getEditionPattern("Actor"); ViewPoint calc6 = calcLibrary .getOntologyCalc("http://www.agilebirds.com/openflexo/ViewPoints/ScopeDefinition/OrganizationalMap.owl"); calc6.loadWhenUnloaded(); returned[9] = calc6.getEditionPattern("ContainsPositionLink"); returned[10] = calc6.getEditionPattern("SubOrganizationUnitLink"); ViewPoint calc7 = calcLibrary.getOntologyCalc("http://www.agilebirds.com/openflexo/ViewPoints/UML/PackageDiagram.owl"); calc7.loadWhenUnloaded(); returned[11] = calc7.getEditionPattern("ImportPackage"); ViewPoint calc9 = calcLibrary.getOntologyCalc("http://www.thalesgroup.com/ViewPoints/sepel-ng/MappingCapture.owl"); calc9.loadWhenUnloaded(); returned[13] = calc9.getEditionPattern("ConceptMapping"); return returned; } @Override public File getFIBFile() { return CEDCst.EDITION_PATTERN_VIEW_FIB; } }; editor.launch(); }
public static void main(String[] args) { FIBAbstractEditor editor = new FIBAbstractEditor() { @Override public Object[] getData() { FlexoResourceCenter resourceCenter = getFlexoResourceCenterService().getFlexoResourceCenter(true); OntologyLibrary ontologyLibrary = resourceCenter.retrieveBaseOntologyLibrary(); ViewPointLibrary calcLibrary = resourceCenter.retrieveViewPointLibrary(); Object[] returned = new Object[13]; ViewPoint calc1 = calcLibrary .getOntologyCalc("http://www.agilebirds.com/openflexo/ViewPoints/Tests/BasicOrganizationTreeEditor.owl"); calc1.loadWhenUnloaded(); returned[0] = calc1.getEditionPattern("Employee"); returned[1] = calc1.getEditionPattern("BOTDepartment"); ViewPoint calc2 = calcLibrary .getOntologyCalc("http://www.agilebirds.com/openflexo/ViewPoints/ScopeDefinition/OrganizationalUnitDefinition.owl"); calc2.loadWhenUnloaded(); returned[2] = calc2.getEditionPattern("OrganizationalUnit"); returned[3] = calc2.getEditionPattern("OrganizationalUnitPosition"); returned[12] = calc2.getEditionPattern("PositionTask"); ViewPoint calc3 = calcLibrary.getOntologyCalc("http://www.agilebirds.com/openflexo/ViewPoints/Basic/BasicOntology.owl"); calc3.loadWhenUnloaded(); returned[4] = calc3.getEditionPattern("Concept"); returned[5] = calc3.getEditionPattern("IsARelationship"); returned[6] = calc3.getEditionPattern("HasRelationship"); ViewPoint calc4 = calcLibrary .getOntologyCalc("http://www.agilebirds.com/openflexo/ViewPoints/SKOS/SKOSThesaurusEditor.owl"); calc4.loadWhenUnloaded(); returned[7] = calc4.getEditionPattern("Concept"); ViewPoint calc5 = calcLibrary.getOntologyCalc("http://www.agilebirds.com/openflexo/ViewPoints/UML/UseCaseDiagram.owl"); calc5.loadWhenUnloaded(); returned[8] = calc5.getEditionPattern("Actor"); ViewPoint calc6 = calcLibrary .getOntologyCalc("http://www.agilebirds.com/openflexo/ViewPoints/ScopeDefinition/OrganizationalMap.owl"); calc6.loadWhenUnloaded(); returned[9] = calc6.getEditionPattern("ContainsPositionLink"); returned[10] = calc6.getEditionPattern("SubOrganizationUnitLink"); ViewPoint calc7 = calcLibrary.getOntologyCalc("http://www.agilebirds.com/openflexo/ViewPoints/UML/PackageDiagram.owl"); calc7.loadWhenUnloaded(); returned[11] = calc7.getEditionPattern("ImportPackage"); /*ViewPoint calc9 = calcLibrary.getOntologyCalc("http://www.thalesgroup.com/ViewPoints/sepel-ng/MappingCapture.owl"); calc9.loadWhenUnloaded(); returned[13] = calc9.getEditionPattern("ConceptMapping");*/ return returned; } @Override public File getFIBFile() { return CEDCst.EDITION_PATTERN_VIEW_FIB; } }; editor.launch(); }
diff --git a/src/main/java/pl/com/it_crowd/seam/framework/conditions/AbstractCondition.java b/src/main/java/pl/com/it_crowd/seam/framework/conditions/AbstractCondition.java index 09ae89c..0e89efc 100644 --- a/src/main/java/pl/com/it_crowd/seam/framework/conditions/AbstractCondition.java +++ b/src/main/java/pl/com/it_crowd/seam/framework/conditions/AbstractCondition.java @@ -1,274 +1,278 @@ package pl.com.it_crowd.seam.framework.conditions; import java.util.Collection; import java.util.HashSet; import java.util.Set; /** * Abstract query condition. * Method #evaluate() calculates dynamic parameters' values and prepares renderedEJBQL. Even if values of dynamic parameters change they will not be taken * under consideration until next #evaluate() call. * Before calling #getRenderedEJBQL() call #evaluate(). */ public abstract class AbstractCondition { // ------------------------------ FIELDS ------------------------------ protected Object[] argValues; protected Object[] args; protected Set<LocalDynamicParameter> dynamicParams = new HashSet<LocalDynamicParameter>(); protected boolean includeNullParameters = false; protected Object[] oldArgValues; protected String oldEJBQL; protected int paramIndexOffset = 1; protected String paramPrefix = "qel"; // --------------------------- CONSTRUCTORS --------------------------- public AbstractCondition(Object... args) { this.args = args == null ? new Object[0] : args; } // --------------------- GETTER / SETTER METHODS --------------------- /** * Gets offset of parameter index. If we have some param already in query i.e.: :qel1,:qel2 then params used in this condition should start from :qel3. * * @return offset of parm index */ public int getParamIndexOffset() { return paramIndexOffset; } public void setParamIndexOffset(int paramIndexOffset) { this.paramIndexOffset = paramIndexOffset; } // -------------------------- OTHER METHODS -------------------------- /** * Calculate values of dynamic parameters and prepares rendered EJBQL fragment. */ public void evaluate() { oldEJBQL = getRenderedEJBQL(); evaluateArgumentValues(); renderEJBQL(); } public int getDynamicParametersCount() { int paramCount = 0; for (Object o : args) { if (o instanceof DynamicParameter) { paramCount++; } else if (o instanceof AbstractCondition) { paramCount += ((AbstractCondition) o).getDynamicParametersCount(); } } return paramCount; } /** * Gets collection of parameters that will be in EJBQL fragment and should be set on Query object. * * @return set of parameters that need to be set on query */ public Set<LocalDynamicParameter> getParamsToSet() { final HashSet<LocalDynamicParameter> set = new HashSet<LocalDynamicParameter>(); for (LocalDynamicParameter parameter : dynamicParams) { if ((parameter.value != null || includeNullParameters) && (!(parameter.value instanceof Collection) || !((Collection) parameter.value).isEmpty())) { set.add(parameter); } } for (Object o : args) { if (o instanceof AbstractCondition) { set.addAll(((AbstractCondition) o).getParamsToSet()); } } return set; } /** * Gets EJBQL fragment representing this condition. * * @return EJBQL fragment representing this condition. */ public abstract String getRenderedEJBQL(); public boolean isDirty() { if (oldArgValues == null || argValues == null || oldArgValues.length != argValues.length) { return true; } String renderedEJBQL = getRenderedEJBQL(); if (oldEJBQL == null && renderedEJBQL != null || oldEJBQL != null && renderedEJBQL == null || oldEJBQL != null && !oldEJBQL.equals(renderedEJBQL)) { return true; } for (int i = 0; i < args.length; i++) { Object oldArgValue = oldArgValues[i]; Object freshArgValue = argValues[i]; Object oldValue; Integer oldHashCode; Integer freshHashCode; Object freshValue; if (freshArgValue instanceof LocalDynamicParameter) { freshValue = ((LocalDynamicParameter) freshArgValue).value; freshHashCode = ((LocalDynamicParameter) freshArgValue).valueHashCode; } else if (freshArgValue instanceof AbstractCondition) { - return ((AbstractCondition) freshArgValue).isDirty(); + if (((AbstractCondition) freshArgValue).isDirty()) { + return true; + } else { + continue; + } } else { freshValue = freshArgValue; freshHashCode = freshValue == null ? null : freshValue.hashCode(); } if (oldArgValue instanceof LocalDynamicParameter) { oldValue = ((LocalDynamicParameter) oldArgValue).value; oldHashCode = ((LocalDynamicParameter) oldArgValue).valueHashCode; } else { oldValue = oldArgValue; oldHashCode = oldValue == null ? null : oldValue.hashCode(); } if (!equals(oldHashCode, freshHashCode) || !equals(oldValue, freshValue)) { return true; } } return false; } public void markParametersSet() { oldArgValues = argValues; for (Object arg : args) { if (arg instanceof AbstractCondition) { ((AbstractCondition) arg).markParametersSet(); } } } /** * Tells if condition has any EJBQL to render. * * @return true if yes; false if nothing will be rendered */ public boolean rendersEJBQL() { String renderedEJBQL = getRenderedEJBQL(); return renderedEJBQL != null && !"".equals(renderedEJBQL.trim()); } @SuppressWarnings("NumberEquality") private boolean equals(Integer object1, Integer object2) { return object1 == object2 || !((object1 == null) || (object2 == null)) && object1.equals(object2); } private boolean equals(Object oldValue, Object freshValue) { if (oldValue == null) { return (freshValue == null || ((freshValue instanceof Collection) && !((Collection) freshValue).isEmpty())); } else { return oldValue.equals(freshValue); } } private void evaluateArgumentValues() { dynamicParams.clear(); argValues = new Object[args.length]; int localDynP = 0; for (int i = 0; i < args.length; i++) { Object o = args[i]; if (o instanceof DynamicParameter) { LocalDynamicParameter localDynamicParameter = new LocalDynamicParameter(paramPrefix + (localDynP++ + paramIndexOffset), ((DynamicParameter) o).getValue()); argValues[i] = localDynamicParameter; dynamicParams.add(localDynamicParameter); } else { if (o instanceof AbstractCondition) { final AbstractCondition condition = (AbstractCondition) o; condition.paramIndexOffset = localDynP + paramIndexOffset; condition.evaluate(); localDynP += condition.getDynamicParametersCount(); } argValues[i] = o; } } } /** * Generates EJBQL fragment representig this condition. */ protected abstract void renderEJBQL(); /** * Gets string representation of object that should be used in EJBQL part. * * @param o object to convert to EJBQL part representation * * @return query parameter name if o is instance of LocalDynamicParameter, renderedEJBQL fragment if o is instance of AbstractCondition, toString if o is not null or null if o is null */ protected String toEJBQLPart(Object o) { if (o instanceof LocalDynamicParameter) { Object value = ((LocalDynamicParameter) o).value; return (!includeNullParameters && value == null) || (value instanceof Collection && ((Collection) value).isEmpty()) ? null : ":" + ((LocalDynamicParameter) o).name; } else if (o instanceof AbstractCondition) { ((AbstractCondition) o).renderEJBQL(); return ((AbstractCondition) o).getRenderedEJBQL(); } else if (o != null) { return o.toString(); } else { return null; } } // -------------------------- INNER CLASSES -------------------------- public class LocalDynamicParameter { // ------------------------------ FIELDS ------------------------------ String name; Object value; /** * This is used for collections and maps */ Integer valueHashCode; // --------------------------- CONSTRUCTORS --------------------------- private LocalDynamicParameter(String name, Object value) { this.name = name; this.value = value; if (value != null) { valueHashCode = value.hashCode(); } } // --------------------- GETTER / SETTER METHODS --------------------- public String getName() { return name; } public Object getValue() { return value; } } }
true
true
public boolean isDirty() { if (oldArgValues == null || argValues == null || oldArgValues.length != argValues.length) { return true; } String renderedEJBQL = getRenderedEJBQL(); if (oldEJBQL == null && renderedEJBQL != null || oldEJBQL != null && renderedEJBQL == null || oldEJBQL != null && !oldEJBQL.equals(renderedEJBQL)) { return true; } for (int i = 0; i < args.length; i++) { Object oldArgValue = oldArgValues[i]; Object freshArgValue = argValues[i]; Object oldValue; Integer oldHashCode; Integer freshHashCode; Object freshValue; if (freshArgValue instanceof LocalDynamicParameter) { freshValue = ((LocalDynamicParameter) freshArgValue).value; freshHashCode = ((LocalDynamicParameter) freshArgValue).valueHashCode; } else if (freshArgValue instanceof AbstractCondition) { return ((AbstractCondition) freshArgValue).isDirty(); } else { freshValue = freshArgValue; freshHashCode = freshValue == null ? null : freshValue.hashCode(); } if (oldArgValue instanceof LocalDynamicParameter) { oldValue = ((LocalDynamicParameter) oldArgValue).value; oldHashCode = ((LocalDynamicParameter) oldArgValue).valueHashCode; } else { oldValue = oldArgValue; oldHashCode = oldValue == null ? null : oldValue.hashCode(); } if (!equals(oldHashCode, freshHashCode) || !equals(oldValue, freshValue)) { return true; } } return false; }
public boolean isDirty() { if (oldArgValues == null || argValues == null || oldArgValues.length != argValues.length) { return true; } String renderedEJBQL = getRenderedEJBQL(); if (oldEJBQL == null && renderedEJBQL != null || oldEJBQL != null && renderedEJBQL == null || oldEJBQL != null && !oldEJBQL.equals(renderedEJBQL)) { return true; } for (int i = 0; i < args.length; i++) { Object oldArgValue = oldArgValues[i]; Object freshArgValue = argValues[i]; Object oldValue; Integer oldHashCode; Integer freshHashCode; Object freshValue; if (freshArgValue instanceof LocalDynamicParameter) { freshValue = ((LocalDynamicParameter) freshArgValue).value; freshHashCode = ((LocalDynamicParameter) freshArgValue).valueHashCode; } else if (freshArgValue instanceof AbstractCondition) { if (((AbstractCondition) freshArgValue).isDirty()) { return true; } else { continue; } } else { freshValue = freshArgValue; freshHashCode = freshValue == null ? null : freshValue.hashCode(); } if (oldArgValue instanceof LocalDynamicParameter) { oldValue = ((LocalDynamicParameter) oldArgValue).value; oldHashCode = ((LocalDynamicParameter) oldArgValue).valueHashCode; } else { oldValue = oldArgValue; oldHashCode = oldValue == null ? null : oldValue.hashCode(); } if (!equals(oldHashCode, freshHashCode) || !equals(oldValue, freshValue)) { return true; } } return false; }
diff --git a/BetterBatteryStats/src/com/asksven/betterbatterystats/BroadcastHandler.java b/BetterBatteryStats/src/com/asksven/betterbatterystats/BroadcastHandler.java index 0e3b35f8..6cbda4a2 100644 --- a/BetterBatteryStats/src/com/asksven/betterbatterystats/BroadcastHandler.java +++ b/BetterBatteryStats/src/com/asksven/betterbatterystats/BroadcastHandler.java @@ -1,139 +1,140 @@ /* * Copyright (C) 2011 asksven * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.asksven.betterbatterystats; import java.util.logging.Logger; import com.asksven.betterbatterystats.data.StatsProvider; import com.asksven.betterbatterystats.R; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.os.BatteryManager; import android.preference.PreferenceManager; import android.util.Log; /** * General broadcast handler: handles event as registered on Manifest * @author sven * */ public class BroadcastHandler extends BroadcastReceiver { private static final String TAG = "BroadcastHandler"; private BatteryChangedHandler m_batteryHandler = null; /* (non-Javadoc) * @see android.content.BroadcastReceiver#onReceive(android.content.Context, android.content.Intent) */ @Override public void onReceive(Context context, Intent intent) { // if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) // { // // start the service // context.startService(new Intent(context, BetterBatteryStatsService.class)); // // Log.i(TAG, "Received Broadcast ACTION_BOOT_COMPLETED"); // // delete whatever references we have saved here // StatsProvider.getInstance(context).deletedSerializedRefs(); // } if (intent.getAction().equals(Intent.ACTION_POWER_DISCONNECTED)) { Log.i(TAG, "Received Broadcast ACTION_POWER_DISCONNECTED, seralizing 'since unplugged'"); // todo: store the "since unplugged" refs here try { // Store the "since unplugged ref StatsProvider.getInstance(context).setReferenceSinceUnplugged(0); // check the battery level and if 100% the store "since charged" ref Intent batteryIntent = context.getApplicationContext().registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); int rawlevel = batteryIntent.getIntExtra("level", -1); double scale = batteryIntent.getIntExtra("scale", -1); double level = -1; if (rawlevel >= 0 && scale > 0) { + // normalize level to [0..1] level = rawlevel / scale; } Log.i(TAG, "Bettery level on uplug is " + level ); - if (level == 100) + if (level == 1) { try { Log.i(TAG, "Level was 100% at unlug, serializing 'since charged'"); StatsProvider.getInstance(context).setReferenceSinceCharged(0); } catch (Exception e) { Log.e(TAG, "An error occured: " + e.getMessage()); } } } catch (Exception e) { Log.e(TAG, "An error occured: " + e.getMessage()); } } if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { Log.i(TAG, "Received Broadcast ACTION_SCREEN_OFF"); // todo: store the "since screen off" refs here try { } catch (Exception e) { Log.e(TAG, "An error occured: " + e.getMessage()); } } if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) { Log.i(TAG, "Received Broadcast ACTION_SCREEN_ON"); // todo: evaluate what hapened while screen was off here try { } catch (Exception e) { Log.e(TAG, "An error occured: " + e.getMessage()); } } } }
false
true
public void onReceive(Context context, Intent intent) { // if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) // { // // start the service // context.startService(new Intent(context, BetterBatteryStatsService.class)); // // Log.i(TAG, "Received Broadcast ACTION_BOOT_COMPLETED"); // // delete whatever references we have saved here // StatsProvider.getInstance(context).deletedSerializedRefs(); // } if (intent.getAction().equals(Intent.ACTION_POWER_DISCONNECTED)) { Log.i(TAG, "Received Broadcast ACTION_POWER_DISCONNECTED, seralizing 'since unplugged'"); // todo: store the "since unplugged" refs here try { // Store the "since unplugged ref StatsProvider.getInstance(context).setReferenceSinceUnplugged(0); // check the battery level and if 100% the store "since charged" ref Intent batteryIntent = context.getApplicationContext().registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); int rawlevel = batteryIntent.getIntExtra("level", -1); double scale = batteryIntent.getIntExtra("scale", -1); double level = -1; if (rawlevel >= 0 && scale > 0) { level = rawlevel / scale; } Log.i(TAG, "Bettery level on uplug is " + level ); if (level == 100) { try { Log.i(TAG, "Level was 100% at unlug, serializing 'since charged'"); StatsProvider.getInstance(context).setReferenceSinceCharged(0); } catch (Exception e) { Log.e(TAG, "An error occured: " + e.getMessage()); } } } catch (Exception e) { Log.e(TAG, "An error occured: " + e.getMessage()); } } if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { Log.i(TAG, "Received Broadcast ACTION_SCREEN_OFF"); // todo: store the "since screen off" refs here try { } catch (Exception e) { Log.e(TAG, "An error occured: " + e.getMessage()); } } if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) { Log.i(TAG, "Received Broadcast ACTION_SCREEN_ON"); // todo: evaluate what hapened while screen was off here try { } catch (Exception e) { Log.e(TAG, "An error occured: " + e.getMessage()); } } }
public void onReceive(Context context, Intent intent) { // if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) // { // // start the service // context.startService(new Intent(context, BetterBatteryStatsService.class)); // // Log.i(TAG, "Received Broadcast ACTION_BOOT_COMPLETED"); // // delete whatever references we have saved here // StatsProvider.getInstance(context).deletedSerializedRefs(); // } if (intent.getAction().equals(Intent.ACTION_POWER_DISCONNECTED)) { Log.i(TAG, "Received Broadcast ACTION_POWER_DISCONNECTED, seralizing 'since unplugged'"); // todo: store the "since unplugged" refs here try { // Store the "since unplugged ref StatsProvider.getInstance(context).setReferenceSinceUnplugged(0); // check the battery level and if 100% the store "since charged" ref Intent batteryIntent = context.getApplicationContext().registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); int rawlevel = batteryIntent.getIntExtra("level", -1); double scale = batteryIntent.getIntExtra("scale", -1); double level = -1; if (rawlevel >= 0 && scale > 0) { // normalize level to [0..1] level = rawlevel / scale; } Log.i(TAG, "Bettery level on uplug is " + level ); if (level == 1) { try { Log.i(TAG, "Level was 100% at unlug, serializing 'since charged'"); StatsProvider.getInstance(context).setReferenceSinceCharged(0); } catch (Exception e) { Log.e(TAG, "An error occured: " + e.getMessage()); } } } catch (Exception e) { Log.e(TAG, "An error occured: " + e.getMessage()); } } if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { Log.i(TAG, "Received Broadcast ACTION_SCREEN_OFF"); // todo: store the "since screen off" refs here try { } catch (Exception e) { Log.e(TAG, "An error occured: " + e.getMessage()); } } if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) { Log.i(TAG, "Received Broadcast ACTION_SCREEN_ON"); // todo: evaluate what hapened while screen was off here try { } catch (Exception e) { Log.e(TAG, "An error occured: " + e.getMessage()); } } }
diff --git a/src/to/joe/j2mc/tournament/command/JoinCommand.java b/src/to/joe/j2mc/tournament/command/JoinCommand.java index 894953a..bdb5ccc 100644 --- a/src/to/joe/j2mc/tournament/command/JoinCommand.java +++ b/src/to/joe/j2mc/tournament/command/JoinCommand.java @@ -1,34 +1,34 @@ package to.joe.j2mc.tournament.command; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import to.joe.j2mc.core.J2MC_Manager; import to.joe.j2mc.core.command.MasterCommand; import to.joe.j2mc.tournament.J2MC_Tournament; public class JoinCommand extends MasterCommand { J2MC_Tournament plugin; public JoinCommand(J2MC_Tournament tournament) { super(tournament); this.plugin = tournament; } @Override public void exec(CommandSender sender, String commandName, String[] args, Player player, boolean isPlayer) { - if (this.plugin.registrationOpen) { + if (this.plugin.participants.contains(player)) { + sender.sendMessage(ChatColor.AQUA + "You are already signed up for this tournament"); + } else if (this.plugin.registrationOpen) { this.plugin.participants.add(player); sender.sendMessage(ChatColor.AQUA + "You have been entered into the tournament"); J2MC_Manager.getCore().adminAndLog(ChatColor.RED + sender.getName() + ChatColor.AQUA + " has entered the tournament!"); J2MC_Manager.getCore().messageNonAdmin(ChatColor.RED + sender.getName() + ChatColor.AQUA + " has entered the tournament!"); - } else if (this.plugin.participants.contains(player)) { - sender.sendMessage(ChatColor.AQUA + "You are already signed up for this tournament"); } else { sender.sendMessage(ChatColor.AQUA + "Tournament registration is closed"); } } }
false
true
public void exec(CommandSender sender, String commandName, String[] args, Player player, boolean isPlayer) { if (this.plugin.registrationOpen) { this.plugin.participants.add(player); sender.sendMessage(ChatColor.AQUA + "You have been entered into the tournament"); J2MC_Manager.getCore().adminAndLog(ChatColor.RED + sender.getName() + ChatColor.AQUA + " has entered the tournament!"); J2MC_Manager.getCore().messageNonAdmin(ChatColor.RED + sender.getName() + ChatColor.AQUA + " has entered the tournament!"); } else if (this.plugin.participants.contains(player)) { sender.sendMessage(ChatColor.AQUA + "You are already signed up for this tournament"); } else { sender.sendMessage(ChatColor.AQUA + "Tournament registration is closed"); } }
public void exec(CommandSender sender, String commandName, String[] args, Player player, boolean isPlayer) { if (this.plugin.participants.contains(player)) { sender.sendMessage(ChatColor.AQUA + "You are already signed up for this tournament"); } else if (this.plugin.registrationOpen) { this.plugin.participants.add(player); sender.sendMessage(ChatColor.AQUA + "You have been entered into the tournament"); J2MC_Manager.getCore().adminAndLog(ChatColor.RED + sender.getName() + ChatColor.AQUA + " has entered the tournament!"); J2MC_Manager.getCore().messageNonAdmin(ChatColor.RED + sender.getName() + ChatColor.AQUA + " has entered the tournament!"); } else { sender.sendMessage(ChatColor.AQUA + "Tournament registration is closed"); } }
diff --git a/android-project/src/org/liballeg/app/AllegroActivity.java b/android-project/src/org/liballeg/app/AllegroActivity.java index bcd2292a8..0023a563a 100644 --- a/android-project/src/org/liballeg/app/AllegroActivity.java +++ b/android-project/src/org/liballeg/app/AllegroActivity.java @@ -1,1400 +1,1399 @@ package org.liballeg.app; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Environment; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.SurfaceView; import android.view.SurfaceHolder; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.OrientationEventListener; import android.view.WindowManager; import android.hardware.*; import android.content.res.Configuration; import android.content.res.AssetManager; import android.content.Context; import android.graphics.Canvas; import android.graphics.PixelFormat; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.ActivityInfo; import android.util.Log; import java.lang.String; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.InvocationTargetException; import java.lang.Runnable; import java.util.List; import java.util.BitSet; import java.io.File; import java.io.InputStream; import java.io.FileOutputStream; import java.nio.ByteBuffer; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.egl.*; import org.liballeg.app.AllegroInputStream; public class AllegroActivity extends Activity implements SensorEventListener { /* properties */ static final int ALLEGRO_DISPLAY_ORIENTATION_UNKNOWN = 0; static final int ALLEGRO_DISPLAY_ORIENTATION_0_DEGREES = 1; static final int ALLEGRO_DISPLAY_ORIENTATION_90_DEGREES = 2; static final int ALLEGRO_DISPLAY_ORIENTATION_180_DEGREES = 4; static final int ALLEGRO_DISPLAY_ORIENTATION_270_DEGREES = 8; static final int ALLEGRO_DISPLAY_ORIENTATION_PORTRAIT = 5; static final int ALLEGRO_DISPLAY_ORIENTATION_LANDSCAPE = 10; static final int ALLEGRO_DISPLAY_ORIENTATION_ALL = 15; static final int ALLEGRO_DISPLAY_ORIENTATION_FACE_UP = 16; static final int ALLEGRO_DISPLAY_ORIENTATION_FACE_DOWN = 32; private static SensorManager sensorManager; private List<Sensor> sensors; private static AllegroSurface surface; private Handler handler; private Configuration currentConfig; /* native methods we call */ public native boolean nativeOnCreate(); public native void nativeOnPause(); public native void nativeOnResume(); public native void nativeOnDestroy(); public native void nativeOnAccel(int id, float x, float y, float z); public native void nativeCreateDisplay(); public native void nativeOnOrientationChange(int orientation, boolean init); /* load allegro */ static { /* FIXME: see if we can't load the allegro library name, or type from the manifest here */ System.loadLibrary("allegro-debug"); System.loadLibrary("allegro_primitives-debug"); System.loadLibrary("allegro_image-debug"); } public static AllegroActivity Self; /* methods native code calls */ public String getLibraryDir() { /* Android 1.6 doesn't have .nativeLibraryDir :( */ /* FIXME: use reflection here to detect the capabilities of the device */ return getApplicationInfo().dataDir + "/lib"; } public String getAppName() { try { return getPackageManager().getActivityInfo(getComponentName(), android.content.pm.PackageManager.GET_META_DATA).metaData.getString("org.liballeg.app_name"); } catch(PackageManager.NameNotFoundException ex) { return new String(); } } public String getResourcesDir() { //return getApplicationInfo().dataDir + "/assets"; //return getApplicationInfo().sourceDir + "/assets/"; return getFilesDir().getAbsolutePath(); } public String getPubDataDir() { return getExternalFilesDir(null).getAbsolutePath(); } public String getApkPath() { return getApplicationInfo().sourceDir; } public void postRunnable(Runnable runme) { try { Log.d("AllegroActivity", "postRunnable"); handler.post( runme ); } catch (Exception x) { Log.d("AllegroActivity", "postRunnable exception: " + x.getMessage()); } } public void createSurface() { try { Log.d("AllegroActivity", "createSurface"); if(surface == null) { surface = new AllegroSurface(getApplicationContext()); } SurfaceHolder holder = surface.getHolder(); holder.addCallback(surface); holder.setType(SurfaceHolder.SURFACE_TYPE_GPU); //setContentView(surface); Window win = getWindow(); win.setContentView(surface); Log.d("AllegroActivity", "createSurface end"); } catch(Exception x) { Log.d("AllegroActivity", "createSurface exception: " + x.getMessage()); } } public void postCreateSurface() { try { Log.d("AllegroActivity", "postCreateSurface"); handler.post( new Runnable() { public void run() { createSurface(); } } ); } catch(Exception x) { Log.d("AllegroActivity", "postCreateSurface exception: " + x.getMessage()); } return; } public void destroySurface() { Log.d("AllegroActivity", "destroySurface"); ViewGroup vg = (ViewGroup)(surface.getParent()); vg.removeView(surface); surface = null; } public void postDestroySurface(View s) { try { Log.d("AllegroActivity", "postDestroySurface"); handler.post( new Runnable() { public void run() { destroySurface(); } } ); } catch(Exception x) { Log.d("AllegroActivity", "postDestroySurface exception: " + x.getMessage()); } return; } public int getNumSensors() { return sensors.size(); } /* * load passes in the buffer, will return the decoded bytebuffer * then I want to change lock/unlock_bitmap to accept a raw pointer * rather than allocating another buffer and making you copy shit again * images are loaded as ARGB_8888 by android by default */ private Bitmap decodedBitmap; private boolean bitmapLoaded; public Bitmap decodeBitmapByteArray(byte[] array) { Log.d("AllegroActivity", "decodeBitmapByteArray"); try { BitmapFactory.Options options = new BitmapFactory.Options(); options.inPreferredConfig = Bitmap.Config.ARGB_8888; Bitmap bmp = BitmapFactory.decodeByteArray(array, 0, array.length, options); //Bitmap.Config conf = bmp.getConfig(); //switch(conf. return bmp; } catch(Exception ex) { Log.e("AllegroActivity", "decodeBitmapByteArray exception: " + ex.getMessage()); } return null; } public Bitmap decodeBitmap(final AllegroInputStream is) { Log.d("AllegroActivity", "decodeBitmap begin"); bitmapLoaded = false; try { //handler.post( new Runnable() { // public void run() { // Log.d("AllegroActivity", "calling decodeStream"); // decodedBitmap = BitmapFactory.decodeStream(is); // bitmapLoaded = true; // Log.d("AllegroActivity", "done decodeStream"); // } //} ); //Log.d("AllegroActivity", "waiting for decodeStream"); //while(bitmapLoaded == false) { Thread.sleep(20); } BitmapFactory.Options options = new BitmapFactory.Options(); options.inPreferredConfig = Bitmap.Config.ARGB_8888; decodedBitmap = BitmapFactory.decodeStream(is, null, options); Log.d("AllegroActivity", "done waiting for decodeStream"); } catch(Exception ex) { Log.e("AllegroActivity", "decodeBitmap exception: " + ex.getMessage()); } Log.d("AllegroActivity", "decodeBitmap end"); return decodedBitmap; } public void postFinish() { try { Log.d("AllegroActivity", "posting finish!"); handler.post( new Runnable() { public void run() { try { AllegroActivity.this.finish(); } catch(Exception x) { Log.d("AllegroActivity", "inner exception: " + x.getMessage()); } } } ); } catch(Exception x) { Log.d("AllegroActivity", "exception: " + x.getMessage()); } } /* end of functions native code calls */ /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Self = this; Log.d("AllegroActivity", "onCreate"); Log.d("AllegroActivity", "Files Dir: " + getFilesDir()); File extdir = Environment.getExternalStorageDirectory(); boolean mExternalStorageAvailable = false; boolean mExternalStorageWriteable = false; String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { // We can read and write the media mExternalStorageAvailable = mExternalStorageWriteable = true; } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { // We can only read the media mExternalStorageAvailable = true; mExternalStorageWriteable = false; } else { // Something else is wrong. It may be one of many other states, but all we need // to know is we can neither read nor write mExternalStorageAvailable = mExternalStorageWriteable = false; } Log.d("AllegroActivity", "External Storage Dir: " + extdir.getAbsolutePath()); Log.d("AllegroActivity", "External Files Dir: " + getExternalFilesDir(null)); Log.d("AllegroActivity", "external: avail = " + mExternalStorageAvailable + " writable = " + mExternalStorageWriteable); Log.d("AllegroActivity", "sourceDir: " + getApplicationInfo().sourceDir); Log.d("AllegroActivity", "publicSourceDir: " + getApplicationInfo().publicSourceDir); unpackAssets(""); handler = new Handler(); initSensors(); currentConfig = new Configuration(getResources().getConfiguration()); Log.d("AllegroActivity", "before nativeOnCreate"); if(!nativeOnCreate()) { finish(); Log.d("AllegroActivity", "onCreate fail"); return; } nativeOnOrientationChange(getAllegroOrientation(currentConfig.orientation), true); requestWindowFeature(Window.FEATURE_NO_TITLE); this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); Log.d("AllegroActivity", "onCreate end"); } @Override public void onStart() { super.onStart(); Log.d("AllegroActivity", "onStart."); } // @Override public void onRestart() { super.onRestart(); Log.d("AllegroActivity", "onRestart."); } @Override public void onStop() { super.onStop(); Log.d("AllegroActivity", "onStop."); } /** Called when the activity is paused. */ @Override public void onPause() { super.onPause(); Log.d("AllegroActivity", "onPause"); disableSensors(); nativeOnPause(); Log.d("AllegroActivity", "onPause end"); } /** Called when the activity is resumed/unpaused */ @Override public void onResume() { Log.d("AllegroActivity", "onResume"); super.onResume(); enableSensors(); nativeOnResume(); Log.d("AllegroActivity", "onResume end"); } /** Called when the activity is destroyed */ @Override public void onDestroy() { super.onDestroy(); Log.d("AllegroActivity", "onDestroy"); nativeOnDestroy(); Log.d("AllegroActivity", "onDestroy end"); } /** Called when config has changed */ @Override public void onConfigurationChanged(Configuration conf) { super.onConfigurationChanged(conf); Log.d("AllegroActivity", "onConfigurationChanged"); // compare conf.orientation with some saved value int changes = currentConfig.diff(conf); Log.d("AllegroActivity", "changes: " + Integer.toBinaryString(changes)); if((changes & ActivityInfo.CONFIG_FONT_SCALE) != 0) Log.d("AllegroActivity", "font scale changed"); if((changes & ActivityInfo.CONFIG_MCC) != 0) Log.d("AllegroActivity", "mcc changed"); if((changes & ActivityInfo.CONFIG_MNC) != 0) Log.d("AllegroActivity", " changed"); if((changes & ActivityInfo.CONFIG_LOCALE) != 0) Log.d("AllegroActivity", "locale changed"); if((changes & ActivityInfo.CONFIG_TOUCHSCREEN) != 0) Log.d("AllegroActivity", "touchscreen changed"); if((changes & ActivityInfo.CONFIG_KEYBOARD) != 0) Log.d("AllegroActivity", "keyboard changed"); if((changes & ActivityInfo.CONFIG_NAVIGATION) != 0) Log.d("AllegroActivity", "navigation changed"); if((changes & ActivityInfo.CONFIG_ORIENTATION) != 0) { Log.d("AllegroActivity", "orientation changed"); nativeOnOrientationChange(getAllegroOrientation(conf.orientation), false); } if((changes & ActivityInfo.CONFIG_SCREEN_LAYOUT) != 0) Log.d("AllegroActivity", "screen layout changed"); if((changes & ActivityInfo.CONFIG_SCREEN_SIZE) != 0) Log.d("AllegroActivity", "screen size changed"); if((changes & ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE) != 0) Log.d("AllegroActivity", "smallest screen size changed"); if((changes & ActivityInfo.CONFIG_UI_MODE) != 0) Log.d("AllegroActivity", "ui mode changed"); if(currentConfig.screenLayout != conf.screenLayout) { Log.d("AllegroActivity", "screenLayout changed!"); } Log.d("AllegroActivity", "old orientation: " + currentConfig.orientation + ", new orientation: " + conf.orientation); currentConfig = new Configuration(conf); } /** Called when app is frozen **/ @Override public void onSaveInstanceState(Bundle state) { Log.d("AllegroActivity", "onSaveInstanceState"); /* do nothing? */ /* this should get rid of the following warning: * couldn't save which view has focus because the focused view has no id. */ } /* sensors */ private boolean initSensors() { sensorManager = (SensorManager)getApplicationContext().getSystemService("sensor"); /* only check for Acclerometers for now, not sure how we should utilize other types */ sensors = sensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER); if(sensors == null) return false; return true; } private void enableSensors() { for(int i = 0; i < sensors.size(); i++) { sensorManager.registerListener(this, sensors.get(i), SensorManager.SENSOR_DELAY_GAME); } } private void disableSensors() { for(int i = 0; i < sensors.size(); i++) { sensorManager.unregisterListener(this, sensors.get(i)); } } public void onAccuracyChanged(Sensor sensor, int accuracy) { /* what to do? */ } public void onSensorChanged(SensorEvent event) { int idx = sensors.indexOf(event.sensor); if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { nativeOnAccel(idx, event.values[0], event.values[1], event.values[2]); } } private int getAllegroOrientation(int orientation) { int allegro_orientation = ALLEGRO_DISPLAY_ORIENTATION_UNKNOWN; switch(orientation) { case Configuration.ORIENTATION_LANDSCAPE: allegro_orientation = ALLEGRO_DISPLAY_ORIENTATION_LANDSCAPE; break; case Configuration.ORIENTATION_PORTRAIT: allegro_orientation = ALLEGRO_DISPLAY_ORIENTATION_PORTRAIT; break; case Configuration.ORIENTATION_SQUARE: // XXX: maybe add a ALLEGRO_DISPLAY_ORIENTATION_SQUARE? // allegro_orientation = ALLEGRO_DISPLAY_ORIENTATION_SQUARE; break; case Configuration.ORIENTATION_UNDEFINED: break; } return allegro_orientation; } // FIXME: this is a horrible hack, needs to be replaced with something smarter // FIXME: or a fshook driver to access assets. private void unpackAssets(String dir) { try { AssetManager am = getResources().getAssets(); String list[] = am.list(dir); for(int i = 0; i < list.length; i++) { String full = dir + (dir.equals("") ? "" : "/") + list[i]; InputStream is = null; try { is = am.open(full); } catch (Exception e) { Log.d("AllegroActivity", "asset["+i+"] (directory): " + full); File f = new File(getResourcesDir()+"/"+full); f.mkdir(); unpackAssets(full); continue; } Log.d("AllegroActivity", "asset["+i+"] (file): " + full); FileOutputStream os = new FileOutputStream(getResourcesDir()+"/"+full); byte buff[] = new byte[4096]; while(true) { int read_ret = is.read(buff); if(read_ret > 0) { os.write(buff, 0, read_ret); } else { break; } } is.close(); os.close(); } } catch(java.io.IOException ex) { Log.e("AllegroActivity", "asset list exception: "+ex.getMessage()); } } } class AllegroSurface extends SurfaceView implements SurfaceHolder.Callback, View.OnKeyListener, View.OnTouchListener { static final int ALLEGRO_PIXEL_FORMAT_RGBA_8888 = 10; static final int ALLEGRO_PIXEL_FORMAT_RGB_888 = 12; static final int ALLEGRO_PIXEL_FORMAT_RGB_565 = 13; static final int ALLEGRO_PIXEL_FORMAT_RGBA_5551 = 15; static final int ALLEGRO_PIXEL_FORMAT_ABGR_8888_LE = 25; static final int ALLEGRO_PIXEL_FORMAT_RGBA_4444 = 26; static final int ALLEGRO_RED_SIZE = 0; static final int ALLEGRO_GREEN_SIZE = 1; static final int ALLEGRO_BLUE_SIZE = 2; static final int ALLEGRO_ALPHA_SIZE = 3; static final int ALLEGRO_DEPTH_SIZE = 15; static final int ALLEGRO_STENCIL_SIZE = 16; static final int ALLEGRO_SAMPLE_BUFFERS = 17; static final int ALLEGRO_SAMPLES = 18; static final int _BIND_TO_TEXTURE_RGBA = 0x1002; static final int EGL_BIND_TO_TEXTURE_RGBA = 0x303A; static final int ALLEGRO_KEY_A = 1; static final int ALLEGRO_KEY_B = 2; static final int ALLEGRO_KEY_C = 3; static final int ALLEGRO_KEY_D = 4; static final int ALLEGRO_KEY_E = 5; static final int ALLEGRO_KEY_F = 6; static final int ALLEGRO_KEY_G = 7; static final int ALLEGRO_KEY_H = 8; static final int ALLEGRO_KEY_I = 9; static final int ALLEGRO_KEY_J = 10; static final int ALLEGRO_KEY_K = 11; static final int ALLEGRO_KEY_L = 12; static final int ALLEGRO_KEY_M = 13; static final int ALLEGRO_KEY_N = 14; static final int ALLEGRO_KEY_O = 15; static final int ALLEGRO_KEY_P = 16; static final int ALLEGRO_KEY_Q = 17; static final int ALLEGRO_KEY_R = 18; static final int ALLEGRO_KEY_S = 19; static final int ALLEGRO_KEY_T = 20; static final int ALLEGRO_KEY_U = 21; static final int ALLEGRO_KEY_V = 22; static final int ALLEGRO_KEY_W = 23; static final int ALLEGRO_KEY_X = 24; static final int ALLEGRO_KEY_Y = 25; static final int ALLEGRO_KEY_Z = 26; static final int ALLEGRO_KEY_0 = 27; static final int ALLEGRO_KEY_1 = 28; static final int ALLEGRO_KEY_2 = 29; static final int ALLEGRO_KEY_3 = 30; static final int ALLEGRO_KEY_4 = 31; static final int ALLEGRO_KEY_5 = 32; static final int ALLEGRO_KEY_6 = 33; static final int ALLEGRO_KEY_7 = 34; static final int ALLEGRO_KEY_8 = 35; static final int ALLEGRO_KEY_9 = 36; static final int ALLEGRO_KEY_PAD_0 = 37; static final int ALLEGRO_KEY_PAD_1 = 38; static final int ALLEGRO_KEY_PAD_2 = 39; static final int ALLEGRO_KEY_PAD_3 = 40; static final int ALLEGRO_KEY_PAD_4 = 41; static final int ALLEGRO_KEY_PAD_5 = 42; static final int ALLEGRO_KEY_PAD_6 = 43; static final int ALLEGRO_KEY_PAD_7 = 44; static final int ALLEGRO_KEY_PAD_8 = 45; static final int ALLEGRO_KEY_PAD_9 = 46; static final int ALLEGRO_KEY_F1 = 47; static final int ALLEGRO_KEY_F2 = 48; static final int ALLEGRO_KEY_F3 = 49; static final int ALLEGRO_KEY_F4 = 50; static final int ALLEGRO_KEY_F5 = 51; static final int ALLEGRO_KEY_F6 = 52; static final int ALLEGRO_KEY_F7 = 53; static final int ALLEGRO_KEY_F8 = 54; static final int ALLEGRO_KEY_F9 = 55; static final int ALLEGRO_KEY_F10 = 56; static final int ALLEGRO_KEY_F11 = 57; static final int ALLEGRO_KEY_F12 = 58; static final int ALLEGRO_KEY_ESCAPE = 59; static final int ALLEGRO_KEY_TILDE = 60; static final int ALLEGRO_KEY_MINUS = 61; static final int ALLEGRO_KEY_EQUALS = 62; static final int ALLEGRO_KEY_BACKSPACE = 63; static final int ALLEGRO_KEY_TAB = 64; static final int ALLEGRO_KEY_OPENBRACE = 65; static final int ALLEGRO_KEY_CLOSEBRACE = 66; static final int ALLEGRO_KEY_ENTER = 67; static final int ALLEGRO_KEY_SEMICOLON = 68; static final int ALLEGRO_KEY_QUOTE = 69; static final int ALLEGRO_KEY_BACKSLASH = 70; static final int ALLEGRO_KEY_BACKSLASH2 = 71; /* DirectInput calls this DIK_OEM_102: "< > | on UK/Germany keyboards" */ static final int ALLEGRO_KEY_COMMA = 72; static final int ALLEGRO_KEY_FULLSTOP = 73; static final int ALLEGRO_KEY_SLASH = 74; static final int ALLEGRO_KEY_SPACE = 75; static final int ALLEGRO_KEY_INSERT = 76; static final int ALLEGRO_KEY_DELETE = 77; static final int ALLEGRO_KEY_HOME = 78; static final int ALLEGRO_KEY_END = 79; static final int ALLEGRO_KEY_PGUP = 80; static final int ALLEGRO_KEY_PGDN = 81; static final int ALLEGRO_KEY_LEFT = 82; static final int ALLEGRO_KEY_RIGHT = 83; static final int ALLEGRO_KEY_UP = 84; static final int ALLEGRO_KEY_DOWN = 85; static final int ALLEGRO_KEY_PAD_SLASH = 86; static final int ALLEGRO_KEY_PAD_ASTERISK = 87; static final int ALLEGRO_KEY_PAD_MINUS = 88; static final int ALLEGRO_KEY_PAD_PLUS = 89; static final int ALLEGRO_KEY_PAD_DELETE = 90; static final int ALLEGRO_KEY_PAD_ENTER = 91; static final int ALLEGRO_KEY_PRINTSCREEN = 92; static final int ALLEGRO_KEY_PAUSE = 93; static final int ALLEGRO_KEY_ABNT_C1 = 94; static final int ALLEGRO_KEY_YEN = 95; static final int ALLEGRO_KEY_KANA = 96; static final int ALLEGRO_KEY_CONVERT = 97; static final int ALLEGRO_KEY_NOCONVERT = 98; static final int ALLEGRO_KEY_AT = 99; static final int ALLEGRO_KEY_CIRCUMFLEX = 100; static final int ALLEGRO_KEY_COLON2 = 101; static final int ALLEGRO_KEY_KANJI = 102; static final int ALLEGRO_KEY_PAD_EQUALS = 103; /* MacOS X */ static final int ALLEGRO_KEY_BACKQUOTE = 104; /* MacOS X */ static final int ALLEGRO_KEY_SEMICOLON2 = 105; /* MacOS X -- TODO: ask lillo what this should be */ static final int ALLEGRO_KEY_COMMAND = 106; /* MacOS X */ static final int ALLEGRO_KEY_BACK = 107; static final int ALLEGRO_KEY_UNKNOWN = 108; /* All codes up to before ALLEGRO_KEY_MODIFIERS can be freely * assignedas additional unknown keys, like various multimedia * and application keys keyboards may have. */ static final int ALLEGRO_KEY_MODIFIERS = 215; static final int ALLEGRO_KEY_LSHIFT = 215; static final int ALLEGRO_KEY_RSHIFT = 216; static final int ALLEGRO_KEY_LCTRL = 217; static final int ALLEGRO_KEY_RCTRL = 218; static final int ALLEGRO_KEY_ALT = 219; static final int ALLEGRO_KEY_ALTGR = 220; static final int ALLEGRO_KEY_LWIN = 221; static final int ALLEGRO_KEY_RWIN = 222; static final int ALLEGRO_KEY_MENU = 223; static final int ALLEGRO_KEY_SCROLLLOCK = 224; static final int ALLEGRO_KEY_NUMLOCK = 225; static final int ALLEGRO_KEY_CAPSLOCK = 226; static final int ALLEGRO_KEY_MAX = 227; private static int[] keyMap = { ALLEGRO_KEY_UNKNOWN, // KeyEvent.KEYCODE_UNKNOWN ALLEGRO_KEY_LEFT, // KeyEvent.KEYCODE_SOFT_LEFT ALLEGRO_KEY_RIGHT, // KeyEvent.KEYCODE_SOFT_RIGHT ALLEGRO_KEY_HOME, // KeyEvent.KEYCODE_HOME ALLEGRO_KEY_BACK, // KeyEvent.KEYCODE_BACK ALLEGRO_KEY_UNKNOWN, // KeyEvent.KEYCODE_CALL ALLEGRO_KEY_UNKNOWN, // KeyEvent.KEYCODE_ENDCALL ALLEGRO_KEY_0, // KeyEvent.KEYCODE_0 ALLEGRO_KEY_1, // KeyEvent.KEYCODE_1 ALLEGRO_KEY_2, // KeyEvent.KEYCODE_2 ALLEGRO_KEY_3, // KeyEvent.KEYCODE_3 ALLEGRO_KEY_4, // KeyEvent.KEYCODE_4 ALLEGRO_KEY_5, // KeyEvent.KEYCODE_5 ALLEGRO_KEY_6, // KeyEvent.KEYCODE_6 ALLEGRO_KEY_7, // KeyEvent.KEYCODE_7 ALLEGRO_KEY_8, // KeyEvent.KEYCODE_8 ALLEGRO_KEY_9, // KeyEvent.KEYCODE_9 ALLEGRO_KEY_UNKNOWN, // KeyEvent.KEYCODE_STAR ALLEGRO_KEY_UNKNOWN, // KeyEvent.KEYCODE_POUND ALLEGRO_KEY_UP, // KeyEvent.KEYCODE_DPAD_UP ALLEGRO_KEY_DOWN, // KeyEvent.KEYCODE_DPAD_DOWN ALLEGRO_KEY_LEFT, // KeyEvent.KEYCODE_DPAD_LEFT ALLEGRO_KEY_RIGHT, // KeyEvent.KEYCODE_DPAD_RIGHT ALLEGRO_KEY_UNKNOWN, // KeyEvent.KEYCODE_DPAD_CENTER ALLEGRO_KEY_UNKNOWN, // KeyEvent.KEYCODE_VOLUME_UP ALLEGRO_KEY_UNKNOWN, // KeyEvent.KEYCODE_VOLUME_DOWN ALLEGRO_KEY_UNKNOWN, // KeyEvent.KEYCODE_POWER ALLEGRO_KEY_UNKNOWN, // KeyEvent.KEYCODE_CAMERA ALLEGRO_KEY_UNKNOWN, // KeyEvent.KEYCODE_CLEAR ALLEGRO_KEY_A, // KeyEvent.KEYCODE_A ALLEGRO_KEY_B, // KeyEvent.KEYCODE_B ALLEGRO_KEY_C, // KeyEvent.KEYCODE_B ALLEGRO_KEY_D, // KeyEvent.KEYCODE_D ALLEGRO_KEY_E, // KeyEvent.KEYCODE_E ALLEGRO_KEY_F, // KeyEvent.KEYCODE_F ALLEGRO_KEY_G, // KeyEvent.KEYCODE_G ALLEGRO_KEY_H, // KeyEvent.KEYCODE_H ALLEGRO_KEY_I, // KeyEvent.KEYCODE_I ALLEGRO_KEY_J, // KeyEvent.KEYCODE_J ALLEGRO_KEY_K, // KeyEvent.KEYCODE_K ALLEGRO_KEY_L, // KeyEvent.KEYCODE_L ALLEGRO_KEY_M, // KeyEvent.KEYCODE_M ALLEGRO_KEY_N, // KeyEvent.KEYCODE_N ALLEGRO_KEY_O, // KeyEvent.KEYCODE_O ALLEGRO_KEY_P, // KeyEvent.KEYCODE_P ALLEGRO_KEY_Q, // KeyEvent.KEYCODE_Q ALLEGRO_KEY_R, // KeyEvent.KEYCODE_R ALLEGRO_KEY_S, // KeyEvent.KEYCODE_S ALLEGRO_KEY_T, // KeyEvent.KEYCODE_T ALLEGRO_KEY_U, // KeyEvent.KEYCODE_U ALLEGRO_KEY_V, // KeyEvent.KEYCODE_V ALLEGRO_KEY_W, // KeyEvent.KEYCODE_W ALLEGRO_KEY_X, // KeyEvent.KEYCODE_X ALLEGRO_KEY_Y, // KeyEvent.KEYCODE_Y ALLEGRO_KEY_Z, // KeyEvent.KEYCODE_Z ALLEGRO_KEY_COMMA, // KeyEvent.KEYCODE_COMMA ALLEGRO_KEY_FULLSTOP, // KeyEvent.KEYCODE_PERIOD ALLEGRO_KEY_ALT, // KeyEvent.KEYCODE_ALT_LEFT ALLEGRO_KEY_ALTGR, // KeyEvent.KEYCODE_ALT_RIGHT ALLEGRO_KEY_LSHIFT, // KeyEvent.KEYCODE_SHIFT_LEFT ALLEGRO_KEY_RSHIFT, // KeyEvent.KEYCODE_SHIFT_RIGHT ALLEGRO_KEY_TAB, // KeyEvent.KEYCODE_TAB ALLEGRO_KEY_SPACE, // KeyEvent.KEYCODE_SPACE ALLEGRO_KEY_UNKNOWN, // KeyEvent.KEYCODE_SYM ALLEGRO_KEY_UNKNOWN, // KeyEvent.KEYCODE_EXPLORER ALLEGRO_KEY_UNKNOWN, // KeyEvent.KEYCODE_ENVELOPE ALLEGRO_KEY_ENTER, // KeyEvent.KEYCODE_ENTER ALLEGRO_KEY_DELETE, // KeyEvent.KEYCODE_DEL ALLEGRO_KEY_TILDE, // KeyEvent.KEYCODE_GRAVE ALLEGRO_KEY_MINUS, // KeyEvent.KEYCODE_MINUS ALLEGRO_KEY_EQUALS, // KeyEvent.KEYCODE_EQUALS ALLEGRO_KEY_OPENBRACE, // KeyEvent.KEYCODE_LEFT_BRACKET ALLEGRO_KEY_CLOSEBRACE, // KeyEvent.KEYCODE_RIGHT_BRACKET ALLEGRO_KEY_BACKSLASH, // KeyEvent.KEYCODE_BACKSLASH ALLEGRO_KEY_SEMICOLON, // KeyEvent.KEYCODE_SEMICOLON ALLEGRO_KEY_QUOTE, // KeyEvent.KEYCODE_APOSTROPHY ALLEGRO_KEY_SLASH, // KeyEvent.KEYCODE_SLASH ALLEGRO_KEY_AT, // KeyEvent.KEYCODE_AT ALLEGRO_KEY_NUMLOCK, // KeyEvent.KEYCODE_NUM ALLEGRO_KEY_UNKNOWN, // KeyEvent.KEYCODE_HEADSETHOOK ALLEGRO_KEY_UNKNOWN, // KeyEvent.KEYCODE_FOCUS ALLEGRO_KEY_PAD_PLUS, // KeyEvent.KEYCODE_PLUS ALLEGRO_KEY_MENU, // KeyEvent.KEYCODE_MENU ALLEGRO_KEY_UNKNOWN, // KeyEvent.KEYCODE_NOTIFICATION ALLEGRO_KEY_UNKNOWN, // KeyEvent.KEYCODE_SEARCH ALLEGRO_KEY_UNKNOWN, // KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE ALLEGRO_KEY_UNKNOWN, // KeyEvent.KEYCODE_MEDIA_STOP ALLEGRO_KEY_UNKNOWN, // KeyEvent.KEYCODE_MEDIA_NEXT ALLEGRO_KEY_UNKNOWN, // KeyEvent.KEYCODE_MEDIA_PREVIOUS ALLEGRO_KEY_UNKNOWN, // KeyEvent.KEYCODE_MEDIA_REWIND ALLEGRO_KEY_UNKNOWN, // KeyEvent.KEYCODE_MEDIA_FAST_FORWARD ALLEGRO_KEY_UNKNOWN, // KeyEvent.KEYCODE_MUTE ALLEGRO_KEY_PGUP, // KeyEvent.KEYCODE_PAGE_UP ALLEGRO_KEY_PGDN, // KeyEvent.KEYCODE_PAGE_DOWN ALLEGRO_KEY_UNKNOWN, // KeyEvent.KEYCODE_PICTSYMBOLS ALLEGRO_KEY_UNKNOWN, // KeyEvent.KEYCODE_SWITCH_CHARSET ALLEGRO_KEY_UNKNOWN, // KeyEvent.KEYCODE_BUTTON_A ALLEGRO_KEY_UNKNOWN, // KeyEvent.KEYCODE_BUTTON_B ALLEGRO_KEY_UNKNOWN, // KeyEvent.KEYCODE_BUTTON_C ALLEGRO_KEY_UNKNOWN, // KeyEvent.KEYCODE_BUTTON_X ALLEGRO_KEY_UNKNOWN, // KeyEvent.KEYCODE_BUTTON_Y ALLEGRO_KEY_UNKNOWN, // KeyEvent.KEYCODE_BUTTON_Z ALLEGRO_KEY_UNKNOWN, // KeyEvent.KEYCODE_BUTTON_L1 ALLEGRO_KEY_UNKNOWN, // KeyEvent.KEYCODE_BUTTON_R1 ALLEGRO_KEY_UNKNOWN, // KeyEvent.KEYCODE_BUTTON_L2 ALLEGRO_KEY_UNKNOWN, // KeyEvent.KEYCODE_BUTTON_R2 ALLEGRO_KEY_UNKNOWN, // KeyEvent.KEYCODE_THUMBL ALLEGRO_KEY_UNKNOWN, // KeyEvent.KEYCODE_THUMBR ALLEGRO_KEY_UNKNOWN, // KeyEvent.KEYCODE_START ALLEGRO_KEY_UNKNOWN, // KeyEvent.KEYCODE_SELECT ALLEGRO_KEY_UNKNOWN, // KeyEvent.KEYCODE_MODE }; final int ALLEGRO_EVENT_TOUCH_BEGIN = 50; final int ALLEGRO_EVENT_TOUCH_END = 51; final int ALLEGRO_EVENT_TOUCH_MOVE = 52; final int ALLEGRO_EVENT_TOUCH_CANCEL = 5; /** native functions we call */ public native void nativeOnCreate(); public native void nativeOnDestroy(); public native void nativeOnChange(int format, int width, int height); public native void nativeOnKeyDown(int key); public native void nativeOnKeyUp(int key); public native void nativeOnTouch(int id, int action, float x, float y, boolean primary); /** functions that native code calls */ private int[] egl_Version = { 0, 0 }; private EGLContext egl_Context; private EGLSurface egl_Surface; private EGLDisplay egl_Display; private int egl_numConfigs = 0; private EGLConfig[] egl_Config; public boolean egl_Init() { Log.d("AllegroSurface", "egl_Init"); EGL10 egl = (EGL10)EGLContext.getEGL(); EGLDisplay dpy = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); if(!egl.eglInitialize(dpy, egl_Version)) { Log.d("AllegroSurface", "egl_Init fail"); return false; } egl_Display = dpy; egl_Config = new EGLConfig[100]; int[] num_config = { 0 }; if(!egl.eglGetConfigs(egl_Display, egl_Config, 100, num_config)) return false; egl_numConfigs = num_config[0]; Log.d("AllegroSurface", "egl_Init end"); return true; } public int egl_getMajorVersion() { return egl_Version[0]; } public int egl_getMinorVersion() { return egl_Version[1]; } public int egl_getNumConfigs() { return egl_numConfigs; } public int egl_getConfigAttrib(int conf, int attr) { EGL10 egl = (EGL10)EGLContext.getEGL(); int egl_attr = 0; switch(attr) { case ALLEGRO_RED_SIZE: egl_attr = egl.EGL_RED_SIZE; break; case ALLEGRO_GREEN_SIZE: egl_attr = egl.EGL_GREEN_SIZE; break; case ALLEGRO_BLUE_SIZE: egl_attr = egl.EGL_BLUE_SIZE; break; case ALLEGRO_ALPHA_SIZE: egl_attr = egl.EGL_ALPHA_SIZE; break; case ALLEGRO_DEPTH_SIZE: egl_attr = egl.EGL_DEPTH_SIZE; break; case ALLEGRO_STENCIL_SIZE: egl_attr = egl.EGL_STENCIL_SIZE; break; case ALLEGRO_SAMPLE_BUFFERS: egl_attr = egl.EGL_SAMPLE_BUFFERS; break; case ALLEGRO_SAMPLES: egl_attr = egl.EGL_SAMPLES; break; case _BIND_TO_TEXTURE_RGBA: egl_attr = _BIND_TO_TEXTURE_RGBA; break; default: Log.e("AllegroSurface", "got unknown attribute " + attr); break; } int[] value = { 0 }; if(!egl.eglGetConfigAttrib(egl_Display, egl_Config[conf], egl_attr, value)) return -1; return value[0]; } public boolean egl_createContext(int conf) { Log.d("AllegroSurface", "egl_createContext"); EGL10 egl = (EGL10)EGLContext.getEGL(); EGLContext ctx = egl.eglCreateContext(egl_Display, egl_Config[conf], EGL10.EGL_NO_CONTEXT, null); if(ctx == EGL10.EGL_NO_CONTEXT) { Log.d("AllegroSurface", "egl_createContext no context"); return false; } egl_Context = ctx; Log.d("AllegroSurface", "egl_createContext end"); return true; } public void egl_destroyContext() { EGL10 egl = (EGL10)EGLContext.getEGL(); Log.d("AllegroSurface", "destroying egl_Context"); egl.eglDestroyContext(egl_Display, egl_Context); egl_Context = EGL10.EGL_NO_CONTEXT; } public boolean egl_createSurface(int conf) { EGL10 egl = (EGL10)EGLContext.getEGL(); EGLSurface surface = egl.eglCreateWindowSurface(egl_Display, egl_Config[conf], this, null); if(surface == EGL10.EGL_NO_SURFACE) { Log.d("AllegroSurface", "egl_createSurface can't create surface"); return false; } if(!egl.eglMakeCurrent(egl_Display, surface, surface, egl_Context)) { egl.eglDestroySurface(egl_Display, surface); Log.d("AllegroSurface", "egl_createSurface can't make current"); return false; } egl_Surface = surface; Log.d("AllegroSurface", "created new surface: " + surface); return true; } public void egl_destroySurface() { EGL10 egl = (EGL10)EGLContext.getEGL(); if(!egl.eglMakeCurrent(egl_Display, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT)) { Log.d("AllegroSurface", "could not clear current context"); } Log.d("AllegroSurface", "destroying egl_Surface"); egl.eglDestroySurface(egl_Display, egl_Surface); egl_Surface = EGL10.EGL_NO_SURFACE; } public void egl_clearCurrent() { Log.d("AllegroSurface", "egl_clearCurrent"); EGL10 egl = (EGL10)EGLContext.getEGL(); if(!egl.eglMakeCurrent(egl_Display, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT)) { Log.d("AllegroSurface", "could not clear current context"); } Log.d("AllegroSurface", "egl_clearCurrent done"); } public void egl_makeCurrent() { EGL10 egl = (EGL10)EGLContext.getEGL(); if(!egl.eglMakeCurrent(egl_Display, egl_Surface, egl_Surface, egl_Context)) { // egl.eglDestroySurface(egl_Display, surface); // egl.eglTerminate(egl_Display); // egl_Display = null; Log.d("AllegroSurface", "can't make thread current: "); switch(egl.eglGetError()) { case EGL10.EGL_BAD_DISPLAY: Log.d("AllegroSurface", "Bad Display"); break; case EGL10.EGL_NOT_INITIALIZED: Log.d("AllegroSurface", "Not Initialized"); break; case EGL10.EGL_BAD_SURFACE: Log.d("AllegroSurface", "Bad Surface"); break; case EGL10.EGL_BAD_CONTEXT: Log.d("AllegroSurface", "Bad Context"); break; case EGL10.EGL_BAD_MATCH: Log.d("AllegroSurface", "Bad Match"); break; case EGL10.EGL_BAD_ACCESS: Log.d("AllegroSurface", "Bad Access"); break; case EGL10.EGL_BAD_NATIVE_PIXMAP: Log.d("AllegroSurface", "Bad Native Pixmap"); break; case EGL10.EGL_BAD_NATIVE_WINDOW: Log.d("AllegroSurface", "Bad Native Window"); break; case EGL10.EGL_BAD_CURRENT_SURFACE: Log.d("AllegroSurface", "Bad Current Surface"); break; case EGL10.EGL_BAD_ALLOC: Log.d("AllegroSurface", "Bad Alloc"); break; default: Log.d("AllegroSurface", "unknown error"); } return; } } public void egl_SwapBuffers() { //try { // Log.d("AllegroSurface", "posting SwapBuffers!"); // AllegroActivity.Self.postRunnable( new Runnable() { // public void run() { try { EGL10 egl = (EGL10)EGLContext.getEGL(); egl.eglSwapBuffers(egl_Display, egl_Surface); switch(egl.eglGetError()) { case EGL10.EGL_SUCCESS: break; // things are ok case EGL10.EGL_BAD_DISPLAY: Log.e("AllegroSurface", "SwapBuffers: Bad Display"); break; case EGL10.EGL_NOT_INITIALIZED: Log.e("AllegroSurface", "SwapBuffers: display not initialized"); break; case EGL10.EGL_BAD_SURFACE: Log.e("AllegroSurface", "SwapBuffers: Bad Surface: " + egl_Surface + " " + (egl_Surface == EGL10.EGL_NO_SURFACE)); break; case EGL11.EGL_CONTEXT_LOST: Log.e("AllegroSurface", "SwapBuffers: Context Lost"); break; case EGL10.EGL_BAD_NATIVE_WINDOW: Log.d("AllegroSurface", "SwapBuffers: Bad native window"); break; default: Log.d("AllegroSurface", "Unhandled SwapBuffers Error"); break; } } catch(Exception x) { Log.d("AllegroSurface", "inner exception: " + x.getMessage()); } // } // } ); //} catch(Exception x) { // Log.d("AllegroSurface", "exception: " + x.getMessage()); //} } /** main handlers */ public AllegroSurface(Context context) { super(context); Log.d("AllegroSurface", "ctor"); setFocusable(true); setFocusableInTouchMode(true); requestFocus(); setOnKeyListener(this); setOnTouchListener(this); getHolder().addCallback(this); Log.d("AllegroSurface", "ctor end"); } public void surfaceCreated(SurfaceHolder holder) { Log.d("AllegroSurface", "surfaceCreated"); nativeOnCreate(); Log.d("AllegroSurface", "surfaceCreated end"); } public void surfaceDestroyed(SurfaceHolder holder) { Log.d("AllegroSurface", "surfaceDestroyed"); nativeOnDestroy(); egl_destroySurface(); egl_destroyContext(); EGL10 egl = (EGL10)EGLContext.getEGL(); egl.eglTerminate(egl_Display); egl_Display = null; Log.d("AllegroSurface", "surfaceDestroyed end"); } public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { Log.d("AllegroSurface", "surfaceChanged"); int allegro_fmt = ALLEGRO_PIXEL_FORMAT_RGB_565; switch(format) { case PixelFormat.RGBA_4444: allegro_fmt = ALLEGRO_PIXEL_FORMAT_RGBA_4444; break; case PixelFormat.RGBA_5551: allegro_fmt = ALLEGRO_PIXEL_FORMAT_RGBA_5551; break; case PixelFormat.RGBA_8888: allegro_fmt = ALLEGRO_PIXEL_FORMAT_ABGR_8888_LE; break; case PixelFormat.RGB_565: allegro_fmt = ALLEGRO_PIXEL_FORMAT_RGB_565; break; case PixelFormat.RGB_888: allegro_fmt = ALLEGRO_PIXEL_FORMAT_RGB_888; break; default: Log.v("AllegroSurface", "unkown pixel format " + format); break; } nativeOnChange(allegro_fmt, width, height); Log.d("AllegroSurface", "surfaceChanged end"); } /* unused */ public void onDraw(Canvas canvas) { } /* events */ /* maybe dump a stacktrace and die, rather than loging, and ignoring errors */ /* all this fancyness is so we work on as many versions of android as possible, * and gracefully degrade, rather than just outright failing */ private boolean fieldExists(Object obj, String fieldName) { try { Class cls = obj.getClass(); Field m = cls.getField(fieldName); return true; } catch(Exception x) { return false; } } private <T> T getField(Object obj, String field) { try { Class cls = obj.getClass(); Field f = cls.getField(field); return (T)f.get(obj); } catch(NoSuchFieldException x) { Log.v("AllegroSurface", "field " + field + " not found in class " + obj.getClass().getCanonicalName()); return null; } catch(IllegalArgumentException x) { Log.v("AllegroSurface", "this shouldn't be possible, but fetching " + field + " from class " + obj.getClass().getCanonicalName() + " failed with an illegal argument exception"); return null; } catch(IllegalAccessException x) { Log.v("AllegroSurface", "field " + field + " is not accessible in class " + obj.getClass().getCanonicalName()); return null; } } private boolean methodExists(Object obj, String methName) { try { Class cls = obj.getClass(); Method m = cls.getMethod(methName); return true; } catch(Exception x) { return false; } } private <T> T callMethod(Object obj, String methName, Class [] types, Object... args) { try { Class cls = obj.getClass(); Method m = cls.getMethod(methName, types); return (T)m.invoke(obj, args); } catch(NoSuchMethodException x) { Log.v("AllegroSurface", "method " + methName + " does not exist in class " + obj.getClass().getCanonicalName()); return null; } catch(NullPointerException x) { Log.v("AllegroSurface", "can't invoke null method name"); return null; } catch(SecurityException x) { Log.v("AllegroSurface", "method " + methName + " is not accessible in class " + obj.getClass().getCanonicalName()); return null; } catch(IllegalAccessException x) { Log.v("AllegroSurface", "method " + methName + " is not accessible in class " + obj.getClass().getCanonicalName()); return null; } catch(InvocationTargetException x) { Log.v("AllegroSurface", "method " + methName + " threw an exception :("); return null; } } public boolean onKey(View v, int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN) { nativeOnKeyDown(keyMap[keyCode]); return true; } else if (event.getAction() == KeyEvent.ACTION_UP) { nativeOnKeyUp(keyMap[keyCode]); return true; } return false; } // FIXME: pull out android version detection into the setup // and just check some flags here, rather than checking for // the existance of the fields and methods over and over public boolean onTouch(View v, MotionEvent event) { //Log.d("AllegroSurface", "onTouch"); int action = 0; int pointer_id = 0; Class[] no_args = new Class[0]; Class[] int_arg = new Class[1]; int_arg[0] = int.class; if(methodExists(event, "getActionMasked")) { // android-8 / 2.2.x action = this.<Integer>callMethod(event, "getActionMasked", no_args); int ptr_idx = this.<Integer>callMethod(event, "getActionIndex", no_args); pointer_id = this.<Integer>callMethod(event, "getPointerId", int_arg, ptr_idx); } else { - int mask = 0xff; int raw_action = event.getAction(); if(fieldExists(event, "ACTION_MASK")) { // android-5 / 2.0 - mask = this.<Integer>getField(event, "ACTION_MASK"); + int mask = this.<Integer>getField(event, "ACTION_MASK"); action = raw_action & mask; int ptr_id_mask = this.<Integer>getField(event, "ACTION_POINTER_ID_MASK"); int ptr_id_shift = this.<Integer>getField(event, "ACTION_POINTER_ID_SHIFT"); - pointer_id = (raw_action & ptr_id_mask) >> ptr_id_shift; + pointer_id = event.getPointerId((raw_action & ptr_id_mask) >> ptr_id_shift); } else { // android-4 / 1.6 /* no ACTION_MASK? no multi touch, no pointer_id, */ action = raw_action; } } boolean primary = false; if(action == MotionEvent.ACTION_DOWN) { primary = true; action = ALLEGRO_EVENT_TOUCH_BEGIN; } else if(action == MotionEvent.ACTION_UP) { primary = true; action = ALLEGRO_EVENT_TOUCH_END; } else if(action == MotionEvent.ACTION_MOVE) { action = ALLEGRO_EVENT_TOUCH_MOVE; } else if(action == MotionEvent.ACTION_CANCEL) { action = ALLEGRO_EVENT_TOUCH_CANCEL; } // android-5 / 2.0 else if(fieldExists(event, "ACTION_POINTER_DOWN") && action == this.<Integer>getField(event, "ACTION_POINTER_DOWN")) { action = ALLEGRO_EVENT_TOUCH_BEGIN; } else if(fieldExists(event, "ACTION_POINTER_UP") && action == this.<Integer>getField(event, "ACTION_POINTER_UP")) { action = ALLEGRO_EVENT_TOUCH_END; } else { Log.v("AllegroSurface", "unknown MotionEvent type: " + action); Log.d("AllegroSurface", "onTouch endf"); return false; } if(methodExists(event, "getPointerCount")) { // android-5 / 2.0 int pointer_count = this.<Integer>callMethod(event, "getPointerCount", no_args); for(int i = 0; i < pointer_count; i++) { float x = this.<Float>callMethod(event, "getX", int_arg, i); float y = this.<Float>callMethod(event, "getY", int_arg, i); int id = this.<Integer>callMethod(event, "getPointerId", int_arg, i); /* not entirely sure we need to report move events for non primary touches here * but examples I've see say that the ACTION_[POINTER_][UP|DOWN] * report all touches and they can change between the last MOVE * and the UP|DOWN event */ if(id == pointer_id) { nativeOnTouch(id, action, x, y, primary); } else { nativeOnTouch(id, ALLEGRO_EVENT_TOUCH_MOVE, x, y, primary); } } } else { nativeOnTouch(pointer_id, action, event.getX(), event.getY(), primary); } //Log.d("AllegroSurface", "onTouch end"); return true; } } /* vim: set sts=3 sw=3 et: */
false
true
public boolean onTouch(View v, MotionEvent event) { //Log.d("AllegroSurface", "onTouch"); int action = 0; int pointer_id = 0; Class[] no_args = new Class[0]; Class[] int_arg = new Class[1]; int_arg[0] = int.class; if(methodExists(event, "getActionMasked")) { // android-8 / 2.2.x action = this.<Integer>callMethod(event, "getActionMasked", no_args); int ptr_idx = this.<Integer>callMethod(event, "getActionIndex", no_args); pointer_id = this.<Integer>callMethod(event, "getPointerId", int_arg, ptr_idx); } else { int mask = 0xff; int raw_action = event.getAction(); if(fieldExists(event, "ACTION_MASK")) { // android-5 / 2.0 mask = this.<Integer>getField(event, "ACTION_MASK"); action = raw_action & mask; int ptr_id_mask = this.<Integer>getField(event, "ACTION_POINTER_ID_MASK"); int ptr_id_shift = this.<Integer>getField(event, "ACTION_POINTER_ID_SHIFT"); pointer_id = (raw_action & ptr_id_mask) >> ptr_id_shift; } else { // android-4 / 1.6 /* no ACTION_MASK? no multi touch, no pointer_id, */ action = raw_action; } } boolean primary = false; if(action == MotionEvent.ACTION_DOWN) { primary = true; action = ALLEGRO_EVENT_TOUCH_BEGIN; } else if(action == MotionEvent.ACTION_UP) { primary = true; action = ALLEGRO_EVENT_TOUCH_END; } else if(action == MotionEvent.ACTION_MOVE) { action = ALLEGRO_EVENT_TOUCH_MOVE; } else if(action == MotionEvent.ACTION_CANCEL) { action = ALLEGRO_EVENT_TOUCH_CANCEL; } // android-5 / 2.0 else if(fieldExists(event, "ACTION_POINTER_DOWN") && action == this.<Integer>getField(event, "ACTION_POINTER_DOWN")) { action = ALLEGRO_EVENT_TOUCH_BEGIN; } else if(fieldExists(event, "ACTION_POINTER_UP") && action == this.<Integer>getField(event, "ACTION_POINTER_UP")) { action = ALLEGRO_EVENT_TOUCH_END; } else { Log.v("AllegroSurface", "unknown MotionEvent type: " + action); Log.d("AllegroSurface", "onTouch endf"); return false; } if(methodExists(event, "getPointerCount")) { // android-5 / 2.0 int pointer_count = this.<Integer>callMethod(event, "getPointerCount", no_args); for(int i = 0; i < pointer_count; i++) { float x = this.<Float>callMethod(event, "getX", int_arg, i); float y = this.<Float>callMethod(event, "getY", int_arg, i); int id = this.<Integer>callMethod(event, "getPointerId", int_arg, i); /* not entirely sure we need to report move events for non primary touches here * but examples I've see say that the ACTION_[POINTER_][UP|DOWN] * report all touches and they can change between the last MOVE * and the UP|DOWN event */ if(id == pointer_id) { nativeOnTouch(id, action, x, y, primary); } else { nativeOnTouch(id, ALLEGRO_EVENT_TOUCH_MOVE, x, y, primary); } } } else { nativeOnTouch(pointer_id, action, event.getX(), event.getY(), primary); } //Log.d("AllegroSurface", "onTouch end"); return true; }
public boolean onTouch(View v, MotionEvent event) { //Log.d("AllegroSurface", "onTouch"); int action = 0; int pointer_id = 0; Class[] no_args = new Class[0]; Class[] int_arg = new Class[1]; int_arg[0] = int.class; if(methodExists(event, "getActionMasked")) { // android-8 / 2.2.x action = this.<Integer>callMethod(event, "getActionMasked", no_args); int ptr_idx = this.<Integer>callMethod(event, "getActionIndex", no_args); pointer_id = this.<Integer>callMethod(event, "getPointerId", int_arg, ptr_idx); } else { int raw_action = event.getAction(); if(fieldExists(event, "ACTION_MASK")) { // android-5 / 2.0 int mask = this.<Integer>getField(event, "ACTION_MASK"); action = raw_action & mask; int ptr_id_mask = this.<Integer>getField(event, "ACTION_POINTER_ID_MASK"); int ptr_id_shift = this.<Integer>getField(event, "ACTION_POINTER_ID_SHIFT"); pointer_id = event.getPointerId((raw_action & ptr_id_mask) >> ptr_id_shift); } else { // android-4 / 1.6 /* no ACTION_MASK? no multi touch, no pointer_id, */ action = raw_action; } } boolean primary = false; if(action == MotionEvent.ACTION_DOWN) { primary = true; action = ALLEGRO_EVENT_TOUCH_BEGIN; } else if(action == MotionEvent.ACTION_UP) { primary = true; action = ALLEGRO_EVENT_TOUCH_END; } else if(action == MotionEvent.ACTION_MOVE) { action = ALLEGRO_EVENT_TOUCH_MOVE; } else if(action == MotionEvent.ACTION_CANCEL) { action = ALLEGRO_EVENT_TOUCH_CANCEL; } // android-5 / 2.0 else if(fieldExists(event, "ACTION_POINTER_DOWN") && action == this.<Integer>getField(event, "ACTION_POINTER_DOWN")) { action = ALLEGRO_EVENT_TOUCH_BEGIN; } else if(fieldExists(event, "ACTION_POINTER_UP") && action == this.<Integer>getField(event, "ACTION_POINTER_UP")) { action = ALLEGRO_EVENT_TOUCH_END; } else { Log.v("AllegroSurface", "unknown MotionEvent type: " + action); Log.d("AllegroSurface", "onTouch endf"); return false; } if(methodExists(event, "getPointerCount")) { // android-5 / 2.0 int pointer_count = this.<Integer>callMethod(event, "getPointerCount", no_args); for(int i = 0; i < pointer_count; i++) { float x = this.<Float>callMethod(event, "getX", int_arg, i); float y = this.<Float>callMethod(event, "getY", int_arg, i); int id = this.<Integer>callMethod(event, "getPointerId", int_arg, i); /* not entirely sure we need to report move events for non primary touches here * but examples I've see say that the ACTION_[POINTER_][UP|DOWN] * report all touches and they can change between the last MOVE * and the UP|DOWN event */ if(id == pointer_id) { nativeOnTouch(id, action, x, y, primary); } else { nativeOnTouch(id, ALLEGRO_EVENT_TOUCH_MOVE, x, y, primary); } } } else { nativeOnTouch(pointer_id, action, event.getX(), event.getY(), primary); } //Log.d("AllegroSurface", "onTouch end"); return true; }
diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/MetadataRepositoryElement.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/MetadataRepositoryElement.java index f047aaff4..d631e4d9f 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/MetadataRepositoryElement.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/MetadataRepositoryElement.java @@ -1,253 +1,252 @@ /******************************************************************************* * Copyright (c) 2007, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.equinox.internal.p2.ui.model; import java.net.URI; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; import org.eclipse.equinox.internal.p2.metadata.repository.MetadataRepositoryManager; import org.eclipse.equinox.internal.p2.ui.ProvUIActivator; import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; import org.eclipse.equinox.internal.provisional.p2.query.IQueryable; import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; import org.eclipse.equinox.internal.provisional.p2.ui.ProvUIImages; import org.eclipse.equinox.internal.provisional.p2.ui.model.IRepositoryElement; import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningUtil; import org.eclipse.equinox.internal.provisional.p2.ui.policy.*; import org.eclipse.osgi.util.NLS; import org.eclipse.ui.statushandlers.StatusManager; /** * Element wrapper class for a metadata repository that gets its * contents in a deferred manner. A metadata repository can be the root * (input) of a viewer, when the view is filtered by repo, or a child of * an input, when the view is showing many repos. * * @since 3.4 */ public class MetadataRepositoryElement extends RootElement implements IRepositoryElement { URI location; boolean isEnabled; boolean alreadyReportedNotFound = false; String name; public MetadataRepositoryElement(Object parent, URI location, boolean isEnabled) { this(parent, null, null, location, isEnabled); } public MetadataRepositoryElement(IUViewQueryContext queryContext, Policy policy, URI location, boolean isEnabled) { super(null, queryContext, policy); this.location = location; this.isEnabled = isEnabled; } private MetadataRepositoryElement(Object parent, IUViewQueryContext queryContext, Policy policy, URI location, boolean isEnabled) { super(parent, queryContext, policy); this.location = location; this.isEnabled = isEnabled; } public Object getAdapter(Class adapter) { if (adapter == IMetadataRepository.class) return getQueryable(); if (adapter == IRepository.class) return getQueryable(); return super.getAdapter(adapter); } protected String getImageId(Object obj) { return ProvUIImages.IMG_METADATA_REPOSITORY; } protected int getDefaultQueryType() { return QueryProvider.AVAILABLE_IUS; } public String getLabel(Object o) { String n = getName(); if (n != null && n.length() > 0) { return n; } return URIUtil.toUnencodedString(getLocation()); } /* * overridden to lazily fetch repository * (non-Javadoc) * @see org.eclipse.equinox.internal.provisional.p2.ui.query.QueriedElement#getQueryable() */ public IQueryable getQueryable() { if (queryable == null) return getMetadataRepository(new NullProgressMonitor()); return queryable; } public IRepository getRepository(IProgressMonitor monitor) { return getMetadataRepository(monitor); } private IMetadataRepository getMetadataRepository(IProgressMonitor monitor) { if (queryable == null) try { queryable = ProvisioningUtil.loadMetadataRepository(location, monitor); } catch (ProvisionException e) { // If repository could not be found, report to the user, but only once. // If the user refreshes the repositories, new elements will be created and // then a failure would be reported again on the next try. switch (e.getStatus().getCode()) { - case ProvisionException.REPOSITORY_FAILED_READ : - case ProvisionException.REPOSITORY_FAILED_AUTHENTICATION : case ProvisionException.REPOSITORY_INVALID_LOCATION : case ProvisionException.REPOSITORY_NOT_FOUND : if (!alreadyReportedNotFound) { // report the status, not the exception, to the user because we // do not want to show them stack trace and exception detail. ProvUI.reportNotFoundStatus(location, e.getStatus(), StatusManager.SHOW); alreadyReportedNotFound = true; } break; default : - // handle other exceptions the normal way + // handle other exceptions the normal way. Silently log as we expect this to get reported + // at a higher level. handleException(e, NLS.bind(ProvUIMessages.MetadataRepositoryElement_RepositoryLoadError, location)); } } catch (OperationCanceledException e) { // Nothing to report } return (IMetadataRepository) queryable; } /* * overridden to check whether url is specified rather * than loading the repo via getQueryable() * (non-Javadoc) * @see org.eclipse.equinox.internal.provisional.p2.ui.query.QueriedElement#knowsQueryable() */ public boolean knowsQueryable() { return location != null; } /* (non-Javadoc) * @see org.eclipse.equinox.internal.provisional.p2.ui.model.RepositoryElement#getURL() */ public URI getLocation() { return location; } /* * (non-Javadoc) * @see org.eclipse.equinox.internal.provisional.p2.ui.model.RepositoryElement#getName() */ public String getName() { if (name == null) { try { name = ProvisioningUtil.getMetadataRepositoryProperty(location, IRepository.PROP_NICKNAME); if (name == null) name = ProvisioningUtil.getMetadataRepositoryProperty(location, IRepository.PROP_NAME); if (name == null) name = ""; //$NON-NLS-1$ } catch (ProvisionException e) { name = ""; //$NON-NLS-1$ } } return name; } public void setNickname(String name) { this.name = name; } public void setLocation(URI location) { this.location = location; setQueryable(null); } /* * (non-Javadoc) * @see org.eclipse.equinox.internal.provisional.p2.ui.model.RepositoryElement#getDescription() */ public String getDescription() { if (alreadyReportedNotFound || ProvUI.hasNotFoundStatusBeenReported(location)) return ProvUIMessages.MetadataRepositoryElement_NotFound; try { String description = ProvisioningUtil.getMetadataRepositoryProperty(location, IRepository.PROP_DESCRIPTION); if (description == null) return ""; //$NON-NLS-1$ return description; } catch (ProvisionException e) { return ""; //$NON-NLS-1$ } } /* (non-Javadoc) * @see org.eclipse.equinox.internal.provisional.p2.ui.model.RepositoryElement#isEnabled() */ public boolean isEnabled() { return isEnabled; } /* (non-Javadoc) * @see org.eclipse.equinox.internal.provisional.p2.ui.model.IRepositoryElement#setEnabled(boolean) */ public void setEnabled(boolean enabled) { isEnabled = enabled; } /* * Overridden to check whether a repository instance has already been loaded. * This is necessary to prevent background loading of an already loaded repository * by the DeferredTreeContentManager, which will add redundant children to the * viewer. * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=229069 * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=226343 * (non-Javadoc) * @see org.eclipse.equinox.internal.provisional.p2.ui.query.QueriedElement#hasQueryable() */ public boolean hasQueryable() { if (queryable != null) return true; if (location == null) return false; IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IMetadataRepositoryManager.class.getName()); if (manager == null || !(manager instanceof MetadataRepositoryManager)) return false; IMetadataRepository repo = ((MetadataRepositoryManager) manager).getRepository(location); if (repo == null) return false; queryable = repo; return true; } public Policy getPolicy() { Object parent = getParent(this); if (parent == null) return super.getPolicy(); if (parent instanceof QueriedElement) return ((QueriedElement) parent).getPolicy(); return Policy.getDefault(); } public String toString() { StringBuffer result = new StringBuffer(); result.append("Metadata Repository Element - "); //$NON-NLS-1$ result.append(URIUtil.toUnencodedString(location)); if (hasQueryable()) result.append(" (loaded)"); //$NON-NLS-1$ else result.append(" (not loaded)"); //$NON-NLS-1$ return result.toString(); } }
false
true
private IMetadataRepository getMetadataRepository(IProgressMonitor monitor) { if (queryable == null) try { queryable = ProvisioningUtil.loadMetadataRepository(location, monitor); } catch (ProvisionException e) { // If repository could not be found, report to the user, but only once. // If the user refreshes the repositories, new elements will be created and // then a failure would be reported again on the next try. switch (e.getStatus().getCode()) { case ProvisionException.REPOSITORY_FAILED_READ : case ProvisionException.REPOSITORY_FAILED_AUTHENTICATION : case ProvisionException.REPOSITORY_INVALID_LOCATION : case ProvisionException.REPOSITORY_NOT_FOUND : if (!alreadyReportedNotFound) { // report the status, not the exception, to the user because we // do not want to show them stack trace and exception detail. ProvUI.reportNotFoundStatus(location, e.getStatus(), StatusManager.SHOW); alreadyReportedNotFound = true; } break; default : // handle other exceptions the normal way handleException(e, NLS.bind(ProvUIMessages.MetadataRepositoryElement_RepositoryLoadError, location)); } } catch (OperationCanceledException e) { // Nothing to report } return (IMetadataRepository) queryable; }
private IMetadataRepository getMetadataRepository(IProgressMonitor monitor) { if (queryable == null) try { queryable = ProvisioningUtil.loadMetadataRepository(location, monitor); } catch (ProvisionException e) { // If repository could not be found, report to the user, but only once. // If the user refreshes the repositories, new elements will be created and // then a failure would be reported again on the next try. switch (e.getStatus().getCode()) { case ProvisionException.REPOSITORY_INVALID_LOCATION : case ProvisionException.REPOSITORY_NOT_FOUND : if (!alreadyReportedNotFound) { // report the status, not the exception, to the user because we // do not want to show them stack trace and exception detail. ProvUI.reportNotFoundStatus(location, e.getStatus(), StatusManager.SHOW); alreadyReportedNotFound = true; } break; default : // handle other exceptions the normal way. Silently log as we expect this to get reported // at a higher level. handleException(e, NLS.bind(ProvUIMessages.MetadataRepositoryElement_RepositoryLoadError, location)); } } catch (OperationCanceledException e) { // Nothing to report } return (IMetadataRepository) queryable; }
diff --git a/plugins/src/org/stripesstuff/plugin/security/AllowedTag.java b/plugins/src/org/stripesstuff/plugin/security/AllowedTag.java index 49b7897..c9e7ef3 100644 --- a/plugins/src/org/stripesstuff/plugin/security/AllowedTag.java +++ b/plugins/src/org/stripesstuff/plugin/security/AllowedTag.java @@ -1,223 +1,226 @@ package org.stripesstuff.plugin.security; import java.lang.reflect.Method; import javax.servlet.jsp.JspException; import javax.servlet.jsp.PageContext; import javax.servlet.jsp.tagext.TagSupport; import net.sourceforge.stripes.action.ActionBean; import net.sourceforge.stripes.controller.StripesConstants; import net.sourceforge.stripes.controller.StripesFilter; import net.sourceforge.stripes.exception.StripesJspException; import net.sourceforge.stripes.exception.StripesServletException; import net.sourceforge.stripes.util.Log; /** * JSP tag to secure part of a JSP file. The body is shown (or not) based on whether performing an event on a supplied * action bean is allowed. This secures any event on any action bean, while leaving the security decisions to the * security manager. * * @author <a href="mailto:[email protected]">Oscar Westra van Holthe - Kind</a> * @version $Id:$ */ public class AllowedTag extends TagSupport { private static final long serialVersionUID = 1L; /** * Logger for this class. */ private static final Log LOG = Log.getInstance(AllowedTag.class); /** * The name of the bean that is the action bean to secure. If null, the current action bean of the page is used. */ private String bean; /** * The event to secure on the action bean. If null, the default event is assumed. */ private String event; /** * Flag to negate the judgement of the security manager: the body of the tag is shown if the event is not allowed. * * @deprecated Use {@link NotAllowedTag} instead. */ @Deprecated private boolean negate; /** * Create the secure tag. */ public AllowedTag() { initValues(); } /** * Release the state of this tag. */ @Override public void release() { super.release(); initValues(); } /** * Initialize the values to (re)use this tag. */ private void initValues() { bean = null; event = null; //noinspection deprecation negate = false; } /** * Determine if the body should be evaluated or not. * * @return EVAL_BODY_INCLUDE if the body should be included, or SKIP_BODY * @throws JspException when the tag cannot (decide if to) write the body content */ @Override public int doStartTag() throws JspException { // Retrieve the action bean and event handler to secure. if (bean == null) { bean = StripesConstants.REQ_ATTR_ACTION_BEAN; } - ActionBean actionBean = (ActionBean)pageContext.getRequest().getAttribute(bean); + ActionBean actionBean = (ActionBean)pageContext.getAttribute(bean); + if (actionBean == null) { + actionBean = (ActionBean)pageContext.getRequest().getAttribute(bean); + } LOG.debug(String.format("Determining access for action bean \"%s\": %s", bean, actionBean)); Method handler; try { if (event == null) { handler = StripesFilter.getConfiguration().getActionResolver().getDefaultHandler(actionBean.getClass()); LOG.debug(String.format("Found a handler for the default event: %s", handler)); } else { handler = StripesFilter.getConfiguration().getActionResolver().getHandler(actionBean.getClass(), event); LOG.debug(String.format("Found a handler for event \"%s\": %s", event, handler)); } } catch (StripesServletException e) { throw new StripesJspException("Failed to get the handler for the event.", e); } // Get the judgement of the security manager. SecurityManager securityManager = (SecurityManager)pageContext.getAttribute(SecurityInterceptor.SECURITY_MANAGER, PageContext.REQUEST_SCOPE); boolean haveSecurityManager = securityManager != null; boolean eventAllowed; if (haveSecurityManager) { LOG.debug(String.format("Determining access using this security manager: %s", securityManager)); eventAllowed = Boolean.TRUE.equals(securityManager.getAccessAllowed(actionBean, handler)); } else { LOG.debug("There is no security manager; allowing access"); eventAllowed = true; } // Show the tag's content (or not) based on this //noinspection deprecation if (haveSecurityManager && negate) { LOG.debug("This tag negates the decision of the security manager."); eventAllowed = !eventAllowed; } LOG.debug(String.format("Access is %s.", eventAllowed ? "allowed" : "denied")); return eventAllowed ? EVAL_BODY_AGAIN : SKIP_BODY; } /** * Getter for the field {@link #bean}. * * @return the value of the field * @see #bean */ public String getBean() { return bean; } /** * Setter for the field {@link #bean}. * * @param bean the new value for the field * @see #bean */ public void setBean(String bean) { this.bean = bean; } /** * Getter for the field {@link #event}. * * @return the value of the field * @see #event */ public String getEvent() { return event; } /** * Setter for the field {@link #event}. * * @param event the new value for the field * @see #event */ public void setEvent(String event) { this.event = event; } /** * Getter for the field {@link #negate}. * * @return the value of the field * @see #negate */ public boolean isNegate() { //noinspection deprecation return negate; } /** * Setter for the field {@link #negate}. * * @param negate the new value for the field * @see #negate */ public void setNegate(boolean negate) { //noinspection deprecation this.negate = negate; } }
true
true
public int doStartTag() throws JspException { // Retrieve the action bean and event handler to secure. if (bean == null) { bean = StripesConstants.REQ_ATTR_ACTION_BEAN; } ActionBean actionBean = (ActionBean)pageContext.getRequest().getAttribute(bean); LOG.debug(String.format("Determining access for action bean \"%s\": %s", bean, actionBean)); Method handler; try { if (event == null) { handler = StripesFilter.getConfiguration().getActionResolver().getDefaultHandler(actionBean.getClass()); LOG.debug(String.format("Found a handler for the default event: %s", handler)); } else { handler = StripesFilter.getConfiguration().getActionResolver().getHandler(actionBean.getClass(), event); LOG.debug(String.format("Found a handler for event \"%s\": %s", event, handler)); } } catch (StripesServletException e) { throw new StripesJspException("Failed to get the handler for the event.", e); } // Get the judgement of the security manager. SecurityManager securityManager = (SecurityManager)pageContext.getAttribute(SecurityInterceptor.SECURITY_MANAGER, PageContext.REQUEST_SCOPE); boolean haveSecurityManager = securityManager != null; boolean eventAllowed; if (haveSecurityManager) { LOG.debug(String.format("Determining access using this security manager: %s", securityManager)); eventAllowed = Boolean.TRUE.equals(securityManager.getAccessAllowed(actionBean, handler)); } else { LOG.debug("There is no security manager; allowing access"); eventAllowed = true; } // Show the tag's content (or not) based on this //noinspection deprecation if (haveSecurityManager && negate) { LOG.debug("This tag negates the decision of the security manager."); eventAllowed = !eventAllowed; } LOG.debug(String.format("Access is %s.", eventAllowed ? "allowed" : "denied")); return eventAllowed ? EVAL_BODY_AGAIN : SKIP_BODY; }
public int doStartTag() throws JspException { // Retrieve the action bean and event handler to secure. if (bean == null) { bean = StripesConstants.REQ_ATTR_ACTION_BEAN; } ActionBean actionBean = (ActionBean)pageContext.getAttribute(bean); if (actionBean == null) { actionBean = (ActionBean)pageContext.getRequest().getAttribute(bean); } LOG.debug(String.format("Determining access for action bean \"%s\": %s", bean, actionBean)); Method handler; try { if (event == null) { handler = StripesFilter.getConfiguration().getActionResolver().getDefaultHandler(actionBean.getClass()); LOG.debug(String.format("Found a handler for the default event: %s", handler)); } else { handler = StripesFilter.getConfiguration().getActionResolver().getHandler(actionBean.getClass(), event); LOG.debug(String.format("Found a handler for event \"%s\": %s", event, handler)); } } catch (StripesServletException e) { throw new StripesJspException("Failed to get the handler for the event.", e); } // Get the judgement of the security manager. SecurityManager securityManager = (SecurityManager)pageContext.getAttribute(SecurityInterceptor.SECURITY_MANAGER, PageContext.REQUEST_SCOPE); boolean haveSecurityManager = securityManager != null; boolean eventAllowed; if (haveSecurityManager) { LOG.debug(String.format("Determining access using this security manager: %s", securityManager)); eventAllowed = Boolean.TRUE.equals(securityManager.getAccessAllowed(actionBean, handler)); } else { LOG.debug("There is no security manager; allowing access"); eventAllowed = true; } // Show the tag's content (or not) based on this //noinspection deprecation if (haveSecurityManager && negate) { LOG.debug("This tag negates the decision of the security manager."); eventAllowed = !eventAllowed; } LOG.debug(String.format("Access is %s.", eventAllowed ? "allowed" : "denied")); return eventAllowed ? EVAL_BODY_AGAIN : SKIP_BODY; }
diff --git a/src/main/java/org/jbei/ice/client/common/table/cell/HasEntryPartIDCell.java b/src/main/java/org/jbei/ice/client/common/table/cell/HasEntryPartIDCell.java index dbde3a61c..f2ff6d0f9 100644 --- a/src/main/java/org/jbei/ice/client/common/table/cell/HasEntryPartIDCell.java +++ b/src/main/java/org/jbei/ice/client/common/table/cell/HasEntryPartIDCell.java @@ -1,156 +1,156 @@ package org.jbei.ice.client.common.table.cell; import com.google.gwt.cell.client.AbstractCell; import com.google.gwt.cell.client.ValueUpdater; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.NativeEvent; import com.google.gwt.event.shared.GwtEvent; import com.google.gwt.event.shared.HandlerManager; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.safehtml.shared.SafeHtmlBuilder; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.PopupPanel; import com.google.gwt.user.client.ui.Widget; import org.jbei.ice.client.Callback; import org.jbei.ice.client.collection.menu.IHasEntryHandlers; import org.jbei.ice.client.collection.presenter.EntryContext; import org.jbei.ice.client.common.TipViewContentFactory; import org.jbei.ice.client.event.EntryViewEvent; import org.jbei.ice.shared.dto.HasEntryInfo; /** * @author Hector Plahar */ public class HasEntryPartIDCell<T extends HasEntryInfo> extends AbstractCell<T> implements IHasEntryHandlers { private static PopupPanel popup = new PopupPanel(true); ; private static final String MOUSEOVER_EVENT_NAME = "mouseover"; private static final String MOUSEOUT_EVENT_NAME = "mouseout"; private static final String MOUSE_CLICK = "click"; private HandlerManager handlerManager; private final EntryContext.Type mode; private boolean hidden = false; public HasEntryPartIDCell(EntryContext.Type mode) { super(MOUSEOVER_EVENT_NAME, MOUSEOUT_EVENT_NAME, MOUSE_CLICK); this.mode = mode; popup.setStyleName("add_to_popup"); } @Override public void render(Context context, T view, SafeHtmlBuilder sb) { if (view == null || view.getEntryInfo().getPartId() == null) return; sb.appendHtmlConstant("<a class=\"cell_mouseover\">" + view.getEntryInfo().getPartId() + "</a>"); } @Override public void onBrowserEvent(Context context, Element parent, T value, NativeEvent event, ValueUpdater<T> valueUpdater) { super.onBrowserEvent(context, parent, value, event, valueUpdater); final String eventType = event.getType(); if (MOUSEOVER_EVENT_NAME.equalsIgnoreCase(eventType)) { if (withinBounds(parent, event)) onMouseOver(parent, event, value); else onMouseOut(parent); } else if (MOUSEOUT_EVENT_NAME.equalsIgnoreCase(eventType)) { onMouseOut(parent); } else if (MOUSE_CLICK.equalsIgnoreCase(eventType)) { if (withinBounds(parent, event)) onMouseClick(value.getEntryInfo().getId()); } } protected void onMouseClick(long recordId) { hidden = true; popup.hide(); dispatchEntryViewEvent(recordId); } protected void dispatchEntryViewEvent(final long recordId) { fireEvent(new GwtEvent<EntryViewEvent.EntryViewEventHandler>() { @Override public Type<EntryViewEvent.EntryViewEventHandler> getAssociatedType() { return EntryViewEvent.getType(); } @Override protected void dispatch(EntryViewEvent.EntryViewEventHandler handler) { handler.onEntryView(new EntryViewEvent(recordId, mode)); } }); } protected void onMouseOut(Element parent) { hidden = true; popup.hide(); } protected boolean withinBounds(Element parent, NativeEvent event) { Element cellElement = event.getEventTarget().cast(); Element element = cellElement.getFirstChildElement(); if (element == null) return true; return false; } protected void onMouseOver(Element parent, NativeEvent event, HasEntryInfo value) { hidden = false; final int x = event.getClientX() + 30 + Window.getScrollLeft(); final int y = event.getClientY() + Window.getScrollTop(); // TODO : set popup loading widget TipViewContentFactory.getContents(value.getEntryInfo(), new Callback<Widget>() { @Override - public void onSucess(Widget contents) { + public void onSuccess(Widget contents) { if (hidden) return; popup.setWidget(contents); // 450 is expected height of popup. adjust accordingly or the bottom will be hidden int bounds = 450 + y; int yPos = y; if (bounds > Window.getClientHeight()) { // move it up; yPos -= (bounds - Window.getClientHeight()); if (yPos < 0) yPos = 0; } popup.setPopupPosition(x, yPos); popup.show(); } @Override public void onFailure() { // doing nothing seems fine. no tooltip will be displayed } }); } @Override public HandlerRegistration addEntryHandler(EntryViewEvent.EntryViewEventHandler handler) { if (handlerManager == null) handlerManager = new HandlerManager(this); return handlerManager.addHandler(EntryViewEvent.getType(), handler); } @Override public void fireEvent(GwtEvent<?> event) { if (handlerManager != null) handlerManager.fireEvent(event); } }
true
true
protected void onMouseOver(Element parent, NativeEvent event, HasEntryInfo value) { hidden = false; final int x = event.getClientX() + 30 + Window.getScrollLeft(); final int y = event.getClientY() + Window.getScrollTop(); // TODO : set popup loading widget TipViewContentFactory.getContents(value.getEntryInfo(), new Callback<Widget>() { @Override public void onSucess(Widget contents) { if (hidden) return; popup.setWidget(contents); // 450 is expected height of popup. adjust accordingly or the bottom will be hidden int bounds = 450 + y; int yPos = y; if (bounds > Window.getClientHeight()) { // move it up; yPos -= (bounds - Window.getClientHeight()); if (yPos < 0) yPos = 0; } popup.setPopupPosition(x, yPos); popup.show(); } @Override public void onFailure() { // doing nothing seems fine. no tooltip will be displayed } }); }
protected void onMouseOver(Element parent, NativeEvent event, HasEntryInfo value) { hidden = false; final int x = event.getClientX() + 30 + Window.getScrollLeft(); final int y = event.getClientY() + Window.getScrollTop(); // TODO : set popup loading widget TipViewContentFactory.getContents(value.getEntryInfo(), new Callback<Widget>() { @Override public void onSuccess(Widget contents) { if (hidden) return; popup.setWidget(contents); // 450 is expected height of popup. adjust accordingly or the bottom will be hidden int bounds = 450 + y; int yPos = y; if (bounds > Window.getClientHeight()) { // move it up; yPos -= (bounds - Window.getClientHeight()); if (yPos < 0) yPos = 0; } popup.setPopupPosition(x, yPos); popup.show(); } @Override public void onFailure() { // doing nothing seems fine. no tooltip will be displayed } }); }
diff --git a/MineteryRPG/src/com/bricou/mineteryarpg/PluginConfigFile.java b/MineteryRPG/src/com/bricou/mineteryarpg/PluginConfigFile.java index fe6e015..eebfa9b 100644 --- a/MineteryRPG/src/com/bricou/mineteryarpg/PluginConfigFile.java +++ b/MineteryRPG/src/com/bricou/mineteryarpg/PluginConfigFile.java @@ -1,72 +1,72 @@ package com.bricou.mineteryarpg; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.HashMap; /** * Classe de chargement et d'initialisation du param�trage du plugin * @author Bricou & Dr.Jack * */ public class PluginConfigFile { /** * * @param file */ public HashMap<String,String> initializeProperties(File configFile) { try { configFile.createNewFile(); BufferedWriter out = new BufferedWriter(new FileWriter(configFile)); out.write("#Fichier de param�trage autog�n�r�"); out.newLine(); out.write("#Principe : param�tre:valeur"); out.newLine(); out.write("LevelMax:100"); out.close(); } catch (Exception e) { e.printStackTrace(); } return null; } /** * * @param file */ public HashMap<String,String> loadProperties(File configFile) { + HashMap<String,String> configMap = new HashMap<String,String>(); try { // Lecture en boucle sur le fichier de param�trage du plugin - HashMap<String,String> configMap = new HashMap<String,String>(); BufferedReader reader = new BufferedReader(new FileReader(configFile)); String line = null; while ((line = reader.readLine()) != null) { // Analyse de chaque enregistrement et stockage dans la hashmap if (!line.contains("#") && (!line.equalsIgnoreCase(""))) { String[] lines = line.split(":"); configMap.put(lines[0], lines[1]); } } reader.close(); } catch (Exception e) { e.printStackTrace(); } - return null; + return configMap; } }
false
true
public HashMap<String,String> loadProperties(File configFile) { try { // Lecture en boucle sur le fichier de param�trage du plugin HashMap<String,String> configMap = new HashMap<String,String>(); BufferedReader reader = new BufferedReader(new FileReader(configFile)); String line = null; while ((line = reader.readLine()) != null) { // Analyse de chaque enregistrement et stockage dans la hashmap if (!line.contains("#") && (!line.equalsIgnoreCase(""))) { String[] lines = line.split(":"); configMap.put(lines[0], lines[1]); } } reader.close(); } catch (Exception e) { e.printStackTrace(); } return null; }
public HashMap<String,String> loadProperties(File configFile) { HashMap<String,String> configMap = new HashMap<String,String>(); try { // Lecture en boucle sur le fichier de param�trage du plugin BufferedReader reader = new BufferedReader(new FileReader(configFile)); String line = null; while ((line = reader.readLine()) != null) { // Analyse de chaque enregistrement et stockage dans la hashmap if (!line.contains("#") && (!line.equalsIgnoreCase(""))) { String[] lines = line.split(":"); configMap.put(lines[0], lines[1]); } } reader.close(); } catch (Exception e) { e.printStackTrace(); } return configMap; }
diff --git a/src/java/com/idega/mobile/WebserviceTest.java b/src/java/com/idega/mobile/WebserviceTest.java index b70c9f1..5eac20e 100644 --- a/src/java/com/idega/mobile/WebserviceTest.java +++ b/src/java/com/idega/mobile/WebserviceTest.java @@ -1,68 +1,68 @@ package com.idega.mobile; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import net.x_rd.ee.municipality.producer.CaseListResponseCaseListEntry; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; import com.google.gson.Gson; import com.idega.core.business.DefaultSpringBean; import com.idega.util.ArrayUtil; import com.idega.util.expression.ELUtil; import com.idega.xroad.webservices.client.CaseDataProvider; /** * Description * User: Simon Sönnby * Date: 2012-03-14 * Time: 09:33 */ @Path("/test") @Service @Scope(BeanDefinition.SCOPE_PROTOTYPE) public class WebserviceTest extends DefaultSpringBean { @Autowired private CaseDataProvider caseDataProvider; CaseDataProvider getCaseDataProvider() { if (caseDataProvider == null) ELUtil.getInstance().autowire(this); return caseDataProvider; } @GET @Path("/get") @Produces(MediaType.APPLICATION_JSON) public String getTestJSON() { return "{\"Test\":\"hello\"}"; } @GET @Path("/cases") @Produces(MediaType.APPLICATION_JSON) public String getCasesList() { + Gson gson = new Gson(); CaseListResponseCaseListEntry[] cases = getCaseDataProvider().getCaseList(); if (ArrayUtil.isEmpty(cases)) { getLogger().warning("No cases found"); - return null; + return gson.toJson("Error"); } - Gson gson = new Gson(); return gson.toJson(cases); } // @POST // @Path("/post") // @Consumes(MediaType.APPLICATION_JSON) // public Response createTestInJSON(String test) { // return Response.status(201).entity("Success").build(); // } }
false
true
public String getCasesList() { CaseListResponseCaseListEntry[] cases = getCaseDataProvider().getCaseList(); if (ArrayUtil.isEmpty(cases)) { getLogger().warning("No cases found"); return null; } Gson gson = new Gson(); return gson.toJson(cases); }
public String getCasesList() { Gson gson = new Gson(); CaseListResponseCaseListEntry[] cases = getCaseDataProvider().getCaseList(); if (ArrayUtil.isEmpty(cases)) { getLogger().warning("No cases found"); return gson.toJson("Error"); } return gson.toJson(cases); }
diff --git a/export-impl/src/main/java/org/clueminer/export/impl/CsvExportRunner.java b/export-impl/src/main/java/org/clueminer/export/impl/CsvExportRunner.java index 9d176ab9c..29e41646a 100644 --- a/export-impl/src/main/java/org/clueminer/export/impl/CsvExportRunner.java +++ b/export-impl/src/main/java/org/clueminer/export/impl/CsvExportRunner.java @@ -1,90 +1,90 @@ package org.clueminer.export.impl; import au.com.bytecode.opencsv.CSVWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.prefs.Preferences; import org.clueminer.clustering.api.Cluster; import org.clueminer.clustering.api.Clustering; import org.clueminer.clustering.api.HierarchicalResult; import org.clueminer.clustering.gui.ClusterAnalysis; import org.clueminer.dataset.api.Instance; import org.openide.util.Exceptions; /** * * @author Tomas Barton */ public class CsvExportRunner implements Runnable { private final File file; private final ClusterAnalysis analysis; private final Preferences pref; public CsvExportRunner(File file, ClusterAnalysis analysis, Preferences pref) { this.file = file; this.analysis = analysis; this.pref = pref; } @Override public void run() { try { CSVWriter writer = new CSVWriter(new FileWriter(file)); String[] line, tmp; int size; Instance raw; HierarchicalResult result = analysis.getResult(); if (result != null) { Clustering<Cluster> clust = result.getClustering(); for (Cluster<? extends Instance> c : clust) { for (Instance inst : c) { line = inst.getName().split(","); size = line.length + 1; int dataSize = 0; String[] data = null; if (pref.getBoolean("raw_data", false)) { raw = inst; while (raw.getAncestor() != null) { raw = raw.getAncestor(); } data = raw.toStringArray(); dataSize = data.length; size += dataSize; } int preprocessSize = 0; String[] prepro = null; if (pref.getBoolean("preprocess_data", false)) { prepro = inst.toStringArray(); preprocessSize = prepro.length; size += preprocessSize; } //append cluster label tmp = new String[size]; System.arraycopy(line, 0, tmp, 0, line.length); if (dataSize > 0) { - System.arraycopy(data, 0, tmp, line.length + 1, dataSize); + System.arraycopy(data, 0, tmp, line.length, dataSize); } if (preprocessSize > 0) { - System.arraycopy(prepro, 0, tmp, line.length + dataSize + 1, preprocessSize); + System.arraycopy(prepro, 0, tmp, line.length + dataSize, preprocessSize); } line = tmp; line[size - 1] = c.getName(); writer.writeNext(line); } } } else { throw new RuntimeException("no clustering result. did you run clustering?"); } } catch (IOException ex) { Exceptions.printStackTrace(ex); } } }
false
true
public void run() { try { CSVWriter writer = new CSVWriter(new FileWriter(file)); String[] line, tmp; int size; Instance raw; HierarchicalResult result = analysis.getResult(); if (result != null) { Clustering<Cluster> clust = result.getClustering(); for (Cluster<? extends Instance> c : clust) { for (Instance inst : c) { line = inst.getName().split(","); size = line.length + 1; int dataSize = 0; String[] data = null; if (pref.getBoolean("raw_data", false)) { raw = inst; while (raw.getAncestor() != null) { raw = raw.getAncestor(); } data = raw.toStringArray(); dataSize = data.length; size += dataSize; } int preprocessSize = 0; String[] prepro = null; if (pref.getBoolean("preprocess_data", false)) { prepro = inst.toStringArray(); preprocessSize = prepro.length; size += preprocessSize; } //append cluster label tmp = new String[size]; System.arraycopy(line, 0, tmp, 0, line.length); if (dataSize > 0) { System.arraycopy(data, 0, tmp, line.length + 1, dataSize); } if (preprocessSize > 0) { System.arraycopy(prepro, 0, tmp, line.length + dataSize + 1, preprocessSize); } line = tmp; line[size - 1] = c.getName(); writer.writeNext(line); } } } else { throw new RuntimeException("no clustering result. did you run clustering?"); } } catch (IOException ex) { Exceptions.printStackTrace(ex); } }
public void run() { try { CSVWriter writer = new CSVWriter(new FileWriter(file)); String[] line, tmp; int size; Instance raw; HierarchicalResult result = analysis.getResult(); if (result != null) { Clustering<Cluster> clust = result.getClustering(); for (Cluster<? extends Instance> c : clust) { for (Instance inst : c) { line = inst.getName().split(","); size = line.length + 1; int dataSize = 0; String[] data = null; if (pref.getBoolean("raw_data", false)) { raw = inst; while (raw.getAncestor() != null) { raw = raw.getAncestor(); } data = raw.toStringArray(); dataSize = data.length; size += dataSize; } int preprocessSize = 0; String[] prepro = null; if (pref.getBoolean("preprocess_data", false)) { prepro = inst.toStringArray(); preprocessSize = prepro.length; size += preprocessSize; } //append cluster label tmp = new String[size]; System.arraycopy(line, 0, tmp, 0, line.length); if (dataSize > 0) { System.arraycopy(data, 0, tmp, line.length, dataSize); } if (preprocessSize > 0) { System.arraycopy(prepro, 0, tmp, line.length + dataSize, preprocessSize); } line = tmp; line[size - 1] = c.getName(); writer.writeNext(line); } } } else { throw new RuntimeException("no clustering result. did you run clustering?"); } } catch (IOException ex) { Exceptions.printStackTrace(ex); } }
diff --git a/src/it/treviso/provincia/documentdecryptor/Gui.java b/src/it/treviso/provincia/documentdecryptor/Gui.java index 8b8ff2b..9339c37 100644 --- a/src/it/treviso/provincia/documentdecryptor/Gui.java +++ b/src/it/treviso/provincia/documentdecryptor/Gui.java @@ -1,256 +1,255 @@ package it.treviso.provincia.documentdecryptor; import it.treviso.provincia.utils.PGPProcessor; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JTextField; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JMenuBar; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JFileChooser; import javax.swing.filechooser.FileFilter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.net.URLClassLoader; import java.security.NoSuchProviderException; import java.security.Security; import java.util.jar.Attributes; import java.util.jar.Manifest; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.ImageIcon; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.openpgp.PGPException; public class Gui { private JFrame frame; private JTextField textFile; private JTextField textKey; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { Gui window = new Gui(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public Gui() { initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { frame = new JFrame(); frame.setBounds(100, 100, 450, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(null); final JPanel panel = new JPanel(); panel.setBounds(12, 26, 428, 263); frame.getContentPane().add(panel); panel.setLayout(null); JLabel lblFileDaCifrare = new JLabel("File da decifrare"); lblFileDaCifrare.setBounds(0, 32, 127, 15); panel.add(lblFileDaCifrare); textFile = new JTextField(); textFile.setEditable(false); textFile.setBounds(127, 30, 227, 25); panel.add(textFile); textFile.setColumns(10); JLabel lblPercorsoChiave = new JLabel("Percorso chiave"); lblPercorsoChiave.setBounds(0, 110, 112, 15); panel.add(lblPercorsoChiave); textKey = new JTextField(); textKey.setEditable(false); textKey.setColumns(10); textKey.setBounds(127, 108, 227, 25); panel.add(textKey); JButton chooseFile = new JButton(""); chooseFile.setToolTipText("Seleziona file da firmare"); chooseFile.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JFileChooser chooser = new JFileChooser(); chooser.setCurrentDirectory(new File(".")); chooser.setFileFilter(new FileFilter() { public boolean accept(File f) { return f.getName().toLowerCase().endsWith(".enc") || f.isDirectory(); } public String getDescription() { return "Encrypted files (*.enc)"; } }); int r = chooser.showOpenDialog(panel); if (r == JFileChooser.APPROVE_OPTION) { String filename = chooser.getSelectedFile().getPath(); textFile.setText(filename); } } } ); chooseFile.setIcon(new ImageIcon(Gui.class.getResource("/com/sun/java/swing/plaf/windows/icons/NewFolder.gif"))); chooseFile.setBounds(374, 30, 42, 25); panel.add(chooseFile); JButton chooseKey = new JButton(""); chooseKey.setToolTipText("Seleziona file key contenente la chiave privata"); chooseKey.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JFileChooser chooser = new JFileChooser(); chooser.setCurrentDirectory(new File(".")); chooser.setFileFilter(new FileFilter() { public boolean accept(File f) { return f.getName().toLowerCase().endsWith(".key") || f.getName().toLowerCase().endsWith(".asc") || f.isDirectory(); } public String getDescription() { return "Key Files (*.key, *.asc)"; } }); int r = chooser.showOpenDialog(panel); if (r == JFileChooser.APPROVE_OPTION) { String keyname = chooser.getSelectedFile().getPath(); textKey.setText(keyname); } } }); chooseKey.setIcon(new ImageIcon(Gui.class.getResource("/com/sun/java/swing/plaf/windows/icons/NewFolder.gif"))); chooseKey.setBounds(374, 108, 42, 25); panel.add(chooseKey); - JButton btnCifraFile = new JButton("Cifra File"); + JButton btnCifraFile = new JButton("Decifra File"); btnCifraFile.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int result; JPasswordField pwd = new JPasswordField(10); - //String password = JOptionPane.showConfirmDialog(frame, pwd, "Inserire Password chiave privata", "Password", JOptionPane.PLAIN_MESSAGE); int ch = JOptionPane.showConfirmDialog(null, pwd,"Inserire password",JOptionPane.OK_CANCEL_OPTION); if (ch < 0 || ch == 2) result = -1; else result = decryptFile(textFile.getText(),textKey.getText(),pwd.getPassword()); switch(result) { case -1: JOptionPane.showMessageDialog(frame,"Decifratura annullata"); break; case 0: JOptionPane.showMessageDialog(frame, "File decifrato correttamente in "+textFile.getText().substring(0, textFile.getText().lastIndexOf("."))); break; case 1: JOptionPane.showMessageDialog(frame, "File da cifrare non specificato","Specificare file", JOptionPane.ERROR_MESSAGE); break; case 2: JOptionPane.showMessageDialog(frame, "Chiave di decifratura non specificata","Specificare chiave", JOptionPane.ERROR_MESSAGE); break; case 3: JOptionPane.showMessageDialog(frame, "Chiave di decifratura non valida","Chiave Invalida", JOptionPane.ERROR_MESSAGE); break; case 4: JOptionPane.showMessageDialog(frame, "Problemi in fase di decifratura","Errore", JOptionPane.ERROR_MESSAGE); break; case 5: JOptionPane.showMessageDialog(frame, "Errore di I/O sul file, controllare di avere i permessi necessari sul file","Errore I/O", JOptionPane.ERROR_MESSAGE); break; - case 6: JOptionPane.showMessageDialog(frame, "Errore nel salvare il file cifrato, controllare di avere i permessi di scrittura sul file","Specificare chiave", JOptionPane.ERROR_MESSAGE); break; + case 6: JOptionPane.showMessageDialog(frame, "Errore nel salvare il file decifrato, controllare di avere i permessi di scrittura sul file","Specificare chiave", JOptionPane.ERROR_MESSAGE); break; default: JOptionPane.showMessageDialog(frame, "Errore inatteso", "Errore", JOptionPane.ERROR_MESSAGE); } } }); btnCifraFile.setBounds(176, 170, 117, 25); panel.add(btnCifraFile); JMenuBar menuBar = new JMenuBar(); frame.setJMenuBar(menuBar); JMenu mnAiuto = new JMenu("Aiuto"); menuBar.add(mnAiuto); JMenuItem mntmInformazioni = new JMenuItem("Informazioni"); mntmInformazioni.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String versione = "0"; URLClassLoader cl = (URLClassLoader) getClass().getClassLoader(); try { URL url = cl.findResource("META-INF/MANIFEST.MF"); Manifest manifest = new Manifest(url.openStream()); Attributes attr = manifest.getMainAttributes(); versione = attr.getValue("Versione"); } catch (IOException E) { E.printStackTrace(); } JOptionPane.showMessageDialog(frame, "DocumentDecryptor versione "+versione+"\nProvincia di Treviso, Settore Sistemi Informatici"); } }); mnAiuto.add(mntmInformazioni); } protected int decryptFile(String file, String key, char[] password) { File f = new File(file); if(!f.exists()) return 1; f = new File(key); if(!f.exists()) return 2; Security.addProvider(new BouncyCastleProvider()); PGPProcessor p = new PGPProcessor(); byte[] original; try { original = p.getBytesFromFile(new File(file)); } catch (IOException e) { return 5; } FileInputStream privKey; try { privKey = new FileInputStream(key); } catch (FileNotFoundException e) { return 3; } byte[] decrypted; try { decrypted = p.decrypt(original, privKey, password); } catch (NoSuchProviderException e) { System.out.println("Error: NoSuchProviderException"); return 4; } catch (IOException e) { System.out.println("Error: IOException"); return 4; } catch (PGPException e) { System.out.println("Error: PGPException"); return 4; } FileOutputStream dfis; try { dfis = new FileOutputStream(file.substring(0, file.lastIndexOf('.'))); dfis.write(decrypted); dfis.close(); } catch (FileNotFoundException e) { System.out.println("Error: FileNotFoundException"); return 6; } catch (IOException e) { System.out.println("Error: IOException"); return 6; } return 0; } }
false
true
private void initialize() { frame = new JFrame(); frame.setBounds(100, 100, 450, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(null); final JPanel panel = new JPanel(); panel.setBounds(12, 26, 428, 263); frame.getContentPane().add(panel); panel.setLayout(null); JLabel lblFileDaCifrare = new JLabel("File da decifrare"); lblFileDaCifrare.setBounds(0, 32, 127, 15); panel.add(lblFileDaCifrare); textFile = new JTextField(); textFile.setEditable(false); textFile.setBounds(127, 30, 227, 25); panel.add(textFile); textFile.setColumns(10); JLabel lblPercorsoChiave = new JLabel("Percorso chiave"); lblPercorsoChiave.setBounds(0, 110, 112, 15); panel.add(lblPercorsoChiave); textKey = new JTextField(); textKey.setEditable(false); textKey.setColumns(10); textKey.setBounds(127, 108, 227, 25); panel.add(textKey); JButton chooseFile = new JButton(""); chooseFile.setToolTipText("Seleziona file da firmare"); chooseFile.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JFileChooser chooser = new JFileChooser(); chooser.setCurrentDirectory(new File(".")); chooser.setFileFilter(new FileFilter() { public boolean accept(File f) { return f.getName().toLowerCase().endsWith(".enc") || f.isDirectory(); } public String getDescription() { return "Encrypted files (*.enc)"; } }); int r = chooser.showOpenDialog(panel); if (r == JFileChooser.APPROVE_OPTION) { String filename = chooser.getSelectedFile().getPath(); textFile.setText(filename); } } } ); chooseFile.setIcon(new ImageIcon(Gui.class.getResource("/com/sun/java/swing/plaf/windows/icons/NewFolder.gif"))); chooseFile.setBounds(374, 30, 42, 25); panel.add(chooseFile); JButton chooseKey = new JButton(""); chooseKey.setToolTipText("Seleziona file key contenente la chiave privata"); chooseKey.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JFileChooser chooser = new JFileChooser(); chooser.setCurrentDirectory(new File(".")); chooser.setFileFilter(new FileFilter() { public boolean accept(File f) { return f.getName().toLowerCase().endsWith(".key") || f.getName().toLowerCase().endsWith(".asc") || f.isDirectory(); } public String getDescription() { return "Key Files (*.key, *.asc)"; } }); int r = chooser.showOpenDialog(panel); if (r == JFileChooser.APPROVE_OPTION) { String keyname = chooser.getSelectedFile().getPath(); textKey.setText(keyname); } } }); chooseKey.setIcon(new ImageIcon(Gui.class.getResource("/com/sun/java/swing/plaf/windows/icons/NewFolder.gif"))); chooseKey.setBounds(374, 108, 42, 25); panel.add(chooseKey); JButton btnCifraFile = new JButton("Cifra File"); btnCifraFile.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int result; JPasswordField pwd = new JPasswordField(10); //String password = JOptionPane.showConfirmDialog(frame, pwd, "Inserire Password chiave privata", "Password", JOptionPane.PLAIN_MESSAGE); int ch = JOptionPane.showConfirmDialog(null, pwd,"Inserire password",JOptionPane.OK_CANCEL_OPTION); if (ch < 0 || ch == 2) result = -1; else result = decryptFile(textFile.getText(),textKey.getText(),pwd.getPassword()); switch(result) { case -1: JOptionPane.showMessageDialog(frame,"Decifratura annullata"); break; case 0: JOptionPane.showMessageDialog(frame, "File decifrato correttamente in "+textFile.getText().substring(0, textFile.getText().lastIndexOf("."))); break; case 1: JOptionPane.showMessageDialog(frame, "File da cifrare non specificato","Specificare file", JOptionPane.ERROR_MESSAGE); break; case 2: JOptionPane.showMessageDialog(frame, "Chiave di decifratura non specificata","Specificare chiave", JOptionPane.ERROR_MESSAGE); break; case 3: JOptionPane.showMessageDialog(frame, "Chiave di decifratura non valida","Chiave Invalida", JOptionPane.ERROR_MESSAGE); break; case 4: JOptionPane.showMessageDialog(frame, "Problemi in fase di decifratura","Errore", JOptionPane.ERROR_MESSAGE); break; case 5: JOptionPane.showMessageDialog(frame, "Errore di I/O sul file, controllare di avere i permessi necessari sul file","Errore I/O", JOptionPane.ERROR_MESSAGE); break; case 6: JOptionPane.showMessageDialog(frame, "Errore nel salvare il file cifrato, controllare di avere i permessi di scrittura sul file","Specificare chiave", JOptionPane.ERROR_MESSAGE); break; default: JOptionPane.showMessageDialog(frame, "Errore inatteso", "Errore", JOptionPane.ERROR_MESSAGE); } } }); btnCifraFile.setBounds(176, 170, 117, 25); panel.add(btnCifraFile); JMenuBar menuBar = new JMenuBar(); frame.setJMenuBar(menuBar); JMenu mnAiuto = new JMenu("Aiuto"); menuBar.add(mnAiuto); JMenuItem mntmInformazioni = new JMenuItem("Informazioni"); mntmInformazioni.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String versione = "0"; URLClassLoader cl = (URLClassLoader) getClass().getClassLoader(); try { URL url = cl.findResource("META-INF/MANIFEST.MF"); Manifest manifest = new Manifest(url.openStream()); Attributes attr = manifest.getMainAttributes(); versione = attr.getValue("Versione"); } catch (IOException E) { E.printStackTrace(); } JOptionPane.showMessageDialog(frame, "DocumentDecryptor versione "+versione+"\nProvincia di Treviso, Settore Sistemi Informatici"); } }); mnAiuto.add(mntmInformazioni); }
private void initialize() { frame = new JFrame(); frame.setBounds(100, 100, 450, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(null); final JPanel panel = new JPanel(); panel.setBounds(12, 26, 428, 263); frame.getContentPane().add(panel); panel.setLayout(null); JLabel lblFileDaCifrare = new JLabel("File da decifrare"); lblFileDaCifrare.setBounds(0, 32, 127, 15); panel.add(lblFileDaCifrare); textFile = new JTextField(); textFile.setEditable(false); textFile.setBounds(127, 30, 227, 25); panel.add(textFile); textFile.setColumns(10); JLabel lblPercorsoChiave = new JLabel("Percorso chiave"); lblPercorsoChiave.setBounds(0, 110, 112, 15); panel.add(lblPercorsoChiave); textKey = new JTextField(); textKey.setEditable(false); textKey.setColumns(10); textKey.setBounds(127, 108, 227, 25); panel.add(textKey); JButton chooseFile = new JButton(""); chooseFile.setToolTipText("Seleziona file da firmare"); chooseFile.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JFileChooser chooser = new JFileChooser(); chooser.setCurrentDirectory(new File(".")); chooser.setFileFilter(new FileFilter() { public boolean accept(File f) { return f.getName().toLowerCase().endsWith(".enc") || f.isDirectory(); } public String getDescription() { return "Encrypted files (*.enc)"; } }); int r = chooser.showOpenDialog(panel); if (r == JFileChooser.APPROVE_OPTION) { String filename = chooser.getSelectedFile().getPath(); textFile.setText(filename); } } } ); chooseFile.setIcon(new ImageIcon(Gui.class.getResource("/com/sun/java/swing/plaf/windows/icons/NewFolder.gif"))); chooseFile.setBounds(374, 30, 42, 25); panel.add(chooseFile); JButton chooseKey = new JButton(""); chooseKey.setToolTipText("Seleziona file key contenente la chiave privata"); chooseKey.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JFileChooser chooser = new JFileChooser(); chooser.setCurrentDirectory(new File(".")); chooser.setFileFilter(new FileFilter() { public boolean accept(File f) { return f.getName().toLowerCase().endsWith(".key") || f.getName().toLowerCase().endsWith(".asc") || f.isDirectory(); } public String getDescription() { return "Key Files (*.key, *.asc)"; } }); int r = chooser.showOpenDialog(panel); if (r == JFileChooser.APPROVE_OPTION) { String keyname = chooser.getSelectedFile().getPath(); textKey.setText(keyname); } } }); chooseKey.setIcon(new ImageIcon(Gui.class.getResource("/com/sun/java/swing/plaf/windows/icons/NewFolder.gif"))); chooseKey.setBounds(374, 108, 42, 25); panel.add(chooseKey); JButton btnCifraFile = new JButton("Decifra File"); btnCifraFile.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int result; JPasswordField pwd = new JPasswordField(10); int ch = JOptionPane.showConfirmDialog(null, pwd,"Inserire password",JOptionPane.OK_CANCEL_OPTION); if (ch < 0 || ch == 2) result = -1; else result = decryptFile(textFile.getText(),textKey.getText(),pwd.getPassword()); switch(result) { case -1: JOptionPane.showMessageDialog(frame,"Decifratura annullata"); break; case 0: JOptionPane.showMessageDialog(frame, "File decifrato correttamente in "+textFile.getText().substring(0, textFile.getText().lastIndexOf("."))); break; case 1: JOptionPane.showMessageDialog(frame, "File da cifrare non specificato","Specificare file", JOptionPane.ERROR_MESSAGE); break; case 2: JOptionPane.showMessageDialog(frame, "Chiave di decifratura non specificata","Specificare chiave", JOptionPane.ERROR_MESSAGE); break; case 3: JOptionPane.showMessageDialog(frame, "Chiave di decifratura non valida","Chiave Invalida", JOptionPane.ERROR_MESSAGE); break; case 4: JOptionPane.showMessageDialog(frame, "Problemi in fase di decifratura","Errore", JOptionPane.ERROR_MESSAGE); break; case 5: JOptionPane.showMessageDialog(frame, "Errore di I/O sul file, controllare di avere i permessi necessari sul file","Errore I/O", JOptionPane.ERROR_MESSAGE); break; case 6: JOptionPane.showMessageDialog(frame, "Errore nel salvare il file decifrato, controllare di avere i permessi di scrittura sul file","Specificare chiave", JOptionPane.ERROR_MESSAGE); break; default: JOptionPane.showMessageDialog(frame, "Errore inatteso", "Errore", JOptionPane.ERROR_MESSAGE); } } }); btnCifraFile.setBounds(176, 170, 117, 25); panel.add(btnCifraFile); JMenuBar menuBar = new JMenuBar(); frame.setJMenuBar(menuBar); JMenu mnAiuto = new JMenu("Aiuto"); menuBar.add(mnAiuto); JMenuItem mntmInformazioni = new JMenuItem("Informazioni"); mntmInformazioni.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String versione = "0"; URLClassLoader cl = (URLClassLoader) getClass().getClassLoader(); try { URL url = cl.findResource("META-INF/MANIFEST.MF"); Manifest manifest = new Manifest(url.openStream()); Attributes attr = manifest.getMainAttributes(); versione = attr.getValue("Versione"); } catch (IOException E) { E.printStackTrace(); } JOptionPane.showMessageDialog(frame, "DocumentDecryptor versione "+versione+"\nProvincia di Treviso, Settore Sistemi Informatici"); } }); mnAiuto.add(mntmInformazioni); }
diff --git a/Framework/java/com/xaf/sql/query/QuerySelectDialogTag.java b/Framework/java/com/xaf/sql/query/QuerySelectDialogTag.java index 26193830..777de045 100644 --- a/Framework/java/com/xaf/sql/query/QuerySelectDialogTag.java +++ b/Framework/java/com/xaf/sql/query/QuerySelectDialogTag.java @@ -1,85 +1,85 @@ package com.xaf.sql.query; import java.io.*; import java.sql.*; import javax.naming.*; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; import com.xaf.form.*; import com.xaf.skin.*; import com.xaf.sql.*; public class QuerySelectDialogTag extends TagSupport { private String name; private String source; private String skinName; public void release() { super.release(); name = null; source = null; skinName = null; } public void setName(String value) { name = value; } public void setSkin(String value) { skinName = value; } public void setSource(String value) { source = value; } public int doStartTag() throws JspException { try { JspWriter out = pageContext.getOut(); ServletContext context = pageContext.getServletContext(); StatementManager manager = StatementManagerFactory.getManager(context); if(manager == null) { out.write("StatementManager not found in ServletContext"); return SKIP_BODY; } QueryDefinition queryDefn = manager.getQueryDefn(source); - if(manager == null) + if(queryDefn == null) { out.write("QueryDefinition '"+source+"' not found in StatementManager"); return SKIP_BODY; } QuerySelectDialog dialog = queryDefn.getSelectDialog(name); - if(manager == null) + if(dialog == null) { - out.write("QuerySelectDialog '"+name+"' not found in QueryDefinition"); + out.write("QuerySelectDialog '"+name+"' not found in QueryDefinition '"+ source +"'"); return SKIP_BODY; } DialogSkin skin = skinName == null ? SkinFactory.getDialogSkin() : SkinFactory.getDialogSkin(skinName); if(skin == null) { out.write("DialogSkin '"+skinName+"' not found in skin factory."); return SKIP_BODY; } DialogContext dc = new DialogContext(pageContext.getServletContext(), (Servlet) pageContext.getPage(), (HttpServletRequest) pageContext.getRequest(), (HttpServletResponse) pageContext.getResponse(), dialog, skin); dialog.prepareContext(dc); out.write(dialog.getHtml(dc, true)); return SKIP_BODY; } catch(IOException e) { throw new JspException(e.toString()); } } public int doEndTag() throws JspException { return EVAL_PAGE; } }
false
true
public int doStartTag() throws JspException { try { JspWriter out = pageContext.getOut(); ServletContext context = pageContext.getServletContext(); StatementManager manager = StatementManagerFactory.getManager(context); if(manager == null) { out.write("StatementManager not found in ServletContext"); return SKIP_BODY; } QueryDefinition queryDefn = manager.getQueryDefn(source); if(manager == null) { out.write("QueryDefinition '"+source+"' not found in StatementManager"); return SKIP_BODY; } QuerySelectDialog dialog = queryDefn.getSelectDialog(name); if(manager == null) { out.write("QuerySelectDialog '"+name+"' not found in QueryDefinition"); return SKIP_BODY; } DialogSkin skin = skinName == null ? SkinFactory.getDialogSkin() : SkinFactory.getDialogSkin(skinName); if(skin == null) { out.write("DialogSkin '"+skinName+"' not found in skin factory."); return SKIP_BODY; } DialogContext dc = new DialogContext(pageContext.getServletContext(), (Servlet) pageContext.getPage(), (HttpServletRequest) pageContext.getRequest(), (HttpServletResponse) pageContext.getResponse(), dialog, skin); dialog.prepareContext(dc); out.write(dialog.getHtml(dc, true)); return SKIP_BODY; } catch(IOException e) { throw new JspException(e.toString()); } }
public int doStartTag() throws JspException { try { JspWriter out = pageContext.getOut(); ServletContext context = pageContext.getServletContext(); StatementManager manager = StatementManagerFactory.getManager(context); if(manager == null) { out.write("StatementManager not found in ServletContext"); return SKIP_BODY; } QueryDefinition queryDefn = manager.getQueryDefn(source); if(queryDefn == null) { out.write("QueryDefinition '"+source+"' not found in StatementManager"); return SKIP_BODY; } QuerySelectDialog dialog = queryDefn.getSelectDialog(name); if(dialog == null) { out.write("QuerySelectDialog '"+name+"' not found in QueryDefinition '"+ source +"'"); return SKIP_BODY; } DialogSkin skin = skinName == null ? SkinFactory.getDialogSkin() : SkinFactory.getDialogSkin(skinName); if(skin == null) { out.write("DialogSkin '"+skinName+"' not found in skin factory."); return SKIP_BODY; } DialogContext dc = new DialogContext(pageContext.getServletContext(), (Servlet) pageContext.getPage(), (HttpServletRequest) pageContext.getRequest(), (HttpServletResponse) pageContext.getResponse(), dialog, skin); dialog.prepareContext(dc); out.write(dialog.getHtml(dc, true)); return SKIP_BODY; } catch(IOException e) { throw new JspException(e.toString()); } }
diff --git a/src/com/dmdirc/plugins/PluginClassLoader.java b/src/com/dmdirc/plugins/PluginClassLoader.java index 00cdc8afc..44bc2ad93 100644 --- a/src/com/dmdirc/plugins/PluginClassLoader.java +++ b/src/com/dmdirc/plugins/PluginClassLoader.java @@ -1,223 +1,223 @@ /* * Copyright (c) 2006-2010 Chris Smith, Shane Mc Cormack, Gregory Holmes * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.dmdirc.plugins; import com.dmdirc.util.resourcemanager.ResourceManager; import java.io.IOException; import java.net.URL; import java.util.Enumeration; import java.util.Vector; public class PluginClassLoader extends ClassLoader { /** The plugin Info object for the plugin we are loading. */ final PluginInfo pluginInfo; /** * Create a new PluginClassLoader. * * @param info PluginInfo this classloader will be for */ public PluginClassLoader(final PluginInfo info) { super(); pluginInfo = info; } /** * Create a new PluginClassLoader. * * @param info PluginInfo this classloader will be for * @param parent Parent ClassLoader */ private PluginClassLoader(final PluginInfo info, final PluginClassLoader parent) { super(parent); pluginInfo = info; } /** * Get a PluginClassLoader that is a subclassloader of this one. * * @param info PluginInfo the new classloader will be for * @return A classloader configured with this one as its parent */ public PluginClassLoader getSubClassLoader(final PluginInfo info) { return new PluginClassLoader(info, this); } /** * Load the plugin with the given className * * @param name Class Name of plugin * @return plugin class * @throws ClassNotFoundException if the class to be loaded could not be found. */ @Override public Class<?> loadClass(final String name) throws ClassNotFoundException { return loadClass(name, true); } /** * Have we already loaded the given class name? * * @param name Name to check. * @param checkGlobal Should we check if the GCL has loaded it aswell? * @return True if the specified class is loaded, false otherwise */ public boolean isClassLoaded(final String name, final boolean checkGlobal) { // Don't duplicate a class final Class existing = findLoadedClass(name); final boolean gcl = checkGlobal ? GlobalClassLoader.getGlobalClassLoader().isClassLoaded(name) : false; return existing != null || gcl; } /** * Load the plugin with the given className * * @param name Class Name of plugin * @param askGlobal Ask the gobal class loaded for this class if we can't find it? * @return plugin class * @throws ClassNotFoundException if the class to be loaded could not be found. */ @Override public Class<?> loadClass(final String name, final boolean askGlobal) throws ClassNotFoundException { Class<?> loadedClass = null; if (getParent() instanceof PluginClassLoader) { try { loadedClass = ((PluginClassLoader) getParent()).loadClass(name, false); if (loadedClass != null) { return loadedClass; } } catch (ClassNotFoundException cnfe) { /* Parent doesn't have the class, load ourself */ } } ResourceManager res; try { res = pluginInfo.getResourceManager(); } catch (IOException ioe) { throw new ClassNotFoundException("Error with resourcemanager", ioe); } final String fileName = name.replace('.', '/') + ".class"; try { if (pluginInfo.isPersistent(name) || !res.resourceExists(fileName)) { if (!pluginInfo.isPersistent(name) && askGlobal) { return GlobalClassLoader.getGlobalClassLoader().loadClass(name); } else { // Try to load class from previous load. try { if (askGlobal) { return GlobalClassLoader.getGlobalClassLoader().loadClass(name, pluginInfo); } } catch (ClassNotFoundException e) { /* Class doesn't exist, we load it ourself below */ } } } } catch (NoClassDefFoundError e) { throw new ClassNotFoundException("Error loading '" + name + "' (wanted by " + pluginInfo.getName() + ") -> " + e.getMessage(), e); } // Don't duplicate a class if (isClassLoaded(name, false)) { return findLoadedClass(name); } // We are ment to be loading this one! byte[] data = null; if (res.resourceExists(fileName)) { data = res.getResourceBytes(fileName); } else { throw new ClassNotFoundException("Resource '" + name + "' (wanted by " + pluginInfo.getName() + ") does not exist."); } try { if (pluginInfo.isPersistent(name)) { GlobalClassLoader.getGlobalClassLoader().defineClass(name, data); } else { loadedClass = defineClass(name, data, 0, data.length); } - } catch (NoClassDefFoundError e) { + } catch (LinkageError e) { throw new ClassNotFoundException(e.getMessage(), e); } if (loadedClass == null) { throw new ClassNotFoundException("Could not load " + name); } else { resolveClass(loadedClass); } return loadedClass; } /** * {@inheritDoc} * * @since 0.6.3 */ @Override protected URL findResource(final String name) { try { final ResourceManager res = pluginInfo.getResourceManager(); final URL url = res.getResourceURL(name); if (url != null) { return url; } } catch (IOException ioe) { // Do nothing, fall through } return super.findResource(name); } /** * {@inheritDoc} * * @since 0.6.3 */ @Override protected Enumeration<URL> findResources(final String name) throws IOException { final URL resource = findResource(name); final Vector<URL> resources = new Vector<URL>(); // URG if (resource != null) { resources.add(resource); } final Enumeration<URL> urls = super.findResources(name); while (urls.hasMoreElements()) { // More URG resources.add(urls.nextElement()); } return resources.elements(); } }
true
true
public Class<?> loadClass(final String name, final boolean askGlobal) throws ClassNotFoundException { Class<?> loadedClass = null; if (getParent() instanceof PluginClassLoader) { try { loadedClass = ((PluginClassLoader) getParent()).loadClass(name, false); if (loadedClass != null) { return loadedClass; } } catch (ClassNotFoundException cnfe) { /* Parent doesn't have the class, load ourself */ } } ResourceManager res; try { res = pluginInfo.getResourceManager(); } catch (IOException ioe) { throw new ClassNotFoundException("Error with resourcemanager", ioe); } final String fileName = name.replace('.', '/') + ".class"; try { if (pluginInfo.isPersistent(name) || !res.resourceExists(fileName)) { if (!pluginInfo.isPersistent(name) && askGlobal) { return GlobalClassLoader.getGlobalClassLoader().loadClass(name); } else { // Try to load class from previous load. try { if (askGlobal) { return GlobalClassLoader.getGlobalClassLoader().loadClass(name, pluginInfo); } } catch (ClassNotFoundException e) { /* Class doesn't exist, we load it ourself below */ } } } } catch (NoClassDefFoundError e) { throw new ClassNotFoundException("Error loading '" + name + "' (wanted by " + pluginInfo.getName() + ") -> " + e.getMessage(), e); } // Don't duplicate a class if (isClassLoaded(name, false)) { return findLoadedClass(name); } // We are ment to be loading this one! byte[] data = null; if (res.resourceExists(fileName)) { data = res.getResourceBytes(fileName); } else { throw new ClassNotFoundException("Resource '" + name + "' (wanted by " + pluginInfo.getName() + ") does not exist."); } try { if (pluginInfo.isPersistent(name)) { GlobalClassLoader.getGlobalClassLoader().defineClass(name, data); } else { loadedClass = defineClass(name, data, 0, data.length); } } catch (NoClassDefFoundError e) { throw new ClassNotFoundException(e.getMessage(), e); } if (loadedClass == null) { throw new ClassNotFoundException("Could not load " + name); } else { resolveClass(loadedClass); } return loadedClass; }
public Class<?> loadClass(final String name, final boolean askGlobal) throws ClassNotFoundException { Class<?> loadedClass = null; if (getParent() instanceof PluginClassLoader) { try { loadedClass = ((PluginClassLoader) getParent()).loadClass(name, false); if (loadedClass != null) { return loadedClass; } } catch (ClassNotFoundException cnfe) { /* Parent doesn't have the class, load ourself */ } } ResourceManager res; try { res = pluginInfo.getResourceManager(); } catch (IOException ioe) { throw new ClassNotFoundException("Error with resourcemanager", ioe); } final String fileName = name.replace('.', '/') + ".class"; try { if (pluginInfo.isPersistent(name) || !res.resourceExists(fileName)) { if (!pluginInfo.isPersistent(name) && askGlobal) { return GlobalClassLoader.getGlobalClassLoader().loadClass(name); } else { // Try to load class from previous load. try { if (askGlobal) { return GlobalClassLoader.getGlobalClassLoader().loadClass(name, pluginInfo); } } catch (ClassNotFoundException e) { /* Class doesn't exist, we load it ourself below */ } } } } catch (NoClassDefFoundError e) { throw new ClassNotFoundException("Error loading '" + name + "' (wanted by " + pluginInfo.getName() + ") -> " + e.getMessage(), e); } // Don't duplicate a class if (isClassLoaded(name, false)) { return findLoadedClass(name); } // We are ment to be loading this one! byte[] data = null; if (res.resourceExists(fileName)) { data = res.getResourceBytes(fileName); } else { throw new ClassNotFoundException("Resource '" + name + "' (wanted by " + pluginInfo.getName() + ") does not exist."); } try { if (pluginInfo.isPersistent(name)) { GlobalClassLoader.getGlobalClassLoader().defineClass(name, data); } else { loadedClass = defineClass(name, data, 0, data.length); } } catch (LinkageError e) { throw new ClassNotFoundException(e.getMessage(), e); } if (loadedClass == null) { throw new ClassNotFoundException("Could not load " + name); } else { resolveClass(loadedClass); } return loadedClass; }
diff --git a/jOOQ/src/main/java/org/jooq/impl/DefaultRenderContext.java b/jOOQ/src/main/java/org/jooq/impl/DefaultRenderContext.java index 4e822053c..5f8ea21c2 100644 --- a/jOOQ/src/main/java/org/jooq/impl/DefaultRenderContext.java +++ b/jOOQ/src/main/java/org/jooq/impl/DefaultRenderContext.java @@ -1,671 +1,672 @@ /** * Copyright (c) 2009-2013, Lukas Eder, [email protected] * All rights reserved. * * This software is licensed to you under the Apache License, Version 2.0 * (the "License"); You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * . Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * . Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * . Neither the name "jOOQ" nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package org.jooq.impl; import static java.util.Arrays.asList; import static org.jooq.conf.ParamType.INDEXED; import static org.jooq.conf.ParamType.INLINED; import static org.jooq.conf.ParamType.NAMED; import static org.jooq.impl.Utils.DATA_COUNT_BIND_VALUES; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.Stack; import java.util.regex.Pattern; import org.jooq.Configuration; import org.jooq.Param; import org.jooq.QueryPart; import org.jooq.QueryPartInternal; import org.jooq.RenderContext; import org.jooq.SQLDialect; import org.jooq.conf.ParamType; import org.jooq.conf.RenderKeywordStyle; import org.jooq.conf.RenderNameStyle; import org.jooq.conf.Settings; import org.jooq.exception.ControlFlowSignal; import org.jooq.tools.JooqLogger; import org.jooq.tools.StringUtils; /** * @author Lukas Eder */ class DefaultRenderContext extends AbstractContext<RenderContext> implements RenderContext { private static final JooqLogger log = JooqLogger.getLogger(DefaultRenderContext.class); private static final Pattern IDENTIFIER_PATTERN = Pattern.compile("[A-Za-z][A-Za-z0-9_]*"); private static final Pattern NEWLINE = Pattern.compile("[\\n\\r]"); private static final Set<String> SQLITE_KEYWORDS; private final StringBuilder sql; private ParamType paramType; private int params; private boolean qualify = true; private int alias; private CastMode castMode = CastMode.DEFAULT; private SQLDialect[] castDialects; private int indent; private Stack<Integer> indentLock = new Stack<Integer>(); private int printMargin = 80; // [#1632] Cached values from Settings private RenderKeywordStyle cachedRenderKeywordStyle; private RenderNameStyle cachedRenderNameStyle; private boolean cachedRenderFormatted; DefaultRenderContext(Configuration configuration) { super(configuration); Settings settings = configuration.settings(); this.sql = new StringBuilder(); this.cachedRenderKeywordStyle = settings.getRenderKeywordStyle(); this.cachedRenderFormatted = Boolean.TRUE.equals(settings.isRenderFormatted()); this.cachedRenderNameStyle = settings.getRenderNameStyle(); } DefaultRenderContext(RenderContext context) { this(context.configuration()); paramType(context.paramType()); qualify(context.qualify()); castMode(context.castMode()); declareFields(context.declareFields()); declareTables(context.declareTables()); data().putAll(context.data()); } // ------------------------------------------------------------------------ // RenderContext API // ------------------------------------------------------------------------ @Override public final String peekAlias() { return "alias_" + (alias + 1); } @Override public final String nextAlias() { return "alias_" + (++alias); } @Override public final String render() { return sql.toString(); } @Override public final String render(QueryPart part) { return new DefaultRenderContext(this).sql(part).render(); } @Override public final RenderContext keyword(String keyword) { if (RenderKeywordStyle.UPPER == cachedRenderKeywordStyle) { return sql(keyword.toUpperCase()); } else { return sql(keyword.toLowerCase()); } } @Override public final RenderContext sql(String s) { return sql(s, s == null || !cachedRenderFormatted); } @Override public final RenderContext sql(String s, boolean literal) { if (literal) { sql.append(s); } else { sql.append(NEWLINE.matcher(s).replaceAll("$0" + indentation())); } return this; } @Override public final RenderContext sql(char c) { sql.append(c); return this; } @Override public final RenderContext sql(int i) { sql.append(i); return this; } @Override public final RenderContext formatNewLine() { if (cachedRenderFormatted) { sql.append("\n"); sql.append(indentation()); } return this; } @Override public final RenderContext formatNewLineAfterPrintMargin() { if (cachedRenderFormatted && printMargin > 0) { if (sql.length() - sql.lastIndexOf("\n") > printMargin) { formatNewLine(); } } return this; } private final String indentation() { return StringUtils.leftPad("", indent, " "); } @Override public final RenderContext format(boolean format) { cachedRenderFormatted = format; return this; } @Override public final boolean format() { return cachedRenderFormatted; } @Override public final RenderContext formatSeparator() { if (cachedRenderFormatted) { formatNewLine(); } else { sql.append(" "); } return this; } @Override public final RenderContext formatIndentStart() { return formatIndentStart(2); } @Override public final RenderContext formatIndentEnd() { return formatIndentEnd(2); } @Override public final RenderContext formatIndentStart(int i) { if (cachedRenderFormatted) { indent += i; } return this; } @Override public final RenderContext formatIndentEnd(int i) { if (cachedRenderFormatted) { indent -= i; } return this; } @Override public final RenderContext formatIndentLockStart() { if (cachedRenderFormatted) { indentLock.push(indent); String[] lines = sql.toString().split("[\\n\\r]"); indent = lines[lines.length - 1].length(); } return this; } @Override public final RenderContext formatIndentLockEnd() { if (cachedRenderFormatted) { indent = indentLock.pop(); } return this; } @Override public final RenderContext formatPrintMargin(int margin) { printMargin = margin; return this; } @Override public final RenderContext literal(String literal) { // Literal usually originates from NamedQueryPart.getName(). This could // be null for CustomTable et al. if (literal == null) { return this; } // Quoting is needed when explicitly requested... boolean needsQuote = (RenderNameStyle.QUOTED == cachedRenderNameStyle // [#2367] ... but in SQLite, quoting "normal" literals is generally // asking for trouble, as SQLite bends the rules here, see // http://www.sqlite.org/lang_keywords.html for details ... && configuration.dialect() != SQLDialect.SQLITE) || // [#2367] ... yet, do quote when an identifier is a SQLite keyword (configuration.dialect() == SQLDialect.SQLITE && SQLITE_KEYWORDS.contains(literal.toUpperCase())) || // [#1982] ... yet, do quote when an identifier contains special characters (!IDENTIFIER_PATTERN.matcher(literal).matches()); if (RenderNameStyle.LOWER == cachedRenderNameStyle) { literal = literal.toLowerCase(); } else if (RenderNameStyle.UPPER == cachedRenderNameStyle) { literal = literal.toUpperCase(); } if (!needsQuote) { sql(literal); } else { switch (configuration.dialect().family()) { // MySQL supports backticks and double quotes case MARIADB: case MYSQL: sql("`").sql(StringUtils.replace(literal, "`", "``")).sql("`"); break; // T-SQL databases use brackets + case ACCESS: case ASE: case SQLSERVER: case SYBASE: sql("[").sql(StringUtils.replace(literal, "]", "]]")).sql("]"); break; // Most dialects implement the SQL standard, using double quotes case SQLITE: case CUBRID: case DB2: case DERBY: case FIREBIRD: case H2: case HSQLDB: case INGRES: case ORACLE: case POSTGRES: default: sql('"').sql(StringUtils.replace(literal, "\"", "\"\"")).sql('"'); break; } } return this; } @Override public final RenderContext sql(QueryPart part) { if (part != null) { checkForceInline(part); QueryPartInternal internal = (QueryPartInternal) part; // If this is supposed to be a declaration section and the part // isn't able to declare anything, then disable declaration temporarily // We're declaring fields, but "part" does not declare fields if (declareFields() && !internal.declaresFields()) { declareFields(false); internal.toSQL(this); declareFields(true); } // We're declaring tables, but "part" does not declare tables else if (declareTables() && !internal.declaresTables()) { declareTables(false); internal.toSQL(this); declareTables(true); } // We're not declaring, or "part" can declare else { internal.toSQL(this); } } return this; } private final void checkForceInline(QueryPart part) throws ForceInlineSignal { if (paramType == INLINED) return; if (part instanceof Param) { if (((Param<?>) part).isInline()) return; switch (configuration().dialect().family()) { case ASE: checkForceInline(2000); return; case INGRES: checkForceInline(1024); return; case SQLITE: checkForceInline(999); return; case SQLSERVER: checkForceInline(2100); return; default: return; } } } private final void checkForceInline(int max) throws ForceInlineSignal { if (Boolean.TRUE.equals(data(DATA_COUNT_BIND_VALUES))) if (++params > max) throw new ForceInlineSignal(); } @Override public final boolean inline() { return paramType == INLINED; } @Override @Deprecated public final RenderContext inline(boolean i) { this.paramType = i ? INLINED : INDEXED; return this; } @Override public final ParamType paramType() { return paramType; } @Override public final RenderContext paramType(ParamType p) { paramType = p; return this; } @Override public final boolean qualify() { return qualify; } @Override public final RenderContext qualify(boolean q) { this.qualify = q; return this; } @Override public final boolean namedParams() { return paramType == NAMED; } @Override @Deprecated public final RenderContext namedParams(boolean r) { this.paramType = r ? NAMED : INDEXED; return this; } @Override public final CastMode castMode() { return castMode; } @Override public final RenderContext castMode(CastMode mode) { this.castMode = mode; this.castDialects = null; return this; } @Override public final Boolean cast() { switch (castMode) { case ALWAYS: return true; case NEVER: return false; case SOME: return asList(castDialects).contains(configuration.dialect()); } return null; } @Override public final RenderContext castModeSome(SQLDialect... dialects) { this.castMode = CastMode.SOME; this.castDialects = dialects; return this; } // ------------------------------------------------------------------------ // Object API // ------------------------------------------------------------------------ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("rendering ["); sb.append(render()); sb.append("]\n"); sb.append("parameters ["); sb.append(paramType); sb.append("]\n"); toString(sb); return sb.toString(); } // ------------------------------------------------------------------------ // Static initialisation // ------------------------------------------------------------------------ static { SQLITE_KEYWORDS = new HashSet<String>(); // [#2367] Taken from http://www.sqlite.org/lang_keywords.html SQLITE_KEYWORDS.addAll(Arrays.asList( "ABORT", "ACTION", "ADD", "AFTER", "ALL", "ALTER", "ANALYZE", "AND", "AS", "ASC", "ATTACH", "AUTOINCREMENT", "BEFORE", "BEGIN", "BETWEEN", "BY", "CASCADE", "CASE", "CAST", "CHECK", "COLLATE", "COLUMN", "COMMIT", "CONFLICT", "CONSTRAINT", "CREATE", "CROSS", "CURRENT_DATE", "CURRENT_TIME", "CURRENT_TIMESTAMP", "DATABASE", "DEFAULT", "DEFERRABLE", "DEFERRED", "DELETE", "DESC", "DETACH", "DISTINCT", "DROP", "EACH", "ELSE", "END", "ESCAPE", "EXCEPT", "EXCLUSIVE", "EXISTS", "EXPLAIN", "FAIL", "FOR", "FOREIGN", "FROM", "FULL", "GLOB", "GROUP", "HAVING", "IF", "IGNORE", "IMMEDIATE", "IN", "INDEX", "INDEXED", "INITIALLY", "INNER", "INSERT", "INSTEAD", "INTERSECT", "INTO", "IS", "ISNULL", "JOIN", "KEY", "LEFT", "LIKE", "LIMIT", "MATCH", "NATURAL", "NO", "NOT", "NOTNULL", "NULL", "OF", "OFFSET", "ON", "OR", "ORDER", "OUTER", "PLAN", "PRAGMA", "PRIMARY", "QUERY", "RAISE", "REFERENCES", "REGEXP", "REINDEX", "RELEASE", "RENAME", "REPLACE", "RESTRICT", "RIGHT", "ROLLBACK", "ROW", "SAVEPOINT", "SELECT", "SET", "TABLE", "TEMP", "TEMPORARY", "THEN", "TO", "TRANSACTION", "TRIGGER", "UNION", "UNIQUE", "UPDATE", "USING", "VACUUM", "VALUES", "VIEW", "VIRTUAL", "WHEN", "WHERE" )); } /** * A query execution interception signal. * <p> * This exception is used as a signal for jOOQ's internals to abort query * execution, and return generated SQL back to batch execution. */ class ForceInlineSignal extends ControlFlowSignal { /** * Generated UID */ private static final long serialVersionUID = -9131368742983295195L; public ForceInlineSignal() { if (log.isDebugEnabled()) log.debug("Re-render query", "Forcing bind variable inlining as " + configuration().dialect() + " does not support " + params + " bind variables (or more) in a single query"); } } }
true
true
public final RenderContext literal(String literal) { // Literal usually originates from NamedQueryPart.getName(). This could // be null for CustomTable et al. if (literal == null) { return this; } // Quoting is needed when explicitly requested... boolean needsQuote = (RenderNameStyle.QUOTED == cachedRenderNameStyle // [#2367] ... but in SQLite, quoting "normal" literals is generally // asking for trouble, as SQLite bends the rules here, see // http://www.sqlite.org/lang_keywords.html for details ... && configuration.dialect() != SQLDialect.SQLITE) || // [#2367] ... yet, do quote when an identifier is a SQLite keyword (configuration.dialect() == SQLDialect.SQLITE && SQLITE_KEYWORDS.contains(literal.toUpperCase())) || // [#1982] ... yet, do quote when an identifier contains special characters (!IDENTIFIER_PATTERN.matcher(literal).matches()); if (RenderNameStyle.LOWER == cachedRenderNameStyle) { literal = literal.toLowerCase(); } else if (RenderNameStyle.UPPER == cachedRenderNameStyle) { literal = literal.toUpperCase(); } if (!needsQuote) { sql(literal); } else { switch (configuration.dialect().family()) { // MySQL supports backticks and double quotes case MARIADB: case MYSQL: sql("`").sql(StringUtils.replace(literal, "`", "``")).sql("`"); break; // T-SQL databases use brackets case ASE: case SQLSERVER: case SYBASE: sql("[").sql(StringUtils.replace(literal, "]", "]]")).sql("]"); break; // Most dialects implement the SQL standard, using double quotes case SQLITE: case CUBRID: case DB2: case DERBY: case FIREBIRD: case H2: case HSQLDB: case INGRES: case ORACLE: case POSTGRES: default: sql('"').sql(StringUtils.replace(literal, "\"", "\"\"")).sql('"'); break; } } return this; }
public final RenderContext literal(String literal) { // Literal usually originates from NamedQueryPart.getName(). This could // be null for CustomTable et al. if (literal == null) { return this; } // Quoting is needed when explicitly requested... boolean needsQuote = (RenderNameStyle.QUOTED == cachedRenderNameStyle // [#2367] ... but in SQLite, quoting "normal" literals is generally // asking for trouble, as SQLite bends the rules here, see // http://www.sqlite.org/lang_keywords.html for details ... && configuration.dialect() != SQLDialect.SQLITE) || // [#2367] ... yet, do quote when an identifier is a SQLite keyword (configuration.dialect() == SQLDialect.SQLITE && SQLITE_KEYWORDS.contains(literal.toUpperCase())) || // [#1982] ... yet, do quote when an identifier contains special characters (!IDENTIFIER_PATTERN.matcher(literal).matches()); if (RenderNameStyle.LOWER == cachedRenderNameStyle) { literal = literal.toLowerCase(); } else if (RenderNameStyle.UPPER == cachedRenderNameStyle) { literal = literal.toUpperCase(); } if (!needsQuote) { sql(literal); } else { switch (configuration.dialect().family()) { // MySQL supports backticks and double quotes case MARIADB: case MYSQL: sql("`").sql(StringUtils.replace(literal, "`", "``")).sql("`"); break; // T-SQL databases use brackets case ACCESS: case ASE: case SQLSERVER: case SYBASE: sql("[").sql(StringUtils.replace(literal, "]", "]]")).sql("]"); break; // Most dialects implement the SQL standard, using double quotes case SQLITE: case CUBRID: case DB2: case DERBY: case FIREBIRD: case H2: case HSQLDB: case INGRES: case ORACLE: case POSTGRES: default: sql('"').sql(StringUtils.replace(literal, "\"", "\"\"")).sql('"'); break; } } return this; }
diff --git a/src/com/android/settings/ChooseLockPassword.java b/src/com/android/settings/ChooseLockPassword.java index 294044241..4657be563 100644 --- a/src/com/android/settings/ChooseLockPassword.java +++ b/src/com/android/settings/ChooseLockPassword.java @@ -1,479 +1,479 @@ /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.settings; import com.android.internal.widget.LockPatternUtils; import com.android.internal.widget.PasswordEntryKeyboardHelper; import com.android.internal.widget.PasswordEntryKeyboardView; import android.app.Activity; import android.app.Fragment; import android.app.admin.DevicePolicyManager; import android.content.Intent; import android.inputmethodservice.KeyboardView; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.preference.PreferenceActivity; import android.text.Editable; import android.text.InputType; import android.text.Selection; import android.text.Spannable; import android.text.TextUtils; import android.text.TextWatcher; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.view.inputmethod.EditorInfo; import android.widget.Button; import android.widget.TextView; import android.widget.TextView.OnEditorActionListener; public class ChooseLockPassword extends PreferenceActivity { public static final String PASSWORD_MIN_KEY = "lockscreen.password_min"; public static final String PASSWORD_MAX_KEY = "lockscreen.password_max"; public static final String PASSWORD_MIN_LETTERS_KEY = "lockscreen.password_min_letters"; public static final String PASSWORD_MIN_LOWERCASE_KEY = "lockscreen.password_min_lowercase"; public static final String PASSWORD_MIN_UPPERCASE_KEY = "lockscreen.password_min_uppercase"; public static final String PASSWORD_MIN_NUMERIC_KEY = "lockscreen.password_min_numeric"; public static final String PASSWORD_MIN_SYMBOLS_KEY = "lockscreen.password_min_symbols"; public static final String PASSWORD_MIN_NONLETTER_KEY = "lockscreen.password_min_nonletter"; @Override public Intent getIntent() { Intent modIntent = new Intent(super.getIntent()); modIntent.putExtra(EXTRA_SHOW_FRAGMENT, ChooseLockPasswordFragment.class.getName()); modIntent.putExtra(EXTRA_NO_HEADERS, true); return modIntent; } @Override public void onCreate(Bundle savedInstanceState) { // TODO: Fix on phones // Disable IME on our window since we provide our own keyboard //getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM, //WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM); super.onCreate(savedInstanceState); CharSequence msg = getText(R.string.lockpassword_choose_your_password_header); showBreadCrumbs(msg, msg); } public static class ChooseLockPasswordFragment extends Fragment implements OnClickListener, OnEditorActionListener, TextWatcher { private static final String KEY_FIRST_PIN = "first_pin"; private static final String KEY_UI_STAGE = "ui_stage"; private TextView mPasswordEntry; private int mPasswordMinLength = 4; private int mPasswordMaxLength = 16; private int mPasswordMinLetters = 0; private int mPasswordMinUpperCase = 0; private int mPasswordMinLowerCase = 0; private int mPasswordMinSymbols = 0; private int mPasswordMinNumeric = 0; private int mPasswordMinNonLetter = 0; private LockPatternUtils mLockPatternUtils; private int mRequestedQuality = DevicePolicyManager.PASSWORD_QUALITY_NUMERIC; private ChooseLockSettingsHelper mChooseLockSettingsHelper; private Stage mUiStage = Stage.Introduction; private TextView mHeaderText; private String mFirstPin; private KeyboardView mKeyboardView; private PasswordEntryKeyboardHelper mKeyboardHelper; private boolean mIsAlphaMode; private Button mCancelButton; private Button mNextButton; private static final int CONFIRM_EXISTING_REQUEST = 58; static final int RESULT_FINISHED = RESULT_FIRST_USER; private static final long ERROR_MESSAGE_TIMEOUT = 3000; private static final int MSG_SHOW_ERROR = 1; private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == MSG_SHOW_ERROR) { updateStage((Stage) msg.obj); } } }; /** * Keep track internally of where the user is in choosing a pattern. */ protected enum Stage { Introduction(R.string.lockpassword_choose_your_password_header, R.string.lockpassword_choose_your_pin_header, R.string.lockpassword_continue_label), NeedToConfirm(R.string.lockpassword_confirm_your_password_header, R.string.lockpassword_confirm_your_pin_header, R.string.lockpassword_ok_label), ConfirmWrong(R.string.lockpassword_confirm_passwords_dont_match, R.string.lockpassword_confirm_pins_dont_match, R.string.lockpassword_continue_label); /** * @param headerMessage The message displayed at the top. */ Stage(int hintInAlpha, int hintInNumeric, int nextButtonText) { this.alphaHint = hintInAlpha; this.numericHint = hintInNumeric; this.buttonText = nextButtonText; } public final int alphaHint; public final int numericHint; public final int buttonText; } // required constructor for fragments public ChooseLockPasswordFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mLockPatternUtils = new LockPatternUtils(getActivity()); Intent intent = getActivity().getIntent(); mRequestedQuality = Math.max(intent.getIntExtra(LockPatternUtils.PASSWORD_TYPE_KEY, mRequestedQuality), mLockPatternUtils.getRequestedPasswordQuality()); mPasswordMinLength = Math.max( intent.getIntExtra(PASSWORD_MIN_KEY, mPasswordMinLength), mLockPatternUtils .getRequestedMinimumPasswordLength()); mPasswordMaxLength = intent.getIntExtra(PASSWORD_MAX_KEY, mPasswordMaxLength); mPasswordMinLetters = Math.max(intent.getIntExtra(PASSWORD_MIN_LETTERS_KEY, mPasswordMinLetters), mLockPatternUtils.getRequestedPasswordMinimumLetters()); mPasswordMinUpperCase = Math.max(intent.getIntExtra(PASSWORD_MIN_UPPERCASE_KEY, mPasswordMinUpperCase), mLockPatternUtils.getRequestedPasswordMinimumUpperCase()); mPasswordMinLowerCase = Math.max(intent.getIntExtra(PASSWORD_MIN_LOWERCASE_KEY, mPasswordMinLowerCase), mLockPatternUtils.getRequestedPasswordMinimumLowerCase()); mPasswordMinNumeric = Math.max(intent.getIntExtra(PASSWORD_MIN_NUMERIC_KEY, mPasswordMinNumeric), mLockPatternUtils.getRequestedPasswordMinimumNumeric()); mPasswordMinSymbols = Math.max(intent.getIntExtra(PASSWORD_MIN_SYMBOLS_KEY, mPasswordMinSymbols), mLockPatternUtils.getRequestedPasswordMinimumSymbols()); mPasswordMinNonLetter = Math.max(intent.getIntExtra(PASSWORD_MIN_NONLETTER_KEY, mPasswordMinNonLetter), mLockPatternUtils.getRequestedPasswordMinimumNonLetter()); mChooseLockSettingsHelper = new ChooseLockSettingsHelper(getActivity()); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.choose_lock_password, null); mCancelButton = (Button) view.findViewById(R.id.cancel_button); mCancelButton.setOnClickListener(this); mNextButton = (Button) view.findViewById(R.id.next_button); mNextButton.setOnClickListener(this); mIsAlphaMode = DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC == mRequestedQuality || DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC == mRequestedQuality || DevicePolicyManager.PASSWORD_QUALITY_COMPLEX == mRequestedQuality; mKeyboardView = (PasswordEntryKeyboardView) view.findViewById(R.id.keyboard); mPasswordEntry = (TextView) view.findViewById(R.id.password_entry); mPasswordEntry.setOnEditorActionListener(this); mPasswordEntry.addTextChangedListener(this); final Activity activity = getActivity(); mKeyboardHelper = new PasswordEntryKeyboardHelper(activity, mKeyboardView, mPasswordEntry); mKeyboardHelper.setKeyboardMode(mIsAlphaMode ? PasswordEntryKeyboardHelper.KEYBOARD_MODE_ALPHA : PasswordEntryKeyboardHelper.KEYBOARD_MODE_NUMERIC); mHeaderText = (TextView) view.findViewById(R.id.headerText); mKeyboardView.requestFocus(); int currentType = mPasswordEntry.getInputType(); mPasswordEntry.setInputType(mIsAlphaMode ? currentType : (InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD)); Intent intent = getActivity().getIntent(); final boolean confirmCredentials = intent.getBooleanExtra("confirm_credentials", true); if (savedInstanceState == null) { updateStage(Stage.Introduction); if (confirmCredentials) { mChooseLockSettingsHelper.launchConfirmationActivity(CONFIRM_EXISTING_REQUEST, null, null); } } else { mFirstPin = savedInstanceState.getString(KEY_FIRST_PIN); final String state = savedInstanceState.getString(KEY_UI_STAGE); if (state != null) { mUiStage = Stage.valueOf(state); updateStage(mUiStage); } } // Update the breadcrumb (title) if this is embedded in a PreferenceActivity if (activity instanceof PreferenceActivity) { final PreferenceActivity preferenceActivity = (PreferenceActivity) activity; int id = mIsAlphaMode ? R.string.lockpassword_choose_your_password_header : R.string.lockpassword_choose_your_pin_header; CharSequence title = getText(id); preferenceActivity.showBreadCrumbs(title, title); } return view; } @Override public void onResume() { super.onResume(); updateStage(mUiStage); mKeyboardView.requestFocus(); } @Override public void onPause() { mHandler.removeMessages(MSG_SHOW_ERROR); super.onPause(); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(KEY_UI_STAGE, mUiStage.name()); outState.putString(KEY_FIRST_PIN, mFirstPin); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case CONFIRM_EXISTING_REQUEST: if (resultCode != Activity.RESULT_OK) { getActivity().setResult(RESULT_FINISHED); getActivity().finish(); } break; } } protected void updateStage(Stage stage) { mUiStage = stage; updateUi(); } /** * Validates PIN and returns a message to display if PIN fails test. * @param password the raw password the user typed in * @return error message to show to user or null if password is OK */ private String validatePassword(String password) { if (password.length() < mPasswordMinLength) { return getString(mIsAlphaMode ? R.string.lockpassword_password_too_short : R.string.lockpassword_pin_too_short, mPasswordMinLength); } if (password.length() > mPasswordMaxLength) { return getString(mIsAlphaMode ? R.string.lockpassword_password_too_long : R.string.lockpassword_pin_too_long, mPasswordMaxLength + 1); } int letters = 0; int numbers = 0; int lowercase = 0; int symbols = 0; int uppercase = 0; int nonletter = 0; for (int i = 0; i < password.length(); i++) { char c = password.charAt(i); - // allow non white space Latin-1 characters only - if (c <= 32 || c > 127) { + // allow non control Latin-1 characters only + if (c < 32 || c > 127) { return getString(R.string.lockpassword_illegal_character); } if (c >= '0' && c <= '9') { numbers++; nonletter++; } else if (c >= 'A' && c <= 'Z') { letters++; uppercase++; } else if (c >= 'a' && c <= 'z') { letters++; lowercase++; } else { symbols++; nonletter++; } } if (DevicePolicyManager.PASSWORD_QUALITY_NUMERIC == mRequestedQuality && (letters > 0 || symbols > 0)) { // This shouldn't be possible unless user finds some way to bring up // soft keyboard return getString(R.string.lockpassword_pin_contains_non_digits); } else if (DevicePolicyManager.PASSWORD_QUALITY_COMPLEX == mRequestedQuality) { if (letters < mPasswordMinLetters) { return String.format(getResources().getQuantityString( R.plurals.lockpassword_password_requires_letters, mPasswordMinLetters), mPasswordMinLetters); } else if (numbers < mPasswordMinNumeric) { return String.format(getResources().getQuantityString( R.plurals.lockpassword_password_requires_numeric, mPasswordMinNumeric), mPasswordMinNumeric); } else if (lowercase < mPasswordMinLowerCase) { return String.format(getResources().getQuantityString( R.plurals.lockpassword_password_requires_lowercase, mPasswordMinLowerCase), mPasswordMinLowerCase); } else if (uppercase < mPasswordMinUpperCase) { return String.format(getResources().getQuantityString( R.plurals.lockpassword_password_requires_uppercase, mPasswordMinUpperCase), mPasswordMinUpperCase); } else if (symbols < mPasswordMinSymbols) { return String.format(getResources().getQuantityString( R.plurals.lockpassword_password_requires_symbols, mPasswordMinSymbols), mPasswordMinSymbols); } else if (nonletter < mPasswordMinNonLetter) { return String.format(getResources().getQuantityString( R.plurals.lockpassword_password_requires_nonletter, mPasswordMinNonLetter), mPasswordMinNonLetter); } } else { final boolean alphabetic = DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC == mRequestedQuality; final boolean alphanumeric = DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC == mRequestedQuality; if ((alphabetic || alphanumeric) && letters == 0) { return getString(R.string.lockpassword_password_requires_alpha); } if (alphanumeric && numbers == 0) { return getString(R.string.lockpassword_password_requires_digit); } } if(mLockPatternUtils.checkPasswordHistory(password)) { return getString(mIsAlphaMode ? R.string.lockpassword_password_recently_used : R.string.lockpassword_pin_recently_used); } return null; } private void handleNext() { final String pin = mPasswordEntry.getText().toString(); if (TextUtils.isEmpty(pin)) { return; } String errorMsg = null; if (mUiStage == Stage.Introduction) { errorMsg = validatePassword(pin); if (errorMsg == null) { mFirstPin = pin; updateStage(Stage.NeedToConfirm); mPasswordEntry.setText(""); } } else if (mUiStage == Stage.NeedToConfirm) { if (mFirstPin.equals(pin)) { final boolean isFallback = getActivity().getIntent().getBooleanExtra( LockPatternUtils.LOCKSCREEN_BIOMETRIC_WEAK_FALLBACK, false); mLockPatternUtils.clearLock(isFallback); mLockPatternUtils.saveLockPassword(pin, mRequestedQuality, isFallback); getActivity().finish(); } else { updateStage(Stage.ConfirmWrong); CharSequence tmp = mPasswordEntry.getText(); if (tmp != null) { Selection.setSelection((Spannable) tmp, 0, tmp.length()); } } } if (errorMsg != null) { showError(errorMsg, mUiStage); } } public void onClick(View v) { switch (v.getId()) { case R.id.next_button: handleNext(); break; case R.id.cancel_button: getActivity().finish(); break; } } private void showError(String msg, final Stage next) { mHeaderText.setText(msg); Message mesg = mHandler.obtainMessage(MSG_SHOW_ERROR, next); mHandler.removeMessages(MSG_SHOW_ERROR); mHandler.sendMessageDelayed(mesg, ERROR_MESSAGE_TIMEOUT); } public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { // Check if this was the result of hitting the enter or "done" key if (actionId == EditorInfo.IME_NULL || actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_NEXT) { handleNext(); return true; } return false; } /** * Update the hint based on current Stage and length of password entry */ private void updateUi() { String password = mPasswordEntry.getText().toString(); final int length = password.length(); if (mUiStage == Stage.Introduction && length > 0) { if (length < mPasswordMinLength) { String msg = getString(mIsAlphaMode ? R.string.lockpassword_password_too_short : R.string.lockpassword_pin_too_short, mPasswordMinLength); mHeaderText.setText(msg); mNextButton.setEnabled(false); } else { String error = validatePassword(password); if (error != null) { mHeaderText.setText(error); mNextButton.setEnabled(false); } else { mHeaderText.setText(R.string.lockpassword_press_continue); mNextButton.setEnabled(true); } } } else { mHeaderText.setText(mIsAlphaMode ? mUiStage.alphaHint : mUiStage.numericHint); mNextButton.setEnabled(length > 0); } mNextButton.setText(mUiStage.buttonText); } public void afterTextChanged(Editable s) { // Changing the text while error displayed resets to NeedToConfirm state if (mUiStage == Stage.ConfirmWrong) { mUiStage = Stage.NeedToConfirm; } updateUi(); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { } } }
true
true
private String validatePassword(String password) { if (password.length() < mPasswordMinLength) { return getString(mIsAlphaMode ? R.string.lockpassword_password_too_short : R.string.lockpassword_pin_too_short, mPasswordMinLength); } if (password.length() > mPasswordMaxLength) { return getString(mIsAlphaMode ? R.string.lockpassword_password_too_long : R.string.lockpassword_pin_too_long, mPasswordMaxLength + 1); } int letters = 0; int numbers = 0; int lowercase = 0; int symbols = 0; int uppercase = 0; int nonletter = 0; for (int i = 0; i < password.length(); i++) { char c = password.charAt(i); // allow non white space Latin-1 characters only if (c <= 32 || c > 127) { return getString(R.string.lockpassword_illegal_character); } if (c >= '0' && c <= '9') { numbers++; nonletter++; } else if (c >= 'A' && c <= 'Z') { letters++; uppercase++; } else if (c >= 'a' && c <= 'z') { letters++; lowercase++; } else { symbols++; nonletter++; } } if (DevicePolicyManager.PASSWORD_QUALITY_NUMERIC == mRequestedQuality && (letters > 0 || symbols > 0)) { // This shouldn't be possible unless user finds some way to bring up // soft keyboard return getString(R.string.lockpassword_pin_contains_non_digits); } else if (DevicePolicyManager.PASSWORD_QUALITY_COMPLEX == mRequestedQuality) { if (letters < mPasswordMinLetters) { return String.format(getResources().getQuantityString( R.plurals.lockpassword_password_requires_letters, mPasswordMinLetters), mPasswordMinLetters); } else if (numbers < mPasswordMinNumeric) { return String.format(getResources().getQuantityString( R.plurals.lockpassword_password_requires_numeric, mPasswordMinNumeric), mPasswordMinNumeric); } else if (lowercase < mPasswordMinLowerCase) { return String.format(getResources().getQuantityString( R.plurals.lockpassword_password_requires_lowercase, mPasswordMinLowerCase), mPasswordMinLowerCase); } else if (uppercase < mPasswordMinUpperCase) { return String.format(getResources().getQuantityString( R.plurals.lockpassword_password_requires_uppercase, mPasswordMinUpperCase), mPasswordMinUpperCase); } else if (symbols < mPasswordMinSymbols) { return String.format(getResources().getQuantityString( R.plurals.lockpassword_password_requires_symbols, mPasswordMinSymbols), mPasswordMinSymbols); } else if (nonletter < mPasswordMinNonLetter) { return String.format(getResources().getQuantityString( R.plurals.lockpassword_password_requires_nonletter, mPasswordMinNonLetter), mPasswordMinNonLetter); } } else { final boolean alphabetic = DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC == mRequestedQuality; final boolean alphanumeric = DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC == mRequestedQuality; if ((alphabetic || alphanumeric) && letters == 0) { return getString(R.string.lockpassword_password_requires_alpha); } if (alphanumeric && numbers == 0) { return getString(R.string.lockpassword_password_requires_digit); } } if(mLockPatternUtils.checkPasswordHistory(password)) { return getString(mIsAlphaMode ? R.string.lockpassword_password_recently_used : R.string.lockpassword_pin_recently_used); } return null; }
private String validatePassword(String password) { if (password.length() < mPasswordMinLength) { return getString(mIsAlphaMode ? R.string.lockpassword_password_too_short : R.string.lockpassword_pin_too_short, mPasswordMinLength); } if (password.length() > mPasswordMaxLength) { return getString(mIsAlphaMode ? R.string.lockpassword_password_too_long : R.string.lockpassword_pin_too_long, mPasswordMaxLength + 1); } int letters = 0; int numbers = 0; int lowercase = 0; int symbols = 0; int uppercase = 0; int nonletter = 0; for (int i = 0; i < password.length(); i++) { char c = password.charAt(i); // allow non control Latin-1 characters only if (c < 32 || c > 127) { return getString(R.string.lockpassword_illegal_character); } if (c >= '0' && c <= '9') { numbers++; nonletter++; } else if (c >= 'A' && c <= 'Z') { letters++; uppercase++; } else if (c >= 'a' && c <= 'z') { letters++; lowercase++; } else { symbols++; nonletter++; } } if (DevicePolicyManager.PASSWORD_QUALITY_NUMERIC == mRequestedQuality && (letters > 0 || symbols > 0)) { // This shouldn't be possible unless user finds some way to bring up // soft keyboard return getString(R.string.lockpassword_pin_contains_non_digits); } else if (DevicePolicyManager.PASSWORD_QUALITY_COMPLEX == mRequestedQuality) { if (letters < mPasswordMinLetters) { return String.format(getResources().getQuantityString( R.plurals.lockpassword_password_requires_letters, mPasswordMinLetters), mPasswordMinLetters); } else if (numbers < mPasswordMinNumeric) { return String.format(getResources().getQuantityString( R.plurals.lockpassword_password_requires_numeric, mPasswordMinNumeric), mPasswordMinNumeric); } else if (lowercase < mPasswordMinLowerCase) { return String.format(getResources().getQuantityString( R.plurals.lockpassword_password_requires_lowercase, mPasswordMinLowerCase), mPasswordMinLowerCase); } else if (uppercase < mPasswordMinUpperCase) { return String.format(getResources().getQuantityString( R.plurals.lockpassword_password_requires_uppercase, mPasswordMinUpperCase), mPasswordMinUpperCase); } else if (symbols < mPasswordMinSymbols) { return String.format(getResources().getQuantityString( R.plurals.lockpassword_password_requires_symbols, mPasswordMinSymbols), mPasswordMinSymbols); } else if (nonletter < mPasswordMinNonLetter) { return String.format(getResources().getQuantityString( R.plurals.lockpassword_password_requires_nonletter, mPasswordMinNonLetter), mPasswordMinNonLetter); } } else { final boolean alphabetic = DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC == mRequestedQuality; final boolean alphanumeric = DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC == mRequestedQuality; if ((alphabetic || alphanumeric) && letters == 0) { return getString(R.string.lockpassword_password_requires_alpha); } if (alphanumeric && numbers == 0) { return getString(R.string.lockpassword_password_requires_digit); } } if(mLockPatternUtils.checkPasswordHistory(password)) { return getString(mIsAlphaMode ? R.string.lockpassword_password_recently_used : R.string.lockpassword_pin_recently_used); } return null; }
diff --git a/proxy/src/main/java/net/md_5/bungee/command/CommandAlertRaw.java b/proxy/src/main/java/net/md_5/bungee/command/CommandAlertRaw.java index 39f12ba1..0c9ac0e5 100644 --- a/proxy/src/main/java/net/md_5/bungee/command/CommandAlertRaw.java +++ b/proxy/src/main/java/net/md_5/bungee/command/CommandAlertRaw.java @@ -1,47 +1,47 @@ package net.md_5.bungee.command; import com.google.common.base.Joiner; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.chat.ComponentBuilder; import net.md_5.bungee.api.chat.HoverEvent; import net.md_5.bungee.api.chat.TextComponent; import net.md_5.bungee.api.plugin.Command; import net.md_5.bungee.chat.ComponentSerializer; import java.util.Arrays; public class CommandAlertRaw extends Command { public CommandAlertRaw() { super( "alertraw", "bungeecord.command.alert" ); } @Override public void execute(CommandSender sender, String[] args) { if ( args.length == 0 ) { sender.sendMessage( ChatColor.RED + "You must supply a message." ); } else { String message = Joiner.on(' ').join( args ); try { ProxyServer.getInstance().broadcast( ComponentSerializer.parse( message ) ); } catch ( Exception e ) { sender.sendMessage( - new ComponentBuilder( "An error occured while parsing your message. (Hover for details)" ). + new ComponentBuilder( "An error occurred while parsing your message. (Hover for details)" ). color( ChatColor.RED ).underlined( true ). event( new HoverEvent( HoverEvent.Action.SHOW_TEXT, new ComponentBuilder( e.getMessage() ).color( ChatColor.RED ).create() ) ). create() ); } } } }
true
true
public void execute(CommandSender sender, String[] args) { if ( args.length == 0 ) { sender.sendMessage( ChatColor.RED + "You must supply a message." ); } else { String message = Joiner.on(' ').join( args ); try { ProxyServer.getInstance().broadcast( ComponentSerializer.parse( message ) ); } catch ( Exception e ) { sender.sendMessage( new ComponentBuilder( "An error occured while parsing your message. (Hover for details)" ). color( ChatColor.RED ).underlined( true ). event( new HoverEvent( HoverEvent.Action.SHOW_TEXT, new ComponentBuilder( e.getMessage() ).color( ChatColor.RED ).create() ) ). create() ); } } }
public void execute(CommandSender sender, String[] args) { if ( args.length == 0 ) { sender.sendMessage( ChatColor.RED + "You must supply a message." ); } else { String message = Joiner.on(' ').join( args ); try { ProxyServer.getInstance().broadcast( ComponentSerializer.parse( message ) ); } catch ( Exception e ) { sender.sendMessage( new ComponentBuilder( "An error occurred while parsing your message. (Hover for details)" ). color( ChatColor.RED ).underlined( true ). event( new HoverEvent( HoverEvent.Action.SHOW_TEXT, new ComponentBuilder( e.getMessage() ).color( ChatColor.RED ).create() ) ). create() ); } } }
diff --git a/src/de/ub0r/android/websms/connector/cherrysms/ConnectorCherrySMS.java b/src/de/ub0r/android/websms/connector/cherrysms/ConnectorCherrySMS.java index 79cdf78..fd171a3 100644 --- a/src/de/ub0r/android/websms/connector/cherrysms/ConnectorCherrySMS.java +++ b/src/de/ub0r/android/websms/connector/cherrysms/ConnectorCherrySMS.java @@ -1,229 +1,231 @@ /* * Copyright (C) 2010 Felix Bechstein * * This file is part of WebSMS. * * 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 3 of the License, or (at your option) 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, see <http://www.gnu.org/licenses/>. */ package de.ub0r.android.websms.connector.cherrysms; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URLEncoder; import org.apache.http.HttpResponse; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.util.Log; import de.ub0r.android.websms.connector.common.Connector; import de.ub0r.android.websms.connector.common.ConnectorCommand; import de.ub0r.android.websms.connector.common.ConnectorSpec; import de.ub0r.android.websms.connector.common.Utils; import de.ub0r.android.websms.connector.common.WebSMSException; import de.ub0r.android.websms.connector.common.ConnectorSpec.SubConnectorSpec; /** * AsyncTask to manage IO to cherry-sms.com API. * * @author flx */ public class ConnectorCherrySMS extends Connector { /** Tag for output. */ private static final String TAG = "WebSMS.cherry"; /** {@link SubConnectorSpec} ID: with sender. */ private static final String ID_W_SENDER = "w_sender"; /** {@link SubConnectorSpec} ID: without sender. */ private static final String ID_WO_SENDER = "wo_sender"; /** CherrySMS Gateway URL. */ private static final String URL = "https://gw.cherry-sms.com/"; /** * {@inheritDoc} */ @Override public final ConnectorSpec initSpec(final Context context) { final String name = context .getString(R.string.connector_cherrysms_name); ConnectorSpec c = new ConnectorSpec(TAG, name); c.setAuthor(// . context.getString(R.string.connector_cherrysms_author)); c.setBalance(null); c.setPrefsTitle(context .getString(R.string.connector_cherrysms_preferences)); c.setCapabilities(ConnectorSpec.CAPABILITIES_UPDATE | ConnectorSpec.CAPABILITIES_SEND | ConnectorSpec.CAPABILITIES_PREFS); c.addSubConnector(ID_WO_SENDER, context.getString(R.string.wo_sender), SubConnectorSpec.FEATURE_MULTIRECIPIENTS); c.addSubConnector(ID_W_SENDER, context.getString(R.string.w_sender), SubConnectorSpec.FEATURE_MULTIRECIPIENTS); return c; } /** * {@inheritDoc} */ @Override public final ConnectorSpec updateSpec(final Context context, final ConnectorSpec connectorSpec) { final SharedPreferences p = PreferenceManager .getDefaultSharedPreferences(context); if (p.getBoolean(Preferences.PREFS_ENABLED, false)) { if (p.getString(Preferences.PREFS_PASSWORD, "").length() > 0) { connectorSpec.setReady(); } else { connectorSpec.setStatus(ConnectorSpec.STATUS_ENABLED); } } else { connectorSpec.setStatus(ConnectorSpec.STATUS_INACTIVE); } return connectorSpec; } /** * Check return code from cherry-sms.com. * * @param context * {@link Context} * @param ret * return code * @return true if no error code * @throws WebSMSException * WebSMSException */ private static boolean checkReturnCode(final Context context, final int ret) throws WebSMSException { Log.d(TAG, "ret=" + ret); switch (ret) { case 100: return true; case 10: throw new WebSMSException(context, R.string.error_cherry_10); case 20: throw new WebSMSException(context, R.string.error_cherry_20); case 30: throw new WebSMSException(context, R.string.error_cherry_30); case 31: throw new WebSMSException(context, R.string.error_cherry_31); case 40: throw new WebSMSException(context, R.string.error_cherry_40); case 50: throw new WebSMSException(context, R.string.error_cherry_50); case 60: throw new WebSMSException(context, R.string.error_cherry_60); case 70: throw new WebSMSException(context, R.string.error_cherry_70); case 71: throw new WebSMSException(context, R.string.error_cherry_71); case 80: throw new WebSMSException(context, R.string.error_cherry_80); case 90: throw new WebSMSException(context, R.string.error_cherry_90); default: throw new WebSMSException(context, R.string.error, " code: " + ret); } } /** * Send data. * * @param context * {@link Context} * @param command * {@link ConnectorCommand} * @throws WebSMSException * WebSMSException */ private void sendData(final Context context, final ConnectorCommand command) throws WebSMSException { // do IO try { // get Connection final StringBuilder url = new StringBuilder(URL); final ConnectorSpec cs = this.getSpec(context); final SharedPreferences p = PreferenceManager .getDefaultSharedPreferences(context); url.append("?user="); url.append(Utils.international2oldformat(Utils.getSender(context, command.getDefSender()))); url.append("&password="); url.append(Utils.md5(p.getString(Preferences.PREFS_PASSWORD, ""))); final String text = command.getText(); if (text != null && text.length() > 0) { boolean sendWithSender = false; final String sub = command.getSelectedSubConnector(); if (sub != null && sub.equals(ID_W_SENDER)) { sendWithSender = true; } Log.d(TAG, "send with sender = " + sendWithSender); if (sendWithSender) { url.append("&from=1"); } url.append("&message="); - url.append(URLEncoder.encode(text)); + url.append(URLEncoder.encode(text, "ISO-8859-15")); url.append("&to="); url.append(Utils.joinRecipientsNumbers(command.getRecipients(), ";", true)); } else { url.append("&check=guthaben"); } + Log.d(TAG, "--HTTP GET--"); Log.d(TAG, url.toString()); + Log.d(TAG, "--HTTP GET--"); // send data HttpResponse response = Utils.getHttpClient(url.toString(), null, null, null, null); int resp = response.getStatusLine().getStatusCode(); if (resp != HttpURLConnection.HTTP_OK) { throw new WebSMSException(context, R.string.error_http, "" + resp); } String htmlText = Utils.stream2str( response.getEntity().getContent()).trim(); String[] lines = htmlText.split("\n"); Log.d(TAG, "--HTTP RESPONSE--"); Log.d(TAG, htmlText); Log.d(TAG, "--HTTP RESPONSE--"); htmlText = null; int l = lines.length; cs.setBalance(lines[l - 1].trim()); if (l > 1) { final int ret = Integer.parseInt(lines[0].trim()); checkReturnCode(context, ret); } } catch (IOException e) { Log.e(TAG, null, e); throw new WebSMSException(e.getMessage()); } } /** * {@inheritDoc} */ @Override protected final void doUpdate(final Context context, final Intent intent) throws WebSMSException { this.sendData(context, new ConnectorCommand(intent)); } /** * {@inheritDoc} */ @Override protected final void doSend(final Context context, final Intent intent) throws WebSMSException { this.sendData(context, new ConnectorCommand(intent)); } }
false
true
private void sendData(final Context context, final ConnectorCommand command) throws WebSMSException { // do IO try { // get Connection final StringBuilder url = new StringBuilder(URL); final ConnectorSpec cs = this.getSpec(context); final SharedPreferences p = PreferenceManager .getDefaultSharedPreferences(context); url.append("?user="); url.append(Utils.international2oldformat(Utils.getSender(context, command.getDefSender()))); url.append("&password="); url.append(Utils.md5(p.getString(Preferences.PREFS_PASSWORD, ""))); final String text = command.getText(); if (text != null && text.length() > 0) { boolean sendWithSender = false; final String sub = command.getSelectedSubConnector(); if (sub != null && sub.equals(ID_W_SENDER)) { sendWithSender = true; } Log.d(TAG, "send with sender = " + sendWithSender); if (sendWithSender) { url.append("&from=1"); } url.append("&message="); url.append(URLEncoder.encode(text)); url.append("&to="); url.append(Utils.joinRecipientsNumbers(command.getRecipients(), ";", true)); } else { url.append("&check=guthaben"); } Log.d(TAG, url.toString()); // send data HttpResponse response = Utils.getHttpClient(url.toString(), null, null, null, null); int resp = response.getStatusLine().getStatusCode(); if (resp != HttpURLConnection.HTTP_OK) { throw new WebSMSException(context, R.string.error_http, "" + resp); } String htmlText = Utils.stream2str( response.getEntity().getContent()).trim(); String[] lines = htmlText.split("\n"); Log.d(TAG, "--HTTP RESPONSE--"); Log.d(TAG, htmlText); Log.d(TAG, "--HTTP RESPONSE--"); htmlText = null; int l = lines.length; cs.setBalance(lines[l - 1].trim()); if (l > 1) { final int ret = Integer.parseInt(lines[0].trim()); checkReturnCode(context, ret); } } catch (IOException e) { Log.e(TAG, null, e); throw new WebSMSException(e.getMessage()); } }
private void sendData(final Context context, final ConnectorCommand command) throws WebSMSException { // do IO try { // get Connection final StringBuilder url = new StringBuilder(URL); final ConnectorSpec cs = this.getSpec(context); final SharedPreferences p = PreferenceManager .getDefaultSharedPreferences(context); url.append("?user="); url.append(Utils.international2oldformat(Utils.getSender(context, command.getDefSender()))); url.append("&password="); url.append(Utils.md5(p.getString(Preferences.PREFS_PASSWORD, ""))); final String text = command.getText(); if (text != null && text.length() > 0) { boolean sendWithSender = false; final String sub = command.getSelectedSubConnector(); if (sub != null && sub.equals(ID_W_SENDER)) { sendWithSender = true; } Log.d(TAG, "send with sender = " + sendWithSender); if (sendWithSender) { url.append("&from=1"); } url.append("&message="); url.append(URLEncoder.encode(text, "ISO-8859-15")); url.append("&to="); url.append(Utils.joinRecipientsNumbers(command.getRecipients(), ";", true)); } else { url.append("&check=guthaben"); } Log.d(TAG, "--HTTP GET--"); Log.d(TAG, url.toString()); Log.d(TAG, "--HTTP GET--"); // send data HttpResponse response = Utils.getHttpClient(url.toString(), null, null, null, null); int resp = response.getStatusLine().getStatusCode(); if (resp != HttpURLConnection.HTTP_OK) { throw new WebSMSException(context, R.string.error_http, "" + resp); } String htmlText = Utils.stream2str( response.getEntity().getContent()).trim(); String[] lines = htmlText.split("\n"); Log.d(TAG, "--HTTP RESPONSE--"); Log.d(TAG, htmlText); Log.d(TAG, "--HTTP RESPONSE--"); htmlText = null; int l = lines.length; cs.setBalance(lines[l - 1].trim()); if (l > 1) { final int ret = Integer.parseInt(lines[0].trim()); checkReturnCode(context, ret); } } catch (IOException e) { Log.e(TAG, null, e); throw new WebSMSException(e.getMessage()); } }
diff --git a/seedboxer-web/src/main/java/net/seedboxer/web/controller/rs/TorrentsAPI.java b/seedboxer-web/src/main/java/net/seedboxer/web/controller/rs/TorrentsAPI.java index d145250..f6a6cba 100644 --- a/seedboxer-web/src/main/java/net/seedboxer/web/controller/rs/TorrentsAPI.java +++ b/seedboxer-web/src/main/java/net/seedboxer/web/controller/rs/TorrentsAPI.java @@ -1,65 +1,66 @@ /******************************************************************************* * TorrentsAPI.java * * Copyright (c) 2012 SeedBoxer Team. * * This file is part of SeedBoxer. * * SeedBoxer 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 3 of the License, or * (at your option) any later version. * * SeedBoxer 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 SeedBoxer. If not, see <http ://www.gnu.org/licenses/>. ******************************************************************************/ package net.seedboxer.web.controller.rs; import net.seedboxer.web.service.DownloadsService; import net.seedboxer.web.type.api.APIResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; /** * WebService that expose method to work with torrent files * @author Jorge Davison (jdavisonc) * */ @Controller @RequestMapping("/webservices/torrents") public class TorrentsAPI extends SeedBoxerAPI { private static final Logger LOGGER = LoggerFactory.getLogger(TorrentsAPI.class); @Autowired private DownloadsService controller; @RequestMapping(value="add", method = RequestMethod.POST) public @ResponseBody APIResponse addTorrent(@RequestPart("file") MultipartFile file) { try { - if (file.getName().endsWith(".torrent")) { - controller.addTorrent(getUser(), file.getName(), file.getInputStream()); + String filename = file.getOriginalFilename(); + if (filename.endsWith(".torrent")) { + controller.addTorrent(getUser(), filename, file.getInputStream()); return APIResponse.createSuccessfulResponse(); } else { return APIResponse.createErrorResponse("Wrong file type, only accept .torrent files"); } } catch (Exception e) { LOGGER.error("Can not read list of downloads", e); return APIResponse.createErrorResponse("Can not put to download"); } } }
true
true
public @ResponseBody APIResponse addTorrent(@RequestPart("file") MultipartFile file) { try { if (file.getName().endsWith(".torrent")) { controller.addTorrent(getUser(), file.getName(), file.getInputStream()); return APIResponse.createSuccessfulResponse(); } else { return APIResponse.createErrorResponse("Wrong file type, only accept .torrent files"); } } catch (Exception e) { LOGGER.error("Can not read list of downloads", e); return APIResponse.createErrorResponse("Can not put to download"); } }
public @ResponseBody APIResponse addTorrent(@RequestPart("file") MultipartFile file) { try { String filename = file.getOriginalFilename(); if (filename.endsWith(".torrent")) { controller.addTorrent(getUser(), filename, file.getInputStream()); return APIResponse.createSuccessfulResponse(); } else { return APIResponse.createErrorResponse("Wrong file type, only accept .torrent files"); } } catch (Exception e) { LOGGER.error("Can not read list of downloads", e); return APIResponse.createErrorResponse("Can not put to download"); } }
diff --git a/svnkit/src/org/tmatesoft/svn/core/wc/SVNCopyClient.java b/svnkit/src/org/tmatesoft/svn/core/wc/SVNCopyClient.java index a55f064f7..26cb7e5bc 100644 --- a/svnkit/src/org/tmatesoft/svn/core/wc/SVNCopyClient.java +++ b/svnkit/src/org/tmatesoft/svn/core/wc/SVNCopyClient.java @@ -1,1615 +1,1618 @@ /* * ==================================================================== * Copyright (c) 2004-2007 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.wc; import java.io.File; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collection; import org.tmatesoft.svn.core.internal.util.SVNHashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.tmatesoft.svn.core.SVNCancelException; import org.tmatesoft.svn.core.SVNCommitInfo; import org.tmatesoft.svn.core.SVNDepth; import org.tmatesoft.svn.core.SVNDirEntry; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNMergeInfoInheritance; import org.tmatesoft.svn.core.SVNNodeKind; import org.tmatesoft.svn.core.SVNProperty; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.SVNProperties; import org.tmatesoft.svn.core.SVNPropertyValue; import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager; import org.tmatesoft.svn.core.internal.util.SVNEncodingUtil; import org.tmatesoft.svn.core.internal.util.SVNMergeInfoUtil; import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import org.tmatesoft.svn.core.internal.wc.ISVNCommitPathHandler; import org.tmatesoft.svn.core.internal.wc.SVNAdminUtil; import org.tmatesoft.svn.core.internal.wc.SVNCancellableOutputStream; import org.tmatesoft.svn.core.internal.wc.SVNCommitMediator; import org.tmatesoft.svn.core.internal.wc.SVNCommitUtil; import org.tmatesoft.svn.core.internal.wc.SVNCommitter; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNEventFactory; import org.tmatesoft.svn.core.internal.wc.SVNFileListUtil; import org.tmatesoft.svn.core.internal.wc.SVNFileType; import org.tmatesoft.svn.core.internal.wc.SVNFileUtil; import org.tmatesoft.svn.core.internal.wc.SVNPath; import org.tmatesoft.svn.core.internal.wc.SVNPropertiesManager; import org.tmatesoft.svn.core.internal.wc.SVNWCManager; import org.tmatesoft.svn.core.internal.wc.admin.SVNAdminArea; import org.tmatesoft.svn.core.internal.wc.admin.SVNEntry; import org.tmatesoft.svn.core.internal.wc.admin.SVNVersionedProperties; import org.tmatesoft.svn.core.internal.wc.admin.SVNWCAccess; import org.tmatesoft.svn.core.io.ISVNEditor; import org.tmatesoft.svn.core.io.SVNLocationEntry; import org.tmatesoft.svn.core.io.SVNRepository; import org.tmatesoft.svn.util.SVNDebugLog; /** * The <b>SVNCopyClient</b> provides methods to perform any kinds of copying and moving that SVN * supports - operating on both Working Copies (WC) and URLs. * * <p> * Copy operations allow a user to copy versioned files and directories with all their * previous history in several ways. * * <p> * Supported copy operations are: * <ul> * <li> Working Copy to Working Copy (WC-to-WC) copying - this operation copies the source * Working Copy item to the destination one and schedules the source copy for addition with history. * <li> Working Copy to URL (WC-to-URL) copying - this operation commits to the repository (exactly * to that repository location that is specified by URL) a copy of the Working Copy item. * <li> URL to Working Copy (URL-to-WC) copying - this operation will copy the source item from * the repository to the Working Copy item and schedule the source copy for addition with history. * <li> URL to URL (URL-to-URL) copying - this is a fully repository-side operation, it commits * a copy of the source item to a specified repository location (within the same repository, of * course). * </ul> * * <p> * Besides just copying <b>SVNCopyClient</b> also is able to move a versioned item - that is * first making a copy of the source item and then scheduling the source item for deletion * when operating on a Working Copy, or right committing the deletion of the source item when * operating immediately on the repository. * * <p> * Supported move operations are: * <ul> * <li> Working Copy to Working Copy (WC-to-WC) moving - this operation copies the source * Working Copy item to the destination one and schedules the source item for deletion. * <li> URL to URL (URL-to-URL) moving - this is a fully repository-side operation, it commits * a copy of the source item to a specified repository location and deletes the source item. * </ul> * * <p> * Overloaded <b>doCopy()</b> methods of <b>SVNCopyClient</b> are similar to * <code>'svn copy'</code> and <code>'svn move'</code> commands of the SVN command line client. * * @version 1.1.1 * @author TMate Software Ltd. * @see <a target="_top" href="http://svnkit.com/kb/examples/">Examples</a> * */ public class SVNCopyClient extends SVNBasicClient { private ISVNCommitHandler myCommitHandler; private ISVNCommitParameters myCommitParameters; /** * Constructs and initializes an <b>SVNCopyClient</b> object * with the specified run-time configuration and authentication * drivers. * * <p> * If <code>options</code> is <span class="javakeyword">null</span>, * then this <b>SVNCopyClient</b> will be using a default run-time * configuration driver which takes client-side settings from the * default SVN's run-time configuration area but is not able to * change those settings (read more on {@link ISVNOptions} and {@link SVNWCUtil}). * * <p> * If <code>authManager</code> is <span class="javakeyword">null</span>, * then this <b>SVNCopyClient</b> will be using a default authentication * and network layers driver (see {@link SVNWCUtil#createDefaultAuthenticationManager()}) * which uses server-side settings and auth storage from the * default SVN's run-time configuration area (or system properties * if that area is not found). * * @param authManager an authentication and network layers driver * @param options a run-time configuration options driver */ public SVNCopyClient(ISVNAuthenticationManager authManager, ISVNOptions options) { super(authManager, options); } public SVNCopyClient(ISVNRepositoryPool repositoryPool, ISVNOptions options) { super(repositoryPool, options); } /** * Sets an implementation of <b>ISVNCommitHandler</b> to * the commit handler that will be used during commit operations to handle * commit log messages. The handler will receive a clien's log message and items * (represented as <b>SVNCommitItem</b> objects) that will be * committed. Depending on implementor's aims the initial log message can * be modified (or something else) and returned back. * * <p> * If using <b>SVNCopyClient</b> without specifying any * commit handler then a default one will be used - {@link DefaultSVNCommitHandler}. * * @param handler an implementor's handler that will be used to handle * commit log messages * @see #getCommitHandler() * @see SVNCommitItem */ public void setCommitHandler(ISVNCommitHandler handler) { myCommitHandler = handler; } /** * Returns the specified commit handler (if set) being in use or a default one * (<b>DefaultSVNCommitHandler</b>) if no special * implementations of <b>ISVNCommitHandler</b> were * previousely provided. * * @return the commit handler being in use or a default one * @see #setCommitHandler(ISVNCommitHandler) * @see DefaultSVNCommitHandler */ public ISVNCommitHandler getCommitHandler() { if (myCommitHandler == null) { myCommitHandler = new DefaultSVNCommitHandler(); } return myCommitHandler; } /** * Sets commit parameters to use. * * <p> * When no parameters are set {@link DefaultSVNCommitParameters default} * ones are used. * * @param parameters commit parameters * @see #getCommitParameters() */ public void setCommitParameters(ISVNCommitParameters parameters) { myCommitParameters = parameters; } /** * Returns commit parameters. * * <p> * If no user parameters were previously specified, once creates and * returns {@link DefaultSVNCommitParameters default} ones. * * @return commit parameters * @see #setCommitParameters(ISVNCommitParameters) */ public ISVNCommitParameters getCommitParameters() { if (myCommitParameters == null) { myCommitParameters = new DefaultSVNCommitParameters(); } return myCommitParameters; } public void doCopy(SVNCopySource[] sources, File dst, boolean isMove, boolean makeParents, boolean failWhenDstExists) throws SVNException { if (sources.length > 1 && failWhenDstExists) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CLIENT_MULTIPLE_SOURCES_DISALLOWED); SVNErrorManager.error(err); } sources = expandCopySources(sources); if (sources.length == 0) { return; } try { setupCopy(sources, new SVNPath(dst.getAbsolutePath()), isMove, makeParents, null, null); } catch (SVNException e) { SVNErrorCode err = e.getErrorMessage().getErrorCode(); if (!failWhenDstExists && sources.length == 1 && (err == SVNErrorCode.ENTRY_EXISTS || err == SVNErrorCode.FS_ALREADY_EXISTS)) { SVNCopySource source = sources[0]; String baseName = source.getName(); if (source.isURL()) { baseName = SVNEncodingUtil.uriDecode(baseName); } try { setupCopy(sources, new SVNPath(new File(dst, baseName).getAbsolutePath()), isMove, makeParents, null, null); } catch (SVNException second) { throw second; } return; } throw e; } } public SVNCommitInfo doCopy(SVNCopySource[] sources, SVNURL dst, boolean isMove, boolean makeParents, boolean failWhenDstExists, String commitMessage, SVNProperties revisionProperties) throws SVNException { if (sources.length > 1 && failWhenDstExists) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CLIENT_MULTIPLE_SOURCES_DISALLOWED); SVNErrorManager.error(err); } sources = expandCopySources(sources); if (sources.length == 0) { return SVNCommitInfo.NULL; } try { return setupCopy(sources, new SVNPath(dst.toString()), isMove, makeParents, commitMessage, revisionProperties); } catch (SVNException e) { SVNErrorCode err = e.getErrorMessage().getErrorCode(); if (!failWhenDstExists && sources.length == 1 && (err == SVNErrorCode.ENTRY_EXISTS || err == SVNErrorCode.FS_ALREADY_EXISTS)) { SVNCopySource source = sources[0]; String baseName = source.getName(); if (!source.isURL()) { baseName = SVNEncodingUtil.uriEncode(baseName); } try { return setupCopy(sources, new SVNPath(dst.appendPath(baseName, true).toString()), isMove, makeParents, commitMessage, revisionProperties); } catch (SVNException second) { throw second; } } throw e; } } private SVNCopySource[] expandCopySources(SVNCopySource[] sources) throws SVNException { Collection expanded = new ArrayList(sources.length); for (int i = 0; i < sources.length; i++) { SVNCopySource source = sources[i]; if (source.isCopyContents() && source.isURL()) { // get children at revision. SVNRevision pegRevision = source.getPegRevision(); if (!pegRevision.isValid()) { pegRevision = SVNRevision.HEAD; } SVNRevision startRevision = source.getRevision(); if (!startRevision.isValid()) { startRevision = pegRevision; } SVNRepositoryLocation[] locations = getLocations(source.getURL(), null, null, pegRevision, startRevision, SVNRevision.UNDEFINED); SVNRepository repository = createRepository(locations[0].getURL(), null, null, true); long revision = locations[0].getRevisionNumber(); Collection entries = new ArrayList(); repository.getDir("", revision, null, 0, entries); for (Iterator ents = entries.iterator(); ents.hasNext();) { SVNDirEntry entry = (SVNDirEntry) ents.next(); // add new copy source. expanded.add(new SVNCopySource(SVNRevision.UNDEFINED, source.getRevision(), entry.getURL())); } } else { expanded.add(source); } } return (SVNCopySource[]) expanded.toArray(new SVNCopySource[expanded.size()]); } private String getUUIDFromPath(SVNWCAccess wcAccess, File path) throws SVNException { SVNEntry entry = wcAccess.getVersionedEntry(path, true); String uuid = null; if (entry.getUUID() != null) { uuid = entry.getUUID(); } else if (entry.getURL() != null) { SVNRepository repos = createRepository(entry.getSVNURL(), null, null, false); try { uuid = repos.getRepositoryUUID(true); } finally { repos.closeSession(); } } else { if (wcAccess.isWCRoot(path)) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ENTRY_MISSING_URL, "''{0}'' has no URL", path); SVNErrorManager.error(err); } uuid = getUUIDFromPath(wcAccess, path.getParentFile()); } return uuid; } private static void postCopyCleanup(SVNAdminArea dir) throws SVNException { SVNPropertiesManager.deleteWCProperties(dir, null, false); SVNFileUtil.setHidden(dir.getAdminDirectory(), true); Map attributes = new SVNHashMap(); boolean save = false; for(Iterator entries = dir.entries(true); entries.hasNext();) { SVNEntry entry = (SVNEntry) entries.next(); boolean deleted = entry.isDeleted(); SVNNodeKind kind = entry.getKind(); boolean force = false; if (entry.isDeleted()) { force = true; attributes.put(SVNProperty.SCHEDULE, SVNProperty.SCHEDULE_DELETE); attributes.put(SVNProperty.DELETED, null); if (entry.isDirectory()) { attributes.put(SVNProperty.KIND, SVNProperty.KIND_FILE); } } if (entry.getLockToken() != null) { force = true; attributes.put(SVNProperty.LOCK_TOKEN, null); attributes.put(SVNProperty.LOCK_OWNER, null); attributes.put(SVNProperty.LOCK_CREATION_DATE, null); } if (force) { dir.modifyEntry(entry.getName(), attributes, false, force); save = true; } if (!deleted && kind == SVNNodeKind.DIR && !dir.getThisDirName().equals(entry.getName())) { SVNAdminArea childDir = dir.getWCAccess().retrieve(dir.getFile(entry.getName())); postCopyCleanup(childDir); } attributes.clear(); } if (save) { dir.saveEntries(false); } } private SVNCommitInfo setupCopy(SVNCopySource[] sources, SVNPath dst, boolean isMove, boolean makeParents, String message, SVNProperties revprops) throws SVNException { List pairs = new ArrayList(sources.length); for (int i = 0; i < sources.length; i++) { SVNCopySource source = sources[i]; if (source.isURL() && (source.getPegRevision() == SVNRevision.BASE || source.getPegRevision() == SVNRevision.COMMITTED || source.getPegRevision() == SVNRevision.PREVIOUS)) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CLIENT_BAD_REVISION, "Revision type requires a working copy path, not URL"); SVNErrorManager.error(err); } } boolean srcIsURL = sources[0].isURL(); boolean dstIsURL = dst.isURL(); if (sources.length > 1) { for (int i = 0; i < sources.length; i++) { SVNCopySource source = sources[i]; CopyPair pair = new CopyPair(); pair.mySource = source.isURL() ? source.getURL().toString() : source.getFile().getAbsolutePath().replace(File.separatorChar, '/'); pair.setSourceRevisions(source.getPegRevision(), source.getRevision()); if (SVNPathUtil.isURL(pair.mySource) != srcIsURL) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE, "Cannot mix repository and working copy sources"); SVNErrorManager.error(err); } String baseName = source.getName(); if (srcIsURL && !dstIsURL) { baseName = SVNEncodingUtil.uriDecode(baseName); } pair.myDst = dstIsURL ? dst.getURL().appendPath(baseName, true).toString() : new File(dst.getFile(), baseName).getAbsolutePath().replace(File.separatorChar, '/'); pairs.add(pair); } } else { SVNCopySource source = sources[0]; CopyPair pair = new CopyPair(); pair.mySource = source.isURL() ? source.getURL().toString() : source.getFile().getAbsolutePath().replace(File.separatorChar, '/'); pair.setSourceRevisions(source.getPegRevision(), source.getRevision()); pair.myDst = dstIsURL ? dst.getURL().toString() : dst.getFile().getAbsolutePath().replace(File.separatorChar, '/'); pairs.add(pair); } if (!srcIsURL && !dstIsURL) { for (Iterator ps = pairs.iterator(); ps.hasNext();) { CopyPair pair = (CopyPair) ps.next(); String srcPath = pair.mySource; String dstPath = pair.myDst; if (SVNPathUtil.isAncestor(srcPath, dstPath)) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE, "Cannot copy path ''{0}'' into its own child ''{1}", new Object[] {srcPath, dstPath}); SVNErrorManager.error(err); } } } if (isMove) { if (srcIsURL == dstIsURL) { for (Iterator ps = pairs.iterator(); ps.hasNext();) { CopyPair pair = (CopyPair) ps.next(); File srcPath = new File(pair.mySource); File dstPath = new File(pair.myDst); if (srcPath.equals(dstPath)) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE, "Cannot move path ''{0}'' into itself", srcPath); SVNErrorManager.error(err); } } } else { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE, "Moves between the working copy and the repository are not supported"); SVNErrorManager.error(err); } } else { if (!srcIsURL) { boolean needReposRevision = false; boolean needReposPegRevision = false; for (Iterator ps = pairs.iterator(); ps.hasNext();) { CopyPair pair = (CopyPair) ps.next(); if (pair.mySourceRevision != SVNRevision.UNDEFINED && pair.mySourceRevision != SVNRevision.WORKING) { needReposRevision = true; } if (pair.mySourcePegRevision != SVNRevision.UNDEFINED && pair.mySourcePegRevision != SVNRevision.WORKING) { needReposPegRevision = true; } if (needReposRevision || needReposPegRevision) { break; } } if (needReposRevision || needReposPegRevision) { for (Iterator ps = pairs.iterator(); ps.hasNext();) { CopyPair pair = (CopyPair) ps.next(); SVNWCAccess wcAccess = createWCAccess(); try { wcAccess.probeOpen(new File(pair.mySource), false, 0); SVNEntry entry = wcAccess.getEntry(new File(pair.mySource), false); SVNURL url = entry.isCopied() ? entry.getCopyFromSVNURL() : entry.getSVNURL(); if (url == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ENTRY_MISSING_URL, "''{0}'' does not have a URL associated with it", new File(pair.mySource)); SVNErrorManager.error(err); } pair.mySource = url.toString(); if (!needReposPegRevision || pair.mySourcePegRevision == SVNRevision.BASE) { pair.mySourcePegRevision = entry.isCopied() ? SVNRevision.create(entry.getCopyFromRevision()) : SVNRevision.create(entry.getRevision()); } if (pair.mySourceRevision == SVNRevision.BASE) { pair.mySourceRevision = entry.isCopied() ? SVNRevision.create(entry.getCopyFromRevision()) : SVNRevision.create(entry.getRevision()); } } finally { wcAccess.close(); } } srcIsURL = true; } } } if (!srcIsURL && !dstIsURL) { copyWCToWC(pairs, isMove, makeParents); return SVNCommitInfo.NULL; } else if (!srcIsURL && dstIsURL) { //wc2url. return copyWCToRepos(pairs, makeParents, message, revprops); } else if (srcIsURL && !dstIsURL) { // url2wc. copyReposToWC(pairs, makeParents); return SVNCommitInfo.NULL; } else { return copyReposToRepos(pairs, makeParents, isMove, message, revprops); } } private SVNCommitInfo copyWCToRepos(List copyPairs, boolean makeParents, String message, SVNProperties revprops) throws SVNException { String topSrc = ((CopyPair) copyPairs.get(0)).mySource; for (int i = 1; i < copyPairs.size(); i++) { CopyPair pair = (CopyPair) copyPairs.get(i); topSrc = SVNPathUtil.getCommonPathAncestor(topSrc, pair.mySource); } SVNWCAccess wcAccess = createWCAccess(); SVNCommitInfo info = null; ISVNEditor commitEditor = null; Collection tmpFiles = null; try { SVNAdminArea adminArea = wcAccess.probeOpen(new File(topSrc), false, -1); wcAccess.setAnchor(adminArea.getRoot()); String topDstURL = ((CopyPair) copyPairs.get(0)).myDst; topDstURL = SVNPathUtil.removeTail(topDstURL); for (int i = 1; i < copyPairs.size(); i++) { CopyPair pair = (CopyPair) copyPairs.get(i); topDstURL = SVNPathUtil.getCommonPathAncestor(topDstURL, pair.myDst); } // should we use also wcAccess here? i do not think so. SVNRepository repos = createRepository(SVNURL.parseURIEncoded(topDstURL), adminArea.getRoot(), wcAccess, true); List newDirs = new ArrayList(); if (makeParents) { String rootURL = topDstURL; SVNNodeKind kind = repos.checkPath("", -1); while(kind == SVNNodeKind.NONE) { newDirs.add(rootURL); rootURL = SVNPathUtil.removeTail(rootURL); repos.setLocation(SVNURL.parseURIEncoded(rootURL), false); kind = repos.checkPath("", -1); } topDstURL = rootURL; } for (int i = 0; i < copyPairs.size(); i++) { CopyPair pair = (CopyPair) copyPairs.get(i); SVNEntry entry = wcAccess.getEntry(new File(pair.mySource), false); pair.mySourceRevisionNumber = entry.getRevision(); String dstRelativePath = SVNPathUtil.getPathAsChild(topDstURL, pair.myDst); dstRelativePath = SVNEncodingUtil.uriDecode(dstRelativePath); SVNNodeKind kind = repos.checkPath(dstRelativePath, -1); if (kind != SVNNodeKind.NONE) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.FS_ALREADY_EXISTS, "Path ''{0}'' already exists", SVNURL.parseURIEncoded(pair.myDst)); SVNErrorManager.error(err); } } // create commit items list to fetch log messages. List commitItems = new ArrayList(copyPairs.size()); if (makeParents) { for (int i = 0; i < newDirs.size(); i++) { String newDirURL = (String) newDirs.get(i); SVNURL url = SVNURL.parseURIEncoded(newDirURL); SVNCommitItem item = new SVNCommitItem(null, url, null, null, null, null, true, false, false, false, false, false); commitItems.add(item); } } for (int i = 0; i < copyPairs.size(); i++) { CopyPair pair = (CopyPair) copyPairs.get(i); SVNURL url = SVNURL.parseURIEncoded(pair.myDst); SVNCommitItem item = new SVNCommitItem(null, url, null, null, null, null, true, false, false, false, false, false); commitItems.add(item); } SVNCommitItem[] commitables = (SVNCommitItem[]) commitItems.toArray(new SVNCommitItem[commitItems.size()]); message = getCommitHandler().getCommitMessage(message, commitables); if (message == null) { return SVNCommitInfo.NULL; } revprops = getCommitHandler().getRevisionProperties(message, commitables, revprops == null ? new SVNProperties() : revprops); if (revprops == null) { return SVNCommitInfo.NULL; } Map allCommitables = new TreeMap(); repos.setLocation(repos.getRepositoryRoot(true), false); for (int i = 0; i < copyPairs.size(); i++) { CopyPair source = (CopyPair) copyPairs.get(i); File srcFile = new File(source.mySource); SVNEntry entry = wcAccess.getVersionedEntry(srcFile, false); SVNAdminArea dirArea = null; if (entry.isDirectory()) { dirArea = wcAccess.retrieve(srcFile); } else { dirArea = wcAccess.retrieve(srcFile.getParentFile()); } SVNCommitUtil.harvestCommitables(allCommitables, dirArea, srcFile, null, entry, source.myDst, entry.getURL(), true, false, false, null, SVNDepth.INFINITY, false, null, getCommitParameters()); SVNCommitItem item = (SVNCommitItem) allCommitables.get(srcFile); SVNURL srcURL = entry.getSVNURL(); Map mergeInfo = calculateTargetMergeInfo(new File(source.mySource), wcAccess, srcURL, source.mySourceRevisionNumber, repos, false); Map wcMergeInfo = SVNPropertiesManager.parseMergeInfo(new File(source.mySource), entry, false); if (wcMergeInfo != null && mergeInfo != null) { mergeInfo = SVNMergeInfoUtil.mergeMergeInfos(mergeInfo, wcMergeInfo); } else if (mergeInfo == null) { mergeInfo = wcMergeInfo; } if (mergeInfo != null) { String mergeInfoString = SVNMergeInfoUtil.formatMergeInfoToString(mergeInfo); item.setMergeInfoProp(mergeInfoString); } } commitItems = new ArrayList(allCommitables.values()); // add parents to commits hash? if (makeParents) { for (int i = 0; i < newDirs.size(); i++) { String newDirURL = (String) newDirs.get(i); SVNURL url = SVNURL.parseURIEncoded(newDirURL); SVNCommitItem item = new SVNCommitItem(null, url, null, null, null, null, true, false, false, false, false, false); commitItems.add(item); } } commitables = (SVNCommitItem[]) commitItems.toArray(new SVNCommitItem[commitItems.size()]); for (int i = 0; i < commitables.length; i++) { commitables[i].setWCAccess(wcAccess); } allCommitables.clear(); SVNURL url = SVNCommitUtil.translateCommitables(commitables, allCommitables); repos = createRepository(url, null, null, true); SVNCommitMediator mediator = new SVNCommitMediator(allCommitables); tmpFiles = mediator.getTmpFiles(); message = SVNCommitClient.validateCommitMessage(message); SVNURL rootURL = repos.getRepositoryRoot(true); commitEditor = repos.getCommitEditor(message, null, true, revprops, mediator); info = SVNCommitter.commit(tmpFiles, allCommitables, rootURL.getPath(), commitEditor); commitEditor = null; } catch (SVNCancelException cancel) { throw cancel; } catch (SVNException e) { // wrap error message. SVNErrorMessage err = e.getErrorMessage().wrap("Commit failed (details follow):"); SVNErrorManager.error(err); } finally { if (tmpFiles != null) { for (Iterator files = tmpFiles.iterator(); files.hasNext();) { File file = (File) files.next(); SVNFileUtil.deleteFile(file); } } if (commitEditor != null && info == null) { // should we hide this exception? try { commitEditor.abortEdit(); } catch (SVNException e) { SVNDebugLog.getDefaultLog().info(e); } } if (wcAccess != null) { wcAccess.close(); } } if (info != null && info.getNewRevision() >= 0) { dispatchEvent(SVNEventFactory.createSVNEvent(null, SVNNodeKind.NONE, null, info.getNewRevision(), SVNEventAction.COMMIT_COMPLETED, null, null, null), ISVNEventHandler.UNKNOWN); } return info != null ? info : SVNCommitInfo.NULL; } private SVNCommitInfo copyReposToRepos(List copyPairs, boolean makeParents, boolean isMove, String message, SVNProperties revprops) throws SVNException { List pathInfos = new ArrayList(); Map pathsMap = new SVNHashMap(); for (int i = 0; i < copyPairs.size(); i++) { CopyPathInfo info = new CopyPathInfo(); pathInfos.add(info); } String topURL = ((CopyPair) copyPairs.get(0)).mySource; String topDstURL = ((CopyPair) copyPairs.get(0)).myDst; for (int i = 1; i < copyPairs.size(); i++) { CopyPair pair = (CopyPair) copyPairs.get(i); topURL = SVNPathUtil.getCommonPathAncestor(topURL, pair.mySource); } if (copyPairs.size() == 1) { topURL = SVNPathUtil.getCommonPathAncestor(topURL, topDstURL); } else { topURL = SVNPathUtil.getCommonPathAncestor(topURL, SVNPathUtil.removeTail(topDstURL)); } try { SVNURL.parseURIEncoded(topURL); } catch (SVNException e) { topURL = null; } if (topURL == null) { SVNURL url1 = SVNURL.parseURIEncoded(((CopyPair) copyPairs.get(0)).mySource); SVNURL url2 = SVNURL.parseURIEncoded(((CopyPair) copyPairs.get(0)).myDst); SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE, "Source and dest appear not to be in the same repository (src: ''{0}''; dst: ''{1}'')", new Object[] {url1, url2}); SVNErrorManager.error(err); } for (int i = 0; i < copyPairs.size(); i++) { CopyPair pair = (CopyPair) copyPairs.get(i); CopyPathInfo info = (CopyPathInfo) pathInfos.get(i); if (pair.mySource.equals(pair.myDst)) { info.isResurrection = true; if (topURL.equals(pair.mySource)) { topURL = SVNPathUtil.removeTail(topURL); } } } SVNRepository topRepos = createRepository(SVNURL.parseURIEncoded(topURL), null, null, true); List newDirs = new ArrayList(); if (makeParents) { CopyPair pair = (CopyPair) copyPairs.get(0); String relativeDir = SVNPathUtil.getPathAsChild(topURL, SVNPathUtil.removeTail(pair.myDst)); + if (relativeDir == null) { + relativeDir = ""; + } relativeDir = SVNEncodingUtil.uriDecode(relativeDir); SVNNodeKind kind = topRepos.checkPath(relativeDir, -1); while(kind == SVNNodeKind.NONE) { newDirs.add(relativeDir); relativeDir = SVNPathUtil.removeTail(relativeDir); kind = topRepos.checkPath(relativeDir, -1); } } String rootURL = topRepos.getRepositoryRoot(true).toString(); for (int i = 0; i < copyPairs.size(); i++) { CopyPair pair = (CopyPair) copyPairs.get(i); CopyPathInfo info = (CopyPathInfo) pathInfos.get(i); if (!pair.myDst.equals(rootURL) && SVNPathUtil.getPathAsChild(pair.myDst, pair.mySource) != null) { info.isResurrection = true; // TODO still looks like a bug. // if (SVNPathUtil.removeTail(pair.myDst).equals(topURL)) { topURL = SVNPathUtil.removeTail(topURL); // } } } topRepos.setLocation(SVNURL.parseURIEncoded(topURL), false); long latestRevision = topRepos.getLatestRevision(); for (int i = 0; i < copyPairs.size(); i++) { CopyPair pair = (CopyPair) copyPairs.get(i); CopyPathInfo info = (CopyPathInfo) pathInfos.get(i); pair.mySourceRevisionNumber = getRevisionNumber(pair.mySourceRevision, topRepos, null); info.mySourceRevisionNumber = pair.mySourceRevisionNumber; SVNRepositoryLocation[] locations = getLocations(SVNURL.parseURIEncoded(pair.mySource), null, topRepos, pair.mySourcePegRevision, pair.mySourceRevision, SVNRevision.UNDEFINED); pair.mySource = locations[0].getURL().toString(); String srcRelative = SVNPathUtil.getPathAsChild(topURL, pair.mySource); if (srcRelative != null) { srcRelative = SVNEncodingUtil.uriDecode(srcRelative); } else { srcRelative = ""; } String dstRelative = SVNPathUtil.getPathAsChild(topURL, pair.myDst); if (dstRelative != null) { dstRelative = SVNEncodingUtil.uriDecode(dstRelative); } else { dstRelative = ""; } if ("".equals(srcRelative) && isMove) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE, "Cannot move URL ''{0}'' into itself", SVNURL.parseURIEncoded(pair.mySource)); SVNErrorManager.error(err); } info.mySourceKind = topRepos.checkPath(srcRelative, pair.mySourceRevisionNumber); if (info.mySourceKind == SVNNodeKind.NONE) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.FS_NOT_FOUND, "Path ''{0}'' does not exist in revision {1}", new Object[] {SVNURL.parseURIEncoded(pair.mySource), new Long(pair.mySourceRevisionNumber)}); SVNErrorManager.error(err); } SVNNodeKind dstKind = topRepos.checkPath(dstRelative, latestRevision); if (dstKind != SVNNodeKind.NONE) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.FS_ALREADY_EXISTS, "Path ''{0}'' already exists", dstRelative); SVNErrorManager.error(err); } info.mySource = pair.mySource; info.mySourcePath = srcRelative; info.myDstPath = dstRelative; } List paths = new ArrayList(copyPairs.size() * 2); if (makeParents) { for (Iterator dirs = newDirs.iterator(); dirs.hasNext();) { String dirPath = (String) dirs.next(); CopyPathInfo info = new CopyPathInfo(); info.myDstPath = dirPath; info.isDirAdded = true; paths.add(info.myDstPath); pathsMap.put(dirPath, info); } } List commitItems = new ArrayList(copyPairs.size() * 2); for (Iterator infos = pathInfos.iterator(); infos.hasNext();) { CopyPathInfo info = (CopyPathInfo) infos.next(); SVNURL itemURL = SVNURL.parseURIEncoded(SVNPathUtil.append(topURL, info.myDstPath)); SVNCommitItem item = new SVNCommitItem(null, itemURL, null, null, null, null, true, false, false, false, false, false); commitItems.add(item); pathsMap.put(info.myDstPath, info); if (isMove && !info.isResurrection) { itemURL = SVNURL.parseURIEncoded(SVNPathUtil.append(topURL, info.mySourcePath)); item = new SVNCommitItem(null, itemURL, null, null, null, null, false, true, false, false, false, false); commitItems.add(item); pathsMap.put(info.mySourcePath, info); } } for (Iterator infos = pathInfos.iterator(); infos.hasNext();) { CopyPathInfo info = (CopyPathInfo) infos.next(); Map mergeInfo = calculateTargetMergeInfo(null, null, SVNURL.parseURIEncoded(info.mySource), info.mySourceRevisionNumber, topRepos, false); if (mergeInfo != null) { info.myMergeInfoProp = SVNMergeInfoUtil.formatMergeInfoToString(mergeInfo); } paths.add(info.myDstPath); if (isMove && !info.isResurrection) { paths.add(info.mySourcePath); } } SVNCommitItem[] commitables = (SVNCommitItem[]) commitItems.toArray(new SVNCommitItem[commitItems.size()]); message = getCommitHandler().getCommitMessage(message, commitables); if (message == null) { return SVNCommitInfo.NULL; } message = SVNCommitClient.validateCommitMessage(message); revprops = getCommitHandler().getRevisionProperties(message, commitables, revprops == null ? new SVNProperties() : revprops); if (revprops == null) { return SVNCommitInfo.NULL; } // now do real commit. ISVNEditor commitEditor = topRepos.getCommitEditor(message, null, true, revprops, null); ISVNCommitPathHandler committer = new CopyCommitPathHandler(pathsMap, isMove); SVNCommitInfo result = null; try { SVNCommitUtil.driveCommitEditor(committer, paths, commitEditor, latestRevision); result = commitEditor.closeEdit(); } catch (SVNCancelException cancel) { throw cancel; } catch (SVNException e) { SVNErrorMessage err = e.getErrorMessage().wrap("Commit failed (details follow):"); SVNErrorManager.error(err); } finally { if (commitEditor != null && result == null) { try { commitEditor.abortEdit(); } catch (SVNException e) { SVNDebugLog.getDefaultLog().info(e); // } } } if (result != null && result.getNewRevision() >= 0) { dispatchEvent(SVNEventFactory.createSVNEvent(null, SVNNodeKind.NONE, null, result.getNewRevision(), SVNEventAction.COMMIT_COMPLETED, null, null, null), ISVNEventHandler.UNKNOWN); } return result != null ? result : SVNCommitInfo.NULL; } private void copyReposToWC(List copyPairs, boolean makeParents) throws SVNException { for (Iterator pairs = copyPairs.iterator(); pairs.hasNext();) { CopyPair pair = (CopyPair) pairs.next(); SVNRepositoryLocation[] locations = getLocations(SVNURL.parseURIEncoded(pair.mySource), null, null, pair.mySourcePegRevision, pair.mySourceRevision, SVNRevision.UNDEFINED); // new String actualURL = locations[0].getURL().toString(); String originalSource = pair.mySource; pair.mySource = actualURL; pair.myOriginalSource = originalSource; } // get src and dst ancestors. String topDst = ((CopyPair) copyPairs.get(0)).myDst; if (copyPairs.size() > 1) { topDst = SVNPathUtil.removeTail(topDst); } String topSrc = ((CopyPair) copyPairs.get(0)).mySource; for(int i = 1; i < copyPairs.size(); i++) { CopyPair pair = (CopyPair) copyPairs.get(i); topSrc = SVNPathUtil.getCommonPathAncestor(topSrc, pair.mySource); } if (copyPairs.size() == 1) { topSrc = SVNPathUtil.removeTail(topSrc); } SVNRepository topSrcRepos = createRepository(SVNURL.parseURIEncoded(topSrc), null, null, false); try { for (Iterator pairs = copyPairs.iterator(); pairs.hasNext();) { CopyPair pair = (CopyPair) pairs.next(); pair.mySourceRevisionNumber = getRevisionNumber(pair.mySourceRevision, topSrcRepos, null); } String reposPath = topSrcRepos.getLocation().toString(); for (Iterator pairs = copyPairs.iterator(); pairs.hasNext();) { CopyPair pair = (CopyPair) pairs.next(); String relativePath = SVNPathUtil.getPathAsChild(reposPath, pair.mySource); relativePath = SVNEncodingUtil.uriDecode(relativePath); SVNNodeKind kind = topSrcRepos.checkPath(relativePath, pair.mySourceRevisionNumber); if (kind == SVNNodeKind.NONE) { SVNErrorMessage err = null; if (pair.mySourceRevisionNumber >= 0) { err = SVNErrorMessage.create(SVNErrorCode.FS_NOT_FOUND, "Path ''{0}'' not found in revision {1}", new Object[] {SVNURL.parseURIEncoded(pair.mySource), new Long(pair.mySourceRevisionNumber)}); } else { err = SVNErrorMessage.create(SVNErrorCode.FS_NOT_FOUND, "Path ''{0}'' not found in head revision", SVNURL.parseURIEncoded(pair.mySource)); } SVNErrorManager.error(err); } pair.mySourceKind = kind; SVNFileType dstType = SVNFileType.getType(new File(pair.myDst)); if (dstType != SVNFileType.NONE) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ENTRY_EXISTS, "Path ''{0}'' already exists", new File(pair.myDst)); SVNErrorManager.error(err); } String dstParent = SVNPathUtil.removeTail(pair.myDst); SVNFileType dstParentFileType = SVNFileType.getType(new File(dstParent)); if (makeParents && dstParentFileType == SVNFileType.NONE) { // create parents. addLocalParents(new File(dstParent), getEventDispatcher()); } else if (dstParentFileType != SVNFileType.DIRECTORY) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_NOT_DIRECTORY, "Path ''{0}'' is not a directory", dstParent); SVNErrorManager.error(err); } } SVNWCAccess dstAccess = createWCAccess(); try { dstAccess.probeOpen(new File(topDst), true, 0); for (Iterator pairs = copyPairs.iterator(); pairs.hasNext();) { CopyPair pair = (CopyPair) pairs.next(); SVNEntry dstEntry = dstAccess.getEntry(new File(pair.myDst), false); if (dstEntry != null && !dstEntry.isDirectory() && !dstEntry.isScheduledForDeletion()) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_OBSTRUCTED_UPDATE, "Entry for ''{0}'' exists (though the working file is missing)", new File(pair.myDst)); SVNErrorManager.error(err); } } String srcUUID = null; String dstUUID = null; try { srcUUID = topSrcRepos.getRepositoryUUID(true); } catch (SVNException e) { if (e.getErrorMessage().getErrorCode() != SVNErrorCode.RA_NO_REPOS_UUID) { throw e; } } String dstParent = topDst; if (copyPairs.size() == 1) { dstParent = SVNPathUtil.removeTail(topDst); } try { dstUUID = getUUIDFromPath(dstAccess, new File(dstParent)); } catch (SVNException e) { if (e.getErrorMessage().getErrorCode() != SVNErrorCode.RA_NO_REPOS_UUID) { throw e; } } boolean sameRepos = false; if (srcUUID != null) { sameRepos = srcUUID.equals(dstUUID); } for (Iterator pairs = copyPairs.iterator(); pairs.hasNext();) { CopyPair pair = (CopyPair) pairs.next(); copyReposToWC(pair, sameRepos, topSrcRepos, dstAccess); } } finally { dstAccess.close(); } } finally { topSrcRepos.closeSession(); } } private void copyReposToWC(CopyPair pair, boolean sameRepositories, SVNRepository topSrcRepos, SVNWCAccess dstAccess) throws SVNException { long srcRevNum = pair.mySourceRevisionNumber; if (pair.mySourceKind == SVNNodeKind.DIR) { // do checkout String srcURL = pair.myOriginalSource; SVNURL url = SVNURL.parseURIEncoded(srcURL); SVNUpdateClient updateClient = new SVNUpdateClient(getRepositoryPool(), getOptions()); updateClient.setEventHandler(getEventDispatcher()); File dstFile = new File(pair.myDst); SVNRevision srcRevision = pair.mySourceRevision; SVNRevision srcPegRevision = pair.mySourcePegRevision; updateClient.doCheckout(url, dstFile, srcPegRevision, srcRevision, SVNDepth.INFINITY, false); if (sameRepositories) { url = SVNURL.parseURIEncoded(pair.mySource); SVNAdminArea dstArea = dstAccess.open(dstFile, true, SVNWCAccess.INFINITE_DEPTH); SVNEntry dstRootEntry = dstArea.getEntry(dstArea.getThisDirName(), false); if (srcRevision == SVNRevision.HEAD) { srcRevNum = dstRootEntry.getRevision(); } SVNAdminArea dir = dstAccess.getAdminArea(dstFile.getParentFile()); SVNWCManager.add(dstFile, dir, url, srcRevNum); Map srcMergeInfo = calculateTargetMergeInfo(null, null, url, srcRevNum, topSrcRepos, false); extendWCMergeInfo(dstFile, dstRootEntry, srcMergeInfo, dstAccess); } else { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE, "Source URL ''{0}'' is from foreign repository; leaving it as a disjoint WC", url); SVNErrorManager.error(err); } } else if (pair.mySourceKind == SVNNodeKind.FILE) { String srcURL = pair.mySource; SVNURL url = SVNURL.parseURIEncoded(srcURL); File dst = new File(pair.myDst); SVNAdminArea dir = dstAccess.getAdminArea(dst.getParentFile()); File tmpFile = SVNAdminUtil.createTmpFile(dir); String path = getPathRelativeToRoot(null, url, null, null, topSrcRepos); SVNProperties props = new SVNProperties(); OutputStream os = null; long revision = -1; try { os = SVNFileUtil.openFileForWriting(tmpFile); revision = topSrcRepos.getFile(path, srcRevNum, props, new SVNCancellableOutputStream(os, this)); } finally { SVNFileUtil.closeFile(os); } if (srcRevNum < 0) { srcRevNum = revision; } SVNWCManager.addRepositoryFile(dir, dst.getName(), null, tmpFile, props, null, sameRepositories ? pair.mySource : null, sameRepositories ? srcRevNum : -1); SVNEntry entry = dstAccess.getEntry(dst, false); Map mergeInfo = calculateTargetMergeInfo(null, null, url, srcRevNum, topSrcRepos, false); extendWCMergeInfo(dst, entry, mergeInfo, dstAccess); SVNEvent event = SVNEventFactory.createSVNEvent(dst, SVNNodeKind.FILE, null, SVNRepository.INVALID_REVISION, SVNEventAction.ADD, null, null, null); dstAccess.handleEvent(event); sleepForTimeStamp(); } } private void copyWCToWC(List copyPairs, boolean isMove, boolean makeParents) throws SVNException { for (Iterator pairs = copyPairs.iterator(); pairs.hasNext();) { CopyPair pair = (CopyPair) pairs.next(); SVNFileType srcFileType = SVNFileType.getType(new File(pair.mySource)); if (srcFileType == SVNFileType.NONE) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.NODE_UNKNOWN_KIND, "Path ''{0}'' does not exist", new File(pair.mySource)); SVNErrorManager.error(err); } SVNFileType dstFileType = SVNFileType.getType(new File(pair.myDst)); if (dstFileType != SVNFileType.NONE) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ENTRY_EXISTS, "Path ''{0}'' already exists", new File(pair.myDst)); SVNErrorManager.error(err); } File dstParent = new File(SVNPathUtil.removeTail(pair.myDst)); pair.myBaseName = SVNPathUtil.tail(pair.myDst); SVNFileType dstParentFileType = SVNFileType.getType(dstParent); if (makeParents && dstParentFileType == SVNFileType.NONE) { // create parents. addLocalParents(dstParent, getEventDispatcher()); } else if (dstParentFileType != SVNFileType.DIRECTORY) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_NOT_DIRECTORY, "Path ''{0}'' is not a directory", dstParent); SVNErrorManager.error(err); } } if (isMove) { moveWCToWC(copyPairs); } else { copyWCToWC(copyPairs); } } private void copyDisjointWCToWC(List copyPairs, boolean isMove, boolean makeParents) throws SVNException { for (Iterator pairs = copyPairs.iterator(); pairs.hasNext();) { CopyPair pair = (CopyPair) pairs.next(); File srcFile = new File(pair.mySource); SVNFileType srcFileType = SVNFileType.getType(srcFile); if (srcFileType == SVNFileType.NONE) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.NODE_UNKNOWN_KIND, "Path ''{0}'' does not exist", new File(pair.mySource)); SVNErrorManager.error(err); } File dstFile = new File(pair.myDst); SVNFileType dstFileType = SVNFileType.getType(dstFile); if (dstFileType != SVNFileType.NONE) { // if () { // } SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ENTRY_EXISTS, "Path ''{0}'' already exists", new File(pair.myDst)); SVNErrorManager.error(err); } else { } File dstParent = new File(SVNPathUtil.removeTail(pair.myDst)); pair.myBaseName = SVNPathUtil.tail(pair.myDst); SVNFileType dstParentFileType = SVNFileType.getType(dstParent); if (makeParents && dstParentFileType == SVNFileType.NONE) { // create parents. addLocalParents(dstParent, getEventDispatcher()); } else if (dstParentFileType != SVNFileType.DIRECTORY) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_NOT_DIRECTORY, "Path ''{0}'' is not a directory", dstParent); SVNErrorManager.error(err); } } if (isMove) { moveWCToWC(copyPairs); } else { copyWCToWC(copyPairs); } } private void copyWCToWC(List pairs) throws SVNException { // find common ancestor for all dsts. String dstParentPath = null; for (Iterator ps = pairs.iterator(); ps.hasNext();) { CopyPair pair = (CopyPair) ps.next(); String dstPath = pair.myDst; if (dstParentPath == null) { dstParentPath = SVNPathUtil.removeTail(pair.myDst); } dstParentPath = SVNPathUtil.getCommonPathAncestor(dstParentPath, dstPath); } SVNWCAccess dstAccess = createWCAccess(); try { dstAccess.open(new File(dstParentPath), true, 0); for (Iterator ps = pairs.iterator(); ps.hasNext();) { CopyPair pair = (CopyPair) ps.next(); checkCancelled(); SVNWCAccess srcAccess = null; String srcParent = SVNPathUtil.removeTail(pair.mySource); SVNFileType srcType = SVNFileType.getType(new File(pair.mySource)); try { if (srcParent.equals(dstParentPath)) { if (srcType == SVNFileType.DIRECTORY) { srcAccess = createWCAccess(); srcAccess.open(new File(pair.mySource), false, -1); } else { srcAccess = dstAccess; } } else { try { srcAccess = createWCAccess(); srcAccess.open(new File(srcParent), false, srcType == SVNFileType.DIRECTORY ? -1 : 0); } catch (SVNException e) { if (e.getErrorMessage().getErrorCode() == SVNErrorCode.WC_NOT_DIRECTORY) { srcAccess = null; } else { throw e; } } } // do real copy. copyFiles(new File(pair.mySource), new File(dstParentPath), dstAccess, pair.myBaseName); if (srcAccess != null) { propagateMegeInfo(pair, srcAccess, dstAccess); } } finally { if (srcAccess != null && srcAccess != dstAccess) { srcAccess.close(); } } } } finally { dstAccess.close(); sleepForTimeStamp(); } } private void moveWCToWC(List pairs) throws SVNException { for (Iterator ps = pairs.iterator(); ps.hasNext();) { CopyPair pair = (CopyPair) ps.next(); checkCancelled(); File srcParent = new File(SVNPathUtil.removeTail(pair.mySource)); File dstParent = new File(SVNPathUtil.removeTail(pair.myDst)); SVNFileType srcType = SVNFileType.getType(new File(pair.mySource)); SVNWCAccess srcAccess = createWCAccess(); SVNWCAccess dstAccess = null; try { srcAccess.open(srcParent, true, srcType == SVNFileType.DIRECTORY ? -1 : 0); if (srcParent.equals(dstParent)) { dstAccess = srcAccess; } else { String srcParentPath = srcParent.getAbsolutePath().replace(File.separatorChar, '/'); String dstParentPath = dstParent.getAbsolutePath().replace(File.separatorChar, '/'); if (srcType == SVNFileType.DIRECTORY && SVNPathUtil.isAncestor(srcParentPath, dstParentPath)) { dstAccess = srcAccess; } else { dstAccess = createWCAccess(); dstAccess.open(dstParent, true, 0); } } copyFiles(new File(pair.mySource), dstParent, dstAccess, pair.myBaseName); propagateMegeInfo(pair, srcAccess, dstAccess); // delete src. SVNWCManager.delete(srcAccess, srcAccess.getAdminArea(srcParent), new File(pair.mySource), true, true); } finally { if (dstAccess != srcAccess) { dstAccess.close(); } srcAccess.close(); } } sleepForTimeStamp(); } private void propagateMegeInfo(CopyPair pair, SVNWCAccess srcAccess, SVNWCAccess dstAccess) throws SVNException { SVNEntry entry = srcAccess.getVersionedEntry(new File(pair.mySource), false); if (entry.getSchedule() == null || (entry.isScheduledForAddition() && entry.isCopied())) { SVNRepository repos = createRepository(entry.getSVNURL(), null, null, true); Map mergeInfo = calculateTargetMergeInfo(new File(pair.mySource), srcAccess, entry.getSVNURL(), entry.getRevision(), repos, true); if (mergeInfo == null) { mergeInfo = new TreeMap(); } SVNEntry dstEntry = dstAccess.getEntry(new File(pair.myDst), false); extendWCMergeInfo(new File(pair.myDst), dstEntry, mergeInfo, dstAccess); return; } Map mergeInfo = SVNPropertiesManager.parseMergeInfo(new File(pair.mySource), entry, false); if (mergeInfo == null) { mergeInfo = new TreeMap(); SVNPropertiesManager.recordWCMergeInfo(new File(pair.myDst), mergeInfo, dstAccess); } } private void copyFiles(File src, File dstParent, SVNWCAccess dstAccess, String dstName) throws SVNException { SVNWCAccess srcAccess = createWCAccess(); try { srcAccess.probeOpen(src, false, -1); SVNEntry dstEntry = dstAccess.getVersionedEntry(dstParent, false); SVNEntry srcEntry = srcAccess.getVersionedEntry(src, false); if ((srcEntry.getRepositoryRoot() == null && dstEntry.getRepositoryRoot() != null) || !srcEntry.getRepositoryRoot().equals(dstEntry.getRepositoryRoot())) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_INVALID_SCHEDULE, "Cannot copy to ''{0}'', as it is not from repository ''{1}''; it is from ''{2}''", new Object[] {dstParent, srcEntry.getRepositoryRootURL(), dstEntry.getRepositoryRootURL()}); SVNErrorManager.error(err); } if (dstEntry.isScheduledForDeletion()) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_INVALID_SCHEDULE, "Cannot copy to ''{0}'', as it is scheduled for deletion", dstParent); SVNErrorManager.error(err); } SVNFileType srcType = SVNFileType.getType(src); if (srcType == SVNFileType.FILE || srcType == SVNFileType.SYMLINK) { if (srcEntry.isScheduledForAddition() && !srcEntry.isCopied()) { copyAddedFileAdm(src, dstAccess, dstParent, dstName, true); } else { copyFileAdm(src, srcAccess, dstParent, dstAccess, dstName); } } else if (srcType == SVNFileType.DIRECTORY) { if (srcEntry.isScheduledForAddition() && !srcEntry.isCopied()) { copyAddedDirAdm(src, srcAccess, dstParent, dstAccess, dstName, true); } else { copyDirAdm(src, srcAccess, dstAccess, dstParent, dstName); } } } finally { srcAccess.close(); } } private void copyFileAdm(File src, SVNWCAccess srcAccess, File dstParent, SVNWCAccess dstAccess, String dstName) throws SVNException { File dst = new File(dstParent, dstName); SVNFileType dstType = SVNFileType.getType(dst); if (dstType != SVNFileType.NONE) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ENTRY_EXISTS, "''{0}'' already exists and is in the way", dst); SVNErrorManager.error(err); } SVNEntry dstEntry = dstAccess.getEntry(dst, false); if (dstEntry != null && dstEntry.isFile()) { if (!dstEntry.isScheduledForDeletion()) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ENTRY_EXISTS, "There is already a versioned item ''{0}''", dst); SVNErrorManager.error(err); } } SVNEntry srcEntry = srcAccess.getVersionedEntry(src, false); if ((srcEntry.isScheduledForAddition() && !srcEntry.isCopied()) || srcEntry.getURL() == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ENTRY_EXISTS, "Cannot copy or move ''{0}'': it is not in repository yet; " + "try committing first", src); SVNErrorManager.error(err); } String copyFromURL = null; long copyFromRevision = -1; SVNAdminArea srcDir = srcAccess.getAdminArea(src.getParentFile()); if (srcEntry.isCopied()) { // get cf info - one of the parents has to keep that. SVNLocationEntry location = determineCopyFromInfo(src, srcAccess, srcEntry, dstEntry); copyFromURL = location.getPath(); copyFromRevision = location.getRevision(); } else { copyFromURL = srcEntry.getURL(); copyFromRevision = srcEntry.getRevision(); } // copy base file. File srcBaseFile = new File(src.getParentFile(), SVNAdminUtil.getTextBasePath(src.getName(), false)); File dstBaseFile = new File(dstParent, SVNAdminUtil.getTextBasePath(dstName, true)); SVNFileUtil.copyFile(srcBaseFile, dstBaseFile, false); SVNVersionedProperties srcBaseProps = srcDir.getBaseProperties(src.getName()); SVNVersionedProperties srcWorkingProps = srcDir.getProperties(src.getName()); // copy wc file. SVNAdminArea dstDir = dstAccess.getAdminArea(dstParent); File tmpWCFile = SVNAdminUtil.createTmpFile(dstDir); if (srcWorkingProps.getPropertyValue(SVNProperty.SPECIAL) != null) { // TODO create symlink there? SVNFileUtil.copyFile(src, tmpWCFile, false); } else { SVNFileUtil.copyFile(src, tmpWCFile, false); } SVNWCManager.addRepositoryFile(dstDir, dstName, tmpWCFile, null, srcBaseProps.asMap(), srcWorkingProps.asMap(), copyFromURL, copyFromRevision); SVNEvent event = SVNEventFactory.createSVNEvent(dst, SVNNodeKind.FILE, null, SVNRepository.INVALID_REVISION, SVNEventAction.ADD, null, null, null); dstAccess.handleEvent(event); } private void copyAddedFileAdm(File src, SVNWCAccess dstAccess, File dstParent, String dstName, boolean isAdded) throws SVNException { File dst = new File(dstParent, dstName); SVNFileUtil.copyFile(src, dst, false); if (isAdded) { SVNWCManager.add(dst, dstAccess.getAdminArea(dstParent), null, SVNRepository.INVALID_REVISION); } } private void copyDirAdm(File src, SVNWCAccess srcAccess, SVNWCAccess dstAccess, File dstParent, String dstName) throws SVNException { File dst = new File(dstParent, dstName); SVNEntry srcEntry = srcAccess.getVersionedEntry(src, false); if ((srcEntry.isScheduledForAddition() && !srcEntry.isCopied()) || srcEntry.getURL() == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ENTRY_EXISTS, "Cannot copy or move ''{0}'': it is not in repository yet; " + "try committing first", src); SVNErrorManager.error(err); } SVNFileUtil.copyDirectory(src, dst, true, getEventDispatcher()); SVNWCClient wcClient = new SVNWCClient((ISVNAuthenticationManager) null, null); wcClient.setEventHandler(getEventDispatcher()); wcClient.doCleanup(dst); SVNWCAccess tgtAccess = createWCAccess(); SVNAdminArea dir = null; String copyFromURL = null; long copyFromRevision = -1; try { dir = tgtAccess.open(dst, true, -1); postCopyCleanup(dir); if (srcEntry.isCopied()) { SVNEntry dstEntry = dstAccess.getEntry(dst, false); SVNLocationEntry info = determineCopyFromInfo(src, srcAccess, srcEntry, dstEntry); copyFromURL = info.getPath(); copyFromRevision = info.getRevision(); Map attributes = new SVNHashMap(); attributes.put(SVNProperty.URL, copyFromURL); dir.modifyEntry(dir.getThisDirName(), attributes, true, false); } else { copyFromURL = srcEntry.getURL(); copyFromRevision = srcEntry.getRevision(); } } finally { tgtAccess.close(); } SVNWCManager.add(dst, dstAccess.getAdminArea(dstParent), SVNURL.parseURIEncoded(copyFromURL), copyFromRevision); } private void copyAddedDirAdm(File src, SVNWCAccess srcAccess, File dstParent, SVNWCAccess dstParentAccess, String dstName, boolean isAdded) throws SVNException { File dst = new File(dstParent, dstName); if (!isAdded) { SVNFileUtil.copyDirectory(src, dst, true, getEventDispatcher()); } else { checkCancelled(); dst.mkdirs(); SVNWCManager.add(dst, dstParentAccess.getAdminArea(dstParent), null, SVNRepository.INVALID_REVISION); SVNAdminArea srcChildArea = srcAccess.retrieve(src); File[] entries = SVNFileListUtil.listFiles(src); for (int i = 0; entries != null && i < entries.length; i++) { checkCancelled(); File fsEntry = entries[i]; String name = fsEntry.getName(); if (SVNFileUtil.getAdminDirectoryName().equals(name)) { continue; } SVNEntry entry = srcChildArea.getEntry(name, true); if (fsEntry.isDirectory()) { copyAddedDirAdm(fsEntry, srcAccess, dst, dstParentAccess, name, entry != null); } else if (fsEntry.isFile()) { copyAddedFileAdm(fsEntry, dstParentAccess, dst, name, entry != null); } } } } private SVNLocationEntry determineCopyFromInfo(File src, SVNWCAccess srcAccess, SVNEntry srcEntry, SVNEntry dstEntry) throws SVNException { String url = null; long rev = -1; if (srcEntry.getCopyFromURL() != null) { url = srcEntry.getCopyFromURL(); rev = srcEntry.getCopyFromRevision(); } else { SVNLocationEntry info = getCopyFromInfoFromParent(src, srcAccess); url = info.getPath(); rev = info.getRevision(); } if (dstEntry != null && rev == dstEntry.getRevision() && url.equals(dstEntry.getCopyFromURL())) { url = null; rev = -1; } return new SVNLocationEntry(rev, url); } private SVNLocationEntry getCopyFromInfoFromParent(File file, SVNWCAccess access) throws SVNException { File parent = file.getParentFile(); String rest = file.getName(); String url = null; long rev = -1; while (parent != null && url == null) { try { SVNEntry entry = access.getVersionedEntry(parent, false); url = entry.getCopyFromURL(); rev = entry.getCopyFromRevision(); } catch (SVNException e) { SVNWCAccess wcAccess = SVNWCAccess.newInstance(null); try { wcAccess.probeOpen(parent, false, -1); SVNEntry entry = wcAccess.getVersionedEntry(parent, false); url = entry.getCopyFromURL(); rev = entry.getCopyFromRevision(); } finally { wcAccess.close(); } } if (url != null) { url = SVNPathUtil.append(url, SVNEncodingUtil.uriEncode(rest)); } else { rest = SVNPathUtil.append(parent.getName(), rest); parent = parent.getParentFile(); } } return new SVNLocationEntry(rev, url); } private void addLocalParents(File path, ISVNEventHandler handler) throws SVNException { boolean created = path.mkdirs(); SVNWCClient wcClient = new SVNWCClient((ISVNAuthenticationManager) null, null); try { wcClient.setEventHandler(handler); wcClient.doAdd(path, false, false, true, SVNDepth.EMPTY, true, true); } catch (SVNException e) { if (created) { SVNFileUtil.deleteAll(path, true); } throw e; } } private void extendWCMergeInfo(File path, SVNEntry entry, Map mergeInfo, SVNWCAccess access) throws SVNException { Map wcMergeInfo = SVNPropertiesManager.parseMergeInfo(path, entry, false); if (wcMergeInfo != null && mergeInfo != null) { wcMergeInfo = SVNMergeInfoUtil.mergeMergeInfos(wcMergeInfo, mergeInfo); } else if (wcMergeInfo == null) { wcMergeInfo = mergeInfo; } SVNPropertiesManager.recordWCMergeInfo(path, wcMergeInfo, access); } private Map calculateTargetMergeInfo(File srcFile, SVNWCAccess access, SVNURL srcURL, long srcRevision, SVNRepository repository, boolean noReposAccess) throws SVNException { boolean isLocallyAdded = false; SVNEntry entry = null; SVNURL url = null; if (access != null) { entry = access.getVersionedEntry(srcFile, false); if (entry.isScheduledForAddition() && !entry.isCopied()) { isLocallyAdded = true; } else { if (entry.getCopyFromURL() != null) { url = entry.getCopyFromSVNURL(); srcRevision = entry.getCopyFromRevision(); } else if (entry.getURL() != null) { url = entry.getSVNURL(); srcRevision = entry.getRevision(); } else { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ENTRY_MISSING_URL, "Entry for ''{0}'' has no URL", srcFile); SVNErrorManager.error(err); } } } else { url = srcURL; } Map targetMergeInfo = null; if (!isLocallyAdded) { String mergeInfoPath = null; if (!noReposAccess) { // TODO reparent repository if needed and then ensure that repository has the same location as before that call. mergeInfoPath = getPathRelativeToRoot(null, url, entry != null ? entry.getRepositoryRootURL() : null, access, repository); targetMergeInfo = getReposMergeInfo(repository, mergeInfoPath, srcRevision, SVNMergeInfoInheritance.INHERITED, true); } else { targetMergeInfo = getWCMergeInfo(srcFile, entry, null, SVNMergeInfoInheritance.INHERITED, false, new boolean[1]); } } return targetMergeInfo; } private static class CopyCommitPathHandler implements ISVNCommitPathHandler { private Map myPathInfos; private boolean myIsMove; public CopyCommitPathHandler(Map pathInfos, boolean isMove) { myPathInfos = pathInfos; myIsMove = isMove; } public boolean handleCommitPath(String commitPath, ISVNEditor commitEditor) throws SVNException { CopyPathInfo pathInfo = (CopyPathInfo) myPathInfos.get(commitPath); boolean doAdd = false; boolean doDelete = false; if (pathInfo.isDirAdded) { commitEditor.addDir(commitPath, null, SVNRepository.INVALID_REVISION); return true; } if (pathInfo.isResurrection) { if (!myIsMove) { doAdd = true; } } else { if (myIsMove) { if (commitPath.equals(pathInfo.mySourcePath)) { doDelete = true; } else { doAdd = true; } } else { doAdd = true; } } if (doDelete) { commitEditor.deleteEntry(commitPath, -1); } boolean closeDir = false; if (doAdd) { SVNPathUtil.checkPathIsValid(commitPath); if (pathInfo.mySourceKind == SVNNodeKind.DIR) { commitEditor.addDir(commitPath, pathInfo.mySourcePath, pathInfo.mySourceRevisionNumber); if (pathInfo.myMergeInfoProp != null) { commitEditor.changeDirProperty(SVNProperty.MERGE_INFO, SVNPropertyValue.create(pathInfo.myMergeInfoProp)); } closeDir = true; } else { commitEditor.addFile(commitPath, pathInfo.mySourcePath, pathInfo.mySourceRevisionNumber); if (pathInfo.myMergeInfoProp != null) { commitEditor.changeFileProperty(commitPath, SVNProperty.MERGE_INFO, SVNPropertyValue.create(pathInfo.myMergeInfoProp)); } commitEditor.closeFile(commitPath, null); } } return closeDir; } } private static class CopyPathInfo { public boolean isDirAdded; public boolean isResurrection; public SVNNodeKind mySourceKind; public String mySource; public String mySourcePath; public String myDstPath; public String myMergeInfoProp; public long mySourceRevisionNumber; } private static class CopyPair { public String mySource; public String myOriginalSource; public SVNNodeKind mySourceKind; public SVNRevision mySourceRevision; public SVNRevision mySourcePegRevision; public long mySourceRevisionNumber; public String myBaseName; public String myDst; public void setSourceRevisions(SVNRevision pegRevision, SVNRevision revision) { if (pegRevision == SVNRevision.UNDEFINED) { if (SVNPathUtil.isURL(mySource)) { pegRevision = SVNRevision.HEAD; } else { pegRevision = SVNRevision.WORKING; } } if (revision == SVNRevision.UNDEFINED) { revision = pegRevision; } mySourceRevision = revision; mySourcePegRevision = pegRevision; } } }
true
true
private SVNCommitInfo copyReposToRepos(List copyPairs, boolean makeParents, boolean isMove, String message, SVNProperties revprops) throws SVNException { List pathInfos = new ArrayList(); Map pathsMap = new SVNHashMap(); for (int i = 0; i < copyPairs.size(); i++) { CopyPathInfo info = new CopyPathInfo(); pathInfos.add(info); } String topURL = ((CopyPair) copyPairs.get(0)).mySource; String topDstURL = ((CopyPair) copyPairs.get(0)).myDst; for (int i = 1; i < copyPairs.size(); i++) { CopyPair pair = (CopyPair) copyPairs.get(i); topURL = SVNPathUtil.getCommonPathAncestor(topURL, pair.mySource); } if (copyPairs.size() == 1) { topURL = SVNPathUtil.getCommonPathAncestor(topURL, topDstURL); } else { topURL = SVNPathUtil.getCommonPathAncestor(topURL, SVNPathUtil.removeTail(topDstURL)); } try { SVNURL.parseURIEncoded(topURL); } catch (SVNException e) { topURL = null; } if (topURL == null) { SVNURL url1 = SVNURL.parseURIEncoded(((CopyPair) copyPairs.get(0)).mySource); SVNURL url2 = SVNURL.parseURIEncoded(((CopyPair) copyPairs.get(0)).myDst); SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE, "Source and dest appear not to be in the same repository (src: ''{0}''; dst: ''{1}'')", new Object[] {url1, url2}); SVNErrorManager.error(err); } for (int i = 0; i < copyPairs.size(); i++) { CopyPair pair = (CopyPair) copyPairs.get(i); CopyPathInfo info = (CopyPathInfo) pathInfos.get(i); if (pair.mySource.equals(pair.myDst)) { info.isResurrection = true; if (topURL.equals(pair.mySource)) { topURL = SVNPathUtil.removeTail(topURL); } } } SVNRepository topRepos = createRepository(SVNURL.parseURIEncoded(topURL), null, null, true); List newDirs = new ArrayList(); if (makeParents) { CopyPair pair = (CopyPair) copyPairs.get(0); String relativeDir = SVNPathUtil.getPathAsChild(topURL, SVNPathUtil.removeTail(pair.myDst)); relativeDir = SVNEncodingUtil.uriDecode(relativeDir); SVNNodeKind kind = topRepos.checkPath(relativeDir, -1); while(kind == SVNNodeKind.NONE) { newDirs.add(relativeDir); relativeDir = SVNPathUtil.removeTail(relativeDir); kind = topRepos.checkPath(relativeDir, -1); } } String rootURL = topRepos.getRepositoryRoot(true).toString(); for (int i = 0; i < copyPairs.size(); i++) { CopyPair pair = (CopyPair) copyPairs.get(i); CopyPathInfo info = (CopyPathInfo) pathInfos.get(i); if (!pair.myDst.equals(rootURL) && SVNPathUtil.getPathAsChild(pair.myDst, pair.mySource) != null) { info.isResurrection = true; // TODO still looks like a bug. // if (SVNPathUtil.removeTail(pair.myDst).equals(topURL)) { topURL = SVNPathUtil.removeTail(topURL); // } } } topRepos.setLocation(SVNURL.parseURIEncoded(topURL), false); long latestRevision = topRepos.getLatestRevision(); for (int i = 0; i < copyPairs.size(); i++) { CopyPair pair = (CopyPair) copyPairs.get(i); CopyPathInfo info = (CopyPathInfo) pathInfos.get(i); pair.mySourceRevisionNumber = getRevisionNumber(pair.mySourceRevision, topRepos, null); info.mySourceRevisionNumber = pair.mySourceRevisionNumber; SVNRepositoryLocation[] locations = getLocations(SVNURL.parseURIEncoded(pair.mySource), null, topRepos, pair.mySourcePegRevision, pair.mySourceRevision, SVNRevision.UNDEFINED); pair.mySource = locations[0].getURL().toString(); String srcRelative = SVNPathUtil.getPathAsChild(topURL, pair.mySource); if (srcRelative != null) { srcRelative = SVNEncodingUtil.uriDecode(srcRelative); } else { srcRelative = ""; } String dstRelative = SVNPathUtil.getPathAsChild(topURL, pair.myDst); if (dstRelative != null) { dstRelative = SVNEncodingUtil.uriDecode(dstRelative); } else { dstRelative = ""; } if ("".equals(srcRelative) && isMove) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE, "Cannot move URL ''{0}'' into itself", SVNURL.parseURIEncoded(pair.mySource)); SVNErrorManager.error(err); } info.mySourceKind = topRepos.checkPath(srcRelative, pair.mySourceRevisionNumber); if (info.mySourceKind == SVNNodeKind.NONE) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.FS_NOT_FOUND, "Path ''{0}'' does not exist in revision {1}", new Object[] {SVNURL.parseURIEncoded(pair.mySource), new Long(pair.mySourceRevisionNumber)}); SVNErrorManager.error(err); } SVNNodeKind dstKind = topRepos.checkPath(dstRelative, latestRevision); if (dstKind != SVNNodeKind.NONE) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.FS_ALREADY_EXISTS, "Path ''{0}'' already exists", dstRelative); SVNErrorManager.error(err); } info.mySource = pair.mySource; info.mySourcePath = srcRelative; info.myDstPath = dstRelative; } List paths = new ArrayList(copyPairs.size() * 2); if (makeParents) { for (Iterator dirs = newDirs.iterator(); dirs.hasNext();) { String dirPath = (String) dirs.next(); CopyPathInfo info = new CopyPathInfo(); info.myDstPath = dirPath; info.isDirAdded = true; paths.add(info.myDstPath); pathsMap.put(dirPath, info); } } List commitItems = new ArrayList(copyPairs.size() * 2); for (Iterator infos = pathInfos.iterator(); infos.hasNext();) { CopyPathInfo info = (CopyPathInfo) infos.next(); SVNURL itemURL = SVNURL.parseURIEncoded(SVNPathUtil.append(topURL, info.myDstPath)); SVNCommitItem item = new SVNCommitItem(null, itemURL, null, null, null, null, true, false, false, false, false, false); commitItems.add(item); pathsMap.put(info.myDstPath, info); if (isMove && !info.isResurrection) { itemURL = SVNURL.parseURIEncoded(SVNPathUtil.append(topURL, info.mySourcePath)); item = new SVNCommitItem(null, itemURL, null, null, null, null, false, true, false, false, false, false); commitItems.add(item); pathsMap.put(info.mySourcePath, info); } } for (Iterator infos = pathInfos.iterator(); infos.hasNext();) { CopyPathInfo info = (CopyPathInfo) infos.next(); Map mergeInfo = calculateTargetMergeInfo(null, null, SVNURL.parseURIEncoded(info.mySource), info.mySourceRevisionNumber, topRepos, false); if (mergeInfo != null) { info.myMergeInfoProp = SVNMergeInfoUtil.formatMergeInfoToString(mergeInfo); } paths.add(info.myDstPath); if (isMove && !info.isResurrection) { paths.add(info.mySourcePath); } } SVNCommitItem[] commitables = (SVNCommitItem[]) commitItems.toArray(new SVNCommitItem[commitItems.size()]); message = getCommitHandler().getCommitMessage(message, commitables); if (message == null) { return SVNCommitInfo.NULL; } message = SVNCommitClient.validateCommitMessage(message); revprops = getCommitHandler().getRevisionProperties(message, commitables, revprops == null ? new SVNProperties() : revprops); if (revprops == null) { return SVNCommitInfo.NULL; } // now do real commit. ISVNEditor commitEditor = topRepos.getCommitEditor(message, null, true, revprops, null); ISVNCommitPathHandler committer = new CopyCommitPathHandler(pathsMap, isMove); SVNCommitInfo result = null; try { SVNCommitUtil.driveCommitEditor(committer, paths, commitEditor, latestRevision); result = commitEditor.closeEdit(); } catch (SVNCancelException cancel) { throw cancel; } catch (SVNException e) { SVNErrorMessage err = e.getErrorMessage().wrap("Commit failed (details follow):"); SVNErrorManager.error(err); } finally { if (commitEditor != null && result == null) { try { commitEditor.abortEdit(); } catch (SVNException e) { SVNDebugLog.getDefaultLog().info(e); // } } } if (result != null && result.getNewRevision() >= 0) { dispatchEvent(SVNEventFactory.createSVNEvent(null, SVNNodeKind.NONE, null, result.getNewRevision(), SVNEventAction.COMMIT_COMPLETED, null, null, null), ISVNEventHandler.UNKNOWN); } return result != null ? result : SVNCommitInfo.NULL; }
private SVNCommitInfo copyReposToRepos(List copyPairs, boolean makeParents, boolean isMove, String message, SVNProperties revprops) throws SVNException { List pathInfos = new ArrayList(); Map pathsMap = new SVNHashMap(); for (int i = 0; i < copyPairs.size(); i++) { CopyPathInfo info = new CopyPathInfo(); pathInfos.add(info); } String topURL = ((CopyPair) copyPairs.get(0)).mySource; String topDstURL = ((CopyPair) copyPairs.get(0)).myDst; for (int i = 1; i < copyPairs.size(); i++) { CopyPair pair = (CopyPair) copyPairs.get(i); topURL = SVNPathUtil.getCommonPathAncestor(topURL, pair.mySource); } if (copyPairs.size() == 1) { topURL = SVNPathUtil.getCommonPathAncestor(topURL, topDstURL); } else { topURL = SVNPathUtil.getCommonPathAncestor(topURL, SVNPathUtil.removeTail(topDstURL)); } try { SVNURL.parseURIEncoded(topURL); } catch (SVNException e) { topURL = null; } if (topURL == null) { SVNURL url1 = SVNURL.parseURIEncoded(((CopyPair) copyPairs.get(0)).mySource); SVNURL url2 = SVNURL.parseURIEncoded(((CopyPair) copyPairs.get(0)).myDst); SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE, "Source and dest appear not to be in the same repository (src: ''{0}''; dst: ''{1}'')", new Object[] {url1, url2}); SVNErrorManager.error(err); } for (int i = 0; i < copyPairs.size(); i++) { CopyPair pair = (CopyPair) copyPairs.get(i); CopyPathInfo info = (CopyPathInfo) pathInfos.get(i); if (pair.mySource.equals(pair.myDst)) { info.isResurrection = true; if (topURL.equals(pair.mySource)) { topURL = SVNPathUtil.removeTail(topURL); } } } SVNRepository topRepos = createRepository(SVNURL.parseURIEncoded(topURL), null, null, true); List newDirs = new ArrayList(); if (makeParents) { CopyPair pair = (CopyPair) copyPairs.get(0); String relativeDir = SVNPathUtil.getPathAsChild(topURL, SVNPathUtil.removeTail(pair.myDst)); if (relativeDir == null) { relativeDir = ""; } relativeDir = SVNEncodingUtil.uriDecode(relativeDir); SVNNodeKind kind = topRepos.checkPath(relativeDir, -1); while(kind == SVNNodeKind.NONE) { newDirs.add(relativeDir); relativeDir = SVNPathUtil.removeTail(relativeDir); kind = topRepos.checkPath(relativeDir, -1); } } String rootURL = topRepos.getRepositoryRoot(true).toString(); for (int i = 0; i < copyPairs.size(); i++) { CopyPair pair = (CopyPair) copyPairs.get(i); CopyPathInfo info = (CopyPathInfo) pathInfos.get(i); if (!pair.myDst.equals(rootURL) && SVNPathUtil.getPathAsChild(pair.myDst, pair.mySource) != null) { info.isResurrection = true; // TODO still looks like a bug. // if (SVNPathUtil.removeTail(pair.myDst).equals(topURL)) { topURL = SVNPathUtil.removeTail(topURL); // } } } topRepos.setLocation(SVNURL.parseURIEncoded(topURL), false); long latestRevision = topRepos.getLatestRevision(); for (int i = 0; i < copyPairs.size(); i++) { CopyPair pair = (CopyPair) copyPairs.get(i); CopyPathInfo info = (CopyPathInfo) pathInfos.get(i); pair.mySourceRevisionNumber = getRevisionNumber(pair.mySourceRevision, topRepos, null); info.mySourceRevisionNumber = pair.mySourceRevisionNumber; SVNRepositoryLocation[] locations = getLocations(SVNURL.parseURIEncoded(pair.mySource), null, topRepos, pair.mySourcePegRevision, pair.mySourceRevision, SVNRevision.UNDEFINED); pair.mySource = locations[0].getURL().toString(); String srcRelative = SVNPathUtil.getPathAsChild(topURL, pair.mySource); if (srcRelative != null) { srcRelative = SVNEncodingUtil.uriDecode(srcRelative); } else { srcRelative = ""; } String dstRelative = SVNPathUtil.getPathAsChild(topURL, pair.myDst); if (dstRelative != null) { dstRelative = SVNEncodingUtil.uriDecode(dstRelative); } else { dstRelative = ""; } if ("".equals(srcRelative) && isMove) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE, "Cannot move URL ''{0}'' into itself", SVNURL.parseURIEncoded(pair.mySource)); SVNErrorManager.error(err); } info.mySourceKind = topRepos.checkPath(srcRelative, pair.mySourceRevisionNumber); if (info.mySourceKind == SVNNodeKind.NONE) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.FS_NOT_FOUND, "Path ''{0}'' does not exist in revision {1}", new Object[] {SVNURL.parseURIEncoded(pair.mySource), new Long(pair.mySourceRevisionNumber)}); SVNErrorManager.error(err); } SVNNodeKind dstKind = topRepos.checkPath(dstRelative, latestRevision); if (dstKind != SVNNodeKind.NONE) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.FS_ALREADY_EXISTS, "Path ''{0}'' already exists", dstRelative); SVNErrorManager.error(err); } info.mySource = pair.mySource; info.mySourcePath = srcRelative; info.myDstPath = dstRelative; } List paths = new ArrayList(copyPairs.size() * 2); if (makeParents) { for (Iterator dirs = newDirs.iterator(); dirs.hasNext();) { String dirPath = (String) dirs.next(); CopyPathInfo info = new CopyPathInfo(); info.myDstPath = dirPath; info.isDirAdded = true; paths.add(info.myDstPath); pathsMap.put(dirPath, info); } } List commitItems = new ArrayList(copyPairs.size() * 2); for (Iterator infos = pathInfos.iterator(); infos.hasNext();) { CopyPathInfo info = (CopyPathInfo) infos.next(); SVNURL itemURL = SVNURL.parseURIEncoded(SVNPathUtil.append(topURL, info.myDstPath)); SVNCommitItem item = new SVNCommitItem(null, itemURL, null, null, null, null, true, false, false, false, false, false); commitItems.add(item); pathsMap.put(info.myDstPath, info); if (isMove && !info.isResurrection) { itemURL = SVNURL.parseURIEncoded(SVNPathUtil.append(topURL, info.mySourcePath)); item = new SVNCommitItem(null, itemURL, null, null, null, null, false, true, false, false, false, false); commitItems.add(item); pathsMap.put(info.mySourcePath, info); } } for (Iterator infos = pathInfos.iterator(); infos.hasNext();) { CopyPathInfo info = (CopyPathInfo) infos.next(); Map mergeInfo = calculateTargetMergeInfo(null, null, SVNURL.parseURIEncoded(info.mySource), info.mySourceRevisionNumber, topRepos, false); if (mergeInfo != null) { info.myMergeInfoProp = SVNMergeInfoUtil.formatMergeInfoToString(mergeInfo); } paths.add(info.myDstPath); if (isMove && !info.isResurrection) { paths.add(info.mySourcePath); } } SVNCommitItem[] commitables = (SVNCommitItem[]) commitItems.toArray(new SVNCommitItem[commitItems.size()]); message = getCommitHandler().getCommitMessage(message, commitables); if (message == null) { return SVNCommitInfo.NULL; } message = SVNCommitClient.validateCommitMessage(message); revprops = getCommitHandler().getRevisionProperties(message, commitables, revprops == null ? new SVNProperties() : revprops); if (revprops == null) { return SVNCommitInfo.NULL; } // now do real commit. ISVNEditor commitEditor = topRepos.getCommitEditor(message, null, true, revprops, null); ISVNCommitPathHandler committer = new CopyCommitPathHandler(pathsMap, isMove); SVNCommitInfo result = null; try { SVNCommitUtil.driveCommitEditor(committer, paths, commitEditor, latestRevision); result = commitEditor.closeEdit(); } catch (SVNCancelException cancel) { throw cancel; } catch (SVNException e) { SVNErrorMessage err = e.getErrorMessage().wrap("Commit failed (details follow):"); SVNErrorManager.error(err); } finally { if (commitEditor != null && result == null) { try { commitEditor.abortEdit(); } catch (SVNException e) { SVNDebugLog.getDefaultLog().info(e); // } } } if (result != null && result.getNewRevision() >= 0) { dispatchEvent(SVNEventFactory.createSVNEvent(null, SVNNodeKind.NONE, null, result.getNewRevision(), SVNEventAction.COMMIT_COMPLETED, null, null, null), ISVNEventHandler.UNKNOWN); } return result != null ? result : SVNCommitInfo.NULL; }
diff --git a/app/delegates/UtilitiesDelegate.java b/app/delegates/UtilitiesDelegate.java index ef5280f..8ab6fd5 100644 --- a/app/delegates/UtilitiesDelegate.java +++ b/app/delegates/UtilitiesDelegate.java @@ -1,298 +1,298 @@ package delegates; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.UUID; import javax.imageio.ImageIO; import org.joda.time.DateTime; import akka.event.slf4j.Logger; import play.Play; import play.mvc.Http.MultipartFormData.FilePart; import pojos.CityBean; import pojos.FileBean; import utils.FileUtilities; import utils.PlayDozerMapper; public class UtilitiesDelegate { public String uploadDir = Play.application().configuration() .getString("files.home"); public String filesBaseURL = Play.application().configuration() .getString("files.baseurl"); public static UtilitiesDelegate getInstance() { return new UtilitiesDelegate(); } public List<CityBean> getCities() { List<models.City> modelCities = models.City.all(); List<CityBean> pojosCities = new ArrayList<CityBean>(); for (models.City city : modelCities) { CityBean cityBean = PlayDozerMapper.getInstance().map(city, CityBean.class); pojosCities.add(cityBean); } return pojosCities; } public List<CityBean> getCitiesByCountryId(Long countryId) { List<models.City> modelCities = models.City.readByCountry(countryId); List<CityBean> pojosCities = new ArrayList<CityBean>(); for (models.City city : modelCities) { CityBean cityBean = PlayDozerMapper.getInstance().map(city, CityBean.class); pojosCities.add(cityBean); } return pojosCities; } public List<CityBean> getCitiesByCountryName(String countryName) { List<models.City> modelCities = models.City .readByCountryName(countryName); List<CityBean> pojosCities = new ArrayList<CityBean>(); for (models.City city : modelCities) { CityBean cityBean = PlayDozerMapper.getInstance().map(city, CityBean.class); pojosCities.add(cityBean); } return pojosCities; } public List<CityBean> getCitiesByCountryNameAndRegion(String country, String region) { List<models.City> modelCities = models.City.readByCountryNameAndRegion( country, region); List<CityBean> pojosCities = new ArrayList<CityBean>(); for (models.City city : modelCities) { CityBean cityBean = PlayDozerMapper.getInstance().map(city, CityBean.class); pojosCities.add(cityBean); } return pojosCities; } public List<CityBean> getNewCities(Long lastCityId) { List<models.City> modelCities = models.City.readNewById(lastCityId); List<CityBean> pojosCities = new ArrayList<CityBean>(); for (models.City city : modelCities) { CityBean cityBean = PlayDozerMapper.getInstance().map(city, CityBean.class); pojosCities.add(cityBean); } return pojosCities; } public List<CityBean> getCityByName(String cityName) { List<models.City> modelCities = models.City.findByName(cityName); List<CityBean> pojosCities = new ArrayList<CityBean>(); for (models.City city : modelCities) { CityBean cityBean = PlayDozerMapper.getInstance().map(city, CityBean.class); pojosCities.add(cityBean); } return pojosCities; } public CityBean getCitiesById(Long cityId) { models.City city = models.City.read(cityId); CityBean cityBean = PlayDozerMapper.getInstance().map(city, CityBean.class); return cityBean; } public FileBean saveFile(FilePart file, FileBean fileBean) throws IOException { /* * 1. Prepare file metadata before saving the file in the final * destination */ String fileName = "U_" + fileBean.getOwner().toString() + "_" + "D" + DateTime.now() + "_" + file.getFilename(); // TODO check how to make uploadDir also cross-platform String fullPath = uploadDir + FileUtilities.slash + fileName; String contentType = file.getContentType(); File uploadFile = file.getFile(); String[] parts = contentType.split("/"); String fileExtension = ""; if (parts != null && parts.length > 0) { fileExtension = parts[parts.length - 1]; } Logger.root().debug("Saving File...."); Logger.root().debug("--> fileName=" + fileName); Logger.root().debug("--> contentType=" + contentType); Logger.root().debug("--> uploadFile=" + uploadFile); /* * 2. Save the file in the final destination */ File localFile = new File(fullPath); uploadFile.renameTo(localFile); Logger.root().debug("--> localFile=" + localFile); - if (play.mvc.Controller.request().host().contains("localhost")) { + if (play.mvc.Controller.request().getHeader("Origin").contains("localhost")) { filesBaseURL = "http://localhost/files"; } /* * 3. Save scaled down versions */ File thumbnailFile = null; File smallFile = null; File mediumFile = null; File largeFile = null; if (contentType.contains("image")) { thumbnailFile = scalePictureAndSave(localFile, fileExtension, "THUMBNAIL"); smallFile = scalePictureAndSave(localFile, fileExtension, "SMALL"); mediumFile = scalePictureAndSave(localFile, fileExtension, "MEDIUM"); largeFile = scalePictureAndSave(localFile, fileExtension, "LARGE"); } String thumbnailURI = ""; String smallURI = ""; String mediumURI = ""; String largeURI = ""; if (thumbnailFile != null) { thumbnailURI = filesBaseURL + "/" + thumbnailFile.getName(); } if (smallFile != null) { smallURI = filesBaseURL + "/" + smallFile.getName(); } if (mediumFile != null) { mediumURI = filesBaseURL + "/" + mediumFile.getName(); } if (largeFile != null) { largeURI = filesBaseURL + "/" + largeFile.getName(); } /* * 4. Generate Hashcode to use as new name */ String hashcode = UUID.nameUUIDFromBytes(fullPath.getBytes()) .toString(); /* * 5. Save File metadata in Database */ fileBean.setFilename(fileName); fileBean.setURI(filesBaseURL + "/" + fileName); fileBean.setThumbnailURI(thumbnailURI); fileBean.setMediumURI(mediumURI); fileBean.setSmallURI(smallURI); fileBean.setLargeURI(largeURI); fileBean.setContentType(contentType); fileBean.setCreationDate(DateTime.now()); fileBean.setHashcode(hashcode); fileBean.setExtension(fileExtension); Logger.root().debug("--> creationDate=" + fileBean.getCreationDate()); Logger.root().debug("--> hashcode=" + fileBean.getHashcode()); models.File f = PlayDozerMapper.getInstance().map(fileBean, models.File.class); f.save(); fileBean.setFileId(f.getFileId()); return fileBean; } private File scalePictureAndSave(File sourceImageFile, String fileExtension, String size) throws IOException { // 1. Read image BufferedImage img = ImageIO.read(sourceImageFile); // 2. Create scaled image BufferedImage scaled = null; if (size.equals("THUMBNAIL")) { // thumbnail=150px scaled = FileUtilities.createThumbnail(img); } else if (size.equals("SMALL")) { // small=250px scaled = FileUtilities.createSmall(img); } else if (size.equals("MEDIUM")) { // medium=500px scaled = FileUtilities.createMedium(img); } else { // large=1024px scaled = FileUtilities.createLarge(img); } scaled.flush(); // 3. prepare the path and filename for the scaled image String fileName = size + "_" + sourceImageFile.getName(); String fullPath = uploadDir + FileUtilities.slash + fileName; File thumbFile = new File(fullPath); // 4. save scaled image ImageIO.write(scaled, fileExtension, thumbFile); return thumbFile; } public java.io.File getFile(String hashcode, Long userId, String type) { models.File f = models.File.readByHashCodeAndUserId(hashcode, userId); if (f != null) { if (!f.getContentType().contains("image")) type = ""; String uploadDir = Play.application().configuration() .getString("files.home"); String fileName = f == null ? "" : f.getFilename(); String typePrefix = type != null && !type.isEmpty() ? type .toUpperCase() + "_" : ""; String fullPath = f == null ? "" : uploadDir + FileUtilities.slash + typePrefix + fileName; return new java.io.File(fullPath); } else { return null; } } public java.io.File getFile(String hashcode, Long userId) { return getFile(hashcode, userId, ""); } public java.io.File getFileNoLogin(String hashcode, String type) { models.File f = models.File.readByHashCode(hashcode); if (f != null) { if (!f.getContentType().contains("image")) type = ""; String uploadDir = Play.application().configuration() .getString("files.home"); String fileName = f == null ? "" : f.getFilename(); String typePrefix = type != null && !type.isEmpty() ? type .toUpperCase() + "_" : ""; String fullPath = f == null ? "" : uploadDir + FileUtilities.slash + typePrefix + fileName; return new java.io.File(fullPath); } else { return null; } } public java.io.File getFileNoLogin(String hashcode) { return getFileNoLogin(hashcode, ""); } }
true
true
public FileBean saveFile(FilePart file, FileBean fileBean) throws IOException { /* * 1. Prepare file metadata before saving the file in the final * destination */ String fileName = "U_" + fileBean.getOwner().toString() + "_" + "D" + DateTime.now() + "_" + file.getFilename(); // TODO check how to make uploadDir also cross-platform String fullPath = uploadDir + FileUtilities.slash + fileName; String contentType = file.getContentType(); File uploadFile = file.getFile(); String[] parts = contentType.split("/"); String fileExtension = ""; if (parts != null && parts.length > 0) { fileExtension = parts[parts.length - 1]; } Logger.root().debug("Saving File...."); Logger.root().debug("--> fileName=" + fileName); Logger.root().debug("--> contentType=" + contentType); Logger.root().debug("--> uploadFile=" + uploadFile); /* * 2. Save the file in the final destination */ File localFile = new File(fullPath); uploadFile.renameTo(localFile); Logger.root().debug("--> localFile=" + localFile); if (play.mvc.Controller.request().host().contains("localhost")) { filesBaseURL = "http://localhost/files"; } /* * 3. Save scaled down versions */ File thumbnailFile = null; File smallFile = null; File mediumFile = null; File largeFile = null; if (contentType.contains("image")) { thumbnailFile = scalePictureAndSave(localFile, fileExtension, "THUMBNAIL"); smallFile = scalePictureAndSave(localFile, fileExtension, "SMALL"); mediumFile = scalePictureAndSave(localFile, fileExtension, "MEDIUM"); largeFile = scalePictureAndSave(localFile, fileExtension, "LARGE"); } String thumbnailURI = ""; String smallURI = ""; String mediumURI = ""; String largeURI = ""; if (thumbnailFile != null) { thumbnailURI = filesBaseURL + "/" + thumbnailFile.getName(); } if (smallFile != null) { smallURI = filesBaseURL + "/" + smallFile.getName(); } if (mediumFile != null) { mediumURI = filesBaseURL + "/" + mediumFile.getName(); } if (largeFile != null) { largeURI = filesBaseURL + "/" + largeFile.getName(); } /* * 4. Generate Hashcode to use as new name */ String hashcode = UUID.nameUUIDFromBytes(fullPath.getBytes()) .toString(); /* * 5. Save File metadata in Database */ fileBean.setFilename(fileName); fileBean.setURI(filesBaseURL + "/" + fileName); fileBean.setThumbnailURI(thumbnailURI); fileBean.setMediumURI(mediumURI); fileBean.setSmallURI(smallURI); fileBean.setLargeURI(largeURI); fileBean.setContentType(contentType); fileBean.setCreationDate(DateTime.now()); fileBean.setHashcode(hashcode); fileBean.setExtension(fileExtension); Logger.root().debug("--> creationDate=" + fileBean.getCreationDate()); Logger.root().debug("--> hashcode=" + fileBean.getHashcode()); models.File f = PlayDozerMapper.getInstance().map(fileBean, models.File.class); f.save(); fileBean.setFileId(f.getFileId()); return fileBean; }
public FileBean saveFile(FilePart file, FileBean fileBean) throws IOException { /* * 1. Prepare file metadata before saving the file in the final * destination */ String fileName = "U_" + fileBean.getOwner().toString() + "_" + "D" + DateTime.now() + "_" + file.getFilename(); // TODO check how to make uploadDir also cross-platform String fullPath = uploadDir + FileUtilities.slash + fileName; String contentType = file.getContentType(); File uploadFile = file.getFile(); String[] parts = contentType.split("/"); String fileExtension = ""; if (parts != null && parts.length > 0) { fileExtension = parts[parts.length - 1]; } Logger.root().debug("Saving File...."); Logger.root().debug("--> fileName=" + fileName); Logger.root().debug("--> contentType=" + contentType); Logger.root().debug("--> uploadFile=" + uploadFile); /* * 2. Save the file in the final destination */ File localFile = new File(fullPath); uploadFile.renameTo(localFile); Logger.root().debug("--> localFile=" + localFile); if (play.mvc.Controller.request().getHeader("Origin").contains("localhost")) { filesBaseURL = "http://localhost/files"; } /* * 3. Save scaled down versions */ File thumbnailFile = null; File smallFile = null; File mediumFile = null; File largeFile = null; if (contentType.contains("image")) { thumbnailFile = scalePictureAndSave(localFile, fileExtension, "THUMBNAIL"); smallFile = scalePictureAndSave(localFile, fileExtension, "SMALL"); mediumFile = scalePictureAndSave(localFile, fileExtension, "MEDIUM"); largeFile = scalePictureAndSave(localFile, fileExtension, "LARGE"); } String thumbnailURI = ""; String smallURI = ""; String mediumURI = ""; String largeURI = ""; if (thumbnailFile != null) { thumbnailURI = filesBaseURL + "/" + thumbnailFile.getName(); } if (smallFile != null) { smallURI = filesBaseURL + "/" + smallFile.getName(); } if (mediumFile != null) { mediumURI = filesBaseURL + "/" + mediumFile.getName(); } if (largeFile != null) { largeURI = filesBaseURL + "/" + largeFile.getName(); } /* * 4. Generate Hashcode to use as new name */ String hashcode = UUID.nameUUIDFromBytes(fullPath.getBytes()) .toString(); /* * 5. Save File metadata in Database */ fileBean.setFilename(fileName); fileBean.setURI(filesBaseURL + "/" + fileName); fileBean.setThumbnailURI(thumbnailURI); fileBean.setMediumURI(mediumURI); fileBean.setSmallURI(smallURI); fileBean.setLargeURI(largeURI); fileBean.setContentType(contentType); fileBean.setCreationDate(DateTime.now()); fileBean.setHashcode(hashcode); fileBean.setExtension(fileExtension); Logger.root().debug("--> creationDate=" + fileBean.getCreationDate()); Logger.root().debug("--> hashcode=" + fileBean.getHashcode()); models.File f = PlayDozerMapper.getInstance().map(fileBean, models.File.class); f.save(); fileBean.setFileId(f.getFileId()); return fileBean; }
diff --git a/geronimo-connector/src/main/java/org/apache/geronimo/connector/ActivationSpecNamedXAResourceFactory.java b/geronimo-connector/src/main/java/org/apache/geronimo/connector/ActivationSpecNamedXAResourceFactory.java index aab2927..0818ba5 100644 --- a/geronimo-connector/src/main/java/org/apache/geronimo/connector/ActivationSpecNamedXAResourceFactory.java +++ b/geronimo-connector/src/main/java/org/apache/geronimo/connector/ActivationSpecNamedXAResourceFactory.java @@ -1,66 +1,66 @@ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.connector; import javax.resource.ResourceException; import javax.resource.spi.ActivationSpec; import javax.resource.spi.ResourceAdapter; import javax.transaction.SystemException; import javax.transaction.xa.XAResource; import org.apache.geronimo.transaction.manager.NamedXAResource; import org.apache.geronimo.transaction.manager.NamedXAResourceFactory; import org.apache.geronimo.transaction.manager.WrapperNamedXAResource; /** * @version $Rev$ $Date$ */ public class ActivationSpecNamedXAResourceFactory implements NamedXAResourceFactory { private final String name; private final ActivationSpec activationSpec; private final ResourceAdapter resourceAdapter; public ActivationSpecNamedXAResourceFactory(String name, ActivationSpec activationSpec, ResourceAdapter resourceAdapter) { this.name = name; this.activationSpec = activationSpec; this.resourceAdapter = resourceAdapter; } public String getName() { return name; } public NamedXAResource getNamedXAResource() throws SystemException { try { XAResource[] xaResources = resourceAdapter.getXAResources(new ActivationSpec[]{activationSpec}); - if (xaResources == null || xaResources.length == 0) { + if (xaResources == null || xaResources.length == 0 || xaResources[0] == null) { return null; } return new WrapperNamedXAResource(xaResources[0], name); } catch (ResourceException e) { throw (SystemException) new SystemException("Could not get XAResource for recovery for mdb: " + name).initCause(e); } } public void returnNamedXAResource(NamedXAResource namedXAResource) { // nothing to do AFAICT } }
true
true
public NamedXAResource getNamedXAResource() throws SystemException { try { XAResource[] xaResources = resourceAdapter.getXAResources(new ActivationSpec[]{activationSpec}); if (xaResources == null || xaResources.length == 0) { return null; } return new WrapperNamedXAResource(xaResources[0], name); } catch (ResourceException e) { throw (SystemException) new SystemException("Could not get XAResource for recovery for mdb: " + name).initCause(e); } }
public NamedXAResource getNamedXAResource() throws SystemException { try { XAResource[] xaResources = resourceAdapter.getXAResources(new ActivationSpec[]{activationSpec}); if (xaResources == null || xaResources.length == 0 || xaResources[0] == null) { return null; } return new WrapperNamedXAResource(xaResources[0], name); } catch (ResourceException e) { throw (SystemException) new SystemException("Could not get XAResource for recovery for mdb: " + name).initCause(e); } }
diff --git a/telosb/src/main/java/de/uniluebeck/itm/wsn/drivers/telosb/TelosbProgramOperation.java b/telosb/src/main/java/de/uniluebeck/itm/wsn/drivers/telosb/TelosbProgramOperation.java index 2d78c4f9..3c0ea561 100644 --- a/telosb/src/main/java/de/uniluebeck/itm/wsn/drivers/telosb/TelosbProgramOperation.java +++ b/telosb/src/main/java/de/uniluebeck/itm/wsn/drivers/telosb/TelosbProgramOperation.java @@ -1,82 +1,82 @@ package de.uniluebeck.itm.wsn.drivers.telosb; import com.google.common.util.concurrent.TimeLimiter; import com.google.inject.Inject; import com.google.inject.assistedinject.Assisted; import de.uniluebeck.itm.wsn.drivers.core.exception.FlashProgramFailedException; import de.uniluebeck.itm.wsn.drivers.core.operation.AbstractProgramOperation; import de.uniluebeck.itm.wsn.drivers.core.operation.OperationFactory; import de.uniluebeck.itm.wsn.drivers.core.operation.OperationListener; import de.uniluebeck.itm.wsn.drivers.core.serialport.SerialPortProgrammingMode; import de.uniluebeck.itm.wsn.drivers.core.util.BinaryImageBlock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.io.IOException; public class TelosbProgramOperation extends AbstractProgramOperation { private static final Logger log = LoggerFactory.getLogger(TelosbProgramOperation.class); private final BSLTelosb bsl; private final OperationFactory operationFactory; @Inject public TelosbProgramOperation(final TimeLimiter timeLimiter, final BSLTelosb bsl, final OperationFactory operationFactory, @Assisted byte[] binaryImage, @Assisted final long timeoutMillis, @Assisted @Nullable final OperationListener<Void> operationCallback) { super(timeLimiter, binaryImage, timeoutMillis, operationCallback); this.bsl = bsl; this.operationFactory = operationFactory; } @Override @SerialPortProgrammingMode protected Void callInternal() throws Exception { final TelosbBinData binData = new TelosbBinData(getBinaryImage()); log.trace("Starting to write program into flash memory..."); - final float workedFraction = 1.0f / binData.getBlockCount(); + final float workedFraction = 0.95f / binData.getBlockCount(); int bytesProgrammed = 0; int blocksWritten = 0; for (BinaryImageBlock block = binData.getNextBlock(); block != null; block = binData.getNextBlock()) { final byte[] data = block.getData(); final int address = block.getAddress(); // write single block try { bsl.writeFlash(address, data, data.length); } catch (FlashProgramFailedException e) { log.error(String.format("Error writing %d bytes into flash " + "at address 0x%02x: " + e + ". Programmed " + bytesProgrammed + " bytes so far. " + ". OperationRunnable will be canceled.", data.length, address ), e ); throw e; } catch (final IOException e) { log.error("I/O error while writing flash. Programmed " + bytesProgrammed + " bytes so far.", e); throw e; } bytesProgrammed += data.length; blocksWritten++; progress(workedFraction * blocksWritten); } log.trace("Programmed {} bytes", bytesProgrammed); runSubOperation(operationFactory.createResetOperation(1000, null), 0.05f); return null; } }
true
true
protected Void callInternal() throws Exception { final TelosbBinData binData = new TelosbBinData(getBinaryImage()); log.trace("Starting to write program into flash memory..."); final float workedFraction = 1.0f / binData.getBlockCount(); int bytesProgrammed = 0; int blocksWritten = 0; for (BinaryImageBlock block = binData.getNextBlock(); block != null; block = binData.getNextBlock()) { final byte[] data = block.getData(); final int address = block.getAddress(); // write single block try { bsl.writeFlash(address, data, data.length); } catch (FlashProgramFailedException e) { log.error(String.format("Error writing %d bytes into flash " + "at address 0x%02x: " + e + ". Programmed " + bytesProgrammed + " bytes so far. " + ". OperationRunnable will be canceled.", data.length, address ), e ); throw e; } catch (final IOException e) { log.error("I/O error while writing flash. Programmed " + bytesProgrammed + " bytes so far.", e); throw e; } bytesProgrammed += data.length; blocksWritten++; progress(workedFraction * blocksWritten); } log.trace("Programmed {} bytes", bytesProgrammed); runSubOperation(operationFactory.createResetOperation(1000, null), 0.05f); return null; }
protected Void callInternal() throws Exception { final TelosbBinData binData = new TelosbBinData(getBinaryImage()); log.trace("Starting to write program into flash memory..."); final float workedFraction = 0.95f / binData.getBlockCount(); int bytesProgrammed = 0; int blocksWritten = 0; for (BinaryImageBlock block = binData.getNextBlock(); block != null; block = binData.getNextBlock()) { final byte[] data = block.getData(); final int address = block.getAddress(); // write single block try { bsl.writeFlash(address, data, data.length); } catch (FlashProgramFailedException e) { log.error(String.format("Error writing %d bytes into flash " + "at address 0x%02x: " + e + ". Programmed " + bytesProgrammed + " bytes so far. " + ". OperationRunnable will be canceled.", data.length, address ), e ); throw e; } catch (final IOException e) { log.error("I/O error while writing flash. Programmed " + bytesProgrammed + " bytes so far.", e); throw e; } bytesProgrammed += data.length; blocksWritten++; progress(workedFraction * blocksWritten); } log.trace("Programmed {} bytes", bytesProgrammed); runSubOperation(operationFactory.createResetOperation(1000, null), 0.05f); return null; }
diff --git a/src/main/java/fi/csc/microarray/client/visualisation/methods/gbrowser/track/SeqBlockTrack.java b/src/main/java/fi/csc/microarray/client/visualisation/methods/gbrowser/track/SeqBlockTrack.java index b6b2326f5..34a0c3ef1 100644 --- a/src/main/java/fi/csc/microarray/client/visualisation/methods/gbrowser/track/SeqBlockTrack.java +++ b/src/main/java/fi/csc/microarray/client/visualisation/methods/gbrowser/track/SeqBlockTrack.java @@ -1,323 +1,323 @@ package fi.csc.microarray.client.visualisation.methods.gbrowser.track; import java.awt.Color; import java.awt.Rectangle; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import fi.csc.microarray.client.visualisation.methods.gbrowser.DataSource; import fi.csc.microarray.client.visualisation.methods.gbrowser.GenomeBrowserConstants; import fi.csc.microarray.client.visualisation.methods.gbrowser.View; import fi.csc.microarray.client.visualisation.methods.gbrowser.dataFetcher.AreaRequestHandler; import fi.csc.microarray.client.visualisation.methods.gbrowser.drawable.Drawable; import fi.csc.microarray.client.visualisation.methods.gbrowser.drawable.RectDrawable; import fi.csc.microarray.client.visualisation.methods.gbrowser.fileFormat.ColumnType; import fi.csc.microarray.client.visualisation.methods.gbrowser.fileFormat.Strand; import fi.csc.microarray.client.visualisation.methods.gbrowser.message.AreaResult; import fi.csc.microarray.client.visualisation.methods.gbrowser.message.Cigar; import fi.csc.microarray.client.visualisation.methods.gbrowser.message.ReadPart; import fi.csc.microarray.client.visualisation.methods.gbrowser.message.RegionContent; import fi.csc.microarray.client.visualisation.methods.gbrowser.utils.Sequence; /** * Track that shows actual content of reads using color coding. * */ public class SeqBlockTrack extends Track { public static final Color[] charColors = new Color[] { new Color(64, 192, 64, 128), // A new Color(64, 64, 192, 128), // C new Color(128, 128, 128, 128), // G new Color(192, 64, 64, 128) // T }; public static final Color CUTOFF_COLOR = Color.ORANGE; private long maxBpLength; private long minBpLength; private DataSource refData; private Collection<RegionContent> refReads = new TreeSet<RegionContent>(); private boolean highlightSNP = false; private ReadpartDataProvider readpartProvider; public SeqBlockTrack(View view, DataSource file, ReadpartDataProvider readpartProvider, Class<? extends AreaRequestHandler> handler, Color fontColor, long minBpLength, long maxBpLength) { super(view, file, handler); this.minBpLength = minBpLength; this.maxBpLength = maxBpLength; this.readpartProvider = readpartProvider; } @Override public Collection<Drawable> getDrawables() { Collection<Drawable> drawables = getEmptyDrawCollection(); // If SNP highlight mode is on, we need reference sequence data char[] refSeq = highlightSNP ? getReferenceArray(refReads, view, strand) : null; // Preprocessing loop: Iterate over RegionContent objects (one object corresponds to one read) Iterable<ReadPart> readParts = readpartProvider.getReadparts(getStrand()); int reads = 0; // Main loop: Iterate over ReadPart objects (one object corresponds to one continuous element) List<Integer> occupiedSpace = new ArrayList<Integer>(); for (ReadPart readPart : readParts) { // Skip elements that are not in this view if (!readPart.intersects(getView().getBpRegion())) { continue; } // Width in basepairs long widthInBps = readPart.getLength(); // Create rectangle covering the correct screen area (x-axis) Rectangle rect = new Rectangle(); rect.x = getView().bpToTrack(readPart.start); - rect.width = (int) Math.round(getView().bpWidth() * widthInBps); + rect.width = (int) Math.floor(getView().bpWidth() * widthInBps); // Do not draw invisible rectangles if (rect.width < 2) { rect.width = 2; } // Read parts are drawn in order and placed in layers int layer = 0; while (occupiedSpace.size() > layer && occupiedSpace.get(layer) > rect.x + 1) { layer++; } // Read part reserves the space of the layer from end to left corner of the screen int end = rect.x + rect.width; if (occupiedSpace.size() > layer) { occupiedSpace.set(layer, end); } else { occupiedSpace.add(end); } reads++; // Now we can decide the y coordinate rect.y = getYCoord(layer, GenomeBrowserConstants.READ_HEIGHT); rect.height = GenomeBrowserConstants.READ_HEIGHT; // Check if we are about to go over the edge of the drawing area boolean lastBeforeMaxStackingDepthCut = getYCoord(layer + 1, GenomeBrowserConstants.READ_HEIGHT) > getHeight(); // Check if we are over the edge of the drawing area if (rect.y > getHeight()) { continue; } // Check if we have enough space for the actual sequence (at least pixel per nucleotide) String seq = readPart.getSequencePart(); Cigar cigar = (Cigar) readPart.getRead().values.get(ColumnType.CIGAR); if (rect.width < seq.length()) { // Too little space - only show one rectangle for each read part Color color = Color.gray; // Mark last line that will be drawn if (lastBeforeMaxStackingDepthCut) { color = CUTOFF_COLOR; } drawables.add(new RectDrawable(rect, color, null, cigar.toInfoString())); } else { // Enough space - show color coding for each nucleotide // Complement the read if on reverse strand if ((Strand) readPart.getRead().values.get(ColumnType.STRAND) == Strand.REVERSED) { StringBuffer buf = new StringBuffer(seq.toUpperCase()); // Complement seq = buf.toString().replace('A', 'x'). // switch A and T replace('T', 'A').replace('x', 'T'). replace('C', 'x'). // switch C and G replace('G', 'C').replace('x', 'G'); } // Prepare to draw single nucleotides float increment = getView().bpWidth(); float startX = getView().bpToTrackFloat(readPart.start); // Draw each nucleotide for (int j = 0; j < seq.length(); j++) { char letter = seq.charAt(j); long refIndex = j; // Choose a color depending on viewing mode Color bg = Color.white; long posInRef = readPart.start.bp.intValue() + refIndex - getView().getBpRegion().start.bp.intValue(); if (highlightSNP && posInRef >= 0 && posInRef < refSeq.length && Character.toLowerCase(refSeq[(int)posInRef]) == Character.toLowerCase(letter)) { bg = Color.gray; } else { switch (letter) { case 'A': bg = charColors[0]; break; case 'C': bg = charColors[1]; break; case 'G': bg = charColors[2]; break; case 'T': bg = charColors[3]; break; } } // Tell that we have reached max. stacking depth if (lastBeforeMaxStackingDepthCut) { bg = CUTOFF_COLOR; } // Draw rectangle int x1 = Math.round(startX + ((float)refIndex) * increment); int x2 = Math.round(startX + ((float)refIndex + 1f) * increment); int width = Math.max(x2 - x1, 1); drawables.add(new RectDrawable(x1, rect.y, width, GenomeBrowserConstants.READ_HEIGHT, bg, null, cigar.toInfoString())); } } } return drawables; } private int getYCoord(int layer, int height) { return (int) ((layer + 1) * (height + GenomeBrowserConstants.SPACE_BETWEEN_READS)); } public void processAreaResult(AreaResult areaResult) { // Do not listen to actual read data, because that is taken care by ReadpartDataProvider // "Spy" on reference sequence data, if available if (areaResult.getStatus().file == refData) { this.refReads.addAll(areaResult.getContents()); } } @Override public Integer getHeight() { if (isVisible()) { return super.getHeight(); } else { return 0; } } @Override public boolean isStretchable() { return isVisible(); // Stretchable unless hidden } @Override public boolean isVisible() { // visible region is not suitable return (super.isVisible() && getView().getBpRegion().getLength() > minBpLength && getView().getBpRegion().getLength() <= maxBpLength); } @Override public Map<DataSource, Set<ColumnType>> requestedData() { HashMap<DataSource, Set<ColumnType>> datas = new HashMap<DataSource, Set<ColumnType>>(); datas.put(file, new HashSet<ColumnType>(Arrays.asList(new ColumnType[] { ColumnType.ID, ColumnType.SEQUENCE, ColumnType.STRAND, ColumnType.CIGAR }))); // We might also need reference sequence data if (highlightSNP) { datas.put(refData, new HashSet<ColumnType>(Arrays.asList(new ColumnType[] { ColumnType.SEQUENCE }))); } return datas; } @Override public boolean isConcised() { return false; } /** * Enable SNP highlighting and set reference data. * * @param highlightSNP * @see SeqBlockTrack.setReferenceSeq */ public void enableSNPHighlight(DataSource file, Class<? extends AreaRequestHandler> handler) { // turn on highlighting mode highlightSNP = true; // set reference data refData = file; view.getQueueManager().createQueue(file, handler); view.getQueueManager().addResultListener(file, this); } /** * Disable SNP highlighting. * * @param file */ public void disableSNPHiglight(DataSource file) { // turn off highlighting mode highlightSNP = false; } /** * Convert reference sequence reads to a char array. */ public static char[] getReferenceArray(Collection<RegionContent> refReads, View view, Strand strand) { char[] refSeq = new char[0]; Iterator<RegionContent> iter = refReads.iterator(); refSeq = new char[view.getBpRegion().getLength().intValue() + 1]; int startBp = view.getBpRegion().start.bp.intValue(); int endBp = view.getBpRegion().end.bp.intValue(); RegionContent read; while (iter.hasNext()) { read = iter.next(); if (!read.region.intersects(view.getBpRegion())) { iter.remove(); continue; } // we might need to reverse reference sequence char[] readBases; if (strand == Strand.REVERSED) { readBases = Sequence.complement((String) read.values.get(ColumnType.SEQUENCE)).toCharArray(); } else { readBases = ((String) read.values.get(ColumnType.SEQUENCE)).toCharArray(); } int readStart = read.region.start.bp.intValue(); int readNum = 0; int nextPos = 0; for (char c : readBases) { nextPos = readStart + readNum++; if (nextPos >= startBp && nextPos <= endBp) { refSeq[nextPos - startBp] = c; } } } return refSeq; } @Override public String getName() { return "Reads"; } }
true
true
public Collection<Drawable> getDrawables() { Collection<Drawable> drawables = getEmptyDrawCollection(); // If SNP highlight mode is on, we need reference sequence data char[] refSeq = highlightSNP ? getReferenceArray(refReads, view, strand) : null; // Preprocessing loop: Iterate over RegionContent objects (one object corresponds to one read) Iterable<ReadPart> readParts = readpartProvider.getReadparts(getStrand()); int reads = 0; // Main loop: Iterate over ReadPart objects (one object corresponds to one continuous element) List<Integer> occupiedSpace = new ArrayList<Integer>(); for (ReadPart readPart : readParts) { // Skip elements that are not in this view if (!readPart.intersects(getView().getBpRegion())) { continue; } // Width in basepairs long widthInBps = readPart.getLength(); // Create rectangle covering the correct screen area (x-axis) Rectangle rect = new Rectangle(); rect.x = getView().bpToTrack(readPart.start); rect.width = (int) Math.round(getView().bpWidth() * widthInBps); // Do not draw invisible rectangles if (rect.width < 2) { rect.width = 2; } // Read parts are drawn in order and placed in layers int layer = 0; while (occupiedSpace.size() > layer && occupiedSpace.get(layer) > rect.x + 1) { layer++; } // Read part reserves the space of the layer from end to left corner of the screen int end = rect.x + rect.width; if (occupiedSpace.size() > layer) { occupiedSpace.set(layer, end); } else { occupiedSpace.add(end); } reads++; // Now we can decide the y coordinate rect.y = getYCoord(layer, GenomeBrowserConstants.READ_HEIGHT); rect.height = GenomeBrowserConstants.READ_HEIGHT; // Check if we are about to go over the edge of the drawing area boolean lastBeforeMaxStackingDepthCut = getYCoord(layer + 1, GenomeBrowserConstants.READ_HEIGHT) > getHeight(); // Check if we are over the edge of the drawing area if (rect.y > getHeight()) { continue; } // Check if we have enough space for the actual sequence (at least pixel per nucleotide) String seq = readPart.getSequencePart(); Cigar cigar = (Cigar) readPart.getRead().values.get(ColumnType.CIGAR); if (rect.width < seq.length()) { // Too little space - only show one rectangle for each read part Color color = Color.gray; // Mark last line that will be drawn if (lastBeforeMaxStackingDepthCut) { color = CUTOFF_COLOR; } drawables.add(new RectDrawable(rect, color, null, cigar.toInfoString())); } else { // Enough space - show color coding for each nucleotide // Complement the read if on reverse strand if ((Strand) readPart.getRead().values.get(ColumnType.STRAND) == Strand.REVERSED) { StringBuffer buf = new StringBuffer(seq.toUpperCase()); // Complement seq = buf.toString().replace('A', 'x'). // switch A and T replace('T', 'A').replace('x', 'T'). replace('C', 'x'). // switch C and G replace('G', 'C').replace('x', 'G'); } // Prepare to draw single nucleotides float increment = getView().bpWidth(); float startX = getView().bpToTrackFloat(readPart.start); // Draw each nucleotide for (int j = 0; j < seq.length(); j++) { char letter = seq.charAt(j); long refIndex = j; // Choose a color depending on viewing mode Color bg = Color.white; long posInRef = readPart.start.bp.intValue() + refIndex - getView().getBpRegion().start.bp.intValue(); if (highlightSNP && posInRef >= 0 && posInRef < refSeq.length && Character.toLowerCase(refSeq[(int)posInRef]) == Character.toLowerCase(letter)) { bg = Color.gray; } else { switch (letter) { case 'A': bg = charColors[0]; break; case 'C': bg = charColors[1]; break; case 'G': bg = charColors[2]; break; case 'T': bg = charColors[3]; break; } } // Tell that we have reached max. stacking depth if (lastBeforeMaxStackingDepthCut) { bg = CUTOFF_COLOR; } // Draw rectangle int x1 = Math.round(startX + ((float)refIndex) * increment); int x2 = Math.round(startX + ((float)refIndex + 1f) * increment); int width = Math.max(x2 - x1, 1); drawables.add(new RectDrawable(x1, rect.y, width, GenomeBrowserConstants.READ_HEIGHT, bg, null, cigar.toInfoString())); } } } return drawables; }
public Collection<Drawable> getDrawables() { Collection<Drawable> drawables = getEmptyDrawCollection(); // If SNP highlight mode is on, we need reference sequence data char[] refSeq = highlightSNP ? getReferenceArray(refReads, view, strand) : null; // Preprocessing loop: Iterate over RegionContent objects (one object corresponds to one read) Iterable<ReadPart> readParts = readpartProvider.getReadparts(getStrand()); int reads = 0; // Main loop: Iterate over ReadPart objects (one object corresponds to one continuous element) List<Integer> occupiedSpace = new ArrayList<Integer>(); for (ReadPart readPart : readParts) { // Skip elements that are not in this view if (!readPart.intersects(getView().getBpRegion())) { continue; } // Width in basepairs long widthInBps = readPart.getLength(); // Create rectangle covering the correct screen area (x-axis) Rectangle rect = new Rectangle(); rect.x = getView().bpToTrack(readPart.start); rect.width = (int) Math.floor(getView().bpWidth() * widthInBps); // Do not draw invisible rectangles if (rect.width < 2) { rect.width = 2; } // Read parts are drawn in order and placed in layers int layer = 0; while (occupiedSpace.size() > layer && occupiedSpace.get(layer) > rect.x + 1) { layer++; } // Read part reserves the space of the layer from end to left corner of the screen int end = rect.x + rect.width; if (occupiedSpace.size() > layer) { occupiedSpace.set(layer, end); } else { occupiedSpace.add(end); } reads++; // Now we can decide the y coordinate rect.y = getYCoord(layer, GenomeBrowserConstants.READ_HEIGHT); rect.height = GenomeBrowserConstants.READ_HEIGHT; // Check if we are about to go over the edge of the drawing area boolean lastBeforeMaxStackingDepthCut = getYCoord(layer + 1, GenomeBrowserConstants.READ_HEIGHT) > getHeight(); // Check if we are over the edge of the drawing area if (rect.y > getHeight()) { continue; } // Check if we have enough space for the actual sequence (at least pixel per nucleotide) String seq = readPart.getSequencePart(); Cigar cigar = (Cigar) readPart.getRead().values.get(ColumnType.CIGAR); if (rect.width < seq.length()) { // Too little space - only show one rectangle for each read part Color color = Color.gray; // Mark last line that will be drawn if (lastBeforeMaxStackingDepthCut) { color = CUTOFF_COLOR; } drawables.add(new RectDrawable(rect, color, null, cigar.toInfoString())); } else { // Enough space - show color coding for each nucleotide // Complement the read if on reverse strand if ((Strand) readPart.getRead().values.get(ColumnType.STRAND) == Strand.REVERSED) { StringBuffer buf = new StringBuffer(seq.toUpperCase()); // Complement seq = buf.toString().replace('A', 'x'). // switch A and T replace('T', 'A').replace('x', 'T'). replace('C', 'x'). // switch C and G replace('G', 'C').replace('x', 'G'); } // Prepare to draw single nucleotides float increment = getView().bpWidth(); float startX = getView().bpToTrackFloat(readPart.start); // Draw each nucleotide for (int j = 0; j < seq.length(); j++) { char letter = seq.charAt(j); long refIndex = j; // Choose a color depending on viewing mode Color bg = Color.white; long posInRef = readPart.start.bp.intValue() + refIndex - getView().getBpRegion().start.bp.intValue(); if (highlightSNP && posInRef >= 0 && posInRef < refSeq.length && Character.toLowerCase(refSeq[(int)posInRef]) == Character.toLowerCase(letter)) { bg = Color.gray; } else { switch (letter) { case 'A': bg = charColors[0]; break; case 'C': bg = charColors[1]; break; case 'G': bg = charColors[2]; break; case 'T': bg = charColors[3]; break; } } // Tell that we have reached max. stacking depth if (lastBeforeMaxStackingDepthCut) { bg = CUTOFF_COLOR; } // Draw rectangle int x1 = Math.round(startX + ((float)refIndex) * increment); int x2 = Math.round(startX + ((float)refIndex + 1f) * increment); int width = Math.max(x2 - x1, 1); drawables.add(new RectDrawable(x1, rect.y, width, GenomeBrowserConstants.READ_HEIGHT, bg, null, cigar.toInfoString())); } } } return drawables; }
diff --git a/src/plugin/lib-parsems/src/java/org/apache/nutch/parse/ms/MSBaseParser.java b/src/plugin/lib-parsems/src/java/org/apache/nutch/parse/ms/MSBaseParser.java index db458d4f..d2fc1ced 100644 --- a/src/plugin/lib-parsems/src/java/org/apache/nutch/parse/ms/MSBaseParser.java +++ b/src/plugin/lib-parsems/src/java/org/apache/nutch/parse/ms/MSBaseParser.java @@ -1,163 +1,165 @@ /** * Copyright 2005 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.nutch.parse.ms; // JDK imports import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.util.Properties; // Commons Logging imports import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; // Hadoop imports import org.apache.hadoop.conf.Configuration; // Nutch imports import org.apache.nutch.metadata.DublinCore; import org.apache.nutch.metadata.Metadata; import org.apache.nutch.net.protocols.Response; import org.apache.nutch.parse.Outlink; import org.apache.nutch.parse.OutlinkExtractor; import org.apache.nutch.parse.Parse; import org.apache.nutch.parse.ParseData; import org.apache.nutch.parse.ParseImpl; import org.apache.nutch.parse.ParseStatus; import org.apache.nutch.parse.Parser; import org.apache.nutch.protocol.Content; import org.apache.nutch.util.LogUtil; import org.apache.nutch.util.NutchConfiguration; /** * A generic Microsoft document parser. * * @author J&eacute;r&ocirc;me Charron */ public abstract class MSBaseParser implements Parser { private Configuration conf; protected static final Log LOG = LogFactory.getLog(MSBaseParser.class); /** * Parses a Content with a specific {@link MSExtractor Microsoft document * extractor}. */ protected Parse getParse(MSExtractor extractor, Content content) { String text = null; String title = null; Outlink[] outlinks = null; Properties properties = null; try { byte[] raw = content.getContent(); String contentLength = content.getMetadata().get(Metadata.CONTENT_LENGTH); if ((contentLength != null) && (raw.length != Integer.parseInt(contentLength))) { return new ParseStatus(ParseStatus.FAILED, ParseStatus.FAILED_TRUNCATED, "Content truncated at " + raw.length +" bytes. " + "Parser can't handle incomplete file.") .getEmptyParse(this.conf); } extractor.extract(new ByteArrayInputStream(raw)); text = extractor.getText(); properties = extractor.getProperties(); outlinks = OutlinkExtractor.getOutlinks(text, content.getUrl(), getConf()); } catch (Exception e) { return new ParseStatus(ParseStatus.FAILED, - "Can't be handled as micrsosoft document. " + e) + "Can't be handled as Microsoft document. " + e) .getEmptyParse(this.conf); } // collect meta data Metadata metadata = new Metadata(); - title = properties.getProperty(DublinCore.TITLE); - properties.remove(DublinCore.TITLE); - metadata.setAll(properties); + if (properties != null) { + title = properties.getProperty(DublinCore.TITLE); + properties.remove(DublinCore.TITLE); + metadata.setAll(properties); + } if (text == null) { text = ""; } if (title == null) { title = ""; } ParseData parseData = new ParseData(ParseStatus.STATUS_SUCCESS, title, outlinks, content.getMetadata(), metadata); parseData.setConf(this.conf); return new ParseImpl(text, parseData); } /** * Main for testing. Pass a ms document as argument */ public static void main(String mime, MSBaseParser parser, String args[]) { if (args.length < 1) { System.err.println("Usage:"); System.err.println("\t" + parser.getClass().getName() + " <file>"); System.exit(1); } String file = args[0]; byte[] raw = getRawBytes(new File(file)); Metadata meta = new Metadata(); meta.set(Response.CONTENT_LENGTH, "" + raw.length); Content content = new Content(file, file, raw, mime, meta, NutchConfiguration.create()); System.out.println(parser.getParse(content).getText()); } private final static byte[] getRawBytes(File f) { try { if (!f.exists()) return null; FileInputStream fin = new FileInputStream(f); byte[] buffer = new byte[(int) f.length()]; fin.read(buffer); fin.close(); return buffer; } catch (Exception err) { err.printStackTrace(LogUtil.getErrorStream(LOG)); return null; } } /* ---------------------------- * * <implemenation:Configurable> * * ---------------------------- */ public void setConf(Configuration conf) { this.conf = conf; } public Configuration getConf() { return this.conf; } /* ----------------------------- * * </implemenation:Configurable> * * ----------------------------- */ }
false
true
protected Parse getParse(MSExtractor extractor, Content content) { String text = null; String title = null; Outlink[] outlinks = null; Properties properties = null; try { byte[] raw = content.getContent(); String contentLength = content.getMetadata().get(Metadata.CONTENT_LENGTH); if ((contentLength != null) && (raw.length != Integer.parseInt(contentLength))) { return new ParseStatus(ParseStatus.FAILED, ParseStatus.FAILED_TRUNCATED, "Content truncated at " + raw.length +" bytes. " + "Parser can't handle incomplete file.") .getEmptyParse(this.conf); } extractor.extract(new ByteArrayInputStream(raw)); text = extractor.getText(); properties = extractor.getProperties(); outlinks = OutlinkExtractor.getOutlinks(text, content.getUrl(), getConf()); } catch (Exception e) { return new ParseStatus(ParseStatus.FAILED, "Can't be handled as micrsosoft document. " + e) .getEmptyParse(this.conf); } // collect meta data Metadata metadata = new Metadata(); title = properties.getProperty(DublinCore.TITLE); properties.remove(DublinCore.TITLE); metadata.setAll(properties); if (text == null) { text = ""; } if (title == null) { title = ""; } ParseData parseData = new ParseData(ParseStatus.STATUS_SUCCESS, title, outlinks, content.getMetadata(), metadata); parseData.setConf(this.conf); return new ParseImpl(text, parseData); }
protected Parse getParse(MSExtractor extractor, Content content) { String text = null; String title = null; Outlink[] outlinks = null; Properties properties = null; try { byte[] raw = content.getContent(); String contentLength = content.getMetadata().get(Metadata.CONTENT_LENGTH); if ((contentLength != null) && (raw.length != Integer.parseInt(contentLength))) { return new ParseStatus(ParseStatus.FAILED, ParseStatus.FAILED_TRUNCATED, "Content truncated at " + raw.length +" bytes. " + "Parser can't handle incomplete file.") .getEmptyParse(this.conf); } extractor.extract(new ByteArrayInputStream(raw)); text = extractor.getText(); properties = extractor.getProperties(); outlinks = OutlinkExtractor.getOutlinks(text, content.getUrl(), getConf()); } catch (Exception e) { return new ParseStatus(ParseStatus.FAILED, "Can't be handled as Microsoft document. " + e) .getEmptyParse(this.conf); } // collect meta data Metadata metadata = new Metadata(); if (properties != null) { title = properties.getProperty(DublinCore.TITLE); properties.remove(DublinCore.TITLE); metadata.setAll(properties); } if (text == null) { text = ""; } if (title == null) { title = ""; } ParseData parseData = new ParseData(ParseStatus.STATUS_SUCCESS, title, outlinks, content.getMetadata(), metadata); parseData.setConf(this.conf); return new ParseImpl(text, parseData); }
diff --git a/src/cx/mccormick/pddroidparty/PdDroidPatchView.java b/src/cx/mccormick/pddroidparty/PdDroidPatchView.java index 56e5f5b..5e00445 100644 --- a/src/cx/mccormick/pddroidparty/PdDroidPatchView.java +++ b/src/cx/mccormick/pddroidparty/PdDroidPatchView.java @@ -1,122 +1,122 @@ package cx.mccormick.pddroidparty; import java.util.ArrayList; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; public class PdDroidPatchView extends View implements OnTouchListener { private static final String TAG = "PdDroidPatchView"; Paint paint = new Paint(); public int patchwidth; public int patchheight; public int fontsize; ArrayList<Widget> widgets = new ArrayList<Widget>(); public PdDroidParty app; public PdDroidPatchView(Context context, PdDroidParty parent) { super(context); app = parent; setFocusable(true); setFocusableInTouchMode(true); this.setOnTouchListener(this); paint.setColor(Color.WHITE); paint.setAntiAlias(true); } @Override public void onDraw(Canvas canvas) { canvas.drawPaint(paint); // draw all widgets if (widgets != null) { for (Widget widget: widgets) { widget.draw(canvas); } } } public boolean onTouch(View view, MotionEvent event) { // if(event.getAction() != MotionEvent.ACTION_DOWN) // return super.onTouchEvent(event); if (widgets != null) { for (Widget widget: widgets) { widget.touch(event); } } invalidate(); //Log.d(TAG, "touch: " + event.getX() + " " + event.getY()); return true; } /** Lets us invalidate this view from the audio thread */ public void threadSafeInvalidate() { final PdDroidPatchView me = this; app.runOnUiThread(new Runnable() { @Override public void run() { me.invalidate(); } }); } /** build a user interface using the lines of atoms found in the patch by the pd file parser */ public void buildUI(PdParser p, ArrayList<String[]> atomlines) { //ArrayList<String> canvases = new ArrayList<String>(); int level = 0; for (String[] line: atomlines) { if (line.length >= 4) { // find canvas begin and end lines if (line[1].equals("canvas")) { /*if (canvases.length == 0) { canvases.add(0, "self"); } else { canvases.add(0, line[6]); }*/ level += 1; if (level == 1) { patchwidth = Integer.parseInt(line[4]); patchheight = Integer.parseInt(line[5]); fontsize = Integer.parseInt(line[6]); } } else if (line[1].equals("restore")) { //canvases.remove(0); level -= 1; // find different types of UI element in the top level patch } else if (level == 1) { - if (line.length >= 5) { - if (line[4].equals("vsl")) { - widgets.add(new Slider(this, line, false)); - } else if (line[4].equals("hsl")) { - widgets.add(new Slider(this, line, true)); - } else if (line[4].equals("tgl")) { - widgets.add(new Toggle(this, line)); - } else if (line[4].equals("bng")) { - widgets.add(new Bang(this, line)); - } else if (line[4].equals("nbx")) { - widgets.add(new Numberbox2(this, line)); - } - } else if (line.length >= 2) { + if (line.length >= 2) { if (line[1].equals("text")) { widgets.add(new Comment(this, line)); } else if (line[1].equals("floatatom")) { widgets.add(new Numberbox(this, line)); + } else if (line.length >= 5) { + if (line[4].equals("vsl")) { + widgets.add(new Slider(this, line, false)); + } else if (line[4].equals("hsl")) { + widgets.add(new Slider(this, line, true)); + } else if (line[4].equals("tgl")) { + widgets.add(new Toggle(this, line)); + } else if (line[4].equals("bng")) { + widgets.add(new Bang(this, line)); + } else if (line[4].equals("nbx")) { + widgets.add(new Numberbox2(this, line)); + } } } } } } threadSafeInvalidate(); } }
false
true
public void buildUI(PdParser p, ArrayList<String[]> atomlines) { //ArrayList<String> canvases = new ArrayList<String>(); int level = 0; for (String[] line: atomlines) { if (line.length >= 4) { // find canvas begin and end lines if (line[1].equals("canvas")) { /*if (canvases.length == 0) { canvases.add(0, "self"); } else { canvases.add(0, line[6]); }*/ level += 1; if (level == 1) { patchwidth = Integer.parseInt(line[4]); patchheight = Integer.parseInt(line[5]); fontsize = Integer.parseInt(line[6]); } } else if (line[1].equals("restore")) { //canvases.remove(0); level -= 1; // find different types of UI element in the top level patch } else if (level == 1) { if (line.length >= 5) { if (line[4].equals("vsl")) { widgets.add(new Slider(this, line, false)); } else if (line[4].equals("hsl")) { widgets.add(new Slider(this, line, true)); } else if (line[4].equals("tgl")) { widgets.add(new Toggle(this, line)); } else if (line[4].equals("bng")) { widgets.add(new Bang(this, line)); } else if (line[4].equals("nbx")) { widgets.add(new Numberbox2(this, line)); } } else if (line.length >= 2) { if (line[1].equals("text")) { widgets.add(new Comment(this, line)); } else if (line[1].equals("floatatom")) { widgets.add(new Numberbox(this, line)); } } } } }
public void buildUI(PdParser p, ArrayList<String[]> atomlines) { //ArrayList<String> canvases = new ArrayList<String>(); int level = 0; for (String[] line: atomlines) { if (line.length >= 4) { // find canvas begin and end lines if (line[1].equals("canvas")) { /*if (canvases.length == 0) { canvases.add(0, "self"); } else { canvases.add(0, line[6]); }*/ level += 1; if (level == 1) { patchwidth = Integer.parseInt(line[4]); patchheight = Integer.parseInt(line[5]); fontsize = Integer.parseInt(line[6]); } } else if (line[1].equals("restore")) { //canvases.remove(0); level -= 1; // find different types of UI element in the top level patch } else if (level == 1) { if (line.length >= 2) { if (line[1].equals("text")) { widgets.add(new Comment(this, line)); } else if (line[1].equals("floatatom")) { widgets.add(new Numberbox(this, line)); } else if (line.length >= 5) { if (line[4].equals("vsl")) { widgets.add(new Slider(this, line, false)); } else if (line[4].equals("hsl")) { widgets.add(new Slider(this, line, true)); } else if (line[4].equals("tgl")) { widgets.add(new Toggle(this, line)); } else if (line[4].equals("bng")) { widgets.add(new Bang(this, line)); } else if (line[4].equals("nbx")) { widgets.add(new Numberbox2(this, line)); } } } } } }
diff --git a/java/gmod_api/src/gmod/Hook.java b/java/gmod_api/src/gmod/Hook.java index c7ae24e..2d57e3b 100644 --- a/java/gmod_api/src/gmod/Hook.java +++ b/java/gmod_api/src/gmod/Hook.java @@ -1,76 +1,76 @@ package gmod; import java.lang.reflect.Method; import java.util.Set; import com.google.common.collect.Sets; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; public class Hook { private static final Handler handler = new Handler(); private static final EventBus eventBus = new EventBus(); private static final Set<String> registeredHooks = Sets.newHashSet(); public static void register(Object o) { eventBus.register(o); for (Method m : o.getClass().getMethods()) { if (!m.isAnnotationPresent(Subscribe.class)) { System.out.println("Continuing because no subscribe"); continue; } if (m.getParameterTypes().length != 1) { System.out.println("Continuing because params != 1"); continue; } Class<?> parmClass = m.getParameterTypes()[0]; - if (!parmClass.isAssignableFrom(Event.class)) { + if (!Event.class.isAssignableFrom(parmClass)) { System.out.println("Continuing because parm not event"); continue; } Class<? extends Event> eventClass = parmClass.asSubclass(Event.class); if (!eventClass.isAnnotationPresent(Event.Info.class)) { System.out.println("Continuing because no Event.Info"); continue; } Event.Info eventInfo = eventClass.getAnnotation(Event.Info.class); if (!registeredHooks.contains(eventInfo.name())) { Lua.getglobal("hook"); Lua.getfield(-1, "Add"); Lua.pushstring(eventInfo.name()); Lua.pushstring("java." + eventClass.getName()); Lua.pushobject(eventClass); Lua.pushclosure(handler, 1); System.out.println("Hooking " + eventInfo.name() + " (" + eventClass.getName() + ")..."); Lua.call(3, 0); registeredHooks.add(eventInfo.name()); } } } public static void unregister(Object o) { eventBus.unregister(o); } private static class Handler implements Lua.Function { @Override public int invoke() throws Exception { Class<? extends Event> eventClass = ((Class<?>) Lua.toobject(Lua.upvalueindex(1))).asSubclass(Event.class); if (eventClass != null) { Event event = eventClass.newInstance(); eventBus.post(event); } return 0; } } }
true
true
public static void register(Object o) { eventBus.register(o); for (Method m : o.getClass().getMethods()) { if (!m.isAnnotationPresent(Subscribe.class)) { System.out.println("Continuing because no subscribe"); continue; } if (m.getParameterTypes().length != 1) { System.out.println("Continuing because params != 1"); continue; } Class<?> parmClass = m.getParameterTypes()[0]; if (!parmClass.isAssignableFrom(Event.class)) { System.out.println("Continuing because parm not event"); continue; } Class<? extends Event> eventClass = parmClass.asSubclass(Event.class); if (!eventClass.isAnnotationPresent(Event.Info.class)) { System.out.println("Continuing because no Event.Info"); continue; } Event.Info eventInfo = eventClass.getAnnotation(Event.Info.class); if (!registeredHooks.contains(eventInfo.name())) { Lua.getglobal("hook"); Lua.getfield(-1, "Add"); Lua.pushstring(eventInfo.name()); Lua.pushstring("java." + eventClass.getName()); Lua.pushobject(eventClass); Lua.pushclosure(handler, 1); System.out.println("Hooking " + eventInfo.name() + " (" + eventClass.getName() + ")..."); Lua.call(3, 0); registeredHooks.add(eventInfo.name()); } } }
public static void register(Object o) { eventBus.register(o); for (Method m : o.getClass().getMethods()) { if (!m.isAnnotationPresent(Subscribe.class)) { System.out.println("Continuing because no subscribe"); continue; } if (m.getParameterTypes().length != 1) { System.out.println("Continuing because params != 1"); continue; } Class<?> parmClass = m.getParameterTypes()[0]; if (!Event.class.isAssignableFrom(parmClass)) { System.out.println("Continuing because parm not event"); continue; } Class<? extends Event> eventClass = parmClass.asSubclass(Event.class); if (!eventClass.isAnnotationPresent(Event.Info.class)) { System.out.println("Continuing because no Event.Info"); continue; } Event.Info eventInfo = eventClass.getAnnotation(Event.Info.class); if (!registeredHooks.contains(eventInfo.name())) { Lua.getglobal("hook"); Lua.getfield(-1, "Add"); Lua.pushstring(eventInfo.name()); Lua.pushstring("java." + eventClass.getName()); Lua.pushobject(eventClass); Lua.pushclosure(handler, 1); System.out.println("Hooking " + eventInfo.name() + " (" + eventClass.getName() + ")..."); Lua.call(3, 0); registeredHooks.add(eventInfo.name()); } } }
diff --git a/src/org/bitstrings/eclipse/m2e/common/JavaProjectUtils.java b/src/org/bitstrings/eclipse/m2e/common/JavaProjectUtils.java index d2c07c8..224eeb0 100644 --- a/src/org/bitstrings/eclipse/m2e/common/JavaProjectUtils.java +++ b/src/org/bitstrings/eclipse/m2e/common/JavaProjectUtils.java @@ -1,27 +1,27 @@ package org.bitstrings.eclipse.m2e.common; import org.eclipse.core.runtime.IPath; import org.eclipse.jdt.core.IClasspathEntry; public class JavaProjectUtils { private JavaProjectUtils() {} public static int indexOfPath(IPath path, IClasspathEntry... classpathEntries) { for (int i = 0; i < classpathEntries.length; i++) { - if (classpathEntries[i].equals(path)) + if (classpathEntries[i].getPath().equals(path)) { return i; } } return -1; } public static boolean containsPath(IPath path, IClasspathEntry... classpathEntries) { return (indexOfPath(path, classpathEntries) != -1); } }
true
true
public static int indexOfPath(IPath path, IClasspathEntry... classpathEntries) { for (int i = 0; i < classpathEntries.length; i++) { if (classpathEntries[i].equals(path)) { return i; } } return -1; }
public static int indexOfPath(IPath path, IClasspathEntry... classpathEntries) { for (int i = 0; i < classpathEntries.length; i++) { if (classpathEntries[i].getPath().equals(path)) { return i; } } return -1; }
diff --git a/src/main/java/pl/llp/aircasting/sensor/bioharness/SummaryPacket.java b/src/main/java/pl/llp/aircasting/sensor/bioharness/SummaryPacket.java index 00fb57ae..cc4ddc59 100644 --- a/src/main/java/pl/llp/aircasting/sensor/bioharness/SummaryPacket.java +++ b/src/main/java/pl/llp/aircasting/sensor/bioharness/SummaryPacket.java @@ -1,165 +1,165 @@ package pl.llp.aircasting.sensor.bioharness; public class SummaryPacket extends Packet { private final int heartRate; private final int heartRateVariability; private final int galvanicSkinResponse; private final double respirationRate; private final double skinTemperature; private final double coreTemperature; private final double activity; private final boolean activityReliable; private final boolean heartRateReliable; private final boolean heartRateVariablityReliable; private final boolean skinTemperatureReliable; private final boolean respirationRateReliable; private final int breathingWaveAmplitude; private final int breathingWaveNoise; private final int ecgAmplitude; private final int ecgNoise; ; public SummaryPacket(byte[] input, int offset) { byte dlc = input[offset + 2]; if(input.length - dlc < 0) { throw new RuntimeException("Not long enough"); } Builder builder = new Builder(input, offset); this.heartRate = builder.intFromBytes().higher(14).lower(13).value(); this.respirationRate = builder.intFromBytes().higher(16).lower(15).value() / 10.0d; this.skinTemperature = (builder.intFromBytes().higher(18).lower(17).value()) / 10.0d; this.heartRateVariability = (builder.intFromBytes().higher(39).lower(38).value()); this.coreTemperature = (builder.intFromBytes().higher(65).lower(64).value()) / 10.0d; this.galvanicSkinResponse = (builder.intFromBytes().higher(42).lower(41).value()); - this.activity = (builder.intFromBytes().higher(22).lower(21).value()) / 100d; + this.activity = (builder.intFromBytes().higher(22).lower(21).value()); this.breathingWaveAmplitude = builder.intFromBytes().higher(29).lower(28).value(); this.breathingWaveNoise = builder.intFromBytes().higher(31).lower(30).value(); this.ecgAmplitude = builder.intFromBytes().higher(34).lower(33).value(); this.ecgNoise = builder.intFromBytes().higher(36).lower(35).value(); byte ls = input[offset + 59]; byte ms = input[offset + 60]; boolean hruf = (ls & 1 << 4) < 1; boolean rruf = (ls & 1 << 5) < 1; boolean stuf = (ls & 1 << 6) < 1; - boolean acuf = (ls & 1 << 0) < 1; + boolean acuf = (ms & 1 << 0) < 1; boolean hrvuf = (ms & 1 << 1) < 1; this.activityReliable = acuf; this.heartRateReliable = hruf; this.heartRateVariablityReliable = hrvuf; this.skinTemperatureReliable = stuf; this.respirationRateReliable = rruf; } public int getHeartRate() { return heartRate; } public double getRespirationRate() { return respirationRate; } public double getSkinTemperature() { return skinTemperature; } public int getHeartRateVariability() { return heartRateVariability; } public int getGalvanicSkinResponse() { return galvanicSkinResponse; } public double getCoreTemperature() { return coreTemperature; } public boolean isRespirationRateReliable() { return respirationRateReliable && inRange(respirationRate, 0, 70); } public boolean isSkinTemperatureReliable() { return skinTemperatureReliable && inRange(skinTemperature, 0, 60); } public boolean isHeartRateVariabilityReliable() { return heartRateVariablityReliable && inRange(heartRateVariability, 0, 30000); } public boolean isHeartRateReliable() { return heartRateReliable && inRange(heartRate, 0, 240); } private boolean inRange(double value, int lower, int upper) { return value <= upper && value >= lower; } public boolean isGSRReliable() { return inRange(galvanicSkinResponse, 0, 65534); } public boolean isCoreTemperatureReliable() { return inRange(coreTemperature, 32, 42); } public boolean isECGReliable() { return inRange(ecgAmplitude, 0, 50000); } public int getBreathingWaveAmplitude() { return breathingWaveAmplitude; } public int getBreathingWaveNoise() { return breathingWaveNoise; } public int getEcgAmplitude() { return ecgAmplitude; } public int getEcgNoise() { return ecgNoise; } public double getActivity() { return activity; } public boolean isActivityReliable() { return activityReliable && inRange(activity, 0, 16); } }
false
true
public SummaryPacket(byte[] input, int offset) { byte dlc = input[offset + 2]; if(input.length - dlc < 0) { throw new RuntimeException("Not long enough"); } Builder builder = new Builder(input, offset); this.heartRate = builder.intFromBytes().higher(14).lower(13).value(); this.respirationRate = builder.intFromBytes().higher(16).lower(15).value() / 10.0d; this.skinTemperature = (builder.intFromBytes().higher(18).lower(17).value()) / 10.0d; this.heartRateVariability = (builder.intFromBytes().higher(39).lower(38).value()); this.coreTemperature = (builder.intFromBytes().higher(65).lower(64).value()) / 10.0d; this.galvanicSkinResponse = (builder.intFromBytes().higher(42).lower(41).value()); this.activity = (builder.intFromBytes().higher(22).lower(21).value()) / 100d; this.breathingWaveAmplitude = builder.intFromBytes().higher(29).lower(28).value(); this.breathingWaveNoise = builder.intFromBytes().higher(31).lower(30).value(); this.ecgAmplitude = builder.intFromBytes().higher(34).lower(33).value(); this.ecgNoise = builder.intFromBytes().higher(36).lower(35).value(); byte ls = input[offset + 59]; byte ms = input[offset + 60]; boolean hruf = (ls & 1 << 4) < 1; boolean rruf = (ls & 1 << 5) < 1; boolean stuf = (ls & 1 << 6) < 1; boolean acuf = (ls & 1 << 0) < 1; boolean hrvuf = (ms & 1 << 1) < 1; this.activityReliable = acuf; this.heartRateReliable = hruf; this.heartRateVariablityReliable = hrvuf; this.skinTemperatureReliable = stuf; this.respirationRateReliable = rruf; }
public SummaryPacket(byte[] input, int offset) { byte dlc = input[offset + 2]; if(input.length - dlc < 0) { throw new RuntimeException("Not long enough"); } Builder builder = new Builder(input, offset); this.heartRate = builder.intFromBytes().higher(14).lower(13).value(); this.respirationRate = builder.intFromBytes().higher(16).lower(15).value() / 10.0d; this.skinTemperature = (builder.intFromBytes().higher(18).lower(17).value()) / 10.0d; this.heartRateVariability = (builder.intFromBytes().higher(39).lower(38).value()); this.coreTemperature = (builder.intFromBytes().higher(65).lower(64).value()) / 10.0d; this.galvanicSkinResponse = (builder.intFromBytes().higher(42).lower(41).value()); this.activity = (builder.intFromBytes().higher(22).lower(21).value()); this.breathingWaveAmplitude = builder.intFromBytes().higher(29).lower(28).value(); this.breathingWaveNoise = builder.intFromBytes().higher(31).lower(30).value(); this.ecgAmplitude = builder.intFromBytes().higher(34).lower(33).value(); this.ecgNoise = builder.intFromBytes().higher(36).lower(35).value(); byte ls = input[offset + 59]; byte ms = input[offset + 60]; boolean hruf = (ls & 1 << 4) < 1; boolean rruf = (ls & 1 << 5) < 1; boolean stuf = (ls & 1 << 6) < 1; boolean acuf = (ms & 1 << 0) < 1; boolean hrvuf = (ms & 1 << 1) < 1; this.activityReliable = acuf; this.heartRateReliable = hruf; this.heartRateVariablityReliable = hrvuf; this.skinTemperatureReliable = stuf; this.respirationRateReliable = rruf; }
diff --git a/org.touge.restclient/src/test/java/org/touge/restclient/test/URLBuilderTestCase.java b/org.touge.restclient/src/test/java/org/touge/restclient/test/URLBuilderTestCase.java index a35fb84..2a16e6e 100644 --- a/org.touge.restclient/src/test/java/org/touge/restclient/test/URLBuilderTestCase.java +++ b/org.touge.restclient/src/test/java/org/touge/restclient/test/URLBuilderTestCase.java @@ -1,61 +1,62 @@ package org.touge.restclient.test; import junit.framework.TestCase; import org.touge.restclient.RestClient; import org.touge.restclient.RestClient.URLBuilder; public class URLBuilderTestCase extends TestCase { public void testURLBuilder() { RestClient restClient = new RestClient(); //This URLBuilder builds https://citibank.com/secureme/halp String url = restClient.buildURL("htTPS://citibank.com/secureme/").append("/halp").toString(); assertTrue(url.equals("https://citibank.com/secureme/halp")); // Builds http://yahoo.com/a/mystore/toodles?index=5 url = restClient.buildURL("yahoo.com") .append("a") .append("mystore/") .append("toodles?index=5").toString(); assertTrue(url.equals("http://yahoo.com/a/mystore/toodles?index=5")); // Builds http://me.com/you/andi/like/each/ohter url = restClient.buildURL("me.com/") .append("/you/") .append("/andi/") .append("like/each/ohter/").toString(); assertTrue(url.equals("http://me.com/you/andi/like/each/ohter")); // Builds https://myhost.com/first/second/third/forth/fith/mypage.asp?i=1&b=2&c=3 url = restClient.buildURL( "myhost.com", "first/", "//second", "third/forth/fith", "mypage.asp?i=1&b=2&c=3").setHttps(true).toString(); assertTrue(url.equals("https://myhost.com/first/second/third/forth/fith/mypage.asp?i=1&b=2&c=3")); // Create child URLs from base URLs URLBuilder origurl = restClient.buildURL("myhost.net/","/homepage"); URLBuilder newurl = origurl .copy() .append("asdf/adf/reqotwoetiywer") .setHttps(true); // Original URL: http://myhost.net/homepage assertTrue(origurl.toString().equals("http://myhost.net/homepage")); // Child URL: https://myhost.net/homepage/asdf/adf/reqotwoetiywer assertTrue(newurl.toString().equals("https://myhost.net/homepage/asdf/adf/reqotwoetiywer")); URLBuilder purl = restClient.buildURL("myhost.net/","/homepage"); purl.addParameter("p1", "v1"); purl.addParameter("p1", "v1-2"); purl.addParameter("p2", "v2"); - assertTrue(purl.toString().equals("http://myhost.net/homepage?v1=p1&v1-2=p1&v2=p2")); + System.out.println(purl.toString()); + assertTrue(purl.toString().equals("http://myhost.net/homepage?p1=v1&p1=v1-2&p2=v2")); } }
true
true
public void testURLBuilder() { RestClient restClient = new RestClient(); //This URLBuilder builds https://citibank.com/secureme/halp String url = restClient.buildURL("htTPS://citibank.com/secureme/").append("/halp").toString(); assertTrue(url.equals("https://citibank.com/secureme/halp")); // Builds http://yahoo.com/a/mystore/toodles?index=5 url = restClient.buildURL("yahoo.com") .append("a") .append("mystore/") .append("toodles?index=5").toString(); assertTrue(url.equals("http://yahoo.com/a/mystore/toodles?index=5")); // Builds http://me.com/you/andi/like/each/ohter url = restClient.buildURL("me.com/") .append("/you/") .append("/andi/") .append("like/each/ohter/").toString(); assertTrue(url.equals("http://me.com/you/andi/like/each/ohter")); // Builds https://myhost.com/first/second/third/forth/fith/mypage.asp?i=1&b=2&c=3 url = restClient.buildURL( "myhost.com", "first/", "//second", "third/forth/fith", "mypage.asp?i=1&b=2&c=3").setHttps(true).toString(); assertTrue(url.equals("https://myhost.com/first/second/third/forth/fith/mypage.asp?i=1&b=2&c=3")); // Create child URLs from base URLs URLBuilder origurl = restClient.buildURL("myhost.net/","/homepage"); URLBuilder newurl = origurl .copy() .append("asdf/adf/reqotwoetiywer") .setHttps(true); // Original URL: http://myhost.net/homepage assertTrue(origurl.toString().equals("http://myhost.net/homepage")); // Child URL: https://myhost.net/homepage/asdf/adf/reqotwoetiywer assertTrue(newurl.toString().equals("https://myhost.net/homepage/asdf/adf/reqotwoetiywer")); URLBuilder purl = restClient.buildURL("myhost.net/","/homepage"); purl.addParameter("p1", "v1"); purl.addParameter("p1", "v1-2"); purl.addParameter("p2", "v2"); assertTrue(purl.toString().equals("http://myhost.net/homepage?v1=p1&v1-2=p1&v2=p2")); }
public void testURLBuilder() { RestClient restClient = new RestClient(); //This URLBuilder builds https://citibank.com/secureme/halp String url = restClient.buildURL("htTPS://citibank.com/secureme/").append("/halp").toString(); assertTrue(url.equals("https://citibank.com/secureme/halp")); // Builds http://yahoo.com/a/mystore/toodles?index=5 url = restClient.buildURL("yahoo.com") .append("a") .append("mystore/") .append("toodles?index=5").toString(); assertTrue(url.equals("http://yahoo.com/a/mystore/toodles?index=5")); // Builds http://me.com/you/andi/like/each/ohter url = restClient.buildURL("me.com/") .append("/you/") .append("/andi/") .append("like/each/ohter/").toString(); assertTrue(url.equals("http://me.com/you/andi/like/each/ohter")); // Builds https://myhost.com/first/second/third/forth/fith/mypage.asp?i=1&b=2&c=3 url = restClient.buildURL( "myhost.com", "first/", "//second", "third/forth/fith", "mypage.asp?i=1&b=2&c=3").setHttps(true).toString(); assertTrue(url.equals("https://myhost.com/first/second/third/forth/fith/mypage.asp?i=1&b=2&c=3")); // Create child URLs from base URLs URLBuilder origurl = restClient.buildURL("myhost.net/","/homepage"); URLBuilder newurl = origurl .copy() .append("asdf/adf/reqotwoetiywer") .setHttps(true); // Original URL: http://myhost.net/homepage assertTrue(origurl.toString().equals("http://myhost.net/homepage")); // Child URL: https://myhost.net/homepage/asdf/adf/reqotwoetiywer assertTrue(newurl.toString().equals("https://myhost.net/homepage/asdf/adf/reqotwoetiywer")); URLBuilder purl = restClient.buildURL("myhost.net/","/homepage"); purl.addParameter("p1", "v1"); purl.addParameter("p1", "v1-2"); purl.addParameter("p2", "v2"); System.out.println(purl.toString()); assertTrue(purl.toString().equals("http://myhost.net/homepage?p1=v1&p1=v1-2&p2=v2")); }
diff --git a/src/java/org/apache/cassandra/io/sstable/SSTableMetadata.java b/src/java/org/apache/cassandra/io/sstable/SSTableMetadata.java index 28a6485ea..e38e0916b 100644 --- a/src/java/org/apache/cassandra/io/sstable/SSTableMetadata.java +++ b/src/java/org/apache/cassandra/io/sstable/SSTableMetadata.java @@ -1,448 +1,446 @@ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.io.sstable; import java.io.*; import java.util.*; import org.apache.cassandra.utils.StreamingHistogram; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.cassandra.db.commitlog.ReplayPosition; import org.apache.cassandra.io.util.FileUtils; import org.apache.cassandra.utils.EstimatedHistogram; /** * Metadata for a SSTable. * Metadata includes: * - estimated row size histogram * - estimated column count histogram * - replay position * - max column timestamp * - max local deletion time * - bloom filter fp chance * - compression ratio * - partitioner * - generations of sstables from which this sstable was compacted, if any * - tombstone drop time histogram * * An SSTableMetadata should be instantiated via the Collector, openFromDescriptor() * or createDefaultInstance() */ public class SSTableMetadata { public static final double NO_BLOOM_FLITER_FP_CHANCE = -1.0; public static final double NO_COMPRESSION_RATIO = -1.0; public static final SSTableMetadataSerializer serializer = new SSTableMetadataSerializer(); public final EstimatedHistogram estimatedRowSize; public final EstimatedHistogram estimatedColumnCount; public final ReplayPosition replayPosition; public final long minTimestamp; public final long maxTimestamp; public final int maxLocalDeletionTime; public final double bloomFilterFPChance; public final double compressionRatio; public final String partitioner; public final Set<Integer> ancestors; public final StreamingHistogram estimatedTombstoneDropTime; public final int sstableLevel; private SSTableMetadata() { this(defaultRowSizeHistogram(), defaultColumnCountHistogram(), ReplayPosition.NONE, Long.MAX_VALUE, Long.MIN_VALUE, Integer.MAX_VALUE, NO_BLOOM_FLITER_FP_CHANCE, NO_COMPRESSION_RATIO, null, Collections.<Integer>emptySet(), defaultTombstoneDropTimeHistogram(), 0); } private SSTableMetadata(EstimatedHistogram rowSizes, EstimatedHistogram columnCounts, ReplayPosition replayPosition, long minTimestamp, long maxTimestamp, int maxLocalDeletionTime, double bloomFilterFPChance, double compressionRatio, String partitioner, Set<Integer> ancestors, StreamingHistogram estimatedTombstoneDropTime, int sstableLevel) { this.estimatedRowSize = rowSizes; this.estimatedColumnCount = columnCounts; this.replayPosition = replayPosition; this.minTimestamp = minTimestamp; this.maxTimestamp = maxTimestamp; this.maxLocalDeletionTime = maxLocalDeletionTime; this.bloomFilterFPChance = bloomFilterFPChance; this.compressionRatio = compressionRatio; this.partitioner = partitioner; this.ancestors = ancestors; this.estimatedTombstoneDropTime = estimatedTombstoneDropTime; this.sstableLevel = sstableLevel; } public static SSTableMetadata createDefaultInstance() { return new SSTableMetadata(); } public static Collector createCollector() { return new Collector(); } /** * Used when updating sstablemetadata files with an sstable level * @param metadata * @param sstableLevel * @return */ @Deprecated public static SSTableMetadata copyWithNewSSTableLevel(SSTableMetadata metadata, int sstableLevel) { return new SSTableMetadata(metadata.estimatedRowSize, metadata.estimatedColumnCount, metadata.replayPosition, metadata.minTimestamp, metadata.maxTimestamp, metadata.maxLocalDeletionTime, metadata.bloomFilterFPChance, metadata.compressionRatio, metadata.partitioner, metadata.ancestors, metadata.estimatedTombstoneDropTime, sstableLevel); } static EstimatedHistogram defaultColumnCountHistogram() { // EH of 114 can track a max value of 2395318855, i.e., > 2B columns return new EstimatedHistogram(114); } static EstimatedHistogram defaultRowSizeHistogram() { // EH of 150 can track a max value of 1697806495183, i.e., > 1.5PB return new EstimatedHistogram(150); } static StreamingHistogram defaultTombstoneDropTimeHistogram() { return new StreamingHistogram(SSTable.TOMBSTONE_HISTOGRAM_BIN_SIZE); } /** * @param gcBefore * @return estimated droppable tombstone ratio at given gcBefore time. */ public double getEstimatedDroppableTombstoneRatio(int gcBefore) { long estimatedColumnCount = this.estimatedColumnCount.mean() * this.estimatedColumnCount.count(); if (estimatedColumnCount > 0) { double droppable = getDroppableTombstonesBefore(gcBefore); return droppable / estimatedColumnCount; } return 0.0f; } /** * Get the amount of droppable tombstones * @param gcBefore the gc time * @return amount of droppable tombstones */ public double getDroppableTombstonesBefore(int gcBefore) { return estimatedTombstoneDropTime.sum(gcBefore); } public static class Collector { protected EstimatedHistogram estimatedRowSize = defaultRowSizeHistogram(); protected EstimatedHistogram estimatedColumnCount = defaultColumnCountHistogram(); protected ReplayPosition replayPosition = ReplayPosition.NONE; protected long minTimestamp = Long.MAX_VALUE; protected long maxTimestamp = Long.MIN_VALUE; protected int maxLocalDeletionTime = Integer.MIN_VALUE; protected double compressionRatio = NO_COMPRESSION_RATIO; protected Set<Integer> ancestors = new HashSet<Integer>(); protected StreamingHistogram estimatedTombstoneDropTime = defaultTombstoneDropTimeHistogram(); protected int sstableLevel; public void addRowSize(long rowSize) { estimatedRowSize.add(rowSize); } public void addColumnCount(long columnCount) { estimatedColumnCount.add(columnCount); } public void mergeTombstoneHistogram(StreamingHistogram histogram) { estimatedTombstoneDropTime.merge(histogram); } /** * Ratio is compressed/uncompressed and it is * if you have 1.x then compression isn't helping */ public void addCompressionRatio(long compressed, long uncompressed) { compressionRatio = (double) compressed/uncompressed; } public void updateMinTimestamp(long potentialMin) { minTimestamp = Math.min(minTimestamp, potentialMin); } public void updateMaxTimestamp(long potentialMax) { maxTimestamp = Math.max(maxTimestamp, potentialMax); } public void updateMaxLocalDeletionTime(int maxLocalDeletionTime) { this.maxLocalDeletionTime = Math.max(this.maxLocalDeletionTime, maxLocalDeletionTime); } public SSTableMetadata finalizeMetadata(String partitioner, double bloomFilterFPChance) { return new SSTableMetadata(estimatedRowSize, estimatedColumnCount, replayPosition, minTimestamp, maxTimestamp, maxLocalDeletionTime, bloomFilterFPChance, compressionRatio, partitioner, ancestors, estimatedTombstoneDropTime, sstableLevel); } public Collector estimatedRowSize(EstimatedHistogram estimatedRowSize) { this.estimatedRowSize = estimatedRowSize; return this; } public Collector estimatedColumnCount(EstimatedHistogram estimatedColumnCount) { this.estimatedColumnCount = estimatedColumnCount; return this; } public Collector replayPosition(ReplayPosition replayPosition) { this.replayPosition = replayPosition; return this; } public Collector addAncestor(int generation) { this.ancestors.add(generation); return this; } void update(long size, ColumnStats stats) { updateMinTimestamp(stats.minTimestamp); /* * The max timestamp is not always collected here (more precisely, row.maxTimestamp() may return Long.MIN_VALUE), * to avoid deserializing an EchoedRow. * This is the reason why it is collected first when calling ColumnFamilyStore.createCompactionWriter * However, for old sstables without timestamp, we still want to update the timestamp (and we know * that in this case we will not use EchoedRow, since CompactionControler.needsDeserialize() will be true). */ updateMaxTimestamp(stats.maxTimestamp); updateMaxLocalDeletionTime(stats.maxLocalDeletionTime); addRowSize(size); addColumnCount(stats.columnCount); mergeTombstoneHistogram(stats.tombstoneHistogram); } public Collector sstableLevel(int sstableLevel) { this.sstableLevel = sstableLevel; return this; } } public static class SSTableMetadataSerializer { private static final Logger logger = LoggerFactory.getLogger(SSTableMetadataSerializer.class); public void serialize(SSTableMetadata sstableStats, DataOutput dos) throws IOException { assert sstableStats.partitioner != null; EstimatedHistogram.serializer.serialize(sstableStats.estimatedRowSize, dos); EstimatedHistogram.serializer.serialize(sstableStats.estimatedColumnCount, dos); ReplayPosition.serializer.serialize(sstableStats.replayPosition, dos); dos.writeLong(sstableStats.minTimestamp); dos.writeLong(sstableStats.maxTimestamp); dos.writeInt(sstableStats.maxLocalDeletionTime); dos.writeDouble(sstableStats.bloomFilterFPChance); dos.writeDouble(sstableStats.compressionRatio); dos.writeUTF(sstableStats.partitioner); dos.writeInt(sstableStats.ancestors.size()); for (Integer g : sstableStats.ancestors) dos.writeInt(g); StreamingHistogram.serializer.serialize(sstableStats.estimatedTombstoneDropTime, dos); dos.writeInt(sstableStats.sstableLevel); } /** * Used to serialize to an old version - needed to be able to update sstable level without a full compaction. * * @deprecated will be removed when it is assumed that the minimum upgrade-from-version is the version that this * patch made it into * * @param sstableStats * @param legacyDesc * @param dos * @throws IOException */ @Deprecated public void legacySerialize(SSTableMetadata sstableStats, Descriptor legacyDesc, DataOutput dos) throws IOException { EstimatedHistogram.serializer.serialize(sstableStats.estimatedRowSize, dos); EstimatedHistogram.serializer.serialize(sstableStats.estimatedColumnCount, dos); if (legacyDesc.version.metadataIncludesReplayPosition) ReplayPosition.serializer.serialize(sstableStats.replayPosition, dos); if (legacyDesc.version.tracksMinTimestamp) dos.writeLong(sstableStats.minTimestamp); if (legacyDesc.version.tracksMaxTimestamp) dos.writeLong(sstableStats.maxTimestamp); if (legacyDesc.version.tracksMaxLocalDeletionTime) dos.writeInt(sstableStats.maxLocalDeletionTime); if (legacyDesc.version.hasBloomFilterFPChance) dos.writeDouble(sstableStats.bloomFilterFPChance); if (legacyDesc.version.hasCompressionRatio) dos.writeDouble(sstableStats.compressionRatio); if (legacyDesc.version.hasPartitioner) dos.writeUTF(sstableStats.partitioner); if (legacyDesc.version.hasAncestors) { dos.writeInt(sstableStats.ancestors.size()); for (Integer g : sstableStats.ancestors) dos.writeInt(g); } if (legacyDesc.version.tracksTombstones) StreamingHistogram.serializer.serialize(sstableStats.estimatedTombstoneDropTime, dos); dos.writeInt(sstableStats.sstableLevel); } public SSTableMetadata deserialize(Descriptor descriptor) throws IOException { return deserialize(descriptor, true); } public SSTableMetadata deserialize(Descriptor descriptor, boolean loadSSTableLevel) throws IOException { logger.debug("Load metadata for {}", descriptor); File statsFile = new File(descriptor.filenameFor(SSTable.COMPONENT_STATS)); if (!statsFile.exists()) { logger.debug("No sstable stats for {}", descriptor); return new SSTableMetadata(); } DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(statsFile))); try { return deserialize(dis, descriptor, loadSSTableLevel); } finally { FileUtils.closeQuietly(dis); } } public SSTableMetadata deserialize(DataInputStream dis, Descriptor desc) throws IOException { return deserialize(dis, desc, true); } public SSTableMetadata deserialize(DataInputStream dis, Descriptor desc, boolean loadSSTableLevel) throws IOException { EstimatedHistogram rowSizes = EstimatedHistogram.serializer.deserialize(dis); EstimatedHistogram columnCounts = EstimatedHistogram.serializer.deserialize(dis); ReplayPosition replayPosition = desc.version.metadataIncludesReplayPosition ? ReplayPosition.serializer.deserialize(dis) : ReplayPosition.NONE; if (!desc.version.metadataIncludesModernReplayPosition) { // replay position may be "from the future" thanks to older versions generating them with nanotime. // make sure we don't omit replaying something that we should. see CASSANDRA-4782 replayPosition = ReplayPosition.NONE; } long minTimestamp = desc.version.tracksMinTimestamp ? dis.readLong() : Long.MIN_VALUE; - if (!desc.version.tracksMinTimestamp) - minTimestamp = Long.MAX_VALUE; - long maxTimestamp = desc.version.containsTimestamp() ? dis.readLong() : Long.MIN_VALUE; + long maxTimestamp = desc.version.containsTimestamp() ? dis.readLong() : Long.MAX_VALUE; if (!desc.version.tracksMaxTimestamp) // see javadoc to Descriptor.containsTimestamp maxTimestamp = Long.MAX_VALUE; int maxLocalDeletionTime = desc.version.tracksMaxLocalDeletionTime ? dis.readInt() : Integer.MAX_VALUE; double bloomFilterFPChance = desc.version.hasBloomFilterFPChance ? dis.readDouble() : NO_BLOOM_FLITER_FP_CHANCE; double compressionRatio = desc.version.hasCompressionRatio ? dis.readDouble() : NO_COMPRESSION_RATIO; String partitioner = desc.version.hasPartitioner ? dis.readUTF() : null; int nbAncestors = desc.version.hasAncestors ? dis.readInt() : 0; Set<Integer> ancestors = new HashSet<Integer>(nbAncestors); for (int i = 0; i < nbAncestors; i++) ancestors.add(dis.readInt()); StreamingHistogram tombstoneHistogram = desc.version.tracksTombstones ? StreamingHistogram.serializer.deserialize(dis) : defaultTombstoneDropTimeHistogram(); int sstableLevel = 0; if (loadSSTableLevel && dis.available() > 0) sstableLevel = dis.readInt(); return new SSTableMetadata(rowSizes, columnCounts, replayPosition, minTimestamp, maxTimestamp, maxLocalDeletionTime, bloomFilterFPChance, compressionRatio, partitioner, ancestors, tombstoneHistogram, sstableLevel); } } }
true
true
public SSTableMetadata deserialize(DataInputStream dis, Descriptor desc, boolean loadSSTableLevel) throws IOException { EstimatedHistogram rowSizes = EstimatedHistogram.serializer.deserialize(dis); EstimatedHistogram columnCounts = EstimatedHistogram.serializer.deserialize(dis); ReplayPosition replayPosition = desc.version.metadataIncludesReplayPosition ? ReplayPosition.serializer.deserialize(dis) : ReplayPosition.NONE; if (!desc.version.metadataIncludesModernReplayPosition) { // replay position may be "from the future" thanks to older versions generating them with nanotime. // make sure we don't omit replaying something that we should. see CASSANDRA-4782 replayPosition = ReplayPosition.NONE; } long minTimestamp = desc.version.tracksMinTimestamp ? dis.readLong() : Long.MIN_VALUE; if (!desc.version.tracksMinTimestamp) minTimestamp = Long.MAX_VALUE; long maxTimestamp = desc.version.containsTimestamp() ? dis.readLong() : Long.MIN_VALUE; if (!desc.version.tracksMaxTimestamp) // see javadoc to Descriptor.containsTimestamp maxTimestamp = Long.MAX_VALUE; int maxLocalDeletionTime = desc.version.tracksMaxLocalDeletionTime ? dis.readInt() : Integer.MAX_VALUE; double bloomFilterFPChance = desc.version.hasBloomFilterFPChance ? dis.readDouble() : NO_BLOOM_FLITER_FP_CHANCE; double compressionRatio = desc.version.hasCompressionRatio ? dis.readDouble() : NO_COMPRESSION_RATIO; String partitioner = desc.version.hasPartitioner ? dis.readUTF() : null; int nbAncestors = desc.version.hasAncestors ? dis.readInt() : 0; Set<Integer> ancestors = new HashSet<Integer>(nbAncestors); for (int i = 0; i < nbAncestors; i++) ancestors.add(dis.readInt()); StreamingHistogram tombstoneHistogram = desc.version.tracksTombstones ? StreamingHistogram.serializer.deserialize(dis) : defaultTombstoneDropTimeHistogram(); int sstableLevel = 0; if (loadSSTableLevel && dis.available() > 0) sstableLevel = dis.readInt(); return new SSTableMetadata(rowSizes, columnCounts, replayPosition, minTimestamp, maxTimestamp, maxLocalDeletionTime, bloomFilterFPChance, compressionRatio, partitioner, ancestors, tombstoneHistogram, sstableLevel); }
public SSTableMetadata deserialize(DataInputStream dis, Descriptor desc, boolean loadSSTableLevel) throws IOException { EstimatedHistogram rowSizes = EstimatedHistogram.serializer.deserialize(dis); EstimatedHistogram columnCounts = EstimatedHistogram.serializer.deserialize(dis); ReplayPosition replayPosition = desc.version.metadataIncludesReplayPosition ? ReplayPosition.serializer.deserialize(dis) : ReplayPosition.NONE; if (!desc.version.metadataIncludesModernReplayPosition) { // replay position may be "from the future" thanks to older versions generating them with nanotime. // make sure we don't omit replaying something that we should. see CASSANDRA-4782 replayPosition = ReplayPosition.NONE; } long minTimestamp = desc.version.tracksMinTimestamp ? dis.readLong() : Long.MIN_VALUE; long maxTimestamp = desc.version.containsTimestamp() ? dis.readLong() : Long.MAX_VALUE; if (!desc.version.tracksMaxTimestamp) // see javadoc to Descriptor.containsTimestamp maxTimestamp = Long.MAX_VALUE; int maxLocalDeletionTime = desc.version.tracksMaxLocalDeletionTime ? dis.readInt() : Integer.MAX_VALUE; double bloomFilterFPChance = desc.version.hasBloomFilterFPChance ? dis.readDouble() : NO_BLOOM_FLITER_FP_CHANCE; double compressionRatio = desc.version.hasCompressionRatio ? dis.readDouble() : NO_COMPRESSION_RATIO; String partitioner = desc.version.hasPartitioner ? dis.readUTF() : null; int nbAncestors = desc.version.hasAncestors ? dis.readInt() : 0; Set<Integer> ancestors = new HashSet<Integer>(nbAncestors); for (int i = 0; i < nbAncestors; i++) ancestors.add(dis.readInt()); StreamingHistogram tombstoneHistogram = desc.version.tracksTombstones ? StreamingHistogram.serializer.deserialize(dis) : defaultTombstoneDropTimeHistogram(); int sstableLevel = 0; if (loadSSTableLevel && dis.available() > 0) sstableLevel = dis.readInt(); return new SSTableMetadata(rowSizes, columnCounts, replayPosition, minTimestamp, maxTimestamp, maxLocalDeletionTime, bloomFilterFPChance, compressionRatio, partitioner, ancestors, tombstoneHistogram, sstableLevel); }
diff --git a/org.cloudsmith.geppetto.forge.tests/src/org/cloudsmith/geppetto/forge/tests/RepositoryTest.java b/org.cloudsmith.geppetto.forge.tests/src/org/cloudsmith/geppetto/forge/tests/RepositoryTest.java index 21e0f81b..ae3ebbfe 100644 --- a/org.cloudsmith.geppetto.forge.tests/src/org/cloudsmith/geppetto/forge/tests/RepositoryTest.java +++ b/org.cloudsmith.geppetto.forge.tests/src/org/cloudsmith/geppetto/forge/tests/RepositoryTest.java @@ -1,138 +1,138 @@ /** * Copyright (c) 2011 Cloudsmith Inc. and other contributors, as listed below. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Cloudsmith * */ package org.cloudsmith.geppetto.forge.tests; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URI; import junit.framework.TestCase; import junit.textui.TestRunner; import org.cloudsmith.geppetto.forge.ForgeFactory; import org.cloudsmith.geppetto.forge.ForgeService; import org.cloudsmith.geppetto.forge.HttpMethod; import org.cloudsmith.geppetto.forge.Repository; /** * <!-- begin-user-doc --> A test case for the model object ' <em><b>Repository</b></em>'. <!-- end-user-doc --> * <p> * The following operations are tested: * <ul> * <li>{@link org.cloudsmith.geppetto.forge.Repository#connect(org.cloudsmith.geppetto.forge.HttpMethod, java.lang.String) <em>Connect</em>}</li> * </ul> * </p> * * @generated */ public class RepositoryTest extends TestCase { /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public static void main(String[] args) { TestRunner.run(RepositoryTest.class); } /** * The fixture for this Repository test case. * <!-- begin-user-doc --> <!-- * end-user-doc --> * * @generated */ protected Repository fixture = null; /** * Constructs a new Repository test case with the given name. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @generated */ public RepositoryTest(String name) { super(name); } /** * Returns the fixture for this Repository test case. * <!-- begin-user-doc * --> <!-- end-user-doc --> * * @generated */ protected Repository getFixture() { return fixture; } /** * Sets the fixture for this Repository test case. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ protected void setFixture(Repository fixture) { this.fixture = fixture; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @see junit.framework.TestCase#setUp() * @generated NOT */ @Override protected void setUp() throws Exception { ForgeService service = ForgeFactory.eINSTANCE.createForgeService(); setFixture(service.createRepository(URI.create("http://forge.puppetlabs.com"))); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @see junit.framework.TestCase#tearDown() * @generated */ @Override protected void tearDown() throws Exception { setFixture(null); } /** */ public void testCacheKey() { assertEquals( "Bad cache key", fixture.getCacheKey(), "http_forge_puppetlabs_com-75a31f1d6f1ef6eb63b4479b3512ee1508209a7f"); } /** * Tests the ' {@link org.cloudsmith.geppetto.forge.Repository#connect(org.cloudsmith.geppetto.forge.HttpMethod, java.lang.String) * <em>Connect</em>}' operation. <!-- begin-user-doc --> <!-- end-user-doc * --> * * @see org.cloudsmith.geppetto.forge.Repository#connect(org.cloudsmith.geppetto.forge.HttpMethod, java.lang.String) * @generated NOT */ public void testConnect__HttpMethod_String() { try { HttpURLConnection conn = getFixture().connect(HttpMethod.HEAD, CacheTest.FILE_TO_TEST); - assertEquals("Unexpected content type", "application/x-gzip", conn.getContentType()); + assertEquals("Unexpected content type", "application/octet-stream", conn.getContentType()); } catch(IOException e) { fail(e.getMessage()); } } } // RepositoryTest
true
true
public void testConnect__HttpMethod_String() { try { HttpURLConnection conn = getFixture().connect(HttpMethod.HEAD, CacheTest.FILE_TO_TEST); assertEquals("Unexpected content type", "application/x-gzip", conn.getContentType()); } catch(IOException e) { fail(e.getMessage()); } }
public void testConnect__HttpMethod_String() { try { HttpURLConnection conn = getFixture().connect(HttpMethod.HEAD, CacheTest.FILE_TO_TEST); assertEquals("Unexpected content type", "application/octet-stream", conn.getContentType()); } catch(IOException e) { fail(e.getMessage()); } }
diff --git a/src/main/java/lcmc/gui/resources/EditableInfo.java b/src/main/java/lcmc/gui/resources/EditableInfo.java index e4e34c4a..d8bcecdf 100644 --- a/src/main/java/lcmc/gui/resources/EditableInfo.java +++ b/src/main/java/lcmc/gui/resources/EditableInfo.java @@ -1,1211 +1,1211 @@ /* * This file is part of DRBD Management Console by LINBIT HA-Solutions GmbH * written by Rasto Levrinc. * * Copyright (C) 2009-2010, LINBIT HA-Solutions GmbH. * Copyright (C) 2009-2010, Rasto Levrinc * * DRBD Management Console 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, or (at your option) * any later version. * * DRBD Management Console 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 drbd; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */ package lcmc.gui.resources; import lcmc.gui.Browser; import lcmc.gui.widget.Widget; import lcmc.gui.widget.WidgetFactory; import lcmc.gui.widget.Label; import lcmc.utilities.ButtonCallback; import lcmc.utilities.MyButton; import lcmc.utilities.Tools; import lcmc.utilities.Unit; import lcmc.utilities.WidgetListener; import lcmc.data.CRMXML; import lcmc.data.ConfigData; import lcmc.data.AccessMode; import lcmc.data.resources.Resource; import lcmc.gui.SpringUtilities; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JComponent; import javax.swing.border.TitledBorder; import javax.swing.SpringLayout; import javax.swing.BoxLayout; import java.util.Map; import java.util.HashMap; import java.util.concurrent.CountDownLatch; import java.util.List; import java.util.ArrayList; import java.util.Set; import java.util.HashSet; import java.util.regex.Pattern; import java.util.regex.Matcher; import java.awt.Color; import java.awt.Font; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FlowLayout; import org.apache.commons.collections15.map.MultiKeyMap; import java.util.concurrent.TimeUnit; /** * This class provides textfields, combo boxes etc. for editable info * objects. */ public abstract class EditableInfo extends Info { /** Hash from parameter to boolean value if the last entered value was * correct. */ private final Map<String, Boolean> paramCorrectValueMap = new HashMap<String, Boolean>(); private final MultiKeyMap<String, JPanel> sectionPanels = new MultiKeyMap<String, JPanel>(); /** Returns section in which is this parameter. */ protected abstract String getSection(String param); /** Returns whether this parameter is required. */ protected abstract boolean isRequired(String param); /** Returns whether this parameter is advanced. */ protected abstract boolean isAdvanced(String param); /** Returns null this parameter should be enabled. Otherwise return a reason that appears in the tooltip. */ protected abstract String isEnabled(String param); /** Returns access type of this parameter. */ protected abstract ConfigData.AccessType getAccessType(String param); /** Returns whether this parameter is enabled in advanced mode. */ protected abstract boolean isEnabledOnlyInAdvancedMode(String param); /** Returns whether this parameter is of label type. */ protected abstract boolean isLabel(String param); /** Returns whether this parameter is of the integer type. */ protected abstract boolean isInteger(String param); /** Returns whether this parameter is of the time type. */ protected abstract boolean isTimeType(String param); /** Returns whether this parameter has a unit prefix. */ protected boolean hasUnitPrefix(final String param) { return false; } /** Returns whether this parameter is of the check box type, like * boolean. */ protected abstract boolean isCheckBox(String param); /** Returns type of the field. */ protected Widget.Type getFieldType(final String param) { return null; } /** Returns the name of the type. */ protected abstract String getParamType(final String param); /** Returns the regexp of the parameter. */ protected String getParamRegexp(final String param) { // TODO: this should be only for Pacemaker if (isInteger(param)) { return "^((-?\\d*|(-|\\+)?" + CRMXML.INFINITY_STRING + "|" + CRMXML.DISABLED_STRING + "))|@NOTHING_SELECTED@$"; } return null; } /** Returns the possible choices for pull down menus if applicable. */ protected abstract Object[] getParamPossibleChoices(String param); /** Returns array of all parameters. */ public abstract String[] getParametersFromXML(); // TODO: no XML /** Old apply button, is used for wizards. */ private MyButton oldApplyButton = null; /** Apply button. */ private MyButton applyButton; /** Revert button. */ private MyButton revertButton; /** Is counted down, first time the info panel is initialized. */ private CountDownLatch infoPanelLatch = new CountDownLatch(1); /** List of advanced panels. */ private final List<JPanel> advancedPanelList = new ArrayList<JPanel>(); /** List of messages if advanced panels are hidden. */ private final List<String> advancedOnlySectionList = new ArrayList<String>(); /** More options panel. */ private final JPanel moreOptionsPanel = new JPanel(); /** Whether dialog was started. It disables the apply button. */ private boolean dialogStarted = false; /** Disabled section, their not visible. */ private final Set<String> disabledSections = new HashSet<String>(); /** Whether is's a wizard element. */ public static final boolean WIZARD = true; /** How much of the info is used. */ public int getUsed() { return -1; } /** * Prepares a new <code>EditableInfo</code> object. * * @param name * name that will be shown to the user. */ EditableInfo(final String name, final Browser browser) { super(name, browser); } /** Inits apply button. */ final void initApplyButton(final ButtonCallback buttonCallback) { initApplyButton(buttonCallback, Tools.getString("Browser.ApplyResource")); } /** Inits commit button. */ final void initCommitButton(final ButtonCallback buttonCallback) { initApplyButton(buttonCallback, Tools.getString("Browser.CommitResources")); } /** Inits apply or commit button button. */ final void initApplyButton(final ButtonCallback buttonCallback, final String text) { if (oldApplyButton == null) { applyButton = new MyButton( text, Browser.APPLY_ICON); applyButton.miniButton(); applyButton.setEnabled(false); oldApplyButton = applyButton; revertButton = new MyButton( Tools.getString("Browser.RevertResource"), Browser.REVERT_ICON); revertButton.setEnabled(false); revertButton.setToolTipText( Tools.getString("Browser.RevertResource.ToolTip")); revertButton.miniButton(); revertButton.setPreferredSize(new Dimension(65, 50)); } else { applyButton = oldApplyButton; } applyButton.setEnabled(false); if (buttonCallback != null) { addMouseOverListener(applyButton, buttonCallback); } } /** Creates apply button and adds it to the panel. */ protected final void addApplyButton(final JPanel panel) { panel.add(applyButton, BorderLayout.WEST); } /** Creates revert button and adds it to the panel. */ protected final void addRevertButton(final JPanel panel) { final JPanel p = new JPanel(new FlowLayout(FlowLayout.RIGHT, 4, 0)); p.setBackground(Browser.BUTTON_PANEL_BACKGROUND); p.add(revertButton); panel.add(p, BorderLayout.CENTER); } /** Adds jlabel field with tooltip. */ public final void addLabelField(final JPanel panel, final String left, final String right, final int leftWidth, final int rightWidth, final int height) { final JLabel leftLabel = new JLabel(left); leftLabel.setToolTipText(left); final JLabel rightLabel = new JLabel(right); rightLabel.setToolTipText(right); addField(panel, leftLabel, rightLabel, leftWidth, rightWidth, height); } /** * Adds field with left and right component to the panel. Use panel * with spring layout for this. */ public final void addField(final JPanel panel, final JComponent left, final JComponent right, final int leftWidth, final int rightWidth, int height) { /* right component with fixed width. */ if (height == 0) { height = Tools.getDefaultSize("Browser.FieldHeight"); } Tools.setSize(left, leftWidth, height); panel.add(left); Tools.setSize(right, rightWidth, height); panel.add(right); right.setBackground(panel.getBackground()); } /** * Adds parameters to the panel in a wizard. * Returns number of rows. */ public final void addWizardParams( final JPanel optionsPanel, final String[] params, final MyButton wizardApplyButton, final int leftWidth, final int rightWidth, final Map<String, Widget> sameAsFields) { addParams(optionsPanel, Widget.WIZARD_PREFIX, params, wizardApplyButton, leftWidth, rightWidth, sameAsFields); } /** * This class holds a part of the panel within the same section, access * type and advanced mode setting. */ private static class PanelPart { /** Section of this panel part. */ private final String section; /** Access type of this panel part. */ private final ConfigData.AccessType accessType; /** Whether it is an advanced panel part. */ private final boolean advanced; /** Creates new panel part object. */ public PanelPart(final String section, final ConfigData.AccessType accessType, final boolean advanced) { this.section = section; this.accessType = accessType; this.advanced = advanced; } /** Returns a section to which this panel part belongs. */ public final String getSection() { return section; } /** Returns access type of this panel part. */ public final ConfigData.AccessType getAccessType() { return accessType; } /** Whether this panel part has advanced options. */ public final boolean isAdvanced() { return advanced; } } /** Adds parameters to the panel. */ public final void addParams(final JPanel optionsPanel, final String[] params, final int leftWidth, final int rightWidth, final Map<String, Widget> sameAsFields) { addParams(optionsPanel, null, params, applyButton, leftWidth, rightWidth, sameAsFields); } /** Adds parameters to the panel. */ private void addParams(final JPanel optionsPanel, final String prefix, final String[] params, final MyButton thisApplyButton, final int leftWidth, final int rightWidth, final Map<String, Widget> sameAsFields) { Tools.isSwingThread(); if (params == null) { return; } final MultiKeyMap<String, JPanel> panelPartsMap = new MultiKeyMap<String, JPanel>(); final List<PanelPart> panelPartsList = new ArrayList<PanelPart>(); final MultiKeyMap<String, Integer> panelPartRowsMap = new MultiKeyMap<String, Integer>(); for (final String param : params) { final Widget paramWi = createWidget(param, prefix, rightWidth); /* sub panel */ final String section = getSection(param); JPanel panel; final ConfigData.AccessType accessType = getAccessType(param); final String accessTypeString = accessType.toString(); final Boolean advanced = isAdvanced(param); final String advancedString = advanced.toString(); if (panelPartsMap.containsKey(section, accessTypeString, advancedString)) { panel = panelPartsMap.get(section, accessTypeString, advancedString); panelPartRowsMap.put(section, accessTypeString, advancedString, panelPartRowsMap.get(section, accessTypeString, advancedString) + 1); } else { panel = new JPanel(new SpringLayout()); panel.setBackground(getSectionColor(section)); if (advanced) { advancedPanelList.add(panel); panel.setVisible(Tools.getConfigData().isAdvancedMode()); } panelPartsMap.put(section, accessTypeString, advancedString, panel); panelPartsList.add(new PanelPart(section, accessType, advanced)); panelPartRowsMap.put(section, accessTypeString, advancedString, 1); } /* label */ final JLabel label = new JLabel(getParamShortDesc(param)); final String longDesc = getParamLongDesc(param); paramWi.setLabel(label, longDesc); /* tool tip */ paramWi.setToolTipText(getToolTipText(param, paramWi)); label.setToolTipText(longDesc + additionalToolTip(param)); int height = 0; if (paramWi instanceof Label) { height = Tools.getDefaultSize("Browser.LabelFieldHeight"); } addField(panel, label, paramWi, leftWidth, rightWidth, height); } final boolean wizard = Widget.WIZARD_PREFIX.equals(prefix); for (final String param : params) { final Widget paramWi = getWidget(param, prefix); Widget rpwi = null; if (wizard) { rpwi = getWidget(param, null); if (rpwi == null) { - Tools.appError("unkown param: " + param + Tools.appError("unknown param: " + param + ". Could not find man pages for " + "your DRBD versions."); continue; } int height = 0; if (rpwi instanceof Label) { height = Tools.getDefaultSize("Browser.LabelFieldHeight"); } if (paramWi.getValue() == null || paramWi.getValue() == Widget.NOTHING_SELECTED_DISPLAY) { rpwi.setValueAndWait(null); } else { final Object value = paramWi.getStringValue(); rpwi.setValueAndWait(value); } } } for (final String param : params) { final Widget paramWi = getWidget(param, prefix); Widget rpwi = null; if (wizard) { rpwi = getWidget(param, null); } final Widget realParamWi = rpwi; paramWi.addListeners(new WidgetListener() { @Override public void check(final Object value) { checkParameterFields(paramWi, realParamWi, param, getParametersFromXML(), thisApplyButton); } }); } /* add sub panels to the option panel */ final Map<String, JPanel> sectionMap = new HashMap<String, JPanel>(); final Set<JPanel> notAdvancedSections = new HashSet<JPanel>(); final Set<JPanel> advancedSections = new HashSet<JPanel>(); for (final PanelPart panelPart : panelPartsList) { final String section = panelPart.getSection(); final ConfigData.AccessType accessType = panelPart.getAccessType(); final String accessTypeString = accessType.toString(); final Boolean advanced = panelPart.isAdvanced(); final String advancedString = advanced.toString(); final JPanel panel = panelPartsMap.get(section, accessTypeString, advancedString); final int rows = panelPartRowsMap.get(section, accessTypeString, advancedString); final int columns = 2; SpringUtilities.makeCompactGrid(panel, rows, columns, 1, 1, // initX, initY 1, 1); // xPad, yPad JPanel sectionPanel; if (sectionMap.containsKey(section)) { sectionPanel = sectionMap.get(section); } else { sectionPanel = getParamPanel(getSectionDisplayName(section), getSectionColor(section)); sectionMap.put(section, sectionPanel); addSectionPanel(section, wizard, sectionPanel); optionsPanel.add(sectionPanel); if (sameAsFields != null) { final Widget sameAsCombo = sameAsFields.get(section); if (sameAsCombo != null) { final JPanel saPanel = new JPanel(new SpringLayout()); saPanel.setBackground(Browser.BUTTON_PANEL_BACKGROUND); final JLabel label = new JLabel("Same As"); sameAsCombo.setLabel(label, ""); addField(saPanel, label, sameAsCombo, leftWidth, rightWidth, 0); SpringUtilities.makeCompactGrid(saPanel, 1, 2, 1, 1, // initX, initY 1, 1); // xPad, yPad sectionPanel.add(saPanel); } } } sectionPanel.setVisible(isSectionEnabled(section)); sectionPanel.add(panel); if (advanced) { advancedSections.add(sectionPanel); } else { notAdvancedSections.add(sectionPanel); } } boolean advanced = false; for (final String section : sectionMap.keySet()) { final JPanel sectionPanel = sectionMap.get(section); if (advancedSections.contains(sectionPanel)) { advanced = true; } if (!notAdvancedSections.contains(sectionPanel)) { advancedOnlySectionList.add(section); sectionPanel.setVisible(Tools.getConfigData().isAdvancedMode() && isSectionEnabled(section)); } } moreOptionsPanel.setVisible(advanced && !Tools.getConfigData().isAdvancedMode()); } /** Returns a more panel with "more options are available" message. */ protected final JPanel getMoreOptionsPanel(final int width) { final JLabel l = new JLabel( Tools.getString("EditableInfo.MoreOptions")); final Font font = l.getFont(); final String name = font.getFontName(); final int style = Font.ITALIC; final int size = font.getSize(); l.setFont(new Font(name, style, size - 3)); moreOptionsPanel.setBackground(Browser.PANEL_BACKGROUND); moreOptionsPanel.add(l); final Dimension d = moreOptionsPanel.getPreferredSize(); d.width = width; moreOptionsPanel.setMaximumSize(d); return moreOptionsPanel; } /** Checks ands sets paramter fields. */ public void checkParameterFields(final Widget paramWi, final Widget realParamWi, final String param, final String[] params, final MyButton thisApplyButton) { final EditableInfo thisClass = this; final Thread thread = new Thread(new Runnable() { @Override public void run() { //Tools.invokeLater(new Runnable() { // @Override // public void run() { // paramWi.setEditable(); // } //}); boolean c; boolean ch = false; if (realParamWi == null) { Tools.waitForSwing(); ch = checkResourceFieldsChanged(param, params); c = checkResourceFieldsCorrect(param, params); } else { Tools.invokeLater(new Runnable() { @Override public void run() { if (paramWi.getValue() == null || paramWi.getValue() == Widget.NOTHING_SELECTED_DISPLAY) { realParamWi.setValueAndWait(null); } else { final Object value = paramWi.getStringValue(); realParamWi.setValueAndWait(value); } } }); Tools.waitForSwing(); c = checkResourceFieldsCorrect(param, params); } final boolean check = c; final boolean changed = ch; Tools.invokeLater(new Runnable() { @Override public void run() { if (thisApplyButton == applyButton) { thisApplyButton.setEnabled( !isDialogStarted() && check && (changed || getResource().isNew())); } else { /* wizard button */ thisApplyButton.setEnabled(check); } if (revertButton != null) { revertButton.setEnabled(changed); } final String toolTip = getToolTipText(param, paramWi); paramWi.setToolTipText(toolTip); if (realParamWi != null) { realParamWi.setToolTipText(toolTip); } } }); } }); thread.start(); } /** Get stored value in the combo box. */ public final String getComboBoxValue(final String param) { final Widget wi = getWidget(param, null); if (wi == null) { return null; } final Object o = wi.getValue(); String value; if (Tools.isStringClass(o)) { value = wi.getStringValue(); } else if (o instanceof Object[]) { value = ((Object[]) o)[0].toString(); if (((Object[]) o)[1] instanceof Unit) { value += ((Unit) ((Object[]) o)[1]).getShortName(); } } else { value = ((Info) o).getInternalValue(); } return value; } /** Stores values in the combo boxes in the component c. */ protected void storeComboBoxValues(final String[] params) { for (String param : params) { final String value = getComboBoxValue(param); getResource().setValue(param, value); final Widget wi = getWidget(param, null); if (wi != null) { wi.setToolTipText(getToolTipText(param, wi)); } } } /** Returns combo box for one parameter. */ protected Widget createWidget(final String param, final String prefix, final int width) { getResource().setPossibleChoices(param, getParamPossibleChoices(param)); /* set default value */ String initValue = getPreviouslySelected(param, prefix); if (initValue == null) { final String value = getParamSaved(param); if (value == null || "".equals(value)) { if (getResource().isNew()) { initValue = getResource().getPreferredValue(param); if (initValue == null) { initValue = getParamPreferred(param); } } if (initValue == null) { initValue = getParamDefault(param); getResource().setValue(param, initValue); } } else { initValue = value; } } final String regexp = getParamRegexp(param); Map<String, String> abbreviations = new HashMap<String, String>(); if (isInteger(param)) { abbreviations = new HashMap<String, String>(); abbreviations.put("i", CRMXML.INFINITY_STRING); abbreviations.put("I", CRMXML.INFINITY_STRING); abbreviations.put("+", CRMXML.PLUS_INFINITY_STRING); abbreviations.put("d", CRMXML.DISABLED_STRING); abbreviations.put("D", CRMXML.DISABLED_STRING); } Widget.Type type = getFieldType(param); Unit[] units = null; if (type == Widget.Type.TEXTFIELDWITHUNIT) { units = getUnits(); } if (isCheckBox(param)) { type = Widget.Type.CHECKBOX; } else if (isTimeType(param)) { type = Widget.Type.TEXTFIELDWITHUNIT; units = getTimeUnits(); } else if (isLabel(param)) { type = Widget.Type.LABELFIELD; } final Widget paramWi = WidgetFactory.createInstance( type, initValue, getPossibleChoices(param), units, regexp, width, abbreviations, new AccessMode( getAccessType(param), isEnabledOnlyInAdvancedMode(param)), null); widgetAdd(param, prefix, paramWi); paramWi.setEditable(true); return paramWi; } /** * Checks new value of the parameter if it correct and has changed. * Returns false if parameter is invalid or has not not changed from * the stored value. This is needed to disable apply button, if some of * the values are invalid or none of the parameters have changed. */ protected abstract boolean checkParam(String param, String newValue); /** Checks whether this value matches the regexp of this field. */ protected final boolean checkRegexp(final String param, final String newValue) { String regexp = getParamRegexp(param); if (regexp == null) { final Widget wi = getWidget(param, null); if (wi != null) { regexp = wi.getRegexp(); } } if (regexp != null) { final Pattern p = Pattern.compile(regexp); final Matcher m = p.matcher(newValue); if (m.matches()) { return true; } return false; } return true; } /** * Checks parameter, but use cached value. This is useful if some other * parameter was modified, but not this one. */ protected boolean checkParamCache(final String param) { if (!paramCorrectValueMap.containsKey(param)) { return false; } final Boolean ret = paramCorrectValueMap.get(param); if (ret == null) { return false; } return ret; } /** Sets the cache for the result of the parameter check. */ protected final void setCheckParamCache(final String param, final boolean correctValue) { paramCorrectValueMap.put(param, correctValue); } /** Returns default value of a parameter. */ protected abstract String getParamDefault(String param); /** Returns saved value of a parameter. */ protected String getParamSaved(final String param) { return getResource().getValue(param); } /** Returns preferred value of a parameter. */ protected abstract String getParamPreferred(String param); /** Returns short description of a parameter. */ protected abstract String getParamShortDesc(String param); /** Returns long description of a parameter. */ protected abstract String getParamLongDesc(String param); /** * Returns possible choices in a combo box, if possible choices are * null, instead of combo box a text field will be generated. */ protected Object[] getPossibleChoices(final String param) { return getResource().getPossibleChoices(param); } /** * Creates panel with border and title for parameters with default * background. */ protected final JPanel getParamPanel(final String title) { return getParamPanel(title, Browser.PANEL_BACKGROUND); } /** * Creates panel with border and title for parameters with specified * background. */ protected final JPanel getParamPanel(final String title, final Color background) { final JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); panel.setBackground(background); final TitledBorder titleBorder = Tools.getBorder(title); panel.setBorder(titleBorder); return panel; } /** * Returns on mouse over text for parameter. If value is different * from default value, default value will be returned. */ protected final String getToolTipText(final String param, final Widget wi) { final String defaultValue = getParamDefault(param); final StringBuilder ret = new StringBuilder(120); if (wi != null) { final Object value = wi.getStringValue(); ret.append("<b>"); ret.append(value); ret.append("</b>"); } if (defaultValue != null && !defaultValue.equals("")) { ret.append("<table><tr><td><b>"); ret.append(Tools.getString("Browser.ParamDefault")); ret.append("</b></td><td>"); ret.append(defaultValue); ret.append("</td></tr></table>"); } ret.append(additionalToolTip(param)); return ret.toString(); } /** Enables and disabled apply and revert button. */ public final void setApplyButtons(final String param, final String[] params) { final boolean ch = checkResourceFieldsChanged(param, params); final boolean cor = checkResourceFieldsCorrect(param, params); Tools.invokeLater(!Tools.CHECK_SWING_THREAD, new Runnable() { @Override public void run() { final MyButton ab = getApplyButton(); final Resource r = getResource(); if (ab != null) { ab.setEnabled((ch || (r != null && r.isNew())) && cor); } final MyButton rb = getRevertButton(); if (rb != null) { rb.setEnabled(ch); } } }); } ///** // * Can be called from dialog box, where it does not need to check if // * fields have changed. // */ //public boolean checkResourceFields(final String param, // final String[] params) { // final boolean cor = checkResourceFieldsCorrect(param, params); // final boolean changed = checkResourceFieldsChanged(param, params); // if (cor) { // return changed; // } // return cor; //} /** Checks one parameter. */ protected void checkOneParam(final String param) { checkResourceFieldsCorrect(param, new String[]{param}); } /** * Returns whether all the parameters are correct. If param is null, * all paremeters will be checked, otherwise only the param, but other * parameters will be checked only in the cache. This is good if only * one value is changed and we don't want to check everything. */ boolean checkResourceFieldsCorrect(final String param, final String[] params) { /* check if values are correct */ boolean correctValue = true; if (params != null) { for (final String otherParam : params) { final Widget wi = getWidget(otherParam, null); if (wi == null) { continue; } String newValue; final Object o = wi.getValue(); if (Tools.isStringClass(o)) { newValue = wi.getStringValue(); } else if (o instanceof Object[]) { final Object o0 = ((Object[]) o)[0]; final Object o1 = ((Object[]) o)[1]; newValue = o0.toString(); if (o1 != null && o1 instanceof Unit) { newValue += ((Unit) o1).getShortName(); } } else { newValue = ((Info) o).getInternalValue(); } if (param == null || otherParam.equals(param) || !paramCorrectValueMap.containsKey(param)) { final Widget wizardWi = getWidget(otherParam, Widget.WIZARD_PREFIX); final String enable = isEnabled(otherParam); if (wizardWi != null) { wizardWi.setDisabledReason(enable); wizardWi.setEnabled(enable == null); final Object wo = wizardWi.getValue(); if (Tools.isStringClass(wo)) { newValue = wizardWi.getStringValue(); } else if (wo instanceof Object[]) { newValue = ((Object[]) wo)[0].toString() + ((Unit) ((Object[]) wo)[1]).getShortName(); } else { newValue = ((Info) wo).getInternalValue(); } } wi.setDisabledReason(enable); wi.setEnabled(enable == null); final boolean check = checkParam(otherParam, newValue) && checkRegexp(otherParam, newValue); if (check) { if (isTimeType(otherParam) || hasUnitPrefix(otherParam)) { wi.setBackground( Tools.extractUnit( getParamDefault(otherParam)), Tools.extractUnit( getParamSaved(otherParam)), isRequired(otherParam)); if (wizardWi != null) { wizardWi.setBackground( Tools.extractUnit( getParamDefault(otherParam)), Tools.extractUnit( getParamSaved(otherParam)), isRequired(otherParam)); } } else { wi.setBackground( getParamDefault(otherParam), getParamSaved(otherParam), isRequired(otherParam)); if (wizardWi != null) { wizardWi.setBackground( getParamDefault(otherParam), getParamSaved(otherParam), isRequired(otherParam)); } } } else { wi.wrongValue(); if (wizardWi != null) { wizardWi.wrongValue(); } correctValue = false; } setCheckParamCache(otherParam, check); } else { correctValue = correctValue && checkParamCache(otherParam); } } } return correctValue; } /** * Returns whetherrs the specified parameter or any of the parameters * have changed. If param is null, only param will be checked, * otherwise all parameters will be checked. */ boolean checkResourceFieldsChanged(final String param, final String[] params) { /* check if something is different from saved values */ boolean changedValue = false; if (params != null) { for (String otherParam : params) { final Widget wi = getWidget(otherParam, null); if (wi == null) { continue; } final Object newValue = wi.getValue(); /* check if value has changed */ Object oldValue = getParamSaved(otherParam); if (oldValue == null) { oldValue = getParamDefault(otherParam); } if (isTimeType(otherParam) || hasUnitPrefix(otherParam)) { oldValue = Tools.extractUnit((String) oldValue); } if (!Tools.areEqual(newValue, oldValue)) { changedValue = true; } wi.processAccessMode(); } } return changedValue; } /** Return JLabel object for the combobox. */ protected final JLabel getLabel(final Widget wi) { return wi.getLabel(); } /** Waits till the info panel is done for the first time. */ public final void waitForInfoPanel() { try { final boolean ret = infoPanelLatch.await(20, TimeUnit.SECONDS); if (!ret) { Tools.printStackTrace("latch timeout detected"); } infoPanelLatch.await(); } catch (InterruptedException ignored) { Thread.currentThread().interrupt(); } } /** Should be called after info panel is done. */ final void infoPanelDone() { infoPanelLatch.countDown(); } /** Reset info panel. */ public void resetInfoPanel() { infoPanelLatch = new CountDownLatch(1); } /** Adds a panel to the advanced list. */ protected final void addToAdvancedList(final JPanel p) { advancedPanelList.add(p); } /** Hide/Show advanced panels. */ @Override public void updateAdvancedPanels() { super.updateAdvancedPanels(); final boolean advancedMode = Tools.getConfigData().isAdvancedMode(); boolean advanced = false; for (final JPanel apl : advancedPanelList) { Tools.invokeLater(new Runnable() { @Override public void run() { apl.setVisible(advancedMode); } }); advanced = true; } for (final String section : advancedOnlySectionList) { final JPanel p = sectionPanels.get(section, Boolean.toString(!WIZARD)); final JPanel pw = sectionPanels.get(section, Boolean.toString(WIZARD)); Tools.invokeLater(new Runnable() { @Override public void run() { final boolean v = advancedMode && isSectionEnabled(section); p.setVisible(v); if (pw != null) { pw.setVisible(v); } } }); advanced = true; } final boolean a = advanced; Tools.invokeLater(new Runnable() { @Override public void run() { moreOptionsPanel.setVisible(a && !advancedMode); } }); } /** Revert valus. */ public void revert() { final String[] params = getParametersFromXML(); if (params == null) { return; } for (final String param : params) { String v = getParamSaved(param); if (v == null) { v = getParamDefault(param); } final Widget wi = getWidget(param, null); if (wi != null && !Tools.areEqual(wi.getStringValue(), v)) { wi.setValue(v); final Widget wizardWi = getWidget(param, Widget.WIZARD_PREFIX); if (wizardWi != null) { wizardWi.setValue(v); } } } } /** Returns apply button. */ final MyButton getApplyButton() { return applyButton; } /** Returns revert button. */ final MyButton getRevertButton() { return revertButton; } /** Sets apply button. */ final void setApplyButton(final MyButton applyButton) { this.applyButton = applyButton; } /** Sets revert button. */ final void setRevertButton(final MyButton revertButton) { this.revertButton = revertButton; } /** Returns if dialog was started. It disables the apply button. */ private boolean isDialogStarted() { return dialogStarted; } /** Sets if dialog was started. It disables the apply button. */ public void setDialogStarted(final boolean dialogStarted) { this.dialogStarted = dialogStarted; } /** Clear panel lists. */ protected void clearPanelLists() { advancedPanelList.clear(); advancedOnlySectionList.clear(); sectionPanels.clear(); disabledSections.clear(); } /** Cleanup. */ @Override final void cleanup() { super.cleanup(); clearPanelLists(); } /** Reload combo boxes. */ public void reloadComboBoxes() { } /** Return previously selected value of the parameter. This is used, when * primitive changes to and from clone. */ protected final String getPreviouslySelected(final String param, final String prefix) { final Widget prevParamWi = getWidget(param, prefix); if (prevParamWi != null) { return prevParamWi.getStringValue(); } return null; } /** Section name that is displayed. */ protected String getSectionDisplayName(final String section) { return Tools.ucfirst(section); } /** * Return section color. */ protected Color getSectionColor(final String section) { return Browser.PANEL_BACKGROUND; } /** * Return section panel. */ private JPanel getSectionPanel(final String section, final boolean wizard) { return sectionPanels.get(section, Boolean.toString(wizard)); } /** Add section panel. */ protected final void addSectionPanel(final String section, final boolean wizard, final JPanel sectionPanel) { sectionPanels.put(section, Boolean.toString(wizard), sectionPanel); } /** Enable/disable a section. */ protected final void enableSection(final String section, final boolean enable, final boolean wizard) { if (enable) { disabledSections.remove(section); } else { disabledSections.add(section); } final JPanel p = getSectionPanel(section, wizard); if (p != null) { p.setVisible(enable); } } /** Return parameters that are not in disabeld sections. */ protected final String[] getEnabledSectionParams( final List<String> params) { final List<String> newParams = new ArrayList<String>(); for (final String param : params) { if (isSectionEnabled(getSection(param))) { newParams.add(param); } } return newParams.toArray(new String[newParams.size()]); } /** Return whether a section is enabled. */ protected final boolean isSectionEnabled(final String section) { return !disabledSections.contains(section); } /** Additional tool tip. */ protected String additionalToolTip(final String param) { return ""; } }
true
true
private void addParams(final JPanel optionsPanel, final String prefix, final String[] params, final MyButton thisApplyButton, final int leftWidth, final int rightWidth, final Map<String, Widget> sameAsFields) { Tools.isSwingThread(); if (params == null) { return; } final MultiKeyMap<String, JPanel> panelPartsMap = new MultiKeyMap<String, JPanel>(); final List<PanelPart> panelPartsList = new ArrayList<PanelPart>(); final MultiKeyMap<String, Integer> panelPartRowsMap = new MultiKeyMap<String, Integer>(); for (final String param : params) { final Widget paramWi = createWidget(param, prefix, rightWidth); /* sub panel */ final String section = getSection(param); JPanel panel; final ConfigData.AccessType accessType = getAccessType(param); final String accessTypeString = accessType.toString(); final Boolean advanced = isAdvanced(param); final String advancedString = advanced.toString(); if (panelPartsMap.containsKey(section, accessTypeString, advancedString)) { panel = panelPartsMap.get(section, accessTypeString, advancedString); panelPartRowsMap.put(section, accessTypeString, advancedString, panelPartRowsMap.get(section, accessTypeString, advancedString) + 1); } else { panel = new JPanel(new SpringLayout()); panel.setBackground(getSectionColor(section)); if (advanced) { advancedPanelList.add(panel); panel.setVisible(Tools.getConfigData().isAdvancedMode()); } panelPartsMap.put(section, accessTypeString, advancedString, panel); panelPartsList.add(new PanelPart(section, accessType, advanced)); panelPartRowsMap.put(section, accessTypeString, advancedString, 1); } /* label */ final JLabel label = new JLabel(getParamShortDesc(param)); final String longDesc = getParamLongDesc(param); paramWi.setLabel(label, longDesc); /* tool tip */ paramWi.setToolTipText(getToolTipText(param, paramWi)); label.setToolTipText(longDesc + additionalToolTip(param)); int height = 0; if (paramWi instanceof Label) { height = Tools.getDefaultSize("Browser.LabelFieldHeight"); } addField(panel, label, paramWi, leftWidth, rightWidth, height); } final boolean wizard = Widget.WIZARD_PREFIX.equals(prefix); for (final String param : params) { final Widget paramWi = getWidget(param, prefix); Widget rpwi = null; if (wizard) { rpwi = getWidget(param, null); if (rpwi == null) { Tools.appError("unkown param: " + param + ". Could not find man pages for " + "your DRBD versions."); continue; } int height = 0; if (rpwi instanceof Label) { height = Tools.getDefaultSize("Browser.LabelFieldHeight"); } if (paramWi.getValue() == null || paramWi.getValue() == Widget.NOTHING_SELECTED_DISPLAY) { rpwi.setValueAndWait(null); } else { final Object value = paramWi.getStringValue(); rpwi.setValueAndWait(value); } } } for (final String param : params) { final Widget paramWi = getWidget(param, prefix); Widget rpwi = null; if (wizard) { rpwi = getWidget(param, null); } final Widget realParamWi = rpwi; paramWi.addListeners(new WidgetListener() { @Override public void check(final Object value) { checkParameterFields(paramWi, realParamWi, param, getParametersFromXML(), thisApplyButton); } }); } /* add sub panels to the option panel */ final Map<String, JPanel> sectionMap = new HashMap<String, JPanel>(); final Set<JPanel> notAdvancedSections = new HashSet<JPanel>(); final Set<JPanel> advancedSections = new HashSet<JPanel>(); for (final PanelPart panelPart : panelPartsList) { final String section = panelPart.getSection(); final ConfigData.AccessType accessType = panelPart.getAccessType(); final String accessTypeString = accessType.toString(); final Boolean advanced = panelPart.isAdvanced(); final String advancedString = advanced.toString(); final JPanel panel = panelPartsMap.get(section, accessTypeString, advancedString); final int rows = panelPartRowsMap.get(section, accessTypeString, advancedString); final int columns = 2; SpringUtilities.makeCompactGrid(panel, rows, columns, 1, 1, // initX, initY 1, 1); // xPad, yPad JPanel sectionPanel; if (sectionMap.containsKey(section)) { sectionPanel = sectionMap.get(section); } else { sectionPanel = getParamPanel(getSectionDisplayName(section), getSectionColor(section)); sectionMap.put(section, sectionPanel); addSectionPanel(section, wizard, sectionPanel); optionsPanel.add(sectionPanel); if (sameAsFields != null) { final Widget sameAsCombo = sameAsFields.get(section); if (sameAsCombo != null) { final JPanel saPanel = new JPanel(new SpringLayout()); saPanel.setBackground(Browser.BUTTON_PANEL_BACKGROUND); final JLabel label = new JLabel("Same As"); sameAsCombo.setLabel(label, ""); addField(saPanel, label, sameAsCombo, leftWidth, rightWidth, 0); SpringUtilities.makeCompactGrid(saPanel, 1, 2, 1, 1, // initX, initY 1, 1); // xPad, yPad sectionPanel.add(saPanel); } } } sectionPanel.setVisible(isSectionEnabled(section)); sectionPanel.add(panel); if (advanced) { advancedSections.add(sectionPanel); } else { notAdvancedSections.add(sectionPanel); } } boolean advanced = false; for (final String section : sectionMap.keySet()) { final JPanel sectionPanel = sectionMap.get(section); if (advancedSections.contains(sectionPanel)) { advanced = true; } if (!notAdvancedSections.contains(sectionPanel)) { advancedOnlySectionList.add(section); sectionPanel.setVisible(Tools.getConfigData().isAdvancedMode() && isSectionEnabled(section)); } } moreOptionsPanel.setVisible(advanced && !Tools.getConfigData().isAdvancedMode()); }
private void addParams(final JPanel optionsPanel, final String prefix, final String[] params, final MyButton thisApplyButton, final int leftWidth, final int rightWidth, final Map<String, Widget> sameAsFields) { Tools.isSwingThread(); if (params == null) { return; } final MultiKeyMap<String, JPanel> panelPartsMap = new MultiKeyMap<String, JPanel>(); final List<PanelPart> panelPartsList = new ArrayList<PanelPart>(); final MultiKeyMap<String, Integer> panelPartRowsMap = new MultiKeyMap<String, Integer>(); for (final String param : params) { final Widget paramWi = createWidget(param, prefix, rightWidth); /* sub panel */ final String section = getSection(param); JPanel panel; final ConfigData.AccessType accessType = getAccessType(param); final String accessTypeString = accessType.toString(); final Boolean advanced = isAdvanced(param); final String advancedString = advanced.toString(); if (panelPartsMap.containsKey(section, accessTypeString, advancedString)) { panel = panelPartsMap.get(section, accessTypeString, advancedString); panelPartRowsMap.put(section, accessTypeString, advancedString, panelPartRowsMap.get(section, accessTypeString, advancedString) + 1); } else { panel = new JPanel(new SpringLayout()); panel.setBackground(getSectionColor(section)); if (advanced) { advancedPanelList.add(panel); panel.setVisible(Tools.getConfigData().isAdvancedMode()); } panelPartsMap.put(section, accessTypeString, advancedString, panel); panelPartsList.add(new PanelPart(section, accessType, advanced)); panelPartRowsMap.put(section, accessTypeString, advancedString, 1); } /* label */ final JLabel label = new JLabel(getParamShortDesc(param)); final String longDesc = getParamLongDesc(param); paramWi.setLabel(label, longDesc); /* tool tip */ paramWi.setToolTipText(getToolTipText(param, paramWi)); label.setToolTipText(longDesc + additionalToolTip(param)); int height = 0; if (paramWi instanceof Label) { height = Tools.getDefaultSize("Browser.LabelFieldHeight"); } addField(panel, label, paramWi, leftWidth, rightWidth, height); } final boolean wizard = Widget.WIZARD_PREFIX.equals(prefix); for (final String param : params) { final Widget paramWi = getWidget(param, prefix); Widget rpwi = null; if (wizard) { rpwi = getWidget(param, null); if (rpwi == null) { Tools.appError("unknown param: " + param + ". Could not find man pages for " + "your DRBD versions."); continue; } int height = 0; if (rpwi instanceof Label) { height = Tools.getDefaultSize("Browser.LabelFieldHeight"); } if (paramWi.getValue() == null || paramWi.getValue() == Widget.NOTHING_SELECTED_DISPLAY) { rpwi.setValueAndWait(null); } else { final Object value = paramWi.getStringValue(); rpwi.setValueAndWait(value); } } } for (final String param : params) { final Widget paramWi = getWidget(param, prefix); Widget rpwi = null; if (wizard) { rpwi = getWidget(param, null); } final Widget realParamWi = rpwi; paramWi.addListeners(new WidgetListener() { @Override public void check(final Object value) { checkParameterFields(paramWi, realParamWi, param, getParametersFromXML(), thisApplyButton); } }); } /* add sub panels to the option panel */ final Map<String, JPanel> sectionMap = new HashMap<String, JPanel>(); final Set<JPanel> notAdvancedSections = new HashSet<JPanel>(); final Set<JPanel> advancedSections = new HashSet<JPanel>(); for (final PanelPart panelPart : panelPartsList) { final String section = panelPart.getSection(); final ConfigData.AccessType accessType = panelPart.getAccessType(); final String accessTypeString = accessType.toString(); final Boolean advanced = panelPart.isAdvanced(); final String advancedString = advanced.toString(); final JPanel panel = panelPartsMap.get(section, accessTypeString, advancedString); final int rows = panelPartRowsMap.get(section, accessTypeString, advancedString); final int columns = 2; SpringUtilities.makeCompactGrid(panel, rows, columns, 1, 1, // initX, initY 1, 1); // xPad, yPad JPanel sectionPanel; if (sectionMap.containsKey(section)) { sectionPanel = sectionMap.get(section); } else { sectionPanel = getParamPanel(getSectionDisplayName(section), getSectionColor(section)); sectionMap.put(section, sectionPanel); addSectionPanel(section, wizard, sectionPanel); optionsPanel.add(sectionPanel); if (sameAsFields != null) { final Widget sameAsCombo = sameAsFields.get(section); if (sameAsCombo != null) { final JPanel saPanel = new JPanel(new SpringLayout()); saPanel.setBackground(Browser.BUTTON_PANEL_BACKGROUND); final JLabel label = new JLabel("Same As"); sameAsCombo.setLabel(label, ""); addField(saPanel, label, sameAsCombo, leftWidth, rightWidth, 0); SpringUtilities.makeCompactGrid(saPanel, 1, 2, 1, 1, // initX, initY 1, 1); // xPad, yPad sectionPanel.add(saPanel); } } } sectionPanel.setVisible(isSectionEnabled(section)); sectionPanel.add(panel); if (advanced) { advancedSections.add(sectionPanel); } else { notAdvancedSections.add(sectionPanel); } } boolean advanced = false; for (final String section : sectionMap.keySet()) { final JPanel sectionPanel = sectionMap.get(section); if (advancedSections.contains(sectionPanel)) { advanced = true; } if (!notAdvancedSections.contains(sectionPanel)) { advancedOnlySectionList.add(section); sectionPanel.setVisible(Tools.getConfigData().isAdvancedMode() && isSectionEnabled(section)); } } moreOptionsPanel.setVisible(advanced && !Tools.getConfigData().isAdvancedMode()); }
diff --git a/src/org/intellij/erlang/inspection/ErlangInspectionBase.java b/src/org/intellij/erlang/inspection/ErlangInspectionBase.java index b20ef60f..95bef648 100644 --- a/src/org/intellij/erlang/inspection/ErlangInspectionBase.java +++ b/src/org/intellij/erlang/inspection/ErlangInspectionBase.java @@ -1,132 +1,136 @@ /* * Copyright 2012-2013 Sergey Ignatov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.intellij.erlang.inspection; import com.intellij.codeInsight.daemon.impl.actions.AbstractSuppressByNoInspectionCommentFix; import com.intellij.codeInspection.*; import com.intellij.lang.Commenter; import com.intellij.lang.LanguageCommenters; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.*; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.IncorrectOperationException; import com.intellij.util.ObjectUtils; import org.intellij.erlang.ErlangLanguage; import org.intellij.erlang.psi.ErlangAttribute; import org.intellij.erlang.psi.ErlangCompositeElement; import org.intellij.erlang.psi.ErlangFunction; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author ignatov */ abstract public class ErlangInspectionBase extends LocalInspectionTool implements CustomSuppressableInspectionTool { private static final Pattern SUPPRESS_PATTERN = Pattern.compile(SuppressionUtil.COMMON_SUPPRESS_REGEXP); @Override public ProblemDescriptor[] checkFile(@NotNull PsiFile file, @NotNull InspectionManager manager, boolean isOnTheFly) { ProblemsHolder problemsHolder = new ProblemsHolder(manager, file, isOnTheFly); try { checkFile(file, problemsHolder); } catch (PsiInvalidElementAccessException ignored) { } return problemsHolder.getResultsArray(); } protected abstract void checkFile(PsiFile file, ProblemsHolder problemsHolder); @Nullable @Override public SuppressIntentionAction[] getSuppressActions(@Nullable PsiElement element) { return new SuppressIntentionAction[]{ new ErlangSuppressInspectionFix(getSuppressId(), "Suppress for function", ErlangFunction.class), new ErlangSuppressInspectionFix(getSuppressId(), "Suppress for attribute", ErlangAttribute.class) }; } @Override public boolean isSuppressedFor(PsiElement element) { return isSuppressedForParent(element, ErlangFunction.class) || isSuppressedForParent(element, ErlangAttribute.class); } private boolean isSuppressedForParent(PsiElement element, final Class<? extends ErlangCompositeElement> parentClass) { PsiElement parent = PsiTreeUtil.getParentOfType(element, parentClass, false); if (parent == null) { return false; } return isSuppressedForElement(parent); } private boolean isSuppressedForElement(@NotNull PsiElement element) { Commenter commenter = LanguageCommenters.INSTANCE.forLanguage(ErlangLanguage.INSTANCE); String prefix = ObjectUtils.notNull(commenter == null ? null : commenter.getLineCommentPrefix(), ""); PsiElement prevSibling = element.getPrevSibling(); if (prevSibling == null) { final PsiElement parent = element.getParent(); if (parent != null) { prevSibling = parent.getPrevSibling(); } } while (prevSibling instanceof PsiComment || prevSibling instanceof PsiWhiteSpace) { - if (prevSibling instanceof PsiComment && isSuppressedInComment(prevSibling.getText().substring(prefix.length()).trim())) { - return true; + if (prevSibling instanceof PsiComment) { + int prefixLength = prefix.length(); + String text = prevSibling.getText(); + if (text.length() >= prefixLength && isSuppressedInComment(text.substring(prefixLength).trim())) { + return true; + } } prevSibling = prevSibling.getPrevSibling(); } return false; } private boolean isSuppressedInComment(String commentText) { Matcher m = SUPPRESS_PATTERN.matcher(commentText); return m.matches() && SuppressionUtil.isInspectionToolIdMentioned(m.group(1), getSuppressId()); } private String getSuppressId() { return getShortName().replace("Inspection", ""); } public static class ErlangSuppressInspectionFix extends AbstractSuppressByNoInspectionCommentFix { private final Class<? extends ErlangCompositeElement> myContainerClass; public ErlangSuppressInspectionFix(final String ID, final String text, final Class<? extends ErlangCompositeElement> containerClass) { super(ID, false); setText(text); myContainerClass = containerClass; } @Override protected PsiElement getContainer(PsiElement context) { return PsiTreeUtil.getParentOfType(context, myContainerClass); } @Override protected void createSuppression(Project project, Editor editor, PsiElement element, PsiElement container) throws IncorrectOperationException { final PsiParserFacade parserFacade = PsiParserFacade.SERVICE.getInstance(project); final String text = SuppressionUtil.SUPPRESS_INSPECTIONS_TAG_NAME + " " + myID; PsiComment comment = parserFacade.createLineOrBlockCommentFromText(element.getContainingFile().getLanguage(), text); PsiElement where = container.getParent().addBefore(comment, container); PsiElement spaceFromText = PsiParserFacade.SERVICE.getInstance(project).createWhiteSpaceFromText("\n"); where.getParent().addAfter(spaceFromText, where); } } }
true
true
private boolean isSuppressedForElement(@NotNull PsiElement element) { Commenter commenter = LanguageCommenters.INSTANCE.forLanguage(ErlangLanguage.INSTANCE); String prefix = ObjectUtils.notNull(commenter == null ? null : commenter.getLineCommentPrefix(), ""); PsiElement prevSibling = element.getPrevSibling(); if (prevSibling == null) { final PsiElement parent = element.getParent(); if (parent != null) { prevSibling = parent.getPrevSibling(); } } while (prevSibling instanceof PsiComment || prevSibling instanceof PsiWhiteSpace) { if (prevSibling instanceof PsiComment && isSuppressedInComment(prevSibling.getText().substring(prefix.length()).trim())) { return true; } prevSibling = prevSibling.getPrevSibling(); } return false; }
private boolean isSuppressedForElement(@NotNull PsiElement element) { Commenter commenter = LanguageCommenters.INSTANCE.forLanguage(ErlangLanguage.INSTANCE); String prefix = ObjectUtils.notNull(commenter == null ? null : commenter.getLineCommentPrefix(), ""); PsiElement prevSibling = element.getPrevSibling(); if (prevSibling == null) { final PsiElement parent = element.getParent(); if (parent != null) { prevSibling = parent.getPrevSibling(); } } while (prevSibling instanceof PsiComment || prevSibling instanceof PsiWhiteSpace) { if (prevSibling instanceof PsiComment) { int prefixLength = prefix.length(); String text = prevSibling.getText(); if (text.length() >= prefixLength && isSuppressedInComment(text.substring(prefixLength).trim())) { return true; } } prevSibling = prevSibling.getPrevSibling(); } return false; }
diff --git a/plugins/org.eclipse.wazaabi.engine.swt/src/org/eclipse/wazaabi/engine/swt/views/collections/DynamicLabelProvider.java b/plugins/org.eclipse.wazaabi.engine.swt/src/org/eclipse/wazaabi/engine/swt/views/collections/DynamicLabelProvider.java index 02d4044e..36072408 100644 --- a/plugins/org.eclipse.wazaabi.engine.swt/src/org/eclipse/wazaabi/engine/swt/views/collections/DynamicLabelProvider.java +++ b/plugins/org.eclipse.wazaabi.engine.swt/src/org/eclipse/wazaabi/engine/swt/views/collections/DynamicLabelProvider.java @@ -1,326 +1,326 @@ /******************************************************************************* * Copyright (c) 2012 Olivier Moises * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Olivier Moises- initial API and implementation *******************************************************************************/ package org.eclipse.wazaabi.engine.swt.views.collections; import java.util.HashMap; import java.util.List; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.widgets.Display; import org.eclipse.wazaabi.engine.edp.EDPSingletons; import org.eclipse.wazaabi.engine.edp.coderesolution.AbstractCodeDescriptor; import org.eclipse.wazaabi.mm.core.styles.ColorRule; import org.eclipse.wazaabi.mm.core.styles.FontRule; import org.eclipse.wazaabi.mm.core.styles.collections.DynamicProvider; public class DynamicLabelProvider implements ILabelProvider, ITableLabelProvider { private AbstractCodeDescriptor.MethodDescriptor getTextMethodDescriptor = null; private AbstractCodeDescriptor.MethodDescriptor getColumnTextMethodDescriptor = null; private AbstractCodeDescriptor.MethodDescriptor getImageMethodDescriptor = null; private AbstractCodeDescriptor.MethodDescriptor getColumnImageMethodDescriptor = null; private AbstractCodeDescriptor.MethodDescriptor getBackgroundColorMethodDescriptor = null; private AbstractCodeDescriptor.MethodDescriptor getColumnBackgroundColorMethodDescriptor = null; private AbstractCodeDescriptor.MethodDescriptor getForegroundColorMethodDescriptor = null; private AbstractCodeDescriptor.MethodDescriptor getColumnForegroundColorMethodDescriptor = null; private AbstractCodeDescriptor.MethodDescriptor getFontMethodDescriptor = null; private AbstractCodeDescriptor.MethodDescriptor getColumnFontMethodDescriptor = null; // TODO : very bad and verbose code // we should be able to get the codeDescriptor from the methodDescriptor private AbstractCodeDescriptor getTextCodeDescriptor = null; private AbstractCodeDescriptor getColumnTextCodeDescriptor = null; private AbstractCodeDescriptor getImageCodeDescriptor = null; private AbstractCodeDescriptor getColumnImageCodeDescriptor = null; private AbstractCodeDescriptor getBackgroundColorCodeDescriptor = null; private AbstractCodeDescriptor getColumnBackgroundColorCodeDescriptor = null; private AbstractCodeDescriptor getForegroundColorCodeDescriptor = null; private AbstractCodeDescriptor getColumnForegroundColorCodeDescriptor = null; private AbstractCodeDescriptor getFontCodeDescriptor = null; private AbstractCodeDescriptor getColumnFontCodeDescriptor = null; public void updateDynamicProviderURIs( List<DynamicProvider> dynamicProviders, String baseURI) { for (DynamicProvider dynamicProvider : dynamicProviders) { String uri = dynamicProvider.getUri(); if (baseURI != null && !baseURI.isEmpty()) uri = EDPSingletons.getComposedCodeLocator().getFullPath( baseURI, uri, dynamicProvider); AbstractCodeDescriptor codeDescriptor = EDPSingletons .getComposedCodeLocator().resolveCodeDescriptor(uri); if (codeDescriptor != null) { AbstractCodeDescriptor.MethodDescriptor methodDescriptor = codeDescriptor .getMethodDescriptor( "getText", new String[] { "element" }, new Class[] { Object.class }, String.class); //$NON-NLS-1$ //$NON-NLS-2$ if (methodDescriptor != null) { getTextMethodDescriptor = methodDescriptor; getTextCodeDescriptor = codeDescriptor; } methodDescriptor = codeDescriptor .getMethodDescriptor( "getText", new String[] { "element", "columnIndex" }, new Class[] { Object.class, int.class }, String.class); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (methodDescriptor != null) { getColumnTextMethodDescriptor = methodDescriptor; getColumnTextCodeDescriptor = codeDescriptor; } methodDescriptor = codeDescriptor .getMethodDescriptor( "getImage", new String[] { "element" }, new Class[] { Object.class }, Image.class); //$NON-NLS-1$ //$NON-NLS-2$ if (methodDescriptor != null) { getImageMethodDescriptor = methodDescriptor; getImageCodeDescriptor = codeDescriptor; } methodDescriptor = codeDescriptor .getMethodDescriptor( "getImage", new String[] { "element", "columnIndex" }, new Class[] { Object.class, int.class }, Image.class); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (methodDescriptor != null) { getColumnImageMethodDescriptor = methodDescriptor; getColumnImageCodeDescriptor = codeDescriptor; } methodDescriptor = codeDescriptor .getMethodDescriptor( "getBackgroundColor", new String[] { "element" }, new Class[] { Object.class }, ColorRule.class); //$NON-NLS-1$ //$NON-NLS-2$ if (methodDescriptor != null) { getBackgroundColorMethodDescriptor = methodDescriptor; getBackgroundColorCodeDescriptor = codeDescriptor; } methodDescriptor = codeDescriptor .getMethodDescriptor( "getBackgroundColor", new String[] { "element", "columnIndex" }, new Class[] { Object.class, int.class }, ColorRule.class); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (methodDescriptor != null) { getColumnBackgroundColorMethodDescriptor = methodDescriptor; getColumnBackgroundColorCodeDescriptor = codeDescriptor; } methodDescriptor = codeDescriptor .getMethodDescriptor( "getForegroundColor", new String[] { "element" }, new Class[] { Object.class }, ColorRule.class); //$NON-NLS-1$ //$NON-NLS-2$ if (methodDescriptor != null) { getForegroundColorMethodDescriptor = methodDescriptor; getForegroundColorCodeDescriptor = codeDescriptor; } methodDescriptor = codeDescriptor .getMethodDescriptor( "getForegroundColor", new String[] { "element", "columnIndex" }, new Class[] { Object.class, int.class }, ColorRule.class); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (methodDescriptor != null) { getColumnForegroundColorMethodDescriptor = methodDescriptor; getColumnForegroundColorCodeDescriptor = codeDescriptor; } methodDescriptor = codeDescriptor .getMethodDescriptor( "getFont", new String[] { "element" }, new Class[] { Object.class }, FontRule.class); //$NON-NLS-1$ //$NON-NLS-2$ if (methodDescriptor != null) { getFontMethodDescriptor = methodDescriptor; getFontCodeDescriptor = codeDescriptor; } methodDescriptor = codeDescriptor .getMethodDescriptor( "getFont", new String[] { "element", "columnIndex" }, new Class[] { Object.class, int.class }, FontRule.class); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (methodDescriptor != null) { getColumnFontMethodDescriptor = methodDescriptor; getColumnFontCodeDescriptor = codeDescriptor; } } } } public void addListener(ILabelProviderListener listener) { // TODO Auto-generated method stub } public void dispose() { for (Color color : registeredColors.values()) color.dispose(); registeredColors.clear(); for (Font font : registeredFonts.values()) font.dispose(); registeredFonts.clear(); } public boolean isLabelProperty(Object element, String property) { // TODO Auto-generated method stub return false; } public void removeListener(ILabelProviderListener listener) { // TODO Auto-generated method stub } public Image getColumnImage(Object element, int columnIndex) { if (getColumnImageMethodDescriptor != null && getColumnImageCodeDescriptor != null) { return (Image) getColumnImageCodeDescriptor.invokeMethod( getColumnImageMethodDescriptor, new Object[] { element, columnIndex }); } if (columnIndex == 0) if (getImageMethodDescriptor != null && getImageCodeDescriptor != null) { return (Image) getImageCodeDescriptor.invokeMethod( getImageMethodDescriptor, new Object[] { element }); } return null; } public String getColumnText(Object element, int columnIndex) { if (getColumnTextMethodDescriptor != null && getColumnTextCodeDescriptor != null) { String result = (String) getColumnTextCodeDescriptor.invokeMethod( getColumnTextMethodDescriptor, new Object[] { element, columnIndex }); return result != null ? result : ""; //$NON-NLS-1$ } if (columnIndex == 0) if (getTextMethodDescriptor != null && getTextCodeDescriptor != null) { String result = (String) getTextCodeDescriptor.invokeMethod( getTextMethodDescriptor, new Object[] { element }); return result != null ? result : ""; //$NON-NLS-1$ } return ""; //$NON-NLS-1$ } public Image getImage(Object element) { return getColumnImage(element, 0); } public String getText(Object element) { if (getTextMethodDescriptor != null && getTextCodeDescriptor != null) { String result = (String) getTextCodeDescriptor.invokeMethod( getTextMethodDescriptor, new Object[] { element }); return result != null ? result : ""; //$NON-NLS-1$ } return getColumnText(element, 0); } public Color getBackgroundColor(Object element, int columnIndex, Display display) { if (getColumnBackgroundColorMethodDescriptor != null && getColumnBackgroundColorCodeDescriptor != null) { return getRegisteredColor( (ColorRule) getColumnBackgroundColorCodeDescriptor.invokeMethod( getColumnBackgroundColorMethodDescriptor, new Object[] { element, columnIndex }), display); } if (getBackgroundColorMethodDescriptor != null && getBackgroundColorCodeDescriptor != null) { return getRegisteredColor( (ColorRule) getBackgroundColorCodeDescriptor.invokeMethod( getBackgroundColorMethodDescriptor, new Object[] { element }), display); } return null; } public Color getForegroundColor(Object element, int columnIndex, Display display) { if (getColumnForegroundColorMethodDescriptor != null && getColumnForegroundColorCodeDescriptor != null) { return getRegisteredColor( (ColorRule) getColumnForegroundColorCodeDescriptor.invokeMethod( getColumnForegroundColorMethodDescriptor, new Object[] { element, columnIndex }), display); } if (getForegroundColorMethodDescriptor != null && getForegroundColorCodeDescriptor != null) { return getRegisteredColor( (ColorRule) getForegroundColorCodeDescriptor.invokeMethod( getForegroundColorMethodDescriptor, new Object[] { element }), display); } return null; } public Font getFont(Object element, int columnIndex, Display display, Font existingFont) { if (getColumnFontMethodDescriptor != null && getColumnFontCodeDescriptor != null) { return getRegisteredFont( (FontRule) getColumnFontCodeDescriptor.invokeMethod( getColumnFontMethodDescriptor, new Object[] { element, columnIndex }), display, existingFont); } if (getFontMethodDescriptor != null && getFontCodeDescriptor != null) { return getRegisteredFont( (FontRule) getFontCodeDescriptor.invokeMethod( getFontMethodDescriptor, new Object[] { element }), display, existingFont); } return null; } private HashMap<RGB, Color> registeredColors = new HashMap<RGB, Color>(); protected Color getRegisteredColor(ColorRule colorRule, Display display) { if (colorRule == null) return null; RGB rgb = new RGB(colorRule.getRed(), colorRule.getGreen(), colorRule.getBlue()); Color color = registeredColors.get(rgb); if (color == null) { color = new Color(display, rgb); registeredColors.put(rgb, color); } return color; } private HashMap<FontData, Font> registeredFonts = new HashMap<FontData, Font>(); protected Font getRegisteredFont(FontRule fontRule, Display display, Font existingFont) { if (fontRule == null) return existingFont; FontData oldFontData = existingFont.getFontData()[0]; FontData newFontData = new FontData(); if (fontRule.getName() != null && !fontRule.getName().isEmpty()) - newFontData.name = fontRule.getName(); + newFontData.setName(fontRule.getName()); else - newFontData.name = oldFontData.name; + newFontData.setName(oldFontData.getName()); if (fontRule.getHeight() > 0) newFontData.height = fontRule.getHeight(); else newFontData.height = oldFontData.height; if (fontRule.isItalic()) - newFontData.style |= SWT.ITALIC; + newFontData.setStyle(SWT.ITALIC | newFontData.getStyle()); if (fontRule.isBold()) - newFontData.style |= SWT.BOLD; + newFontData.setStyle(SWT.BOLD | newFontData.getStyle()); if (oldFontData.equals(newFontData)) return null; Font font = registeredFonts.get(newFontData); if (font == null) { font = new Font(display, newFontData); registeredFonts.put(newFontData, font); } return font; } }
false
true
protected Font getRegisteredFont(FontRule fontRule, Display display, Font existingFont) { if (fontRule == null) return existingFont; FontData oldFontData = existingFont.getFontData()[0]; FontData newFontData = new FontData(); if (fontRule.getName() != null && !fontRule.getName().isEmpty()) newFontData.name = fontRule.getName(); else newFontData.name = oldFontData.name; if (fontRule.getHeight() > 0) newFontData.height = fontRule.getHeight(); else newFontData.height = oldFontData.height; if (fontRule.isItalic()) newFontData.style |= SWT.ITALIC; if (fontRule.isBold()) newFontData.style |= SWT.BOLD; if (oldFontData.equals(newFontData)) return null; Font font = registeredFonts.get(newFontData); if (font == null) { font = new Font(display, newFontData); registeredFonts.put(newFontData, font); } return font; }
protected Font getRegisteredFont(FontRule fontRule, Display display, Font existingFont) { if (fontRule == null) return existingFont; FontData oldFontData = existingFont.getFontData()[0]; FontData newFontData = new FontData(); if (fontRule.getName() != null && !fontRule.getName().isEmpty()) newFontData.setName(fontRule.getName()); else newFontData.setName(oldFontData.getName()); if (fontRule.getHeight() > 0) newFontData.height = fontRule.getHeight(); else newFontData.height = oldFontData.height; if (fontRule.isItalic()) newFontData.setStyle(SWT.ITALIC | newFontData.getStyle()); if (fontRule.isBold()) newFontData.setStyle(SWT.BOLD | newFontData.getStyle()); if (oldFontData.equals(newFontData)) return null; Font font = registeredFonts.get(newFontData); if (font == null) { font = new Font(display, newFontData); registeredFonts.put(newFontData, font); } return font; }
diff --git a/example/webapp/src/main/java/com/spikylee/hyves4j/example/consumer/webapp/HyvesConsole.java b/example/webapp/src/main/java/com/spikylee/hyves4j/example/consumer/webapp/HyvesConsole.java index f8394e7..641c18b 100644 --- a/example/webapp/src/main/java/com/spikylee/hyves4j/example/consumer/webapp/HyvesConsole.java +++ b/example/webapp/src/main/java/com/spikylee/hyves4j/example/consumer/webapp/HyvesConsole.java @@ -1,168 +1,168 @@ /* * Copyright 2008 Arthur Bogaart <spikylee at gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.spikylee.hyves4j.example.consumer.webapp; import java.io.IOException; import java.io.PrintWriter; import java.net.URL; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.oauth.OAuth; import net.oauth.OAuth.Parameter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.spikylee.hyves4j.H4jException; import com.spikylee.hyves4j.Hyves4j; import com.spikylee.hyves4j.client.H4jClient; import com.spikylee.hyves4j.client.config.H4jClientConfig; public final class HyvesConsole extends HttpServlet { private static final long serialVersionUID = 1L; final static Logger logger = LoggerFactory.getLogger(HyvesConsole.class); @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { //Get Console form parameters String action = request.getParameter("doAction"); String oauthToken = request.getParameter("oauthToken"); String oauthTokenSecret = request.getParameter("oauthTokenSecret"); String fancyLayout = request.getParameter("haFancyLayout"); String responseFields = request.getParameter("haResponseFields"); String haMethod = request.getParameter("haMethod") != null ? request.getParameter("haMethod") : ""; List<Parameter> params = new ArrayList<Parameter>(); for (int i = 1; i <= 5; i++) { String key = request.getParameter("key" + i); if (key != null && key.length() > 0) { params.add(new Parameter(key, request.getParameter("value" + i))); } } //Create Hyves4j config, client and Hyves4j - URL consumerPropertiesURL = getClass().getResource("consumer.properties"); + URL consumerPropertiesURL = getClass().getResource("/consumer.properties"); H4jClientConfig config = new H4jClientConfig("hyves", consumerPropertiesURL); if (fancyLayout != null) { config.setFancyLayout(true); } H4jClient client = null; if (oauthToken != null && oauthToken.length() > 0 && oauthTokenSecret != null && oauthTokenSecret.length() > 0) { config.setAccessToken(oauthToken); config.setTokenSecret(oauthTokenSecret); client = new H4jClient(config); } else { client = new H4jClient(config); } Hyves4j h4j = new Hyves4j(client); if (action != null && "continue".equals(action)) { //Execute method String result; try { result = h4j.getConsole().execute(haMethod, responseFields, params); } catch (H4jException e) { throw new ServletException(e.getErrorCode() + "\n" + e.getErrorMessage()); } //print as text result = result.replaceAll("<", "&lt;"); result = result.replaceAll(">", "&gt;"); result = result.replaceAll("\n", "<br/>"); result = result.replaceAll(" ", "&#160;"); response.getWriter().append(result); } else { //Show Console form PrintWriter w = response.getWriter(); w.append("<html><head>"); w.append("<script language=\"javascript\" type=\"text/javascript\" src=\"resources/js/jquery-1.2.3.js\">"); w.append("<script language=\"javascript\" type=\"text/javascript\" src=\"resources/js/formHelper.js\">"); w.append("</head><body>"); w.append("<h1>Hyves4j Console</h1>"); w.append("<form name=\"consoleForm\" id=\"consoleForm\" onSubmit=\"handlePost(this.id, 'resultDiv');return false;\">"); w.append("<table border=\"0\"><tr><td><table border=\"0\">"); addLabel(w, "url", h4j.HYVES_API); addLabel(w, "oauthConsumerKey", client.getConsumer().consumerKey); addLabel(w, "oauthConsumerSecret", client.getConsumer().consumerSecret); addLabel(w, "oauthVersion", OAuth.VERSION_1_0); addLabel(w, "oauthNonce", OAuth.OAUTH_NONCE); addLabel(w, "oauthSignatureMethod", OAuth.HMAC_SHA1); addLabel(w, "haVersion", h4j.HYVES_API_VERSION); addLabel(w, "haFormat", h4j.HYVES_RESPONSE_FORMAT); addInput(w, "haFancyLayout", Boolean.toString(config.isFancyLayout())); addInput(w, "haResponseFields", responseFields); w.append("</table></td><td><table border=\"0\">"); addInput(w, "oauthToken", client.getAccessor().accessToken); addInput(w, "oauthTokenSecret", client.getAccessor().tokenSecret); addInput(w, "haMethod", haMethod); int i = 1; for (Parameter parameter : params) { w.append("<tr><td>"); w.append("key:value " + i); w.append("</td><td>"); addOnlyInput(w, "key" + i, parameter.getKey()); addOnlyInput(w, "value" + i, parameter.getValue()); w.append("</td></tr>"); i++; } for (; i <= 5; i++) { w.append("<tr><td>"); w.append("key:value " + i); w.append("</td><td>"); addOnlyInput(w, "key" + i, ""); addOnlyInput(w, "value" + i, ""); w.append("</td></tr>"); } w.append("</table></td></tr></table><input type=\"submit\" value=\"go\"/><input type=\"hidden\" name=\"doAction\" value=\"continue\" /></form>"); w.append("<br/><h3>Result</h3><p><div id=\"resultDiv\"></div></p>"); w.append("</body></html>"); } } //Append new table row + text input private void addInput(PrintWriter w, String name, String value) throws IOException { if (value == null) value = ""; w.append("<tr><td>"); w.append(name + "</td><td>"); addOnlyInput(w, name, value); w.append("</td></tr>"); } //Append text input private void addOnlyInput(PrintWriter w, String name, String value) throws IOException { w.append("<input type=\"text\" name=\"" + name + "\" id=\"" + name + "\" value=\"" + value + "\""); } //Append table row + label private void addLabel(PrintWriter w, String name, String value) throws IOException { w.append("<tr><td>"); w.append(name + "</td><td>" + value + "</td></tr>"); } }
true
true
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { //Get Console form parameters String action = request.getParameter("doAction"); String oauthToken = request.getParameter("oauthToken"); String oauthTokenSecret = request.getParameter("oauthTokenSecret"); String fancyLayout = request.getParameter("haFancyLayout"); String responseFields = request.getParameter("haResponseFields"); String haMethod = request.getParameter("haMethod") != null ? request.getParameter("haMethod") : ""; List<Parameter> params = new ArrayList<Parameter>(); for (int i = 1; i <= 5; i++) { String key = request.getParameter("key" + i); if (key != null && key.length() > 0) { params.add(new Parameter(key, request.getParameter("value" + i))); } } //Create Hyves4j config, client and Hyves4j URL consumerPropertiesURL = getClass().getResource("consumer.properties"); H4jClientConfig config = new H4jClientConfig("hyves", consumerPropertiesURL); if (fancyLayout != null) { config.setFancyLayout(true); } H4jClient client = null; if (oauthToken != null && oauthToken.length() > 0 && oauthTokenSecret != null && oauthTokenSecret.length() > 0) { config.setAccessToken(oauthToken); config.setTokenSecret(oauthTokenSecret); client = new H4jClient(config); } else { client = new H4jClient(config); } Hyves4j h4j = new Hyves4j(client); if (action != null && "continue".equals(action)) { //Execute method String result; try { result = h4j.getConsole().execute(haMethod, responseFields, params); } catch (H4jException e) { throw new ServletException(e.getErrorCode() + "\n" + e.getErrorMessage()); } //print as text result = result.replaceAll("<", "&lt;"); result = result.replaceAll(">", "&gt;"); result = result.replaceAll("\n", "<br/>"); result = result.replaceAll(" ", "&#160;"); response.getWriter().append(result); } else { //Show Console form PrintWriter w = response.getWriter(); w.append("<html><head>"); w.append("<script language=\"javascript\" type=\"text/javascript\" src=\"resources/js/jquery-1.2.3.js\">"); w.append("<script language=\"javascript\" type=\"text/javascript\" src=\"resources/js/formHelper.js\">"); w.append("</head><body>"); w.append("<h1>Hyves4j Console</h1>"); w.append("<form name=\"consoleForm\" id=\"consoleForm\" onSubmit=\"handlePost(this.id, 'resultDiv');return false;\">"); w.append("<table border=\"0\"><tr><td><table border=\"0\">"); addLabel(w, "url", h4j.HYVES_API); addLabel(w, "oauthConsumerKey", client.getConsumer().consumerKey); addLabel(w, "oauthConsumerSecret", client.getConsumer().consumerSecret); addLabel(w, "oauthVersion", OAuth.VERSION_1_0); addLabel(w, "oauthNonce", OAuth.OAUTH_NONCE); addLabel(w, "oauthSignatureMethod", OAuth.HMAC_SHA1); addLabel(w, "haVersion", h4j.HYVES_API_VERSION); addLabel(w, "haFormat", h4j.HYVES_RESPONSE_FORMAT); addInput(w, "haFancyLayout", Boolean.toString(config.isFancyLayout())); addInput(w, "haResponseFields", responseFields); w.append("</table></td><td><table border=\"0\">"); addInput(w, "oauthToken", client.getAccessor().accessToken); addInput(w, "oauthTokenSecret", client.getAccessor().tokenSecret); addInput(w, "haMethod", haMethod); int i = 1; for (Parameter parameter : params) { w.append("<tr><td>"); w.append("key:value " + i); w.append("</td><td>"); addOnlyInput(w, "key" + i, parameter.getKey()); addOnlyInput(w, "value" + i, parameter.getValue()); w.append("</td></tr>"); i++; } for (; i <= 5; i++) { w.append("<tr><td>"); w.append("key:value " + i); w.append("</td><td>"); addOnlyInput(w, "key" + i, ""); addOnlyInput(w, "value" + i, ""); w.append("</td></tr>"); } w.append("</table></td></tr></table><input type=\"submit\" value=\"go\"/><input type=\"hidden\" name=\"doAction\" value=\"continue\" /></form>"); w.append("<br/><h3>Result</h3><p><div id=\"resultDiv\"></div></p>"); w.append("</body></html>"); } }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { //Get Console form parameters String action = request.getParameter("doAction"); String oauthToken = request.getParameter("oauthToken"); String oauthTokenSecret = request.getParameter("oauthTokenSecret"); String fancyLayout = request.getParameter("haFancyLayout"); String responseFields = request.getParameter("haResponseFields"); String haMethod = request.getParameter("haMethod") != null ? request.getParameter("haMethod") : ""; List<Parameter> params = new ArrayList<Parameter>(); for (int i = 1; i <= 5; i++) { String key = request.getParameter("key" + i); if (key != null && key.length() > 0) { params.add(new Parameter(key, request.getParameter("value" + i))); } } //Create Hyves4j config, client and Hyves4j URL consumerPropertiesURL = getClass().getResource("/consumer.properties"); H4jClientConfig config = new H4jClientConfig("hyves", consumerPropertiesURL); if (fancyLayout != null) { config.setFancyLayout(true); } H4jClient client = null; if (oauthToken != null && oauthToken.length() > 0 && oauthTokenSecret != null && oauthTokenSecret.length() > 0) { config.setAccessToken(oauthToken); config.setTokenSecret(oauthTokenSecret); client = new H4jClient(config); } else { client = new H4jClient(config); } Hyves4j h4j = new Hyves4j(client); if (action != null && "continue".equals(action)) { //Execute method String result; try { result = h4j.getConsole().execute(haMethod, responseFields, params); } catch (H4jException e) { throw new ServletException(e.getErrorCode() + "\n" + e.getErrorMessage()); } //print as text result = result.replaceAll("<", "&lt;"); result = result.replaceAll(">", "&gt;"); result = result.replaceAll("\n", "<br/>"); result = result.replaceAll(" ", "&#160;"); response.getWriter().append(result); } else { //Show Console form PrintWriter w = response.getWriter(); w.append("<html><head>"); w.append("<script language=\"javascript\" type=\"text/javascript\" src=\"resources/js/jquery-1.2.3.js\">"); w.append("<script language=\"javascript\" type=\"text/javascript\" src=\"resources/js/formHelper.js\">"); w.append("</head><body>"); w.append("<h1>Hyves4j Console</h1>"); w.append("<form name=\"consoleForm\" id=\"consoleForm\" onSubmit=\"handlePost(this.id, 'resultDiv');return false;\">"); w.append("<table border=\"0\"><tr><td><table border=\"0\">"); addLabel(w, "url", h4j.HYVES_API); addLabel(w, "oauthConsumerKey", client.getConsumer().consumerKey); addLabel(w, "oauthConsumerSecret", client.getConsumer().consumerSecret); addLabel(w, "oauthVersion", OAuth.VERSION_1_0); addLabel(w, "oauthNonce", OAuth.OAUTH_NONCE); addLabel(w, "oauthSignatureMethod", OAuth.HMAC_SHA1); addLabel(w, "haVersion", h4j.HYVES_API_VERSION); addLabel(w, "haFormat", h4j.HYVES_RESPONSE_FORMAT); addInput(w, "haFancyLayout", Boolean.toString(config.isFancyLayout())); addInput(w, "haResponseFields", responseFields); w.append("</table></td><td><table border=\"0\">"); addInput(w, "oauthToken", client.getAccessor().accessToken); addInput(w, "oauthTokenSecret", client.getAccessor().tokenSecret); addInput(w, "haMethod", haMethod); int i = 1; for (Parameter parameter : params) { w.append("<tr><td>"); w.append("key:value " + i); w.append("</td><td>"); addOnlyInput(w, "key" + i, parameter.getKey()); addOnlyInput(w, "value" + i, parameter.getValue()); w.append("</td></tr>"); i++; } for (; i <= 5; i++) { w.append("<tr><td>"); w.append("key:value " + i); w.append("</td><td>"); addOnlyInput(w, "key" + i, ""); addOnlyInput(w, "value" + i, ""); w.append("</td></tr>"); } w.append("</table></td></tr></table><input type=\"submit\" value=\"go\"/><input type=\"hidden\" name=\"doAction\" value=\"continue\" /></form>"); w.append("<br/><h3>Result</h3><p><div id=\"resultDiv\"></div></p>"); w.append("</body></html>"); } }
diff --git a/src/com/ayan4m1/multiarrow/MultiArrowEntityListener.java b/src/com/ayan4m1/multiarrow/MultiArrowEntityListener.java index a4f2a25..0b65454 100644 --- a/src/com/ayan4m1/multiarrow/MultiArrowEntityListener.java +++ b/src/com/ayan4m1/multiarrow/MultiArrowEntityListener.java @@ -1,73 +1,73 @@ package com.ayan4m1.multiarrow; import java.util.List; import org.bukkit.entity.Arrow; import org.bukkit.entity.Entity; import org.bukkit.entity.Item; import org.bukkit.entity.Player; import org.bukkit.event.entity.EntityDamageByProjectileEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityListener; import org.bukkit.event.entity.ProjectileHitEvent; import com.ayan4m1.multiarrow.arrows.ArrowType; /** * MultiArrow entity listener * @author ayan4m1 */ public class MultiArrowEntityListener extends EntityListener { private MultiArrow plugin; public MultiArrowEntityListener(MultiArrow instance) { plugin = instance; } public void onProjectileHit(ProjectileHitEvent event) { if (event.getEntity() instanceof Arrow) { Arrow arrow = (Arrow)event.getEntity(); ArrowType arrowType = plugin.activeArrowType.get(((Player)arrow.getShooter()).getName()); - List<Entity> entities = arrow.getNearbyEntities(2D, 2D, 2D); - for(int i = 0; i < entities.size(); i++) { - if (entities.get(i) instanceof Arrow || entities.get(i) instanceof Item) { - entities.clear(); - break; + List<Entity> entities = arrow.getNearbyEntities(1D, 1D, 1D); + int entCount = entities.size(); + for(Entity ent : entities) { + if ((ent instanceof Arrow) || (ent instanceof Item) || (ent == arrow.getShooter())) { + entCount--; } } - if (entities.size() == 0) { + if (entCount == 0) { if (plugin.activeArrowEffect.containsKey(arrow)) { if (plugin.chargeFee((Player)arrow.getShooter(), arrowType)) { plugin.activeArrowEffect.get(arrow).hitGround(arrow); plugin.activeArrowEffect.remove(arrow); } if (plugin.config.getArrowRemove(arrowType)) { arrow.remove(); } } } } } public void onEntityDamage(EntityDamageEvent event) { if (event instanceof EntityDamageByProjectileEvent) { EntityDamageByProjectileEvent dpe = ((EntityDamageByProjectileEvent)event); if (dpe.getProjectile() instanceof Arrow) { Arrow arrow = (Arrow)dpe.getProjectile(); ArrowType arrowType = plugin.activeArrowType.get(((Player)arrow.getShooter()).getName()); if (arrowType != ArrowType.NORMAL) { event.setCancelled(true); } if (plugin.activeArrowEffect.containsKey(arrow)) { if (plugin.chargeFee((Player)arrow.getShooter(), arrowType)) { plugin.activeArrowEffect.get(arrow).hitEntity(arrow, event.getEntity()); plugin.activeArrowEffect.remove(arrow); } if (plugin.config.getArrowRemove(arrowType)) { arrow.remove(); } } } } } }
false
true
public void onProjectileHit(ProjectileHitEvent event) { if (event.getEntity() instanceof Arrow) { Arrow arrow = (Arrow)event.getEntity(); ArrowType arrowType = plugin.activeArrowType.get(((Player)arrow.getShooter()).getName()); List<Entity> entities = arrow.getNearbyEntities(2D, 2D, 2D); for(int i = 0; i < entities.size(); i++) { if (entities.get(i) instanceof Arrow || entities.get(i) instanceof Item) { entities.clear(); break; } } if (entities.size() == 0) { if (plugin.activeArrowEffect.containsKey(arrow)) { if (plugin.chargeFee((Player)arrow.getShooter(), arrowType)) { plugin.activeArrowEffect.get(arrow).hitGround(arrow); plugin.activeArrowEffect.remove(arrow); } if (plugin.config.getArrowRemove(arrowType)) { arrow.remove(); } } } } }
public void onProjectileHit(ProjectileHitEvent event) { if (event.getEntity() instanceof Arrow) { Arrow arrow = (Arrow)event.getEntity(); ArrowType arrowType = plugin.activeArrowType.get(((Player)arrow.getShooter()).getName()); List<Entity> entities = arrow.getNearbyEntities(1D, 1D, 1D); int entCount = entities.size(); for(Entity ent : entities) { if ((ent instanceof Arrow) || (ent instanceof Item) || (ent == arrow.getShooter())) { entCount--; } } if (entCount == 0) { if (plugin.activeArrowEffect.containsKey(arrow)) { if (plugin.chargeFee((Player)arrow.getShooter(), arrowType)) { plugin.activeArrowEffect.get(arrow).hitGround(arrow); plugin.activeArrowEffect.remove(arrow); } if (plugin.config.getArrowRemove(arrowType)) { arrow.remove(); } } } } }
diff --git a/BranchedAlkanesTest.java b/BranchedAlkanesTest.java index d10d71f..d49eda5 100644 --- a/BranchedAlkanesTest.java +++ b/BranchedAlkanesTest.java @@ -1,101 +1,101 @@ class BranchedAlkanesTest extends AlkanesTest { private BranchedAlkanesTest( String name, int testsPlanned ) { super( name, testsPlanned ); } private String inMiddleOf(int halfLength, String alkyl) { StringBuilder sb = new StringBuilder(); for ( int i = 0; i < halfLength + 1; i++ ) sb.append("C("); sb.append(alkyl.substring(1)); for ( int i = 0; i < halfLength - 1; i++ ) sb.append("C("); sb.append("C"); for ( int i = 0; i < halfLength; i++ ) sb.append("))"); return sb.toString(); } public void runTests() { is( new Alkane("C(C(C(CC(C))))").iupacName(), "3-Methylpentane", "Side chains and longest chain name the alkyl" ); is( new Alkane("C(C(CC(C(CC(CC)))))").iupacName(), "2,3,5-Trimethylhexane", "Direction chosen so as to give lowest possible numbers I" ); is( new Alkane("C(C(C(CC(CC(C(C(C(C(CC)))))))))").iupacName(), "2,7,8-Trimethyldecane", "Direction chosen so as to give lowest possible numbers II" ); is( new Alkane("C(C(C(C(C(CC(C(C(C))C(C(C))))))))").iupacName(), "5-Methyl-4-propylnonane", "Direction chosen so as to give lowest possible numbers III" ); is( new Alkane("C(C(C(C(C(C(C(" + "C(CC(C(C(C))))" + "C(C(C(C(C(C))))))))))))").iupacName(), "7-(1-Methylpentyl)tridecane", "Branches are numbered from the trunk out along longest chain I" ); is( new Alkane("C(C(C(C(C(C(C(" + "C(C(CC(C(C))))" + "C(C(C(C(C(C))))))))))))").iupacName(), "7-(2-Methylpentyl)tridecane", "Branches are numbered from the trunk out along longest chain II" ); is( new Alkane("C(C(C(C(C(C(C(" + "C(C(C(C(C(C(CC)))))" + "C(C(C(C(C(C(C))))))))))))))").iupacName(), "8-(5-Methylhexyl)pentadecane", "Branches are numbered from the trunk out along longest chain III" ); is( new Alkane( inMiddleOf(4, "-C(CC)") ).iupacName(), "5-Isopropylnonane", "Isopropyl" ); is( new Alkane( inMiddleOf(4, "-C(C(CC))") ).iupacName(), "5-Isobutylnonane", "Isobutyl" ); is( new Alkane( inMiddleOf(4, "-C(CC(C))") ).iupacName(), - "5-sec-butylnonane", + "5-sec-Butylnonane", "sec-butyl" ); is( new Alkane( inMiddleOf(5, "-C(CCC)") ).iupacName(), - "6-tert-butylundecane", + "6-tert-Butylundecane", "tert-butyl" ); is( new Alkane( inMiddleOf(6, "-C(C(C(CC)))") ).iupacName(), "7-Isopentyltridecane", "Isopentyl" ); is( new Alkane( inMiddleOf(5, "-C(C(CCC))") ).iupacName(), "6-Neopentylundecane", "Neopentyl" ); is( new Alkane( inMiddleOf(5, "-C(CCC(C))") ).iupacName(), "6-tert-Pentylundecane", "tert-Pentyl" ); is( new Alkane( inMiddleOf(6, "-C(C(C(C(CC))))") ).iupacName(), "7-Isohexyltridecane", "Isohexyl" ); } public static void main( String args[] ) { new BranchedAlkanesTest( "Branched alkanes", 15 ).test(); } }
false
true
public void runTests() { is( new Alkane("C(C(C(CC(C))))").iupacName(), "3-Methylpentane", "Side chains and longest chain name the alkyl" ); is( new Alkane("C(C(CC(C(CC(CC)))))").iupacName(), "2,3,5-Trimethylhexane", "Direction chosen so as to give lowest possible numbers I" ); is( new Alkane("C(C(C(CC(CC(C(C(C(C(CC)))))))))").iupacName(), "2,7,8-Trimethyldecane", "Direction chosen so as to give lowest possible numbers II" ); is( new Alkane("C(C(C(C(C(CC(C(C(C))C(C(C))))))))").iupacName(), "5-Methyl-4-propylnonane", "Direction chosen so as to give lowest possible numbers III" ); is( new Alkane("C(C(C(C(C(C(C(" + "C(CC(C(C(C))))" + "C(C(C(C(C(C))))))))))))").iupacName(), "7-(1-Methylpentyl)tridecane", "Branches are numbered from the trunk out along longest chain I" ); is( new Alkane("C(C(C(C(C(C(C(" + "C(C(CC(C(C))))" + "C(C(C(C(C(C))))))))))))").iupacName(), "7-(2-Methylpentyl)tridecane", "Branches are numbered from the trunk out along longest chain II" ); is( new Alkane("C(C(C(C(C(C(C(" + "C(C(C(C(C(C(CC)))))" + "C(C(C(C(C(C(C))))))))))))))").iupacName(), "8-(5-Methylhexyl)pentadecane", "Branches are numbered from the trunk out along longest chain III" ); is( new Alkane( inMiddleOf(4, "-C(CC)") ).iupacName(), "5-Isopropylnonane", "Isopropyl" ); is( new Alkane( inMiddleOf(4, "-C(C(CC))") ).iupacName(), "5-Isobutylnonane", "Isobutyl" ); is( new Alkane( inMiddleOf(4, "-C(CC(C))") ).iupacName(), "5-sec-butylnonane", "sec-butyl" ); is( new Alkane( inMiddleOf(5, "-C(CCC)") ).iupacName(), "6-tert-butylundecane", "tert-butyl" ); is( new Alkane( inMiddleOf(6, "-C(C(C(CC)))") ).iupacName(), "7-Isopentyltridecane", "Isopentyl" ); is( new Alkane( inMiddleOf(5, "-C(C(CCC))") ).iupacName(), "6-Neopentylundecane", "Neopentyl" ); is( new Alkane( inMiddleOf(5, "-C(CCC(C))") ).iupacName(), "6-tert-Pentylundecane", "tert-Pentyl" ); is( new Alkane( inMiddleOf(6, "-C(C(C(C(CC))))") ).iupacName(), "7-Isohexyltridecane", "Isohexyl" ); }
public void runTests() { is( new Alkane("C(C(C(CC(C))))").iupacName(), "3-Methylpentane", "Side chains and longest chain name the alkyl" ); is( new Alkane("C(C(CC(C(CC(CC)))))").iupacName(), "2,3,5-Trimethylhexane", "Direction chosen so as to give lowest possible numbers I" ); is( new Alkane("C(C(C(CC(CC(C(C(C(C(CC)))))))))").iupacName(), "2,7,8-Trimethyldecane", "Direction chosen so as to give lowest possible numbers II" ); is( new Alkane("C(C(C(C(C(CC(C(C(C))C(C(C))))))))").iupacName(), "5-Methyl-4-propylnonane", "Direction chosen so as to give lowest possible numbers III" ); is( new Alkane("C(C(C(C(C(C(C(" + "C(CC(C(C(C))))" + "C(C(C(C(C(C))))))))))))").iupacName(), "7-(1-Methylpentyl)tridecane", "Branches are numbered from the trunk out along longest chain I" ); is( new Alkane("C(C(C(C(C(C(C(" + "C(C(CC(C(C))))" + "C(C(C(C(C(C))))))))))))").iupacName(), "7-(2-Methylpentyl)tridecane", "Branches are numbered from the trunk out along longest chain II" ); is( new Alkane("C(C(C(C(C(C(C(" + "C(C(C(C(C(C(CC)))))" + "C(C(C(C(C(C(C))))))))))))))").iupacName(), "8-(5-Methylhexyl)pentadecane", "Branches are numbered from the trunk out along longest chain III" ); is( new Alkane( inMiddleOf(4, "-C(CC)") ).iupacName(), "5-Isopropylnonane", "Isopropyl" ); is( new Alkane( inMiddleOf(4, "-C(C(CC))") ).iupacName(), "5-Isobutylnonane", "Isobutyl" ); is( new Alkane( inMiddleOf(4, "-C(CC(C))") ).iupacName(), "5-sec-Butylnonane", "sec-butyl" ); is( new Alkane( inMiddleOf(5, "-C(CCC)") ).iupacName(), "6-tert-Butylundecane", "tert-butyl" ); is( new Alkane( inMiddleOf(6, "-C(C(C(CC)))") ).iupacName(), "7-Isopentyltridecane", "Isopentyl" ); is( new Alkane( inMiddleOf(5, "-C(C(CCC))") ).iupacName(), "6-Neopentylundecane", "Neopentyl" ); is( new Alkane( inMiddleOf(5, "-C(CCC(C))") ).iupacName(), "6-tert-Pentylundecane", "tert-Pentyl" ); is( new Alkane( inMiddleOf(6, "-C(C(C(C(CC))))") ).iupacName(), "7-Isohexyltridecane", "Isohexyl" ); }
diff --git a/src/com/android/phone/BluetoothHandsfree.java b/src/com/android/phone/BluetoothHandsfree.java index 53d148ec..2a485fce 100644 --- a/src/com/android/phone/BluetoothHandsfree.java +++ b/src/com/android/phone/BluetoothHandsfree.java @@ -1,1870 +1,1871 @@ /* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.phone; import android.bluetooth.AtCommandHandler; import android.bluetooth.AtCommandResult; import android.bluetooth.AtParser; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothHeadset; import android.bluetooth.BluetoothIntent; import android.bluetooth.HeadsetBase; import android.bluetooth.ScoSocket; import android.content.ActivityNotFoundException; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.media.AudioManager; import android.net.Uri; import android.os.AsyncResult; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.os.SystemProperties; import android.telephony.PhoneNumberUtils; import android.telephony.ServiceState; import android.telephony.SignalStrength; import android.util.Log; import com.android.internal.telephony.Call; import com.android.internal.telephony.Connection; import com.android.internal.telephony.Phone; import com.android.internal.telephony.TelephonyIntents; import java.util.LinkedList; /** * Bluetooth headset manager for the Phone app. * @hide */ public class BluetoothHandsfree { private static final String TAG = "BT HS/HF"; private static final boolean DBG = false; private static final boolean VDBG = false; // even more logging public static final int TYPE_UNKNOWN = 0; public static final int TYPE_HEADSET = 1; public static final int TYPE_HANDSFREE = 2; private final Context mContext; private final Phone mPhone; private ServiceState mServiceState; private HeadsetBase mHeadset; // null when not connected private int mHeadsetType; private boolean mAudioPossible; private ScoSocket mIncomingSco; private ScoSocket mOutgoingSco; private ScoSocket mConnectedSco; private Call mForegroundCall; private Call mBackgroundCall; private Call mRingingCall; private AudioManager mAudioManager; private PowerManager mPowerManager; private boolean mUserWantsAudio; private WakeLock mStartCallWakeLock; // held while waiting for the intent to start call private WakeLock mStartVoiceRecognitionWakeLock; // held while waiting for voice recognition // AT command state private static final int MAX_CONNECTIONS = 6; // Max connections allowed by GSM private long mBgndEarliestConnectionTime = 0; private boolean mClip = false; // Calling Line Information Presentation private boolean mIndicatorsEnabled = false; private boolean mCmee = false; // Extended Error reporting private long[] mClccTimestamps; // Timestamps associated with each clcc index private boolean[] mClccUsed; // Is this clcc index in use private boolean mWaitingForCallStart; private boolean mWaitingForVoiceRecognition; // do not connect audio until service connection is established // for 3-way supported devices, this is after AT+CHLD // for non-3-way supported devices, this is after AT+CMER (see spec) private boolean mServiceConnectionEstablished; private final BluetoothPhoneState mPhoneState; // for CIND and CIEV updates private final BluetoothAtPhonebook mPhonebook; private DebugThread mDebugThread; private int mScoGain = Integer.MIN_VALUE; private static Intent sVoiceCommandIntent; // Audio parameters private static final String HEADSET_NREC = "bt_headset_nrec"; private static final String HEADSET_NAME = "bt_headset_name"; private int mRemoteBrsf = 0; private int mLocalBrsf = 0; /* Constants from Bluetooth Specification Hands-Free profile version 1.5 */ private static final int BRSF_AG_THREE_WAY_CALLING = 1 << 0; private static final int BRSF_AG_EC_NR = 1 << 1; private static final int BRSF_AG_VOICE_RECOG = 1 << 2; private static final int BRSF_AG_IN_BAND_RING = 1 << 3; private static final int BRSF_AG_VOICE_TAG_NUMBE = 1 << 4; private static final int BRSF_AG_REJECT_CALL = 1 << 5; private static final int BRSF_AG_ENHANCED_CALL_STATUS = 1 << 6; private static final int BRSF_AG_ENHANCED_CALL_CONTROL = 1 << 7; private static final int BRSF_AG_ENHANCED_ERR_RESULT_CODES = 1 << 8; private static final int BRSF_HF_EC_NR = 1 << 0; private static final int BRSF_HF_CW_THREE_WAY_CALLING = 1 << 1; private static final int BRSF_HF_CLIP = 1 << 2; private static final int BRSF_HF_VOICE_REG_ACT = 1 << 3; private static final int BRSF_HF_REMOTE_VOL_CONTROL = 1 << 4; private static final int BRSF_HF_ENHANCED_CALL_STATUS = 1 << 5; private static final int BRSF_HF_ENHANCED_CALL_CONTROL = 1 << 6; public static String typeToString(int type) { switch (type) { case TYPE_UNKNOWN: return "unknown"; case TYPE_HEADSET: return "headset"; case TYPE_HANDSFREE: return "handsfree"; } return null; } public BluetoothHandsfree(Context context, Phone phone) { mPhone = phone; mContext = context; BluetoothDevice bluetooth = (BluetoothDevice)context.getSystemService(Context.BLUETOOTH_SERVICE); boolean bluetoothCapable = (bluetooth != null); mHeadset = null; // nothing connected yet mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE); mStartCallWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG + ":StartCall"); mStartCallWakeLock.setReferenceCounted(false); mStartVoiceRecognitionWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG + ":VoiceRecognition"); mStartVoiceRecognitionWakeLock.setReferenceCounted(false); mLocalBrsf = BRSF_AG_THREE_WAY_CALLING | BRSF_AG_EC_NR | BRSF_AG_REJECT_CALL | BRSF_AG_ENHANCED_CALL_STATUS; if (sVoiceCommandIntent == null) { sVoiceCommandIntent = new Intent(Intent.ACTION_VOICE_COMMAND); sVoiceCommandIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); } if (mContext.getPackageManager().resolveActivity(sVoiceCommandIntent, 0) != null && !BluetoothHeadset.DISABLE_BT_VOICE_DIALING) { mLocalBrsf |= BRSF_AG_VOICE_RECOG; } if (bluetoothCapable) { resetAtState(); } mRingingCall = mPhone.getRingingCall(); mForegroundCall = mPhone.getForegroundCall(); mBackgroundCall = mPhone.getBackgroundCall(); mPhoneState = new BluetoothPhoneState(); mUserWantsAudio = true; mPhonebook = new BluetoothAtPhonebook(mContext, this); mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); } /* package */ synchronized void onBluetoothEnabled() { /* Bluez has a bug where it will always accept and then orphan * incoming SCO connections, regardless of whether we have a listening * SCO socket. So the best thing to do is always run a listening socket * while bluetooth is on so that at least we can diconnect it * immediately when we don't want it. */ if (mIncomingSco == null) { mIncomingSco = createScoSocket(); mIncomingSco.accept(); } } /* package */ synchronized void onBluetoothDisabled() { if (mConnectedSco != null) { mAudioManager.setBluetoothScoOn(false); broadcastAudioStateIntent(BluetoothHeadset.AUDIO_STATE_DISCONNECTED); mConnectedSco.close(); mConnectedSco = null; } if (mOutgoingSco != null) { mOutgoingSco.close(); mOutgoingSco = null; } if (mIncomingSco != null) { mIncomingSco.close(); mIncomingSco = null; } } private boolean isHeadsetConnected() { if (mHeadset == null) { return false; } return mHeadset.isConnected(); } /* package */ void connectHeadset(HeadsetBase headset, int headsetType) { mHeadset = headset; mHeadsetType = headsetType; if (mHeadsetType == TYPE_HEADSET) { initializeHeadsetAtParser(); } else { initializeHandsfreeAtParser(); } headset.startEventThread(); configAudioParameters(); if (inDebug()) { startDebug(); } if (isIncallAudio()) { audioOn(); } } /* returns true if there is some kind of in-call audio we may wish to route * bluetooth to */ private boolean isIncallAudio() { Call.State state = mForegroundCall.getState(); return (state == Call.State.ACTIVE || state == Call.State.ALERTING); } /* package */ void disconnectHeadset() { mHeadset = null; stopDebug(); resetAtState(); } private void resetAtState() { mClip = false; mIndicatorsEnabled = false; mServiceConnectionEstablished = false; mCmee = false; mClccTimestamps = new long[MAX_CONNECTIONS]; mClccUsed = new boolean[MAX_CONNECTIONS]; for (int i = 0; i < MAX_CONNECTIONS; i++) { mClccUsed[i] = false; } mRemoteBrsf = 0; } private void configAudioParameters() { String name = mHeadset.getName(); if (name == null) { name = "<unknown>"; } mAudioManager.setParameter(HEADSET_NAME, name); mAudioManager.setParameter(HEADSET_NREC, "on"); } /** Represents the data that we send in a +CIND or +CIEV command to the HF */ private class BluetoothPhoneState { // 0: no service // 1: service private int mService; // 0: no active call // 1: active call (where active means audio is routed - not held call) private int mCall; // 0: not in call setup // 1: incoming call setup // 2: outgoing call setup // 3: remote party being alerted in an outgoing call setup private int mCallsetup; // 0: no calls held // 1: held call and active call // 2: held call only private int mCallheld; // cellular signal strength of AG: 0-5 private int mSignal; // cellular signal strength in CSQ rssi scale private int mRssi; // for CSQ // 0: roaming not active (home) // 1: roaming active private int mRoam; // battery charge of AG: 0-5 private int mBattchg; // 0: not registered // 1: registered, home network // 5: registered, roaming private int mStat; // for CREG private String mRingingNumber; // Context for in-progress RING's private int mRingingType; private boolean mIgnoreRing = false; private static final int SERVICE_STATE_CHANGED = 1; private static final int PHONE_STATE_CHANGED = 2; private static final int RING = 3; private Handler mStateChangeHandler = new Handler() { @Override public void handleMessage(Message msg) { switch(msg.what) { case RING: AtCommandResult result = ring(); if (result != null) { sendURC(result.toString()); } break; case SERVICE_STATE_CHANGED: ServiceState state = (ServiceState) ((AsyncResult) msg.obj).result; updateServiceState(sendUpdate(), state); break; case PHONE_STATE_CHANGED: Connection connection = null; if (((AsyncResult) msg.obj).result instanceof Connection) { connection = (Connection) ((AsyncResult) msg.obj).result; } updatePhoneState(sendUpdate(), connection); break; } } }; private BluetoothPhoneState() { // init members updateServiceState(false, mPhone.getServiceState()); updatePhoneState(false, null); mBattchg = 5; // There is currently no API to get battery level // on demand, so set to 5 and wait for an update mSignal = asuToSignal(mPhone.getSignalStrength()); // register for updates mPhone.registerForServiceStateChanged(mStateChangeHandler, SERVICE_STATE_CHANGED, null); mPhone.registerForPhoneStateChanged(mStateChangeHandler, PHONE_STATE_CHANGED, null); IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); filter.addAction(TelephonyIntents.ACTION_SIGNAL_STRENGTH_CHANGED); mContext.registerReceiver(mStateReceiver, filter); } private void updateBtPhoneStateAfterRadioTechnologyChange() { if(DBG) Log.d(TAG, "updateBtPhoneStateAfterRadioTechnologyChange..."); //Unregister all events from the old obsolete phone mPhone.unregisterForServiceStateChanged(mStateChangeHandler); mPhone.unregisterForPhoneStateChanged(mStateChangeHandler); //Register all events new to the new active phone mPhone.registerForServiceStateChanged(mStateChangeHandler, SERVICE_STATE_CHANGED, null); mPhone.registerForPhoneStateChanged(mStateChangeHandler, PHONE_STATE_CHANGED, null); } private boolean sendUpdate() { return isHeadsetConnected() && mHeadsetType == TYPE_HANDSFREE && mIndicatorsEnabled; } private boolean sendClipUpdate() { return isHeadsetConnected() && mHeadsetType == TYPE_HANDSFREE && mClip; } /* convert [0,31] ASU signal strength to the [0,5] expected by * bluetooth devices. Scale is similar to status bar policy */ private int gsmAsuToSignal(int asu) { if (asu >= 16) return 5; else if (asu >= 8) return 4; else if (asu >= 4) return 3; else if (asu >= 2) return 2; else if (asu >= 1) return 1; else return 0; } /* convert cdma dBm signal strength to the [0,5] expected by * bluetooth devices. Scale is similar to status bar policy */ private int cdmaDbmToSignal(int cdmaDbm) { if (cdmaDbm >= -75) return 5; else if (cdmaDbm >= -85) return 4; else if (cdmaDbm >= -95) return 3; else if (cdmaDbm >= -100) return 2; else if (cdmaDbm >= -105) return 2; else return 0; } private int asuToSignal(SignalStrength signalStrength) { if (!signalStrength.isGsm()) { return gsmAsuToSignal(signalStrength.getCdmaDbm()); } else { return cdmaDbmToSignal(signalStrength.getGsmSignalStrength()); } } /* convert [0,5] signal strength to a rssi signal strength for CSQ * which is [0,31]. Despite the same scale, this is not the same value * as ASU. */ private int signalToRssi(int signal) { // using C4A suggested values switch (signal) { case 0: return 0; case 1: return 4; case 2: return 8; case 3: return 13; case 4: return 19; case 5: return 31; } return 0; } private final BroadcastReceiver mStateReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)) { updateBatteryState(intent); } else if (intent.getAction().equals(TelephonyIntents.ACTION_SIGNAL_STRENGTH_CHANGED)) { updateSignalState(intent); } } }; private synchronized void updateBatteryState(Intent intent) { int batteryLevel = intent.getIntExtra("level", -1); int scale = intent.getIntExtra("scale", -1); if (batteryLevel == -1 || scale == -1) { return; // ignore } batteryLevel = batteryLevel * 5 / scale; if (mBattchg != batteryLevel) { mBattchg = batteryLevel; if (sendUpdate()) { sendURC("+CIEV: 7," + mBattchg); } } } private synchronized void updateSignalState(Intent intent) { // NOTE this function is called by the BroadcastReceiver mStateReceiver after intent // ACTION_SIGNAL_STRENGTH_CHANGED and by the DebugThread mDebugThread SignalStrength signalStrength = SignalStrength.newFromBundle(intent.getExtras()); int signal; if (signalStrength != null) { signal = asuToSignal(signalStrength); mRssi = signalToRssi(signal); // no unsolicited CSQ if (signal != mSignal) { mSignal = signal; if (sendUpdate()) { sendURC("+CIEV: 5," + mSignal); } } } else { Log.e(TAG, "Signal Strength null"); } } private synchronized void updateServiceState(boolean sendUpdate, ServiceState state) { int service = state.getState() == ServiceState.STATE_IN_SERVICE ? 1 : 0; int roam = state.getRoaming() ? 1 : 0; int stat; AtCommandResult result = new AtCommandResult(AtCommandResult.UNSOLICITED); if (service == 0) { stat = 0; } else { stat = (roam == 1) ? 5 : 1; } if (service != mService) { mService = service; if (sendUpdate) { result.addResponse("+CIEV: 1," + mService); } } if (roam != mRoam) { mRoam = roam; if (sendUpdate) { result.addResponse("+CIEV: 6," + mRoam); } } if (stat != mStat) { mStat = stat; if (sendUpdate) { result.addResponse(toCregString()); } } sendURC(result.toString()); } private synchronized void updatePhoneState(boolean sendUpdate, Connection connection) { int call = 0; int callsetup = 0; int callheld = 0; int prevCallsetup = mCallsetup; AtCommandResult result = new AtCommandResult(AtCommandResult.UNSOLICITED); if (DBG) log("updatePhoneState()"); switch (mPhone.getState()) { case IDLE: mUserWantsAudio = true; // out of call - reset state audioOff(); break; default: callStarted(); } switch(mForegroundCall.getState()) { case ACTIVE: call = 1; mAudioPossible = true; break; case DIALING: callsetup = 2; mAudioPossible = false; break; case ALERTING: callsetup = 3; // Open the SCO channel for the outgoing call. audioOn(); mAudioPossible = true; break; default: mAudioPossible = false; } switch(mRingingCall.getState()) { case INCOMING: case WAITING: callsetup = 1; break; } switch(mBackgroundCall.getState()) { case HOLDING: if (call == 1) { callheld = 1; } else { call = 1; callheld = 2; } break; } if (mCall != call) { if (call == 1) { // This means that a call has transitioned from NOT ACTIVE to ACTIVE. // Switch on audio. audioOn(); } mCall = call; if (sendUpdate) { result.addResponse("+CIEV: 2," + mCall); } } if (mCallsetup != callsetup) { mCallsetup = callsetup; if (sendUpdate) { // If mCall = 0, send CIEV // mCall = 1, mCallsetup = 0, send CIEV // mCall = 1, mCallsetup = 1, send CIEV after CCWA, // if 3 way supported. // mCall = 1, mCallsetup = 2 / 3 -> send CIEV, // if 3 way is supported if (mCall != 1 || mCallsetup == 0 || mCallsetup != 1 && (mRemoteBrsf & BRSF_HF_CW_THREE_WAY_CALLING) != 0x0) { result.addResponse("+CIEV: 3," + mCallsetup); } } } boolean callsSwitched = (callheld == 1 && ! (mBackgroundCall.getEarliestConnectTime() == mBgndEarliestConnectionTime)); mBgndEarliestConnectionTime = mBackgroundCall.getEarliestConnectTime(); if (mCallheld != callheld || callsSwitched) { mCallheld = callheld; if (sendUpdate) { result.addResponse("+CIEV: 4," + mCallheld); } } if (callsetup == 1 && callsetup != prevCallsetup) { // new incoming call String number = null; int type = 128; // find incoming phone number and type if (connection == null) { connection = mRingingCall.getEarliestConnection(); if (connection == null) { Log.e(TAG, "Could not get a handle on Connection object for new " + "incoming call"); } } if (connection != null) { number = connection.getAddress(); if (number != null) { type = PhoneNumberUtils.toaFromString(number); } } if (number == null) { number = ""; } if ((call != 0 || callheld != 0) && sendUpdate) { // call waiting if ((mRemoteBrsf & BRSF_HF_CW_THREE_WAY_CALLING) != 0x0) { result.addResponse("+CCWA: \"" + number + "\"," + type); result.addResponse("+CIEV: 3," + callsetup); } } else { // regular new incoming call mRingingNumber = number; mRingingType = type; mIgnoreRing = false; if ((mLocalBrsf & BRSF_AG_IN_BAND_RING) == 0x1) { audioOn(); } result.addResult(ring()); } } sendURC(result.toString()); } private AtCommandResult ring() { if (!mIgnoreRing && mRingingCall.isRinging()) { AtCommandResult result = new AtCommandResult(AtCommandResult.UNSOLICITED); result.addResponse("RING"); if (sendClipUpdate()) { result.addResponse("+CLIP: \"" + mRingingNumber + "\"," + mRingingType); } Message msg = mStateChangeHandler.obtainMessage(RING); mStateChangeHandler.sendMessageDelayed(msg, 3000); return result; } return null; } private synchronized String toCregString() { return new String("+CREG: 1," + mStat); } private synchronized AtCommandResult toCindResult() { AtCommandResult result = new AtCommandResult(AtCommandResult.OK); String status = "+CIND: " + mService + "," + mCall + "," + mCallsetup + "," + mCallheld + "," + mSignal + "," + mRoam + "," + mBattchg; result.addResponse(status); return result; } private synchronized AtCommandResult toCsqResult() { AtCommandResult result = new AtCommandResult(AtCommandResult.OK); String status = "+CSQ: " + mRssi + ",99"; result.addResponse(status); return result; } private synchronized AtCommandResult getCindTestResult() { return new AtCommandResult("+CIND: (\"service\",(0-1))," + "(\"call\",(0-1))," + "(\"callsetup\",(0-3)),(\"callheld\",(0-2)),(\"signal\",(0-5))," + "(\"roam\",(0-1)),(\"battchg\",(0-5))"); } private synchronized void ignoreRing() { mCallsetup = 0; mIgnoreRing = true; if (sendUpdate()) { sendURC("+CIEV: 3," + mCallsetup); } } }; private static final int SCO_ACCEPTED = 1; private static final int SCO_CONNECTED = 2; private static final int SCO_CLOSED = 3; private static final int CHECK_CALL_STARTED = 4; private static final int CHECK_VOICE_RECOGNITION_STARTED = 5; private final Handler mHandler = new Handler() { @Override public synchronized void handleMessage(Message msg) { switch (msg.what) { case SCO_ACCEPTED: if (msg.arg1 == ScoSocket.STATE_CONNECTED) { if (isHeadsetConnected() && (mAudioPossible || allowAudioAnytime()) && mConnectedSco == null) { Log.i(TAG, "Routing audio for incoming SCO connection"); mConnectedSco = (ScoSocket)msg.obj; mAudioManager.setBluetoothScoOn(true); broadcastAudioStateIntent(BluetoothHeadset.AUDIO_STATE_CONNECTED); } else { Log.i(TAG, "Rejecting incoming SCO connection"); ((ScoSocket)msg.obj).close(); } } // else error trying to accept, try again mIncomingSco = createScoSocket(); mIncomingSco.accept(); break; case SCO_CONNECTED: if (msg.arg1 == ScoSocket.STATE_CONNECTED && isHeadsetConnected() && mConnectedSco == null) { if (DBG) log("Routing audio for outgoing SCO conection"); mConnectedSco = (ScoSocket)msg.obj; mAudioManager.setBluetoothScoOn(true); broadcastAudioStateIntent(BluetoothHeadset.AUDIO_STATE_CONNECTED); } else if (msg.arg1 == ScoSocket.STATE_CONNECTED) { if (DBG) log("Rejecting new connected outgoing SCO socket"); ((ScoSocket)msg.obj).close(); mOutgoingSco.close(); } mOutgoingSco = null; break; case SCO_CLOSED: if (mConnectedSco == (ScoSocket)msg.obj) { mConnectedSco = null; mAudioManager.setBluetoothScoOn(false); broadcastAudioStateIntent(BluetoothHeadset.AUDIO_STATE_DISCONNECTED); } else if (mOutgoingSco == (ScoSocket)msg.obj) { mOutgoingSco = null; } else if (mIncomingSco == (ScoSocket)msg.obj) { mIncomingSco = null; } break; case CHECK_CALL_STARTED: if (mWaitingForCallStart) { mWaitingForCallStart = false; Log.e(TAG, "Timeout waiting for call to start"); sendURC("ERROR"); if (mStartCallWakeLock.isHeld()) { mStartCallWakeLock.release(); } } break; case CHECK_VOICE_RECOGNITION_STARTED: if (mWaitingForVoiceRecognition) { mWaitingForVoiceRecognition = false; Log.e(TAG, "Timeout waiting for voice recognition to start"); sendURC("ERROR"); } break; } } }; private ScoSocket createScoSocket() { return new ScoSocket(mPowerManager, mHandler, SCO_ACCEPTED, SCO_CONNECTED, SCO_CLOSED); } private void broadcastAudioStateIntent(int state) { if (VDBG) log("broadcastAudioStateIntent(" + state + ")"); Intent intent = new Intent(BluetoothIntent.HEADSET_AUDIO_STATE_CHANGED_ACTION); intent.putExtra(BluetoothIntent.HEADSET_AUDIO_STATE, state); mContext.sendBroadcast(intent, android.Manifest.permission.BLUETOOTH); } void updateBtHandsfreeAfterRadioTechnologyChange() { if(DBG) Log.d(TAG, "updateBtHandsfreeAfterRadioTechnologyChange..."); //Get the Call references from the new active phone again mRingingCall = mPhone.getRingingCall(); mForegroundCall = mPhone.getForegroundCall(); mBackgroundCall = mPhone.getBackgroundCall(); mPhoneState.updateBtPhoneStateAfterRadioTechnologyChange(); } /** Request to establish SCO (audio) connection to bluetooth * headset/handsfree, if one is connected. Does not block. * Returns false if the user has requested audio off, or if there * is some other immediate problem that will prevent BT audio. */ /* package */ synchronized boolean audioOn() { if (VDBG) log("audioOn()"); if (!isHeadsetConnected()) { if (DBG) log("audioOn(): headset is not connected!"); return false; } if (mHeadsetType == TYPE_HANDSFREE && !mServiceConnectionEstablished) { if (DBG) log("audioOn(): service connection not yet established!"); return false; } if (mConnectedSco != null) { if (DBG) log("audioOn(): audio is already connected"); return true; } if (!mUserWantsAudio) { if (DBG) log("audioOn(): user requested no audio, ignoring"); return false; } if (mOutgoingSco != null) { if (DBG) log("audioOn(): outgoing SCO already in progress"); return true; } mOutgoingSco = createScoSocket(); if (!mOutgoingSco.connect(mHeadset.getAddress())) { mOutgoingSco = null; } return true; } /** Used to indicate the user requested BT audio on. * This will establish SCO (BT audio), even if the user requested it off * previously on this call. */ /* package */ synchronized void userWantsAudioOn() { mUserWantsAudio = true; audioOn(); } /** Used to indicate the user requested BT audio off. * This will prevent us from establishing BT audio again during this call * if audioOn() is called. */ /* package */ synchronized void userWantsAudioOff() { mUserWantsAudio = false; audioOff(); } /** Request to disconnect SCO (audio) connection to bluetooth * headset/handsfree, if one is connected. Does not block. */ /* package */ synchronized void audioOff() { if (VDBG) log("audioOff()"); if (mConnectedSco != null) { mAudioManager.setBluetoothScoOn(false); broadcastAudioStateIntent(BluetoothHeadset.AUDIO_STATE_DISCONNECTED); mConnectedSco.close(); mConnectedSco = null; } if (mOutgoingSco != null) { mOutgoingSco.close(); mOutgoingSco = null; } } /* package */ boolean isAudioOn() { return (mConnectedSco != null); } /* package */ void ignoreRing() { mPhoneState.ignoreRing(); } private void sendURC(String urc) { if (isHeadsetConnected()) { mHeadset.sendURC(urc); } } /** helper to redial last dialled number */ private AtCommandResult redial() { String number = mPhonebook.getLastDialledNumber(); if (number == null) { // spec seems to suggest sending ERROR if we dont have a // number to redial if (DBG) log("Bluetooth redial requested (+BLDN), but no previous " + "outgoing calls found. Ignoring"); return new AtCommandResult(AtCommandResult.ERROR); } Intent intent = new Intent(Intent.ACTION_CALL_PRIVILEGED, Uri.fromParts("tel", number, null)); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mContext.startActivity(intent); // We do not immediately respond OK, wait until we get a phone state // update. If we return OK now and the handsfree immeidately requests // our phone state it will say we are not in call yet which confuses // some devices expectCallStart(); return new AtCommandResult(AtCommandResult.UNSOLICITED); // send nothing } /** Build the +CLCC result * The complexity arises from the fact that we need to maintain the same * CLCC index even as a call moves between states. */ private synchronized AtCommandResult getClccResult() { // Collect all known connections Connection[] clccConnections = new Connection[MAX_CONNECTIONS]; // indexed by CLCC index LinkedList<Connection> newConnections = new LinkedList<Connection>(); LinkedList<Connection> connections = new LinkedList<Connection>(); if (mRingingCall.getState().isAlive()) { connections.addAll(mRingingCall.getConnections()); } if (mForegroundCall.getState().isAlive()) { connections.addAll(mForegroundCall.getConnections()); } if (mBackgroundCall.getState().isAlive()) { connections.addAll(mBackgroundCall.getConnections()); } // Mark connections that we already known about boolean clccUsed[] = new boolean[MAX_CONNECTIONS]; for (int i = 0; i < MAX_CONNECTIONS; i++) { clccUsed[i] = mClccUsed[i]; mClccUsed[i] = false; } for (Connection c : connections) { boolean found = false; long timestamp = c.getCreateTime(); for (int i = 0; i < MAX_CONNECTIONS; i++) { if (clccUsed[i] && timestamp == mClccTimestamps[i]) { mClccUsed[i] = true; found = true; clccConnections[i] = c; break; } } if (!found) { newConnections.add(c); } } // Find a CLCC index for new connections while (!newConnections.isEmpty()) { // Find lowest empty index int i = 0; while (mClccUsed[i]) i++; // Find earliest connection long earliestTimestamp = newConnections.get(0).getCreateTime(); Connection earliestConnection = newConnections.get(0); for (int j = 0; j < newConnections.size(); j++) { long timestamp = newConnections.get(j).getCreateTime(); if (timestamp < earliestTimestamp) { earliestTimestamp = timestamp; earliestConnection = newConnections.get(j); } } // update mClccUsed[i] = true; mClccTimestamps[i] = earliestTimestamp; clccConnections[i] = earliestConnection; newConnections.remove(earliestConnection); } // Build CLCC AtCommandResult result = new AtCommandResult(AtCommandResult.OK); for (int i = 0; i < clccConnections.length; i++) { if (mClccUsed[i]) { String clccEntry = connectionToClccEntry(i, clccConnections[i]); if (clccEntry != null) { result.addResponse(clccEntry); } } } return result; } /** Convert a Connection object into a single +CLCC result */ private String connectionToClccEntry(int index, Connection c) { int state; switch (c.getState()) { case ACTIVE: state = 0; break; case HOLDING: state = 1; break; case DIALING: state = 2; break; case ALERTING: state = 3; break; case INCOMING: state = 4; break; case WAITING: state = 5; break; default: return null; // bad state } int mpty = 0; Call call = c.getCall(); if (call != null) { mpty = call.isMultiparty() ? 1 : 0; } int direction = c.isIncoming() ? 1 : 0; String number = c.getAddress(); int type = -1; if (number != null) { type = PhoneNumberUtils.toaFromString(number); } String result = "+CLCC: " + (index + 1) + "," + direction + "," + state + ",0," + mpty; if (number != null) { result += ",\"" + number + "\"," + type; } return result; } /** * Register AT Command handlers to implement the Headset profile */ private void initializeHeadsetAtParser() { if (DBG) log("Registering Headset AT commands"); AtParser parser = mHeadset.getAtParser(); // Headset's usually only have one button, which is meant to cause the // HS to send us AT+CKPD=200 or AT+CKPD. parser.register("+CKPD", new AtCommandHandler() { private AtCommandResult headsetButtonPress() { if (mRingingCall.isRinging()) { // Answer the call PhoneUtils.answerCall(mPhone); // If in-band ring tone is supported, SCO connection will already // be up and the following call will just return. audioOn(); } else if (mForegroundCall.getState().isAlive()) { if (!isAudioOn()) { // Transfer audio from AG to HS audioOn(); } else { if (mHeadset.getDirection() == HeadsetBase.DIRECTION_INCOMING && (System.currentTimeMillis() - mHeadset.getConnectTimestamp()) < 5000) { // Headset made a recent ACL connection to us - and // made a mandatory AT+CKPD request to connect // audio which races with our automatic audio // setup. ignore } else { // Hang up the call audioOff(); PhoneUtils.hangup(mPhone); } } } else { // No current call - redial last number return redial(); } return new AtCommandResult(AtCommandResult.OK); } @Override public AtCommandResult handleActionCommand() { return headsetButtonPress(); } @Override public AtCommandResult handleSetCommand(Object[] args) { return headsetButtonPress(); } }); } /** * Register AT Command handlers to implement the Handsfree profile */ private void initializeHandsfreeAtParser() { if (DBG) log("Registering Handsfree AT commands"); AtParser parser = mHeadset.getAtParser(); // Answer parser.register('A', new AtCommandHandler() { @Override public AtCommandResult handleBasicCommand(String args) { PhoneUtils.answerCall(mPhone); return new AtCommandResult(AtCommandResult.OK); } }); parser.register('D', new AtCommandHandler() { @Override public AtCommandResult handleBasicCommand(String args) { if (args.length() > 0) { if (args.charAt(0) == '>') { // Yuck - memory dialling requested. // Just dial last number for now if (args.startsWith(">9999")) { // for PTS test return new AtCommandResult(AtCommandResult.ERROR); } return redial(); } else { // Remove trailing ';' if (args.charAt(args.length() - 1) == ';') { args = args.substring(0, args.length() - 1); } Intent intent = new Intent(Intent.ACTION_CALL_PRIVILEGED, Uri.fromParts("tel", args, null)); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mContext.startActivity(intent); expectCallStart(); return new AtCommandResult(AtCommandResult.UNSOLICITED); // send nothing } } return new AtCommandResult(AtCommandResult.ERROR); } }); // Hang-up command parser.register("+CHUP", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { if (!mForegroundCall.isIdle()) { PhoneUtils.hangup(mForegroundCall); } else if (!mRingingCall.isIdle()) { PhoneUtils.hangup(mRingingCall); } else if (!mBackgroundCall.isIdle()) { PhoneUtils.hangup(mBackgroundCall); } return new AtCommandResult(AtCommandResult.OK); } }); // Bluetooth Retrieve Supported Features command parser.register("+BRSF", new AtCommandHandler() { private AtCommandResult sendBRSF() { return new AtCommandResult("+BRSF: " + mLocalBrsf); } @Override public AtCommandResult handleSetCommand(Object[] args) { // AT+BRSF=<handsfree supported features bitmap> // Handsfree is telling us which features it supports. We // send the features we support if (args.length == 1 && (args[0] instanceof Integer)) { mRemoteBrsf = (Integer) args[0]; } else { Log.w(TAG, "HF didn't sent BRSF assuming 0"); } return sendBRSF(); } @Override public AtCommandResult handleActionCommand() { // This seems to be out of spec, but lets do the nice thing return sendBRSF(); } @Override public AtCommandResult handleReadCommand() { // This seems to be out of spec, but lets do the nice thing return sendBRSF(); } }); // Call waiting notification on/off parser.register("+CCWA", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { // Seems to be out of spec, but lets return nicely return new AtCommandResult(AtCommandResult.OK); } @Override public AtCommandResult handleReadCommand() { // Call waiting is always on return new AtCommandResult("+CCWA: 1"); } @Override public AtCommandResult handleSetCommand(Object[] args) { // AT+CCWA=<n> // Handsfree is trying to enable/disable call waiting. We // cannot disable in the current implementation. return new AtCommandResult(AtCommandResult.OK); } @Override public AtCommandResult handleTestCommand() { // Request for range of supported CCWA paramters return new AtCommandResult("+CCWA: (\"n\",(1))"); } }); // Mobile Equipment Event Reporting enable/disable command // Of the full 3GPP syntax paramters (mode, keyp, disp, ind, bfr) we // only support paramter ind (disable/enable evert reporting using // +CDEV) parser.register("+CMER", new AtCommandHandler() { @Override public AtCommandResult handleReadCommand() { return new AtCommandResult( "+CMER: 3,0,0," + (mIndicatorsEnabled ? "1" : "0")); } @Override public AtCommandResult handleSetCommand(Object[] args) { if (args.length < 4) { // This is a syntax error return new AtCommandResult(AtCommandResult.ERROR); } else if (args[0].equals(3) && args[1].equals(0) && args[2].equals(0)) { boolean valid = false; if (args[3].equals(0)) { mIndicatorsEnabled = false; valid = true; } else if (args[3].equals(1)) { mIndicatorsEnabled = true; valid = true; } if (valid) { if ((mRemoteBrsf & BRSF_HF_CW_THREE_WAY_CALLING) == 0x0) { mServiceConnectionEstablished = true; sendURC("OK"); // send immediately, then initiate audio if (isIncallAudio()) { audioOn(); } // only send OK once return new AtCommandResult(AtCommandResult.UNSOLICITED); } else { return new AtCommandResult(AtCommandResult.OK); } } } return reportCmeError(BluetoothCmeError.OPERATION_NOT_SUPPORTED); } @Override public AtCommandResult handleTestCommand() { return new AtCommandResult("+CMER: (3),(0),(0),(0-1)"); } }); // Mobile Equipment Error Reporting enable/disable parser.register("+CMEE", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { // out of spec, assume they want to enable mCmee = true; return new AtCommandResult(AtCommandResult.OK); } @Override public AtCommandResult handleReadCommand() { return new AtCommandResult("+CMEE: " + (mCmee ? "1" : "0")); } @Override public AtCommandResult handleSetCommand(Object[] args) { // AT+CMEE=<n> if (args.length == 0) { // <n> ommitted - default to 0 mCmee = false; return new AtCommandResult(AtCommandResult.OK); } else if (!(args[0] instanceof Integer)) { // Syntax error return new AtCommandResult(AtCommandResult.ERROR); } else { mCmee = ((Integer)args[0] == 1); return new AtCommandResult(AtCommandResult.OK); } } @Override public AtCommandResult handleTestCommand() { // Probably not required but spec, but no harm done return new AtCommandResult("+CMEE: (0-1)"); } }); // Bluetooth Last Dialled Number parser.register("+BLDN", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { return redial(); } }); // Indicator Update command parser.register("+CIND", new AtCommandHandler() { @Override public AtCommandResult handleReadCommand() { return mPhoneState.toCindResult(); } @Override public AtCommandResult handleTestCommand() { return mPhoneState.getCindTestResult(); } }); // Query Signal Quality (legacy) parser.register("+CSQ", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { return mPhoneState.toCsqResult(); } }); // Query network registration state parser.register("+CREG", new AtCommandHandler() { @Override public AtCommandResult handleReadCommand() { return new AtCommandResult(mPhoneState.toCregString()); } }); // Send DTMF. I don't know if we are also expected to play the DTMF tone // locally, right now we don't parser.register("+VTS", new AtCommandHandler() { @Override public AtCommandResult handleSetCommand(Object[] args) { if (args.length >= 1) { char c; if (args[0] instanceof Integer) { c = ((Integer) args[0]).toString().charAt(0); } else { c = ((String) args[0]).charAt(0); } if (isValidDtmf(c)) { mPhone.sendDtmf(c); return new AtCommandResult(AtCommandResult.OK); } } return new AtCommandResult(AtCommandResult.ERROR); } private boolean isValidDtmf(char c) { switch (c) { case '#': case '*': return true; default: if (Character.digit(c, 14) != -1) { return true; // 0-9 and A-D } return false; } } }); // List calls parser.register("+CLCC", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { return getClccResult(); } }); // Call Hold and Multiparty Handling command parser.register("+CHLD", new AtCommandHandler() { @Override public AtCommandResult handleSetCommand(Object[] args) { if (args.length >= 1) { if (args[0].equals(0)) { boolean result; if (mRingingCall.isRinging()) { result = PhoneUtils.hangupRingingCall(mPhone); } else { result = PhoneUtils.hangupHoldingCall(mPhone); } if (result) { return new AtCommandResult(AtCommandResult.OK); } else { return new AtCommandResult(AtCommandResult.ERROR); } } else if (args[0].equals(1)) { // Hangup active call, answer held call if (PhoneUtils.answerAndEndActive(mPhone)) { return new AtCommandResult(AtCommandResult.OK); } else { return new AtCommandResult(AtCommandResult.ERROR); } } else if (args[0].equals(2)) { PhoneUtils.switchHoldingAndActive(mPhone); return new AtCommandResult(AtCommandResult.OK); } else if (args[0].equals(3)) { if (mForegroundCall.getState().isAlive() && mBackgroundCall.getState().isAlive()) { PhoneUtils.mergeCalls(mPhone); } return new AtCommandResult(AtCommandResult.OK); } } return new AtCommandResult(AtCommandResult.ERROR); } @Override public AtCommandResult handleTestCommand() { mServiceConnectionEstablished = true; - sendURC("+CHLD: (0,1,2,3)"); // send reply first, then connect audio + sendURC("+CHLD: (0,1,2,3)"); + sendURC("OK"); // send reply first, then connect audio if (isIncallAudio()) { audioOn(); } // already replied return new AtCommandResult(AtCommandResult.UNSOLICITED); } }); // Get Network operator name parser.register("+COPS", new AtCommandHandler() { @Override public AtCommandResult handleReadCommand() { String operatorName = mPhone.getServiceState().getOperatorAlphaLong(); if (operatorName != null) { if (operatorName.length() > 16) { operatorName = operatorName.substring(0, 16); } return new AtCommandResult( "+COPS: 0,0,\"" + operatorName + "\""); } else { return new AtCommandResult( "+COPS: 0,0,\"UNKNOWN\",0"); } } @Override public AtCommandResult handleSetCommand(Object[] args) { // Handsfree only supports AT+COPS=3,0 if (args.length != 2 || !(args[0] instanceof Integer) || !(args[1] instanceof Integer)) { // syntax error return new AtCommandResult(AtCommandResult.ERROR); } else if ((Integer)args[0] != 3 || (Integer)args[1] != 0) { return reportCmeError(BluetoothCmeError.OPERATION_NOT_SUPPORTED); } else { return new AtCommandResult(AtCommandResult.OK); } } @Override public AtCommandResult handleTestCommand() { // Out of spec, but lets be friendly return new AtCommandResult("+COPS: (3),(0)"); } }); // Mobile PIN // AT+CPIN is not in the handsfree spec (although it is in 3GPP) parser.register("+CPIN", new AtCommandHandler() { @Override public AtCommandResult handleReadCommand() { return new AtCommandResult("+CPIN: READY"); } }); // Bluetooth Response and Hold // Only supported on PDC (Japan) and CDMA networks. parser.register("+BTRH", new AtCommandHandler() { @Override public AtCommandResult handleReadCommand() { // Replying with just OK indicates no response and hold // features in use now return new AtCommandResult(AtCommandResult.OK); } @Override public AtCommandResult handleSetCommand(Object[] args) { // Neeed PDC or CDMA return new AtCommandResult(AtCommandResult.ERROR); } }); // Request International Mobile Subscriber Identity (IMSI) // Not in bluetooth handset spec parser.register("+CIMI", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { // AT+CIMI String imsi = mPhone.getSubscriberId(); if (imsi == null || imsi.length() == 0) { return reportCmeError(BluetoothCmeError.SIM_FAILURE); } else { return new AtCommandResult(imsi); } } }); // Calling Line Identification Presentation parser.register("+CLIP", new AtCommandHandler() { @Override public AtCommandResult handleReadCommand() { // Currently assumes the network is provisioned for CLIP return new AtCommandResult("+CLIP: " + (mClip ? "1" : "0") + ",1"); } @Override public AtCommandResult handleSetCommand(Object[] args) { // AT+CLIP=<n> if (args.length >= 1 && (args[0].equals(0) || args[0].equals(1))) { mClip = args[0].equals(1); return new AtCommandResult(AtCommandResult.OK); } else { return new AtCommandResult(AtCommandResult.ERROR); } } @Override public AtCommandResult handleTestCommand() { return new AtCommandResult("+CLIP: (0-1)"); } }); // AT+CGSN - Returns the device IMEI number. parser.register("+CGSN", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { // Get the IMEI of the device. // mPhone will not be NULL at this point. return new AtCommandResult("+CGSN: " + mPhone.getDeviceId()); } }); // AT+CGMM - Query Model Information parser.register("+CGMM", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { // Return the Model Information. String model = SystemProperties.get("ro.product.model"); if (model != null) { return new AtCommandResult("+CGMM: " + model); } else { return new AtCommandResult(AtCommandResult.ERROR); } } }); // AT+CGMI - Query Manufacturer Information parser.register("+CGMI", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { // Return the Model Information. String manuf = SystemProperties.get("ro.product.manufacturer"); if (manuf != null) { return new AtCommandResult("+CGMI: " + manuf); } else { return new AtCommandResult(AtCommandResult.ERROR); } } }); // Noise Reduction and Echo Cancellation control parser.register("+NREC", new AtCommandHandler() { @Override public AtCommandResult handleSetCommand(Object[] args) { if (args[0].equals(0)) { mAudioManager.setParameter(HEADSET_NREC, "off"); return new AtCommandResult(AtCommandResult.OK); } else if (args[0].equals(1)) { mAudioManager.setParameter(HEADSET_NREC, "on"); return new AtCommandResult(AtCommandResult.OK); } return new AtCommandResult(AtCommandResult.ERROR); } }); // Voice recognition (dialing) parser.register("+BVRA", new AtCommandHandler() { @Override public AtCommandResult handleSetCommand(Object[] args) { if (BluetoothHeadset.DISABLE_BT_VOICE_DIALING) { return new AtCommandResult(AtCommandResult.ERROR); } if (args.length >= 1 && args[0].equals(1)) { synchronized (BluetoothHandsfree.this) { if (!mWaitingForVoiceRecognition) { try { mContext.startActivity(sVoiceCommandIntent); } catch (ActivityNotFoundException e) { return new AtCommandResult(AtCommandResult.ERROR); } expectVoiceRecognition(); } } return new AtCommandResult(AtCommandResult.UNSOLICITED); // send nothing yet } else if (args.length >= 1 && args[0].equals(0)) { audioOff(); return new AtCommandResult(AtCommandResult.OK); } return new AtCommandResult(AtCommandResult.ERROR); } @Override public AtCommandResult handleTestCommand() { return new AtCommandResult("+BVRA: (0-1)"); } }); // Retrieve Subscriber Number parser.register("+CNUM", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { String number = mPhone.getLine1Number(); if (number == null) { return new AtCommandResult(AtCommandResult.OK); } return new AtCommandResult("+CNUM: ,\"" + number + "\"," + PhoneNumberUtils.toaFromString(number) + ",,4"); } }); // Microphone Gain parser.register("+VGM", new AtCommandHandler() { @Override public AtCommandResult handleSetCommand(Object[] args) { // AT+VGM=<gain> in range [0,15] // Headset/Handsfree is reporting its current gain setting return new AtCommandResult(AtCommandResult.OK); } }); // Speaker Gain parser.register("+VGS", new AtCommandHandler() { @Override public AtCommandResult handleSetCommand(Object[] args) { // AT+VGS=<gain> in range [0,15] if (args.length != 1 || !(args[0] instanceof Integer)) { return new AtCommandResult(AtCommandResult.ERROR); } mScoGain = (Integer) args[0]; int flag = mAudioManager.isBluetoothScoOn() ? AudioManager.FLAG_SHOW_UI:0; mAudioManager.setStreamVolume(AudioManager.STREAM_BLUETOOTH_SCO, mScoGain, flag); return new AtCommandResult(AtCommandResult.OK); } }); // Phone activity status parser.register("+CPAS", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { int status = 0; switch (mPhone.getState()) { case IDLE: status = 0; break; case RINGING: status = 3; break; case OFFHOOK: status = 4; break; } return new AtCommandResult("+CPAS: " + status); } }); mPhonebook.register(parser); } public void sendScoGainUpdate(int gain) { if (mScoGain != gain && (mRemoteBrsf & BRSF_HF_REMOTE_VOL_CONTROL) != 0x0) { sendURC("+VGS:" + gain); mScoGain = gain; } } public AtCommandResult reportCmeError(int error) { if (mCmee) { AtCommandResult result = new AtCommandResult(AtCommandResult.UNSOLICITED); result.addResponse("+CME ERROR: " + error); return result; } else { return new AtCommandResult(AtCommandResult.ERROR); } } private static final int START_CALL_TIMEOUT = 10000; // ms private synchronized void expectCallStart() { mWaitingForCallStart = true; Message msg = Message.obtain(mHandler, CHECK_CALL_STARTED); mHandler.sendMessageDelayed(msg, START_CALL_TIMEOUT); if (!mStartCallWakeLock.isHeld()) { mStartCallWakeLock.acquire(START_CALL_TIMEOUT); } } private synchronized void callStarted() { if (mWaitingForCallStart) { mWaitingForCallStart = false; sendURC("OK"); if (mStartCallWakeLock.isHeld()) { mStartCallWakeLock.release(); } } } private static final int START_VOICE_RECOGNITION_TIMEOUT = 5000; // ms private synchronized void expectVoiceRecognition() { mWaitingForVoiceRecognition = true; Message msg = Message.obtain(mHandler, CHECK_VOICE_RECOGNITION_STARTED); mHandler.sendMessageDelayed(msg, START_VOICE_RECOGNITION_TIMEOUT); if (!mStartVoiceRecognitionWakeLock.isHeld()) { mStartVoiceRecognitionWakeLock.acquire(START_VOICE_RECOGNITION_TIMEOUT); } } /* package */ synchronized boolean startVoiceRecognition() { if (mWaitingForVoiceRecognition) { // HF initiated mWaitingForVoiceRecognition = false; sendURC("OK"); } else { // AG initiated sendURC("+BVRA: 1"); } boolean ret = audioOn(); if (mStartVoiceRecognitionWakeLock.isHeld()) { mStartVoiceRecognitionWakeLock.release(); } return ret; } /* package */ synchronized boolean stopVoiceRecognition() { sendURC("+BVRA: 0"); audioOff(); return true; } private boolean inDebug() { return DBG && SystemProperties.getBoolean(DebugThread.DEBUG_HANDSFREE, false); } private boolean allowAudioAnytime() { return inDebug() && SystemProperties.getBoolean(DebugThread.DEBUG_HANDSFREE_AUDIO_ANYTIME, false); } private void startDebug() { if (DBG && mDebugThread == null) { mDebugThread = new DebugThread(); mDebugThread.start(); } } private void stopDebug() { if (mDebugThread != null) { mDebugThread.interrupt(); mDebugThread = null; } } /** Debug thread to read debug properties - runs when debug.bt.hfp is true * at the time a bluetooth handsfree device is connected. Debug properties * are polled and mock updates sent every 1 second */ private class DebugThread extends Thread { /** Turns on/off handsfree profile debugging mode */ private static final String DEBUG_HANDSFREE = "debug.bt.hfp"; /** Mock battery level change - use 0 to 5 */ private static final String DEBUG_HANDSFREE_BATTERY = "debug.bt.hfp.battery"; /** Mock no cellular service when false */ private static final String DEBUG_HANDSFREE_SERVICE = "debug.bt.hfp.service"; /** Mock cellular roaming when true */ private static final String DEBUG_HANDSFREE_ROAM = "debug.bt.hfp.roam"; /** false to true transition will force an audio (SCO) connection to * be established. true to false will force audio to be disconnected */ private static final String DEBUG_HANDSFREE_AUDIO = "debug.bt.hfp.audio"; /** true allows incoming SCO connection out of call. */ private static final String DEBUG_HANDSFREE_AUDIO_ANYTIME = "debug.bt.hfp.audio_anytime"; /** Mock signal strength change in ASU - use 0 to 31 */ private static final String DEBUG_HANDSFREE_SIGNAL = "debug.bt.hfp.signal"; /** Debug AT+CLCC: print +CLCC result */ private static final String DEBUG_HANDSFREE_CLCC = "debug.bt.hfp.clcc"; /** Debug AT+BSIR - Send In Band Ringtones Unsolicited AT command. * debug.bt.unsol.inband = 0 => AT+BSIR = 0 sent by the AG * debug.bt.unsol.inband = 1 => AT+BSIR = 0 sent by the AG * Other values are ignored. */ private static final String DEBUG_UNSOL_INBAND_RINGTONE = "debug.bt.unsol.inband"; @Override public void run() { boolean oldService = true; boolean oldRoam = false; boolean oldAudio = false; while (!isInterrupted() && inDebug()) { int batteryLevel = SystemProperties.getInt(DEBUG_HANDSFREE_BATTERY, -1); if (batteryLevel >= 0 && batteryLevel <= 5) { Intent intent = new Intent(); intent.putExtra("level", batteryLevel); intent.putExtra("scale", 5); mPhoneState.updateBatteryState(intent); } boolean serviceStateChanged = false; if (SystemProperties.getBoolean(DEBUG_HANDSFREE_SERVICE, true) != oldService) { oldService = !oldService; serviceStateChanged = true; } if (SystemProperties.getBoolean(DEBUG_HANDSFREE_ROAM, false) != oldRoam) { oldRoam = !oldRoam; serviceStateChanged = true; } if (serviceStateChanged) { Bundle b = new Bundle(); b.putInt("state", oldService ? 0 : 1); b.putBoolean("roaming", oldRoam); mPhoneState.updateServiceState(true, ServiceState.newFromBundle(b)); } if (SystemProperties.getBoolean(DEBUG_HANDSFREE_AUDIO, false) != oldAudio) { oldAudio = !oldAudio; if (oldAudio) { audioOn(); } else { audioOff(); } } int signalLevel = SystemProperties.getInt(DEBUG_HANDSFREE_SIGNAL, -1); if (signalLevel >= 0 && signalLevel <= 31) { SignalStrength signalStrength = new SignalStrength(signalLevel, -1, -1, -1, -1, -1, -1, true); Intent intent = new Intent(); Bundle data = new Bundle(); signalStrength.fillInNotifierBundle(data); intent.putExtras(data); mPhoneState.updateSignalState(intent); } if (SystemProperties.getBoolean(DEBUG_HANDSFREE_CLCC, false)) { log(getClccResult().toString()); } try { sleep(1000); // 1 second } catch (InterruptedException e) { break; } int inBandRing = SystemProperties.getInt(DEBUG_UNSOL_INBAND_RINGTONE, -1); if (inBandRing == 0 || inBandRing == 1) { AtCommandResult result = new AtCommandResult(AtCommandResult.UNSOLICITED); result.addResponse("+BSIR: " + inBandRing); sendURC(result.toString()); } } } } private static void log(String msg) { Log.d(TAG, msg); } }
true
true
private void initializeHandsfreeAtParser() { if (DBG) log("Registering Handsfree AT commands"); AtParser parser = mHeadset.getAtParser(); // Answer parser.register('A', new AtCommandHandler() { @Override public AtCommandResult handleBasicCommand(String args) { PhoneUtils.answerCall(mPhone); return new AtCommandResult(AtCommandResult.OK); } }); parser.register('D', new AtCommandHandler() { @Override public AtCommandResult handleBasicCommand(String args) { if (args.length() > 0) { if (args.charAt(0) == '>') { // Yuck - memory dialling requested. // Just dial last number for now if (args.startsWith(">9999")) { // for PTS test return new AtCommandResult(AtCommandResult.ERROR); } return redial(); } else { // Remove trailing ';' if (args.charAt(args.length() - 1) == ';') { args = args.substring(0, args.length() - 1); } Intent intent = new Intent(Intent.ACTION_CALL_PRIVILEGED, Uri.fromParts("tel", args, null)); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mContext.startActivity(intent); expectCallStart(); return new AtCommandResult(AtCommandResult.UNSOLICITED); // send nothing } } return new AtCommandResult(AtCommandResult.ERROR); } }); // Hang-up command parser.register("+CHUP", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { if (!mForegroundCall.isIdle()) { PhoneUtils.hangup(mForegroundCall); } else if (!mRingingCall.isIdle()) { PhoneUtils.hangup(mRingingCall); } else if (!mBackgroundCall.isIdle()) { PhoneUtils.hangup(mBackgroundCall); } return new AtCommandResult(AtCommandResult.OK); } }); // Bluetooth Retrieve Supported Features command parser.register("+BRSF", new AtCommandHandler() { private AtCommandResult sendBRSF() { return new AtCommandResult("+BRSF: " + mLocalBrsf); } @Override public AtCommandResult handleSetCommand(Object[] args) { // AT+BRSF=<handsfree supported features bitmap> // Handsfree is telling us which features it supports. We // send the features we support if (args.length == 1 && (args[0] instanceof Integer)) { mRemoteBrsf = (Integer) args[0]; } else { Log.w(TAG, "HF didn't sent BRSF assuming 0"); } return sendBRSF(); } @Override public AtCommandResult handleActionCommand() { // This seems to be out of spec, but lets do the nice thing return sendBRSF(); } @Override public AtCommandResult handleReadCommand() { // This seems to be out of spec, but lets do the nice thing return sendBRSF(); } }); // Call waiting notification on/off parser.register("+CCWA", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { // Seems to be out of spec, but lets return nicely return new AtCommandResult(AtCommandResult.OK); } @Override public AtCommandResult handleReadCommand() { // Call waiting is always on return new AtCommandResult("+CCWA: 1"); } @Override public AtCommandResult handleSetCommand(Object[] args) { // AT+CCWA=<n> // Handsfree is trying to enable/disable call waiting. We // cannot disable in the current implementation. return new AtCommandResult(AtCommandResult.OK); } @Override public AtCommandResult handleTestCommand() { // Request for range of supported CCWA paramters return new AtCommandResult("+CCWA: (\"n\",(1))"); } }); // Mobile Equipment Event Reporting enable/disable command // Of the full 3GPP syntax paramters (mode, keyp, disp, ind, bfr) we // only support paramter ind (disable/enable evert reporting using // +CDEV) parser.register("+CMER", new AtCommandHandler() { @Override public AtCommandResult handleReadCommand() { return new AtCommandResult( "+CMER: 3,0,0," + (mIndicatorsEnabled ? "1" : "0")); } @Override public AtCommandResult handleSetCommand(Object[] args) { if (args.length < 4) { // This is a syntax error return new AtCommandResult(AtCommandResult.ERROR); } else if (args[0].equals(3) && args[1].equals(0) && args[2].equals(0)) { boolean valid = false; if (args[3].equals(0)) { mIndicatorsEnabled = false; valid = true; } else if (args[3].equals(1)) { mIndicatorsEnabled = true; valid = true; } if (valid) { if ((mRemoteBrsf & BRSF_HF_CW_THREE_WAY_CALLING) == 0x0) { mServiceConnectionEstablished = true; sendURC("OK"); // send immediately, then initiate audio if (isIncallAudio()) { audioOn(); } // only send OK once return new AtCommandResult(AtCommandResult.UNSOLICITED); } else { return new AtCommandResult(AtCommandResult.OK); } } } return reportCmeError(BluetoothCmeError.OPERATION_NOT_SUPPORTED); } @Override public AtCommandResult handleTestCommand() { return new AtCommandResult("+CMER: (3),(0),(0),(0-1)"); } }); // Mobile Equipment Error Reporting enable/disable parser.register("+CMEE", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { // out of spec, assume they want to enable mCmee = true; return new AtCommandResult(AtCommandResult.OK); } @Override public AtCommandResult handleReadCommand() { return new AtCommandResult("+CMEE: " + (mCmee ? "1" : "0")); } @Override public AtCommandResult handleSetCommand(Object[] args) { // AT+CMEE=<n> if (args.length == 0) { // <n> ommitted - default to 0 mCmee = false; return new AtCommandResult(AtCommandResult.OK); } else if (!(args[0] instanceof Integer)) { // Syntax error return new AtCommandResult(AtCommandResult.ERROR); } else { mCmee = ((Integer)args[0] == 1); return new AtCommandResult(AtCommandResult.OK); } } @Override public AtCommandResult handleTestCommand() { // Probably not required but spec, but no harm done return new AtCommandResult("+CMEE: (0-1)"); } }); // Bluetooth Last Dialled Number parser.register("+BLDN", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { return redial(); } }); // Indicator Update command parser.register("+CIND", new AtCommandHandler() { @Override public AtCommandResult handleReadCommand() { return mPhoneState.toCindResult(); } @Override public AtCommandResult handleTestCommand() { return mPhoneState.getCindTestResult(); } }); // Query Signal Quality (legacy) parser.register("+CSQ", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { return mPhoneState.toCsqResult(); } }); // Query network registration state parser.register("+CREG", new AtCommandHandler() { @Override public AtCommandResult handleReadCommand() { return new AtCommandResult(mPhoneState.toCregString()); } }); // Send DTMF. I don't know if we are also expected to play the DTMF tone // locally, right now we don't parser.register("+VTS", new AtCommandHandler() { @Override public AtCommandResult handleSetCommand(Object[] args) { if (args.length >= 1) { char c; if (args[0] instanceof Integer) { c = ((Integer) args[0]).toString().charAt(0); } else { c = ((String) args[0]).charAt(0); } if (isValidDtmf(c)) { mPhone.sendDtmf(c); return new AtCommandResult(AtCommandResult.OK); } } return new AtCommandResult(AtCommandResult.ERROR); } private boolean isValidDtmf(char c) { switch (c) { case '#': case '*': return true; default: if (Character.digit(c, 14) != -1) { return true; // 0-9 and A-D } return false; } } }); // List calls parser.register("+CLCC", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { return getClccResult(); } }); // Call Hold and Multiparty Handling command parser.register("+CHLD", new AtCommandHandler() { @Override public AtCommandResult handleSetCommand(Object[] args) { if (args.length >= 1) { if (args[0].equals(0)) { boolean result; if (mRingingCall.isRinging()) { result = PhoneUtils.hangupRingingCall(mPhone); } else { result = PhoneUtils.hangupHoldingCall(mPhone); } if (result) { return new AtCommandResult(AtCommandResult.OK); } else { return new AtCommandResult(AtCommandResult.ERROR); } } else if (args[0].equals(1)) { // Hangup active call, answer held call if (PhoneUtils.answerAndEndActive(mPhone)) { return new AtCommandResult(AtCommandResult.OK); } else { return new AtCommandResult(AtCommandResult.ERROR); } } else if (args[0].equals(2)) { PhoneUtils.switchHoldingAndActive(mPhone); return new AtCommandResult(AtCommandResult.OK); } else if (args[0].equals(3)) { if (mForegroundCall.getState().isAlive() && mBackgroundCall.getState().isAlive()) { PhoneUtils.mergeCalls(mPhone); } return new AtCommandResult(AtCommandResult.OK); } } return new AtCommandResult(AtCommandResult.ERROR); } @Override public AtCommandResult handleTestCommand() { mServiceConnectionEstablished = true; sendURC("+CHLD: (0,1,2,3)"); // send reply first, then connect audio if (isIncallAudio()) { audioOn(); } // already replied return new AtCommandResult(AtCommandResult.UNSOLICITED); } }); // Get Network operator name parser.register("+COPS", new AtCommandHandler() { @Override public AtCommandResult handleReadCommand() { String operatorName = mPhone.getServiceState().getOperatorAlphaLong(); if (operatorName != null) { if (operatorName.length() > 16) { operatorName = operatorName.substring(0, 16); } return new AtCommandResult( "+COPS: 0,0,\"" + operatorName + "\""); } else { return new AtCommandResult( "+COPS: 0,0,\"UNKNOWN\",0"); } } @Override public AtCommandResult handleSetCommand(Object[] args) { // Handsfree only supports AT+COPS=3,0 if (args.length != 2 || !(args[0] instanceof Integer) || !(args[1] instanceof Integer)) { // syntax error return new AtCommandResult(AtCommandResult.ERROR); } else if ((Integer)args[0] != 3 || (Integer)args[1] != 0) { return reportCmeError(BluetoothCmeError.OPERATION_NOT_SUPPORTED); } else { return new AtCommandResult(AtCommandResult.OK); } } @Override public AtCommandResult handleTestCommand() { // Out of spec, but lets be friendly return new AtCommandResult("+COPS: (3),(0)"); } }); // Mobile PIN // AT+CPIN is not in the handsfree spec (although it is in 3GPP) parser.register("+CPIN", new AtCommandHandler() { @Override public AtCommandResult handleReadCommand() { return new AtCommandResult("+CPIN: READY"); } }); // Bluetooth Response and Hold // Only supported on PDC (Japan) and CDMA networks. parser.register("+BTRH", new AtCommandHandler() { @Override public AtCommandResult handleReadCommand() { // Replying with just OK indicates no response and hold // features in use now return new AtCommandResult(AtCommandResult.OK); } @Override public AtCommandResult handleSetCommand(Object[] args) { // Neeed PDC or CDMA return new AtCommandResult(AtCommandResult.ERROR); } }); // Request International Mobile Subscriber Identity (IMSI) // Not in bluetooth handset spec parser.register("+CIMI", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { // AT+CIMI String imsi = mPhone.getSubscriberId(); if (imsi == null || imsi.length() == 0) { return reportCmeError(BluetoothCmeError.SIM_FAILURE); } else { return new AtCommandResult(imsi); } } }); // Calling Line Identification Presentation parser.register("+CLIP", new AtCommandHandler() { @Override public AtCommandResult handleReadCommand() { // Currently assumes the network is provisioned for CLIP return new AtCommandResult("+CLIP: " + (mClip ? "1" : "0") + ",1"); } @Override public AtCommandResult handleSetCommand(Object[] args) { // AT+CLIP=<n> if (args.length >= 1 && (args[0].equals(0) || args[0].equals(1))) { mClip = args[0].equals(1); return new AtCommandResult(AtCommandResult.OK); } else { return new AtCommandResult(AtCommandResult.ERROR); } } @Override public AtCommandResult handleTestCommand() { return new AtCommandResult("+CLIP: (0-1)"); } }); // AT+CGSN - Returns the device IMEI number. parser.register("+CGSN", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { // Get the IMEI of the device. // mPhone will not be NULL at this point. return new AtCommandResult("+CGSN: " + mPhone.getDeviceId()); } }); // AT+CGMM - Query Model Information parser.register("+CGMM", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { // Return the Model Information. String model = SystemProperties.get("ro.product.model"); if (model != null) { return new AtCommandResult("+CGMM: " + model); } else { return new AtCommandResult(AtCommandResult.ERROR); } } }); // AT+CGMI - Query Manufacturer Information parser.register("+CGMI", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { // Return the Model Information. String manuf = SystemProperties.get("ro.product.manufacturer"); if (manuf != null) { return new AtCommandResult("+CGMI: " + manuf); } else { return new AtCommandResult(AtCommandResult.ERROR); } } }); // Noise Reduction and Echo Cancellation control parser.register("+NREC", new AtCommandHandler() { @Override public AtCommandResult handleSetCommand(Object[] args) { if (args[0].equals(0)) { mAudioManager.setParameter(HEADSET_NREC, "off"); return new AtCommandResult(AtCommandResult.OK); } else if (args[0].equals(1)) { mAudioManager.setParameter(HEADSET_NREC, "on"); return new AtCommandResult(AtCommandResult.OK); } return new AtCommandResult(AtCommandResult.ERROR); } }); // Voice recognition (dialing) parser.register("+BVRA", new AtCommandHandler() { @Override public AtCommandResult handleSetCommand(Object[] args) { if (BluetoothHeadset.DISABLE_BT_VOICE_DIALING) { return new AtCommandResult(AtCommandResult.ERROR); } if (args.length >= 1 && args[0].equals(1)) { synchronized (BluetoothHandsfree.this) { if (!mWaitingForVoiceRecognition) { try { mContext.startActivity(sVoiceCommandIntent); } catch (ActivityNotFoundException e) { return new AtCommandResult(AtCommandResult.ERROR); } expectVoiceRecognition(); } } return new AtCommandResult(AtCommandResult.UNSOLICITED); // send nothing yet } else if (args.length >= 1 && args[0].equals(0)) { audioOff(); return new AtCommandResult(AtCommandResult.OK); } return new AtCommandResult(AtCommandResult.ERROR); } @Override public AtCommandResult handleTestCommand() { return new AtCommandResult("+BVRA: (0-1)"); } }); // Retrieve Subscriber Number parser.register("+CNUM", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { String number = mPhone.getLine1Number(); if (number == null) { return new AtCommandResult(AtCommandResult.OK); } return new AtCommandResult("+CNUM: ,\"" + number + "\"," + PhoneNumberUtils.toaFromString(number) + ",,4"); } }); // Microphone Gain parser.register("+VGM", new AtCommandHandler() { @Override public AtCommandResult handleSetCommand(Object[] args) { // AT+VGM=<gain> in range [0,15] // Headset/Handsfree is reporting its current gain setting return new AtCommandResult(AtCommandResult.OK); } }); // Speaker Gain parser.register("+VGS", new AtCommandHandler() { @Override public AtCommandResult handleSetCommand(Object[] args) { // AT+VGS=<gain> in range [0,15] if (args.length != 1 || !(args[0] instanceof Integer)) { return new AtCommandResult(AtCommandResult.ERROR); } mScoGain = (Integer) args[0]; int flag = mAudioManager.isBluetoothScoOn() ? AudioManager.FLAG_SHOW_UI:0; mAudioManager.setStreamVolume(AudioManager.STREAM_BLUETOOTH_SCO, mScoGain, flag); return new AtCommandResult(AtCommandResult.OK); } }); // Phone activity status parser.register("+CPAS", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { int status = 0; switch (mPhone.getState()) { case IDLE: status = 0; break; case RINGING: status = 3; break; case OFFHOOK: status = 4; break; } return new AtCommandResult("+CPAS: " + status); } }); mPhonebook.register(parser); }
private void initializeHandsfreeAtParser() { if (DBG) log("Registering Handsfree AT commands"); AtParser parser = mHeadset.getAtParser(); // Answer parser.register('A', new AtCommandHandler() { @Override public AtCommandResult handleBasicCommand(String args) { PhoneUtils.answerCall(mPhone); return new AtCommandResult(AtCommandResult.OK); } }); parser.register('D', new AtCommandHandler() { @Override public AtCommandResult handleBasicCommand(String args) { if (args.length() > 0) { if (args.charAt(0) == '>') { // Yuck - memory dialling requested. // Just dial last number for now if (args.startsWith(">9999")) { // for PTS test return new AtCommandResult(AtCommandResult.ERROR); } return redial(); } else { // Remove trailing ';' if (args.charAt(args.length() - 1) == ';') { args = args.substring(0, args.length() - 1); } Intent intent = new Intent(Intent.ACTION_CALL_PRIVILEGED, Uri.fromParts("tel", args, null)); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mContext.startActivity(intent); expectCallStart(); return new AtCommandResult(AtCommandResult.UNSOLICITED); // send nothing } } return new AtCommandResult(AtCommandResult.ERROR); } }); // Hang-up command parser.register("+CHUP", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { if (!mForegroundCall.isIdle()) { PhoneUtils.hangup(mForegroundCall); } else if (!mRingingCall.isIdle()) { PhoneUtils.hangup(mRingingCall); } else if (!mBackgroundCall.isIdle()) { PhoneUtils.hangup(mBackgroundCall); } return new AtCommandResult(AtCommandResult.OK); } }); // Bluetooth Retrieve Supported Features command parser.register("+BRSF", new AtCommandHandler() { private AtCommandResult sendBRSF() { return new AtCommandResult("+BRSF: " + mLocalBrsf); } @Override public AtCommandResult handleSetCommand(Object[] args) { // AT+BRSF=<handsfree supported features bitmap> // Handsfree is telling us which features it supports. We // send the features we support if (args.length == 1 && (args[0] instanceof Integer)) { mRemoteBrsf = (Integer) args[0]; } else { Log.w(TAG, "HF didn't sent BRSF assuming 0"); } return sendBRSF(); } @Override public AtCommandResult handleActionCommand() { // This seems to be out of spec, but lets do the nice thing return sendBRSF(); } @Override public AtCommandResult handleReadCommand() { // This seems to be out of spec, but lets do the nice thing return sendBRSF(); } }); // Call waiting notification on/off parser.register("+CCWA", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { // Seems to be out of spec, but lets return nicely return new AtCommandResult(AtCommandResult.OK); } @Override public AtCommandResult handleReadCommand() { // Call waiting is always on return new AtCommandResult("+CCWA: 1"); } @Override public AtCommandResult handleSetCommand(Object[] args) { // AT+CCWA=<n> // Handsfree is trying to enable/disable call waiting. We // cannot disable in the current implementation. return new AtCommandResult(AtCommandResult.OK); } @Override public AtCommandResult handleTestCommand() { // Request for range of supported CCWA paramters return new AtCommandResult("+CCWA: (\"n\",(1))"); } }); // Mobile Equipment Event Reporting enable/disable command // Of the full 3GPP syntax paramters (mode, keyp, disp, ind, bfr) we // only support paramter ind (disable/enable evert reporting using // +CDEV) parser.register("+CMER", new AtCommandHandler() { @Override public AtCommandResult handleReadCommand() { return new AtCommandResult( "+CMER: 3,0,0," + (mIndicatorsEnabled ? "1" : "0")); } @Override public AtCommandResult handleSetCommand(Object[] args) { if (args.length < 4) { // This is a syntax error return new AtCommandResult(AtCommandResult.ERROR); } else if (args[0].equals(3) && args[1].equals(0) && args[2].equals(0)) { boolean valid = false; if (args[3].equals(0)) { mIndicatorsEnabled = false; valid = true; } else if (args[3].equals(1)) { mIndicatorsEnabled = true; valid = true; } if (valid) { if ((mRemoteBrsf & BRSF_HF_CW_THREE_WAY_CALLING) == 0x0) { mServiceConnectionEstablished = true; sendURC("OK"); // send immediately, then initiate audio if (isIncallAudio()) { audioOn(); } // only send OK once return new AtCommandResult(AtCommandResult.UNSOLICITED); } else { return new AtCommandResult(AtCommandResult.OK); } } } return reportCmeError(BluetoothCmeError.OPERATION_NOT_SUPPORTED); } @Override public AtCommandResult handleTestCommand() { return new AtCommandResult("+CMER: (3),(0),(0),(0-1)"); } }); // Mobile Equipment Error Reporting enable/disable parser.register("+CMEE", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { // out of spec, assume they want to enable mCmee = true; return new AtCommandResult(AtCommandResult.OK); } @Override public AtCommandResult handleReadCommand() { return new AtCommandResult("+CMEE: " + (mCmee ? "1" : "0")); } @Override public AtCommandResult handleSetCommand(Object[] args) { // AT+CMEE=<n> if (args.length == 0) { // <n> ommitted - default to 0 mCmee = false; return new AtCommandResult(AtCommandResult.OK); } else if (!(args[0] instanceof Integer)) { // Syntax error return new AtCommandResult(AtCommandResult.ERROR); } else { mCmee = ((Integer)args[0] == 1); return new AtCommandResult(AtCommandResult.OK); } } @Override public AtCommandResult handleTestCommand() { // Probably not required but spec, but no harm done return new AtCommandResult("+CMEE: (0-1)"); } }); // Bluetooth Last Dialled Number parser.register("+BLDN", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { return redial(); } }); // Indicator Update command parser.register("+CIND", new AtCommandHandler() { @Override public AtCommandResult handleReadCommand() { return mPhoneState.toCindResult(); } @Override public AtCommandResult handleTestCommand() { return mPhoneState.getCindTestResult(); } }); // Query Signal Quality (legacy) parser.register("+CSQ", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { return mPhoneState.toCsqResult(); } }); // Query network registration state parser.register("+CREG", new AtCommandHandler() { @Override public AtCommandResult handleReadCommand() { return new AtCommandResult(mPhoneState.toCregString()); } }); // Send DTMF. I don't know if we are also expected to play the DTMF tone // locally, right now we don't parser.register("+VTS", new AtCommandHandler() { @Override public AtCommandResult handleSetCommand(Object[] args) { if (args.length >= 1) { char c; if (args[0] instanceof Integer) { c = ((Integer) args[0]).toString().charAt(0); } else { c = ((String) args[0]).charAt(0); } if (isValidDtmf(c)) { mPhone.sendDtmf(c); return new AtCommandResult(AtCommandResult.OK); } } return new AtCommandResult(AtCommandResult.ERROR); } private boolean isValidDtmf(char c) { switch (c) { case '#': case '*': return true; default: if (Character.digit(c, 14) != -1) { return true; // 0-9 and A-D } return false; } } }); // List calls parser.register("+CLCC", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { return getClccResult(); } }); // Call Hold and Multiparty Handling command parser.register("+CHLD", new AtCommandHandler() { @Override public AtCommandResult handleSetCommand(Object[] args) { if (args.length >= 1) { if (args[0].equals(0)) { boolean result; if (mRingingCall.isRinging()) { result = PhoneUtils.hangupRingingCall(mPhone); } else { result = PhoneUtils.hangupHoldingCall(mPhone); } if (result) { return new AtCommandResult(AtCommandResult.OK); } else { return new AtCommandResult(AtCommandResult.ERROR); } } else if (args[0].equals(1)) { // Hangup active call, answer held call if (PhoneUtils.answerAndEndActive(mPhone)) { return new AtCommandResult(AtCommandResult.OK); } else { return new AtCommandResult(AtCommandResult.ERROR); } } else if (args[0].equals(2)) { PhoneUtils.switchHoldingAndActive(mPhone); return new AtCommandResult(AtCommandResult.OK); } else if (args[0].equals(3)) { if (mForegroundCall.getState().isAlive() && mBackgroundCall.getState().isAlive()) { PhoneUtils.mergeCalls(mPhone); } return new AtCommandResult(AtCommandResult.OK); } } return new AtCommandResult(AtCommandResult.ERROR); } @Override public AtCommandResult handleTestCommand() { mServiceConnectionEstablished = true; sendURC("+CHLD: (0,1,2,3)"); sendURC("OK"); // send reply first, then connect audio if (isIncallAudio()) { audioOn(); } // already replied return new AtCommandResult(AtCommandResult.UNSOLICITED); } }); // Get Network operator name parser.register("+COPS", new AtCommandHandler() { @Override public AtCommandResult handleReadCommand() { String operatorName = mPhone.getServiceState().getOperatorAlphaLong(); if (operatorName != null) { if (operatorName.length() > 16) { operatorName = operatorName.substring(0, 16); } return new AtCommandResult( "+COPS: 0,0,\"" + operatorName + "\""); } else { return new AtCommandResult( "+COPS: 0,0,\"UNKNOWN\",0"); } } @Override public AtCommandResult handleSetCommand(Object[] args) { // Handsfree only supports AT+COPS=3,0 if (args.length != 2 || !(args[0] instanceof Integer) || !(args[1] instanceof Integer)) { // syntax error return new AtCommandResult(AtCommandResult.ERROR); } else if ((Integer)args[0] != 3 || (Integer)args[1] != 0) { return reportCmeError(BluetoothCmeError.OPERATION_NOT_SUPPORTED); } else { return new AtCommandResult(AtCommandResult.OK); } } @Override public AtCommandResult handleTestCommand() { // Out of spec, but lets be friendly return new AtCommandResult("+COPS: (3),(0)"); } }); // Mobile PIN // AT+CPIN is not in the handsfree spec (although it is in 3GPP) parser.register("+CPIN", new AtCommandHandler() { @Override public AtCommandResult handleReadCommand() { return new AtCommandResult("+CPIN: READY"); } }); // Bluetooth Response and Hold // Only supported on PDC (Japan) and CDMA networks. parser.register("+BTRH", new AtCommandHandler() { @Override public AtCommandResult handleReadCommand() { // Replying with just OK indicates no response and hold // features in use now return new AtCommandResult(AtCommandResult.OK); } @Override public AtCommandResult handleSetCommand(Object[] args) { // Neeed PDC or CDMA return new AtCommandResult(AtCommandResult.ERROR); } }); // Request International Mobile Subscriber Identity (IMSI) // Not in bluetooth handset spec parser.register("+CIMI", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { // AT+CIMI String imsi = mPhone.getSubscriberId(); if (imsi == null || imsi.length() == 0) { return reportCmeError(BluetoothCmeError.SIM_FAILURE); } else { return new AtCommandResult(imsi); } } }); // Calling Line Identification Presentation parser.register("+CLIP", new AtCommandHandler() { @Override public AtCommandResult handleReadCommand() { // Currently assumes the network is provisioned for CLIP return new AtCommandResult("+CLIP: " + (mClip ? "1" : "0") + ",1"); } @Override public AtCommandResult handleSetCommand(Object[] args) { // AT+CLIP=<n> if (args.length >= 1 && (args[0].equals(0) || args[0].equals(1))) { mClip = args[0].equals(1); return new AtCommandResult(AtCommandResult.OK); } else { return new AtCommandResult(AtCommandResult.ERROR); } } @Override public AtCommandResult handleTestCommand() { return new AtCommandResult("+CLIP: (0-1)"); } }); // AT+CGSN - Returns the device IMEI number. parser.register("+CGSN", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { // Get the IMEI of the device. // mPhone will not be NULL at this point. return new AtCommandResult("+CGSN: " + mPhone.getDeviceId()); } }); // AT+CGMM - Query Model Information parser.register("+CGMM", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { // Return the Model Information. String model = SystemProperties.get("ro.product.model"); if (model != null) { return new AtCommandResult("+CGMM: " + model); } else { return new AtCommandResult(AtCommandResult.ERROR); } } }); // AT+CGMI - Query Manufacturer Information parser.register("+CGMI", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { // Return the Model Information. String manuf = SystemProperties.get("ro.product.manufacturer"); if (manuf != null) { return new AtCommandResult("+CGMI: " + manuf); } else { return new AtCommandResult(AtCommandResult.ERROR); } } }); // Noise Reduction and Echo Cancellation control parser.register("+NREC", new AtCommandHandler() { @Override public AtCommandResult handleSetCommand(Object[] args) { if (args[0].equals(0)) { mAudioManager.setParameter(HEADSET_NREC, "off"); return new AtCommandResult(AtCommandResult.OK); } else if (args[0].equals(1)) { mAudioManager.setParameter(HEADSET_NREC, "on"); return new AtCommandResult(AtCommandResult.OK); } return new AtCommandResult(AtCommandResult.ERROR); } }); // Voice recognition (dialing) parser.register("+BVRA", new AtCommandHandler() { @Override public AtCommandResult handleSetCommand(Object[] args) { if (BluetoothHeadset.DISABLE_BT_VOICE_DIALING) { return new AtCommandResult(AtCommandResult.ERROR); } if (args.length >= 1 && args[0].equals(1)) { synchronized (BluetoothHandsfree.this) { if (!mWaitingForVoiceRecognition) { try { mContext.startActivity(sVoiceCommandIntent); } catch (ActivityNotFoundException e) { return new AtCommandResult(AtCommandResult.ERROR); } expectVoiceRecognition(); } } return new AtCommandResult(AtCommandResult.UNSOLICITED); // send nothing yet } else if (args.length >= 1 && args[0].equals(0)) { audioOff(); return new AtCommandResult(AtCommandResult.OK); } return new AtCommandResult(AtCommandResult.ERROR); } @Override public AtCommandResult handleTestCommand() { return new AtCommandResult("+BVRA: (0-1)"); } }); // Retrieve Subscriber Number parser.register("+CNUM", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { String number = mPhone.getLine1Number(); if (number == null) { return new AtCommandResult(AtCommandResult.OK); } return new AtCommandResult("+CNUM: ,\"" + number + "\"," + PhoneNumberUtils.toaFromString(number) + ",,4"); } }); // Microphone Gain parser.register("+VGM", new AtCommandHandler() { @Override public AtCommandResult handleSetCommand(Object[] args) { // AT+VGM=<gain> in range [0,15] // Headset/Handsfree is reporting its current gain setting return new AtCommandResult(AtCommandResult.OK); } }); // Speaker Gain parser.register("+VGS", new AtCommandHandler() { @Override public AtCommandResult handleSetCommand(Object[] args) { // AT+VGS=<gain> in range [0,15] if (args.length != 1 || !(args[0] instanceof Integer)) { return new AtCommandResult(AtCommandResult.ERROR); } mScoGain = (Integer) args[0]; int flag = mAudioManager.isBluetoothScoOn() ? AudioManager.FLAG_SHOW_UI:0; mAudioManager.setStreamVolume(AudioManager.STREAM_BLUETOOTH_SCO, mScoGain, flag); return new AtCommandResult(AtCommandResult.OK); } }); // Phone activity status parser.register("+CPAS", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { int status = 0; switch (mPhone.getState()) { case IDLE: status = 0; break; case RINGING: status = 3; break; case OFFHOOK: status = 4; break; } return new AtCommandResult("+CPAS: " + status); } }); mPhonebook.register(parser); }
diff --git a/src/com/android/camera/ui/IndicatorWheel.java b/src/com/android/camera/ui/IndicatorWheel.java index dfd717c0..1101db52 100644 --- a/src/com/android/camera/ui/IndicatorWheel.java +++ b/src/com/android/camera/ui/IndicatorWheel.java @@ -1,245 +1,245 @@ /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.camera.ui; import com.android.camera.ComboPreferences; import com.android.camera.PreferenceGroup; import com.android.camera.R; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.RectF; import android.util.AttributeSet; import android.util.Log; import android.widget.Button; import android.view.MotionEvent; import android.view.ViewGroup; import android.view.View; import java.lang.Math; /** * A view that contains shutter button and camera setting indicators. The * indicators are spreaded around the shutter button. The first child is always * the shutter button. */ public class IndicatorWheel extends ViewGroup { private static final String TAG = "IndicatorWheel"; private Listener mListener; // The center of the shutter button. private int mCenterX, mCenterY; // The width of the wheel stroke. private int mStrokeWidth = 60; private final int STROKE_COLOR = 0x12FFFFFF; // The width of the edges on both sides of the wheel, which has less alpha. private final int EDGE_STROKE_WIDTH = 6, EDGE_STROKE_COLOR = 0x07FFFFFF; // Leave some space between the settings wheel and the decoration edges. private final int LINE_SPACE = 2; private final int OUTER_EDGE_STROKE_WIDTH = 3, OUTER_EDGE_STROKE_COLOR = 0x07FFFFFF; private View mShutterButton; private double mShutterButtonRadius; private double mWheelRadius; private double mSectorInitialRadians[]; private Paint mBackgroundPaint; private RectF mBackgroundRect; static public interface Listener { public void onIndicatorClicked(int index); } public void setListener(Listener listener) { mListener = listener; } public IndicatorWheel(Context context, AttributeSet attrs) { super(context, attrs); setWillNotDraw(false); mBackgroundPaint = new Paint(); mBackgroundPaint.setStyle(Paint.Style.STROKE); mBackgroundPaint.setAntiAlias(true); mBackgroundRect = new RectF(); } @Override public boolean onTouchEvent(MotionEvent event) { int count = getChildCount(); if (mListener == null || count <= 1) return false; // Check if any setting is pressed. int action = event.getAction(); if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_MOVE) { double dx = event.getX() - mCenterX; double dy = mCenterY - event.getY(); double radius = Math.sqrt(dx * dx + dy * dy); // Ignore the event if it's too near to the shutter button. if (radius < mShutterButtonRadius) return false; // Ignore the event if it's too far from the shutter button. if ((radius - mWheelRadius) > mStrokeWidth) return false; double intervalDegrees = 180.0 / (count - 2); double delta = Math.atan2(dy, dx); if (delta < 0) delta += Math.PI * 2; // Check which sector is pressed. if (delta > mSectorInitialRadians[0]) { for (int i = 1; i < count; i++) { if (delta < mSectorInitialRadians[i]) { mListener.onIndicatorClicked(i - 1); return true; } } } } return false; } @Override protected void onFinishInflate() { super.onFinishInflate(); // The first view is shutter button. mShutterButton = getChildAt(0); } public void removeIndicators() { // Remove everything but the shutter button. int count = getChildCount(); if (count > 1) { removeViews(1, count - 1); } } @Override protected void onMeasure(int widthSpec, int heightSpec) { // Measure all children. int childCount = getChildCount(); int freeSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); for (int i = 0; i < childCount; i++) { getChildAt(i).measure(freeSpec, freeSpec); } if (childCount > 1) { mStrokeWidth = (int) (getChildAt(1).getMeasuredWidth() * 2.0); } // Measure myself. int desiredWidth = (int)(mShutterButton.getMeasuredWidth() * 3); int desiredHeight = (int)(mShutterButton.getMeasuredHeight() * 4.5) + 2; int widthMode = MeasureSpec.getMode(widthSpec); int heightMode = MeasureSpec.getMode(heightSpec); int measuredWidth, measuredHeight; if (widthMode == MeasureSpec.UNSPECIFIED) { measuredWidth = desiredWidth; } else if (widthMode == MeasureSpec.AT_MOST) { measuredWidth = Math.min(desiredWidth, MeasureSpec.getSize(widthSpec)); } else { // MeasureSpec.EXACTLY measuredWidth = MeasureSpec.getSize(widthSpec); } if (heightMode == MeasureSpec.UNSPECIFIED) { measuredHeight = desiredHeight; } else if (heightMode == MeasureSpec.AT_MOST) { measuredHeight = Math.min(desiredHeight, MeasureSpec.getSize(heightSpec)); } else { // MeasureSpec.EXACTLY measuredHeight = MeasureSpec.getSize(heightSpec); } setMeasuredDimension(measuredWidth, measuredHeight); } @Override protected void onLayout( boolean changed, int left, int top, int right, int bottom) { int count = getChildCount(); if (count == 0) return; // Layout the shutter button. int shutterButtonWidth = mShutterButton.getMeasuredWidth(); mShutterButtonRadius = shutterButtonWidth / 2.0; int shutterButtonHeight = mShutterButton.getMeasuredHeight(); + mCenterX = (int) (right - left - mShutterButtonRadius * 1.2); mCenterY = (bottom - top) / 2; mShutterButton.layout(mCenterX - shutterButtonWidth / 2, mCenterY - shutterButtonHeight / 2, mCenterX + shutterButtonWidth / 2, mCenterY + shutterButtonHeight / 2); // Layout the settings. The icons are spreaded on the left side of the // shutter button. So the angle starts from 90 to 270 degrees. if (count == 1) return; mWheelRadius = mShutterButtonRadius + mStrokeWidth * 1.5; - mCenterX = (int) (right - mShutterButtonRadius * 1.2 - left); double intervalDegrees = 180.0 / (count - 2); double initialDegrees = 90.0; int index = 0; for (int i = 0; i < count; i++) { View view = getChildAt(i); if (view == mShutterButton) continue; double degree = initialDegrees + intervalDegrees * index; double radian = Math.toRadians(degree); int x = mCenterX + (int)(mWheelRadius * Math.cos(radian)); int y = mCenterY - (int)(mWheelRadius * Math.sin(radian)); int width = view.getMeasuredWidth(); int height = view.getMeasuredHeight(); view.layout(x - width / 2, y - height / 2, x + width / 2, y + height / 2); index++; } // Store the radian intervals for each icon. mSectorInitialRadians = new double[count]; mSectorInitialRadians[0] = Math.toRadians( initialDegrees - intervalDegrees / 2.0); for (int i = 1; i < count; i++) { mSectorInitialRadians[i] = mSectorInitialRadians[i - 1] + Math.toRadians(intervalDegrees); } } @Override protected void onDraw(Canvas canvas) { // Draw the dark background. mBackgroundPaint.setStrokeWidth(mStrokeWidth); mBackgroundPaint.setColor(STROKE_COLOR); mBackgroundRect.set((float)(mCenterX - mWheelRadius), (float)(mCenterY - mWheelRadius), (float)(mCenterX + mWheelRadius), (float)(mCenterY + mWheelRadius)); canvas.drawArc(mBackgroundRect, 0, 360, false, mBackgroundPaint); // Draw a lighter background on the both sides of the arc. mBackgroundPaint.setStrokeWidth(EDGE_STROKE_WIDTH); mBackgroundPaint.setColor(EDGE_STROKE_COLOR); float delta = (mStrokeWidth + EDGE_STROKE_WIDTH) / 2.0f; mBackgroundRect.inset(-delta - LINE_SPACE, -delta - LINE_SPACE); canvas.drawArc(mBackgroundRect, 0, 360, false, mBackgroundPaint); mBackgroundRect.inset((delta + LINE_SPACE) * 2, (delta + LINE_SPACE) * 2); canvas.drawArc(mBackgroundRect, 0, 360, false, mBackgroundPaint); // Draw another thinner, lighter background on the outer circle mBackgroundPaint.setStrokeWidth(OUTER_EDGE_STROKE_WIDTH); mBackgroundPaint.setColor(OUTER_EDGE_STROKE_COLOR); mBackgroundRect.inset(-delta * 4 - EDGE_STROKE_WIDTH, -delta * 4 - EDGE_STROKE_WIDTH); canvas.drawArc(mBackgroundRect, 0, 360, false, mBackgroundPaint); super.onDraw(canvas); } public void updateIndicator(int index) { IndicatorButton indicator = (IndicatorButton) getChildAt(index + 1); indicator.reloadPreference(); } }
false
true
protected void onLayout( boolean changed, int left, int top, int right, int bottom) { int count = getChildCount(); if (count == 0) return; // Layout the shutter button. int shutterButtonWidth = mShutterButton.getMeasuredWidth(); mShutterButtonRadius = shutterButtonWidth / 2.0; int shutterButtonHeight = mShutterButton.getMeasuredHeight(); mCenterY = (bottom - top) / 2; mShutterButton.layout(mCenterX - shutterButtonWidth / 2, mCenterY - shutterButtonHeight / 2, mCenterX + shutterButtonWidth / 2, mCenterY + shutterButtonHeight / 2); // Layout the settings. The icons are spreaded on the left side of the // shutter button. So the angle starts from 90 to 270 degrees. if (count == 1) return; mWheelRadius = mShutterButtonRadius + mStrokeWidth * 1.5; mCenterX = (int) (right - mShutterButtonRadius * 1.2 - left); double intervalDegrees = 180.0 / (count - 2); double initialDegrees = 90.0; int index = 0; for (int i = 0; i < count; i++) { View view = getChildAt(i); if (view == mShutterButton) continue; double degree = initialDegrees + intervalDegrees * index; double radian = Math.toRadians(degree); int x = mCenterX + (int)(mWheelRadius * Math.cos(radian)); int y = mCenterY - (int)(mWheelRadius * Math.sin(radian)); int width = view.getMeasuredWidth(); int height = view.getMeasuredHeight(); view.layout(x - width / 2, y - height / 2, x + width / 2, y + height / 2); index++; } // Store the radian intervals for each icon. mSectorInitialRadians = new double[count]; mSectorInitialRadians[0] = Math.toRadians( initialDegrees - intervalDegrees / 2.0); for (int i = 1; i < count; i++) { mSectorInitialRadians[i] = mSectorInitialRadians[i - 1] + Math.toRadians(intervalDegrees); } }
protected void onLayout( boolean changed, int left, int top, int right, int bottom) { int count = getChildCount(); if (count == 0) return; // Layout the shutter button. int shutterButtonWidth = mShutterButton.getMeasuredWidth(); mShutterButtonRadius = shutterButtonWidth / 2.0; int shutterButtonHeight = mShutterButton.getMeasuredHeight(); mCenterX = (int) (right - left - mShutterButtonRadius * 1.2); mCenterY = (bottom - top) / 2; mShutterButton.layout(mCenterX - shutterButtonWidth / 2, mCenterY - shutterButtonHeight / 2, mCenterX + shutterButtonWidth / 2, mCenterY + shutterButtonHeight / 2); // Layout the settings. The icons are spreaded on the left side of the // shutter button. So the angle starts from 90 to 270 degrees. if (count == 1) return; mWheelRadius = mShutterButtonRadius + mStrokeWidth * 1.5; double intervalDegrees = 180.0 / (count - 2); double initialDegrees = 90.0; int index = 0; for (int i = 0; i < count; i++) { View view = getChildAt(i); if (view == mShutterButton) continue; double degree = initialDegrees + intervalDegrees * index; double radian = Math.toRadians(degree); int x = mCenterX + (int)(mWheelRadius * Math.cos(radian)); int y = mCenterY - (int)(mWheelRadius * Math.sin(radian)); int width = view.getMeasuredWidth(); int height = view.getMeasuredHeight(); view.layout(x - width / 2, y - height / 2, x + width / 2, y + height / 2); index++; } // Store the radian intervals for each icon. mSectorInitialRadians = new double[count]; mSectorInitialRadians[0] = Math.toRadians( initialDegrees - intervalDegrees / 2.0); for (int i = 1; i < count; i++) { mSectorInitialRadians[i] = mSectorInitialRadians[i - 1] + Math.toRadians(intervalDegrees); } }
diff --git a/src/main/java/plugins/N2NChat/DisplayChatToadlet.java b/src/main/java/plugins/N2NChat/DisplayChatToadlet.java index da2d896..5c64005 100644 --- a/src/main/java/plugins/N2NChat/DisplayChatToadlet.java +++ b/src/main/java/plugins/N2NChat/DisplayChatToadlet.java @@ -1,199 +1,200 @@ package plugins.N2NChat; import freenet.clients.http.*; import freenet.l10n.NodeL10n; import freenet.l10n.PluginL10n; import freenet.node.DarknetPeerNode; import freenet.node.Node; import freenet.pluginmanager.PluginRespirator; import freenet.support.Base64; import freenet.support.HTMLNode; import freenet.support.IllegalBase64Exception; import freenet.support.MultiValueTable; import freenet.support.api.HTTPRequest; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; public class DisplayChatToadlet extends Toadlet implements LinkEnabledCallback { private HashMap<Long, ChatRoom> chatRooms; private PluginL10n l10n; private Node node; private PluginRespirator pluginRespirator; public DisplayChatToadlet(N2NChatPlugin chatPlugin) { super(chatPlugin.pluginRespirator().getHLSimpleClient()); this.chatRooms = chatPlugin.chatRooms; this.l10n = chatPlugin.l10n(); this.pluginRespirator = chatPlugin.pluginRespirator(); this.node = pluginRespirator.getNode(); } public static String PATH = "/n2n-chat/display/"; public String path() { return PATH; } public boolean isEnabled (ToadletContext ctx) { return (!pluginRespirator.getToadletContainer().publicGatewayMode()) || ((ctx != null) && ctx.isAllowedFullAccess()); } public void handleMethodPOST(URI uri, HTTPRequest request, ToadletContext ctx) throws ToadletContextClosedException, IOException, RedirectException { if (!request.isPartSet("room") || request.getPartAsStringFailsafe("room", 4096).isEmpty()) { super.sendErrorPage(ctx, 500, "Invalid room", "A room was not properly requested."); return; } else if (!chatRooms.containsKey(Long.valueOf(request.getPartAsStringFailsafe("room", 4096)))) { super.sendErrorPage(ctx, 500, "Nonexistent room", "The requested room does not exist."); return; } //TODO: Should the password check be the first thing? long globalIdentifier = Long.valueOf(request.getPartAsStringFailsafe("room", 4096)); //Ensure that the form password is correctly set. String pass = request.getPartAsStringFailsafe("formPassword", 32); if ( pass == null || !pass.equals(node.clientCore.formPassword)) { selfRefresh(globalIdentifier, ctx); return; } if (request.isPartSet("message") && !request.getPartAsStringFailsafe("message", 4096).isEmpty()) { chatRooms.get(globalIdentifier).sendOwnMessage(request.getPartAsStringFailsafe("message", 4096)); selfRefresh(globalIdentifier, ctx); return; } else if (request.isPartSet("invite") && !request.getPartAsStringFailsafe("invite", 4096).isEmpty()) { //TODO: What is the length of a public key hash? (when base 64 encoded?) try { byte[] pubKeyHash = Base64.decode(request.getPartAsStringFailsafe("invite", 4096)); DarknetPeerNode peerNode = null; for (DarknetPeerNode node : this.node.getDarknetConnections()) { if (Arrays.equals(node.getPubKeyHash(), pubKeyHash)) { peerNode = node; break; } } if (peerNode == null) { super.sendErrorPage(ctx, 500, "Invalid public key hash", "A peer with that hash does not exist."); return; } chatRooms.get(globalIdentifier).sendInviteOffer(peerNode, peerNode.getName()); selfRefresh(globalIdentifier, ctx); return; } catch (IllegalBase64Exception e) { super.sendErrorPage(ctx, 500, "Invalid public key hash", "The public key hash to invite was not valid base 64 encoding."); return; } } super.sendErrorPage(ctx, 500, "Argument error", "Not enough recognized arguments were provided to do anything."); } private void selfRefresh(long globalIdentifier, ToadletContext ctx) throws ToadletContextClosedException, IOException{ MultiValueTable<String, String> headers = new MultiValueTable<String, String>(); headers.put("Location", PATH+"?room="+globalIdentifier); ctx.sendReplyHeaders(302, "Found", headers, null, 0); } public void handleMethodGET(URI uri, HTTPRequest request, ToadletContext ctx) throws ToadletContextClosedException, IOException, RedirectException { if (!ctx.isAllowedFullAccess()) { super.sendErrorPage(ctx, 403, "Unauthorized", NodeL10n.getBase() .getString("Toadlet.unauthorized")); return; } if (request.isParameterSet("room") && !request.getParam("room").isEmpty()) { long globalIdentifier = Long.valueOf(request.getParam("room")); //Ensure the chat room is valid. - if (chatRooms.get(globalIdentifier) == null) { + ChatRoom chatRoom = chatRooms.get(globalIdentifier); + if (chatRoom == null) { //TODO: localization super.sendErrorPage(ctx, 500, "Invalid Room", "This node is not present in the specified room."); + return; } - ChatRoom chatRoom = chatRooms.get(globalIdentifier); //Only messages have been requested. if (request.isParameterSet("messagesPane")) { writeHTMLReply(ctx, 200, "OK", null, chatRoom.getLog().generate()); return; } else if (request.isParameterSet("participantsList")) { writeHTMLReply(ctx, 200, "OK", null, chatRoom.getParticipantListing().generate()); return; } PageNode pn = ctx.getPageMaker().getPageNode(chatRoom.getRoomName(), ctx); //pn.addCustomStyleSheet("/n2n-chat/static/css/display.css"); pn.headNode.addChild("script", new String[] { "type", "src" }, new String[] { "text/javascript", "/n2n-chat/static/js/jquery.min.js"}); pn.headNode.addChild("script", new String[] { "type", "src" }, new String[] { "text/javascript", "/n2n-chat/static/js/display.js"}); //So that the members and messages pane share vertical size. HTMLNode panes = pn.content.addChild("div", "style", "display:table;width:100%"); //Add main messages area. panes.addChild("div", new String[] { "style", "id" }, new String[] { "display:table-cell;width:80%;", "messagesPane" }) .addChild(chatRoom.getLog()); //Add listing of current participants. HTMLNode participantsPane = panes.addChild("div", "style", "display:table-cell;width:20%"); //Container for participants listing only; invite dropdown should not be disturbed by the auto-refresh. HTMLNode participantsListing = participantsPane.addChild("div", "id", "participantsList"); participantsListing.addChild(chatRoom.getParticipantListing()); //And ability to invite those not already participating. Don't display if all connected darknet //peers are already participating. ArrayList<DarknetPeerNode> uninvitedPeers = uninvitedPeers(globalIdentifier); if (uninvitedPeers.size() > 0) { //Allow inviting more participants. HTMLNode inviteForm = ctx.addFormChild(participantsPane, path(), "invite-participant"); inviteForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "room", String.valueOf(globalIdentifier) }); HTMLNode dropDown = inviteForm.addChild("select", "name", "invite"); for (DarknetPeerNode peerNode : uninvitedPeers) { dropDown.addChild("option", "value", Base64.encode(peerNode.getPubKeyHash()), peerNode.getName()); } inviteForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", "send-invite", l10n("sendInvitation")}); } //Add message sending area. HTMLNode messageEntry = ctx.addFormChild(pn.content, path(), "send-message"); messageEntry.addChild("input", new String[] { "type", "name", "style" }, new String[] { "text", "message", "width:80%;" }); messageEntry.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "room", String.valueOf(globalIdentifier)} ); messageEntry.addChild("input", new String[] { "type", "name", "value"}, new String[] { "submit", "send-message", l10n("send") } ); writeHTMLReply(ctx, 200, "OK", null, pn.outer.generate()); } else { super.sendErrorPage(ctx, 500, "Room Not Specified", "The room to display was not specified."); } } public ArrayList<DarknetPeerNode> uninvitedPeers(long globalIdentifier) { ChatRoom chatRoom = chatRooms.get(globalIdentifier); ArrayList<DarknetPeerNode> list = new ArrayList<DarknetPeerNode>(); for (DarknetPeerNode peerNode : node.getDarknetConnections()) { if (!chatRoom.containsParticipant(new ByteArray(peerNode.getPubKeyHash())) && !chatRoom.inviteSentTo(new ByteArray(peerNode.getPubKeyHash()))) { list.add(peerNode); } } return list; } private String l10n(String key) { return l10n.getBase().getString("room."+key); } }
false
true
public void handleMethodGET(URI uri, HTTPRequest request, ToadletContext ctx) throws ToadletContextClosedException, IOException, RedirectException { if (!ctx.isAllowedFullAccess()) { super.sendErrorPage(ctx, 403, "Unauthorized", NodeL10n.getBase() .getString("Toadlet.unauthorized")); return; } if (request.isParameterSet("room") && !request.getParam("room").isEmpty()) { long globalIdentifier = Long.valueOf(request.getParam("room")); //Ensure the chat room is valid. if (chatRooms.get(globalIdentifier) == null) { //TODO: localization super.sendErrorPage(ctx, 500, "Invalid Room", "This node is not present in the specified room."); } ChatRoom chatRoom = chatRooms.get(globalIdentifier); //Only messages have been requested. if (request.isParameterSet("messagesPane")) { writeHTMLReply(ctx, 200, "OK", null, chatRoom.getLog().generate()); return; } else if (request.isParameterSet("participantsList")) { writeHTMLReply(ctx, 200, "OK", null, chatRoom.getParticipantListing().generate()); return; } PageNode pn = ctx.getPageMaker().getPageNode(chatRoom.getRoomName(), ctx); //pn.addCustomStyleSheet("/n2n-chat/static/css/display.css"); pn.headNode.addChild("script", new String[] { "type", "src" }, new String[] { "text/javascript", "/n2n-chat/static/js/jquery.min.js"}); pn.headNode.addChild("script", new String[] { "type", "src" }, new String[] { "text/javascript", "/n2n-chat/static/js/display.js"}); //So that the members and messages pane share vertical size. HTMLNode panes = pn.content.addChild("div", "style", "display:table;width:100%"); //Add main messages area. panes.addChild("div", new String[] { "style", "id" }, new String[] { "display:table-cell;width:80%;", "messagesPane" }) .addChild(chatRoom.getLog()); //Add listing of current participants. HTMLNode participantsPane = panes.addChild("div", "style", "display:table-cell;width:20%"); //Container for participants listing only; invite dropdown should not be disturbed by the auto-refresh. HTMLNode participantsListing = participantsPane.addChild("div", "id", "participantsList"); participantsListing.addChild(chatRoom.getParticipantListing()); //And ability to invite those not already participating. Don't display if all connected darknet //peers are already participating. ArrayList<DarknetPeerNode> uninvitedPeers = uninvitedPeers(globalIdentifier); if (uninvitedPeers.size() > 0) { //Allow inviting more participants. HTMLNode inviteForm = ctx.addFormChild(participantsPane, path(), "invite-participant"); inviteForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "room", String.valueOf(globalIdentifier) }); HTMLNode dropDown = inviteForm.addChild("select", "name", "invite"); for (DarknetPeerNode peerNode : uninvitedPeers) { dropDown.addChild("option", "value", Base64.encode(peerNode.getPubKeyHash()), peerNode.getName()); } inviteForm.addChild("input", new String[] { "type", "name", "value" },
public void handleMethodGET(URI uri, HTTPRequest request, ToadletContext ctx) throws ToadletContextClosedException, IOException, RedirectException { if (!ctx.isAllowedFullAccess()) { super.sendErrorPage(ctx, 403, "Unauthorized", NodeL10n.getBase() .getString("Toadlet.unauthorized")); return; } if (request.isParameterSet("room") && !request.getParam("room").isEmpty()) { long globalIdentifier = Long.valueOf(request.getParam("room")); //Ensure the chat room is valid. ChatRoom chatRoom = chatRooms.get(globalIdentifier); if (chatRoom == null) { //TODO: localization super.sendErrorPage(ctx, 500, "Invalid Room", "This node is not present in the specified room."); return; } //Only messages have been requested. if (request.isParameterSet("messagesPane")) { writeHTMLReply(ctx, 200, "OK", null, chatRoom.getLog().generate()); return; } else if (request.isParameterSet("participantsList")) { writeHTMLReply(ctx, 200, "OK", null, chatRoom.getParticipantListing().generate()); return; } PageNode pn = ctx.getPageMaker().getPageNode(chatRoom.getRoomName(), ctx); //pn.addCustomStyleSheet("/n2n-chat/static/css/display.css"); pn.headNode.addChild("script", new String[] { "type", "src" }, new String[] { "text/javascript", "/n2n-chat/static/js/jquery.min.js"}); pn.headNode.addChild("script", new String[] { "type", "src" }, new String[] { "text/javascript", "/n2n-chat/static/js/display.js"}); //So that the members and messages pane share vertical size. HTMLNode panes = pn.content.addChild("div", "style", "display:table;width:100%"); //Add main messages area. panes.addChild("div", new String[] { "style", "id" }, new String[] { "display:table-cell;width:80%;", "messagesPane" }) .addChild(chatRoom.getLog()); //Add listing of current participants. HTMLNode participantsPane = panes.addChild("div", "style", "display:table-cell;width:20%"); //Container for participants listing only; invite dropdown should not be disturbed by the auto-refresh. HTMLNode participantsListing = participantsPane.addChild("div", "id", "participantsList"); participantsListing.addChild(chatRoom.getParticipantListing()); //And ability to invite those not already participating. Don't display if all connected darknet //peers are already participating. ArrayList<DarknetPeerNode> uninvitedPeers = uninvitedPeers(globalIdentifier); if (uninvitedPeers.size() > 0) { //Allow inviting more participants. HTMLNode inviteForm = ctx.addFormChild(participantsPane, path(), "invite-participant"); inviteForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "room", String.valueOf(globalIdentifier) }); HTMLNode dropDown = inviteForm.addChild("select", "name", "invite"); for (DarknetPeerNode peerNode : uninvitedPeers) { dropDown.addChild("option", "value", Base64.encode(peerNode.getPubKeyHash()), peerNode.getName()); } inviteForm.addChild("input", new String[] { "type", "name", "value" },
diff --git a/gshell/gshell-osgi/src/main/java/org/apache/felix/karaf/gshell/osgi/ListBundles.java b/gshell/gshell-osgi/src/main/java/org/apache/felix/karaf/gshell/osgi/ListBundles.java index 9722120b..5c699624 100644 --- a/gshell/gshell-osgi/src/main/java/org/apache/felix/karaf/gshell/osgi/ListBundles.java +++ b/gshell/gshell-osgi/src/main/java/org/apache/felix/karaf/gshell/osgi/ListBundles.java @@ -1,212 +1,212 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.felix.karaf.gshell.osgi; import org.apache.geronimo.gshell.clp.Option; import org.apache.felix.karaf.gshell.core.OsgiCommandSupport; import org.osgi.framework.Bundle; import org.osgi.framework.Constants; import org.osgi.framework.ServiceReference; import org.osgi.service.packageadmin.PackageAdmin; import org.osgi.service.startlevel.StartLevel; public class ListBundles extends OsgiCommandSupport { @Option(name = "-l", description = "Show locations") boolean showLoc; @Option(name = "-s", description = "Show symbolic name") boolean showSymbolic; @Option(name = "-u", description = "Show update") boolean showUpdate; private BlueprintListener blueprintListener; public BlueprintListener getBlueprintListener() { return blueprintListener; } public void setBlueprintListener(BlueprintListener blueprintListener) { this.blueprintListener = blueprintListener; } protected Object doExecute() throws Exception { ServiceReference ref = getBundleContext().getServiceReference(StartLevel.class.getName()); StartLevel sl = null; if (ref != null) { sl = (StartLevel) getBundleContext().getService(ref); } if (sl == null) { io.out.println("StartLevel service is unavailable."); } ServiceReference pkgref = getBundleContext().getServiceReference(PackageAdmin.class.getName()); PackageAdmin admin = null; if (pkgref != null) { admin = (PackageAdmin) getBundleContext().getService(pkgref); if (admin == null) { io.out.println("PackageAdmin service is unavailable."); } } Bundle[] bundles = getBundleContext().getBundles(); if (bundles != null) { // Display active start level. if (sl != null) { io.out.println("START LEVEL " + sl.getStartLevel()); } // Print column headers. String msg = " Name"; if (showLoc) { msg = " Location"; } else if (showSymbolic) { msg = " Symbolic name"; } else if (showUpdate) { msg = " Update location"; } String level = (sl == null) ? "" : " Level "; - io.out.println(" ID State Spring " + level + msg); + io.out.println(" ID State Blueprint " + level + msg); for (int i = 0; i < bundles.length; i++) { // Get the bundle name or location. String name = (String) bundles[i].getHeaders().get(Constants.BUNDLE_NAME); // If there is no name, then default to symbolic name. name = (name == null) ? bundles[i].getSymbolicName() : name; // If there is no symbolic name, resort to location. name = (name == null) ? bundles[i].getLocation() : name; // Overwrite the default value is the user specifically // requested to display one or the other. if (showLoc) { name = bundles[i].getLocation(); } else if (showSymbolic) { name = bundles[i].getSymbolicName(); name = (name == null) ? "<no symbolic name>" : name; } else if (showUpdate) { name = (String) bundles[i].getHeaders().get(Constants.BUNDLE_UPDATELOCATION); name = (name == null) ? bundles[i].getLocation() : name; } // Show bundle version if not showing location. String version = (String) bundles[i].getHeaders().get(Constants.BUNDLE_VERSION); name = (!showLoc && !showUpdate && (version != null)) ? name + " (" + version + ")" : name; long l = bundles[i].getBundleId(); String id = String.valueOf(l); if (sl == null) { level = "1"; } else { level = String.valueOf(sl.getBundleStartLevel(bundles[i])); } while (level.length() < 5) { level = " " + level; } while (id.length() < 4) { id = " " + id; } io.out.println("[" + id + "] [" + getStateString(bundles[i]) + "] [" + getBlueprintStateString(bundles[i]) + "] [" + level + "] " + name); if (admin != null) { Bundle[] fragments = admin.getFragments(bundles[i]); Bundle[] hosts = admin.getHosts(bundles[i]); if (fragments != null) { io.out.print(" Fragments: "); int ii = 0; for (Bundle fragment : fragments) { ii++; io.out.print(fragment.getBundleId()); if ((fragments.length > 1) && ii < (fragments.length)) { io.out.print(","); } } io.out.println(); } if (hosts != null) { io.out.print(" Hosts: "); int ii = 0; for (Bundle host : hosts) { ii++; io.out.print(host.getBundleId()); if ((hosts.length > 1) && ii < (hosts.length)) { io.out.print(","); } } io.out.println(); } } } } else { io.out.println("There are no installed bundles."); } getBundleContext().ungetService(ref); getBundleContext().ungetService(pkgref); return Result.SUCCESS; } public String getStateString(Bundle bundle) { int state = bundle.getState(); if (state == Bundle.ACTIVE) { return "Active "; } else if (state == Bundle.INSTALLED) { return "Installed "; } else if (state == Bundle.RESOLVED) { return "Resolved "; } else if (state == Bundle.STARTING) { return "Starting "; } else if (state == Bundle.STOPPING) { return "Stopping "; } else { return "Unknown "; } } public String getBlueprintStateString(Bundle bundle) { BlueprintListener.BlueprintState state = blueprintListener.getBlueprintState(bundle); switch (state) { case Creating: return "Creating "; case Created: return "Created "; case Destroying: return "Destroying "; case Destroyed: return "Destroyed "; case Failure: return "Failure "; case GracePeriod: return "GracePeriod"; case Waiting: return "Waiting "; default: return " "; } } }
true
true
protected Object doExecute() throws Exception { ServiceReference ref = getBundleContext().getServiceReference(StartLevel.class.getName()); StartLevel sl = null; if (ref != null) { sl = (StartLevel) getBundleContext().getService(ref); } if (sl == null) { io.out.println("StartLevel service is unavailable."); } ServiceReference pkgref = getBundleContext().getServiceReference(PackageAdmin.class.getName()); PackageAdmin admin = null; if (pkgref != null) { admin = (PackageAdmin) getBundleContext().getService(pkgref); if (admin == null) { io.out.println("PackageAdmin service is unavailable."); } } Bundle[] bundles = getBundleContext().getBundles(); if (bundles != null) { // Display active start level. if (sl != null) { io.out.println("START LEVEL " + sl.getStartLevel()); } // Print column headers. String msg = " Name"; if (showLoc) { msg = " Location"; } else if (showSymbolic) { msg = " Symbolic name"; } else if (showUpdate) { msg = " Update location"; } String level = (sl == null) ? "" : " Level "; io.out.println(" ID State Spring " + level + msg); for (int i = 0; i < bundles.length; i++) { // Get the bundle name or location. String name = (String) bundles[i].getHeaders().get(Constants.BUNDLE_NAME); // If there is no name, then default to symbolic name. name = (name == null) ? bundles[i].getSymbolicName() : name; // If there is no symbolic name, resort to location. name = (name == null) ? bundles[i].getLocation() : name; // Overwrite the default value is the user specifically // requested to display one or the other. if (showLoc) { name = bundles[i].getLocation(); } else if (showSymbolic) { name = bundles[i].getSymbolicName(); name = (name == null) ? "<no symbolic name>" : name; } else if (showUpdate) { name = (String) bundles[i].getHeaders().get(Constants.BUNDLE_UPDATELOCATION); name = (name == null) ? bundles[i].getLocation() : name; } // Show bundle version if not showing location. String version = (String) bundles[i].getHeaders().get(Constants.BUNDLE_VERSION); name = (!showLoc && !showUpdate && (version != null)) ? name + " (" + version + ")" : name; long l = bundles[i].getBundleId(); String id = String.valueOf(l); if (sl == null) { level = "1"; } else { level = String.valueOf(sl.getBundleStartLevel(bundles[i])); } while (level.length() < 5) { level = " " + level; } while (id.length() < 4) { id = " " + id; } io.out.println("[" + id + "] [" + getStateString(bundles[i]) + "] [" + getBlueprintStateString(bundles[i]) + "] [" + level + "] " + name); if (admin != null) { Bundle[] fragments = admin.getFragments(bundles[i]); Bundle[] hosts = admin.getHosts(bundles[i]); if (fragments != null) { io.out.print(" Fragments: "); int ii = 0; for (Bundle fragment : fragments) { ii++; io.out.print(fragment.getBundleId()); if ((fragments.length > 1) && ii < (fragments.length)) { io.out.print(","); } } io.out.println(); } if (hosts != null) { io.out.print(" Hosts: "); int ii = 0; for (Bundle host : hosts) { ii++; io.out.print(host.getBundleId()); if ((hosts.length > 1) && ii < (hosts.length)) { io.out.print(","); } } io.out.println(); } } } } else { io.out.println("There are no installed bundles."); } getBundleContext().ungetService(ref); getBundleContext().ungetService(pkgref); return Result.SUCCESS; }
protected Object doExecute() throws Exception { ServiceReference ref = getBundleContext().getServiceReference(StartLevel.class.getName()); StartLevel sl = null; if (ref != null) { sl = (StartLevel) getBundleContext().getService(ref); } if (sl == null) { io.out.println("StartLevel service is unavailable."); } ServiceReference pkgref = getBundleContext().getServiceReference(PackageAdmin.class.getName()); PackageAdmin admin = null; if (pkgref != null) { admin = (PackageAdmin) getBundleContext().getService(pkgref); if (admin == null) { io.out.println("PackageAdmin service is unavailable."); } } Bundle[] bundles = getBundleContext().getBundles(); if (bundles != null) { // Display active start level. if (sl != null) { io.out.println("START LEVEL " + sl.getStartLevel()); } // Print column headers. String msg = " Name"; if (showLoc) { msg = " Location"; } else if (showSymbolic) { msg = " Symbolic name"; } else if (showUpdate) { msg = " Update location"; } String level = (sl == null) ? "" : " Level "; io.out.println(" ID State Blueprint " + level + msg); for (int i = 0; i < bundles.length; i++) { // Get the bundle name or location. String name = (String) bundles[i].getHeaders().get(Constants.BUNDLE_NAME); // If there is no name, then default to symbolic name. name = (name == null) ? bundles[i].getSymbolicName() : name; // If there is no symbolic name, resort to location. name = (name == null) ? bundles[i].getLocation() : name; // Overwrite the default value is the user specifically // requested to display one or the other. if (showLoc) { name = bundles[i].getLocation(); } else if (showSymbolic) { name = bundles[i].getSymbolicName(); name = (name == null) ? "<no symbolic name>" : name; } else if (showUpdate) { name = (String) bundles[i].getHeaders().get(Constants.BUNDLE_UPDATELOCATION); name = (name == null) ? bundles[i].getLocation() : name; } // Show bundle version if not showing location. String version = (String) bundles[i].getHeaders().get(Constants.BUNDLE_VERSION); name = (!showLoc && !showUpdate && (version != null)) ? name + " (" + version + ")" : name; long l = bundles[i].getBundleId(); String id = String.valueOf(l); if (sl == null) { level = "1"; } else { level = String.valueOf(sl.getBundleStartLevel(bundles[i])); } while (level.length() < 5) { level = " " + level; } while (id.length() < 4) { id = " " + id; } io.out.println("[" + id + "] [" + getStateString(bundles[i]) + "] [" + getBlueprintStateString(bundles[i]) + "] [" + level + "] " + name); if (admin != null) { Bundle[] fragments = admin.getFragments(bundles[i]); Bundle[] hosts = admin.getHosts(bundles[i]); if (fragments != null) { io.out.print(" Fragments: "); int ii = 0; for (Bundle fragment : fragments) { ii++; io.out.print(fragment.getBundleId()); if ((fragments.length > 1) && ii < (fragments.length)) { io.out.print(","); } } io.out.println(); } if (hosts != null) { io.out.print(" Hosts: "); int ii = 0; for (Bundle host : hosts) { ii++; io.out.print(host.getBundleId()); if ((hosts.length > 1) && ii < (hosts.length)) { io.out.print(","); } } io.out.println(); } } } } else { io.out.println("There are no installed bundles."); } getBundleContext().ungetService(ref); getBundleContext().ungetService(pkgref); return Result.SUCCESS; }
diff --git a/src/org/geometerplus/zlibrary/core/network/ZLNetworkManager.java b/src/org/geometerplus/zlibrary/core/network/ZLNetworkManager.java index d7ee5b0d..8e60789c 100644 --- a/src/org/geometerplus/zlibrary/core/network/ZLNetworkManager.java +++ b/src/org/geometerplus/zlibrary/core/network/ZLNetworkManager.java @@ -1,225 +1,225 @@ /* * Copyright (C) 2010 Geometer Plus <[email protected]> * * 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 * (at your option) 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., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ package org.geometerplus.zlibrary.core.network; import java.util.*; import java.io.*; import java.net.*; import javax.net.ssl.*; import java.security.GeneralSecurityException; import java.security.cert.*; import org.geometerplus.zlibrary.core.util.ZLNetworkUtil; import org.geometerplus.zlibrary.core.filesystem.ZLResourceFile; public class ZLNetworkManager { private static ZLNetworkManager ourManager; public static ZLNetworkManager Instance() { if (ourManager == null) { ourManager = new ZLNetworkManager(); } return ourManager; } private String doBeforeRequest(ZLNetworkRequest request) { final String err = request.doBefore(); if (err != null) { return err; } /*if (request.isInstanceOf(ZLNetworkPostRequest::TYPE_ID)) { return doBeforePostRequest((ZLNetworkPostRequest &) request); }*/ return null; } private String setCommonHTTPOptions(ZLNetworkRequest request, HttpURLConnection httpConnection) { httpConnection.setInstanceFollowRedirects(request.FollowRedirects); httpConnection.setConnectTimeout(15000); // FIXME: hardcoded timeout value!!! httpConnection.setReadTimeout(30000); // FIXME: hardcoded timeout value!!! //httpConnection.setRequestProperty("Connection", "Close"); httpConnection.setRequestProperty("User-Agent", ZLNetworkUtil.getUserAgent()); httpConnection.setAllowUserInteraction(false); if (httpConnection instanceof HttpsURLConnection) { HttpsURLConnection httpsConnection = (HttpsURLConnection) httpConnection; if (request.SSLCertificate != null) { InputStream stream; try { ZLResourceFile file = ZLResourceFile.createResourceFile(request.SSLCertificate); stream = file.getInputStream(); } catch (IOException ex) { return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_BAD_FILE, request.SSLCertificate); } try { TrustManager[] managers = new TrustManager[] { new ZLX509TrustManager(stream) }; SSLContext context = SSLContext.getInstance("TLS"); context.init(null, managers, null); httpsConnection.setSSLSocketFactory(context.getSocketFactory()); } catch (CertificateExpiredException ex) { return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_EXPIRED, request.SSLCertificate); } catch (CertificateNotYetValidException ex) { return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_NOT_YET_VALID, request.SSLCertificate); } catch (CertificateException ex) { return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_BAD_FILE, request.SSLCertificate); } catch (GeneralSecurityException ex) { return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_SUBSYSTEM); } finally { try { stream.close(); } catch (IOException ex) { } } } } // TODO: handle Authentication return null; } public String perform(ZLNetworkRequest request) { - boolean sucess = false; + boolean success = false; try { final String error = doBeforeRequest(request); if (error != null) { return error; } HttpURLConnection httpConnection = null; int response = -1; for (int retryCounter = 0; retryCounter < 3 && response == -1; ++retryCounter) { final URL url = new URL(request.URL); final URLConnection connection = url.openConnection(); if (!(connection instanceof HttpURLConnection)) { return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_UNSUPPORTED_PROTOCOL); } httpConnection = (HttpURLConnection) connection; String err = setCommonHTTPOptions(request, httpConnection); if (err != null) { return err; } httpConnection.connect(); response = httpConnection.getResponseCode(); } if (response == HttpURLConnection.HTTP_OK) { InputStream stream = httpConnection.getInputStream(); try { final String err = request.doHandleStream(httpConnection, stream); if (err != null) { return err; } } finally { stream.close(); } - sucess = true; + success = true; } else { if (response == HttpURLConnection.HTTP_UNAUTHORIZED) { return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_AUTHENTICATION_FAILED); } else { return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SOMETHING_WRONG, ZLNetworkUtil.hostFromUrl(request.URL)); } } } catch (SSLHandshakeException ex) { return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_CONNECT, ZLNetworkUtil.hostFromUrl(request.URL)); } catch (SSLKeyException ex) { return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_BAD_KEY, ZLNetworkUtil.hostFromUrl(request.URL)); } catch (SSLPeerUnverifiedException ex) { return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_PEER_UNVERIFIED, ZLNetworkUtil.hostFromUrl(request.URL)); } catch (SSLProtocolException ex) { return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_PROTOCOL_ERROR); } catch (SSLException ex) { return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_SUBSYSTEM); } catch (ConnectException ex) { return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_CONNECTION_REFUSED, ZLNetworkUtil.hostFromUrl(request.URL)); } catch (NoRouteToHostException ex) { return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_HOST_CANNOT_BE_REACHED, ZLNetworkUtil.hostFromUrl(request.URL)); } catch (UnknownHostException ex) { return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_RESOLVE_HOST, ZLNetworkUtil.hostFromUrl(request.URL)); } catch (MalformedURLException ex) { return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_INVALID_URL); } catch (SocketTimeoutException ex) { return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_TIMEOUT); } catch (IOException ex) { ex.printStackTrace(); return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SOMETHING_WRONG, ZLNetworkUtil.hostFromUrl(request.URL)); } finally { - final String err = request.doAfter(sucess); - if (sucess && err != null) { + final String err = request.doAfter(success); + if (success && err != null) { return err; } } return null; } public String perform(List<ZLNetworkRequest> requests) { if (requests.size() == 0) { return ""; } if (requests.size() == 1) { return perform(requests.get(0)); } HashSet<String> errors = new HashSet<String>(); // TODO: implement concurrent execution !!! for (ZLNetworkRequest r: requests) { final String e = perform(r); if (e != null && !errors.contains(e)) { errors.add(e); } } if (errors.size() == 0) { return null; } StringBuilder message = new StringBuilder(); for (String e: errors) { if (message.length() != 0) { message.append(", "); } message.append(e); } return message.toString(); } public final String downloadToFile(String url, final File outFile) { return downloadToFile(url, outFile, 8192); } public final String downloadToFile(String url, final File outFile, final int bufferSize) { return perform(new ZLNetworkRequest(url) { public String handleStream(URLConnection connection, InputStream inputStream) throws IOException { OutputStream outStream = new FileOutputStream(outFile); try { final byte[] buffer = new byte[bufferSize]; while (true) { final int size = inputStream.read(buffer); if (size <= 0) { break; } outStream.write(buffer, 0, size); } } finally { outStream.close(); } return null; } }); } }
false
true
public String perform(ZLNetworkRequest request) { boolean sucess = false; try { final String error = doBeforeRequest(request); if (error != null) { return error; } HttpURLConnection httpConnection = null; int response = -1; for (int retryCounter = 0; retryCounter < 3 && response == -1; ++retryCounter) { final URL url = new URL(request.URL); final URLConnection connection = url.openConnection(); if (!(connection instanceof HttpURLConnection)) { return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_UNSUPPORTED_PROTOCOL); } httpConnection = (HttpURLConnection) connection; String err = setCommonHTTPOptions(request, httpConnection); if (err != null) { return err; } httpConnection.connect(); response = httpConnection.getResponseCode(); } if (response == HttpURLConnection.HTTP_OK) { InputStream stream = httpConnection.getInputStream(); try { final String err = request.doHandleStream(httpConnection, stream); if (err != null) { return err; } } finally { stream.close(); } sucess = true; } else { if (response == HttpURLConnection.HTTP_UNAUTHORIZED) { return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_AUTHENTICATION_FAILED); } else { return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SOMETHING_WRONG, ZLNetworkUtil.hostFromUrl(request.URL)); } } } catch (SSLHandshakeException ex) { return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_CONNECT, ZLNetworkUtil.hostFromUrl(request.URL)); } catch (SSLKeyException ex) { return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_BAD_KEY, ZLNetworkUtil.hostFromUrl(request.URL)); } catch (SSLPeerUnverifiedException ex) { return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_PEER_UNVERIFIED, ZLNetworkUtil.hostFromUrl(request.URL)); } catch (SSLProtocolException ex) { return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_PROTOCOL_ERROR); } catch (SSLException ex) { return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_SUBSYSTEM); } catch (ConnectException ex) { return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_CONNECTION_REFUSED, ZLNetworkUtil.hostFromUrl(request.URL)); } catch (NoRouteToHostException ex) { return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_HOST_CANNOT_BE_REACHED, ZLNetworkUtil.hostFromUrl(request.URL)); } catch (UnknownHostException ex) { return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_RESOLVE_HOST, ZLNetworkUtil.hostFromUrl(request.URL)); } catch (MalformedURLException ex) { return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_INVALID_URL); } catch (SocketTimeoutException ex) { return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_TIMEOUT); } catch (IOException ex) { ex.printStackTrace(); return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SOMETHING_WRONG, ZLNetworkUtil.hostFromUrl(request.URL)); } finally { final String err = request.doAfter(sucess); if (sucess && err != null) { return err; } } return null; }
public String perform(ZLNetworkRequest request) { boolean success = false; try { final String error = doBeforeRequest(request); if (error != null) { return error; } HttpURLConnection httpConnection = null; int response = -1; for (int retryCounter = 0; retryCounter < 3 && response == -1; ++retryCounter) { final URL url = new URL(request.URL); final URLConnection connection = url.openConnection(); if (!(connection instanceof HttpURLConnection)) { return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_UNSUPPORTED_PROTOCOL); } httpConnection = (HttpURLConnection) connection; String err = setCommonHTTPOptions(request, httpConnection); if (err != null) { return err; } httpConnection.connect(); response = httpConnection.getResponseCode(); } if (response == HttpURLConnection.HTTP_OK) { InputStream stream = httpConnection.getInputStream(); try { final String err = request.doHandleStream(httpConnection, stream); if (err != null) { return err; } } finally { stream.close(); } success = true; } else { if (response == HttpURLConnection.HTTP_UNAUTHORIZED) { return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_AUTHENTICATION_FAILED); } else { return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SOMETHING_WRONG, ZLNetworkUtil.hostFromUrl(request.URL)); } } } catch (SSLHandshakeException ex) { return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_CONNECT, ZLNetworkUtil.hostFromUrl(request.URL)); } catch (SSLKeyException ex) { return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_BAD_KEY, ZLNetworkUtil.hostFromUrl(request.URL)); } catch (SSLPeerUnverifiedException ex) { return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_PEER_UNVERIFIED, ZLNetworkUtil.hostFromUrl(request.URL)); } catch (SSLProtocolException ex) { return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_PROTOCOL_ERROR); } catch (SSLException ex) { return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_SUBSYSTEM); } catch (ConnectException ex) { return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_CONNECTION_REFUSED, ZLNetworkUtil.hostFromUrl(request.URL)); } catch (NoRouteToHostException ex) { return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_HOST_CANNOT_BE_REACHED, ZLNetworkUtil.hostFromUrl(request.URL)); } catch (UnknownHostException ex) { return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_RESOLVE_HOST, ZLNetworkUtil.hostFromUrl(request.URL)); } catch (MalformedURLException ex) { return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_INVALID_URL); } catch (SocketTimeoutException ex) { return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_TIMEOUT); } catch (IOException ex) { ex.printStackTrace(); return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SOMETHING_WRONG, ZLNetworkUtil.hostFromUrl(request.URL)); } finally { final String err = request.doAfter(success); if (success && err != null) { return err; } } return null; }
diff --git a/xjc/src/com/sun/tools/xjc/reader/internalizer/NamespaceContextImpl.java b/xjc/src/com/sun/tools/xjc/reader/internalizer/NamespaceContextImpl.java index dbeb2953..f478c965 100644 --- a/xjc/src/com/sun/tools/xjc/reader/internalizer/NamespaceContextImpl.java +++ b/xjc/src/com/sun/tools/xjc/reader/internalizer/NamespaceContextImpl.java @@ -1,90 +1,93 @@ package com.sun.tools.xjc.reader.internalizer; import java.util.Iterator; import javax.xml.namespace.NamespaceContext; import com.sun.xml.bind.v2.WellKnownNamespace; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; /** * Implements {@link NamespaceContext} by looking at the in-scope * namespace binding of a DOM element. * * @author Kohsuke Kawaguchi */ final class NamespaceContextImpl implements NamespaceContext { private final Element e; public NamespaceContextImpl(Element e) { this.e = e; } /* * Copyright 1999-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public String getNamespaceURI(String prefix) { Node parent = e; String namespace = null; + final String prefixColon = prefix + ':'; if (prefix.equals("xml")) { namespace = WellKnownNamespace.XML_NAMESPACE_URI; } else { int type; while ((null != parent) && (null == namespace) && (((type = parent.getNodeType()) == Node.ELEMENT_NODE) || (type == Node.ENTITY_REFERENCE_NODE))) { if (type == Node.ELEMENT_NODE) { - if (parent.getNodeName().indexOf(prefix + ':') == 0) + if (parent.getNodeName().startsWith(prefixColon)) return parent.getNamespaceURI(); NamedNodeMap nnm = parent.getAttributes(); for (int i = 0; i < nnm.getLength(); i++) { Node attr = nnm.item(i); String aname = attr.getNodeName(); boolean isPrefix = aname.startsWith("xmlns:"); if (isPrefix || aname.equals("xmlns")) { int index = aname.indexOf(':'); String p = isPrefix ? aname.substring(index + 1) : ""; if (p.equals(prefix)) { namespace = attr.getNodeValue(); break; } } } } parent = parent.getParentNode(); } } + if(prefix.equals("")) + return ""; // default namespace return namespace; } public String getPrefix(String namespaceURI) { throw new UnsupportedOperationException(); } public Iterator getPrefixes(String namespaceURI) { throw new UnsupportedOperationException(); } }
false
true
public String getNamespaceURI(String prefix) { Node parent = e; String namespace = null; if (prefix.equals("xml")) { namespace = WellKnownNamespace.XML_NAMESPACE_URI; } else { int type; while ((null != parent) && (null == namespace) && (((type = parent.getNodeType()) == Node.ELEMENT_NODE) || (type == Node.ENTITY_REFERENCE_NODE))) { if (type == Node.ELEMENT_NODE) { if (parent.getNodeName().indexOf(prefix + ':') == 0) return parent.getNamespaceURI(); NamedNodeMap nnm = parent.getAttributes(); for (int i = 0; i < nnm.getLength(); i++) { Node attr = nnm.item(i); String aname = attr.getNodeName(); boolean isPrefix = aname.startsWith("xmlns:"); if (isPrefix || aname.equals("xmlns")) { int index = aname.indexOf(':'); String p = isPrefix ? aname.substring(index + 1) : ""; if (p.equals(prefix)) { namespace = attr.getNodeValue(); break; } } } } parent = parent.getParentNode(); } } return namespace; }
public String getNamespaceURI(String prefix) { Node parent = e; String namespace = null; final String prefixColon = prefix + ':'; if (prefix.equals("xml")) { namespace = WellKnownNamespace.XML_NAMESPACE_URI; } else { int type; while ((null != parent) && (null == namespace) && (((type = parent.getNodeType()) == Node.ELEMENT_NODE) || (type == Node.ENTITY_REFERENCE_NODE))) { if (type == Node.ELEMENT_NODE) { if (parent.getNodeName().startsWith(prefixColon)) return parent.getNamespaceURI(); NamedNodeMap nnm = parent.getAttributes(); for (int i = 0; i < nnm.getLength(); i++) { Node attr = nnm.item(i); String aname = attr.getNodeName(); boolean isPrefix = aname.startsWith("xmlns:"); if (isPrefix || aname.equals("xmlns")) { int index = aname.indexOf(':'); String p = isPrefix ? aname.substring(index + 1) : ""; if (p.equals(prefix)) { namespace = attr.getNodeValue(); break; } } } } parent = parent.getParentNode(); } } if(prefix.equals("")) return ""; // default namespace return namespace; }
diff --git a/src/dk/itu/big_red/editors/signature/SignatureEditor.java b/src/dk/itu/big_red/editors/signature/SignatureEditor.java index 83cb8829..7a87c219 100644 --- a/src/dk/itu/big_red/editors/signature/SignatureEditor.java +++ b/src/dk/itu/big_red/editors/signature/SignatureEditor.java @@ -1,572 +1,572 @@ package dk.itu.big_red.editors.signature; import java.beans.PropertyChangeListener; import java.util.EventObject; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.draw2d.ColorConstants; import org.eclipse.draw2d.geometry.PointList; import org.eclipse.gef.commands.CommandStackListener; import org.eclipse.jface.preference.ColorSelector; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.ISelection; import org.eclipse.swt.SWT; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.layout.RowLayout; 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.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeItem; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorSite; import org.eclipse.ui.ISelectionListener; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchPartConstants; import org.eclipse.ui.PartInitException; import org.eclipse.ui.part.EditorPart; import org.eclipse.ui.part.FileEditorInput; import dk.itu.big_red.model.Control; import dk.itu.big_red.model.Control.Kind; import dk.itu.big_red.model.Control.Shape; import dk.itu.big_red.model.Colourable; import dk.itu.big_red.model.PortSpec; import dk.itu.big_red.model.Signature; import dk.itu.big_red.model.changes.ChangeRejectedException; import dk.itu.big_red.model.import_export.SignatureXMLExport; import dk.itu.big_red.model.import_export.SignatureXMLImport; import dk.itu.big_red.utilities.Colour; import dk.itu.big_red.utilities.Lists; import dk.itu.big_red.utilities.io.IOAdapter; import dk.itu.big_red.utilities.resources.Project; import dk.itu.big_red.utilities.ui.UI; public class SignatureEditor extends EditorPart implements CommandStackListener, ISelectionListener, PropertyChangeListener { public static final String ID = "dk.itu.big_red.SignatureEditor"; public SignatureEditor() { } @Override public void doSave(IProgressMonitor monitor) { try { IOAdapter io = new IOAdapter(); FileEditorInput i = (FileEditorInput)getEditorInput(); SignatureXMLExport ex = new SignatureXMLExport(); ex.setModel(model).setOutputStream(io.getOutputStream()). exportObject(); Project.setContents(i.getFile(), io.getInputStream()); setDirty(false); } catch (Exception ex) { if (monitor != null) monitor.setCanceled(true); UI.openError("Unable to save the document.", ex); } } @Override public void doSaveAs() { // TODO Auto-generated method stub } @Override public void init(IEditorSite site, IEditorInput input) throws PartInitException { setSite(site); setInput(input); firePropertyChange(IWorkbenchPartConstants.PROP_INPUT); getSite().getWorkbenchWindow().getSelectionService().addSelectionListener(this); } protected boolean dirty = false; protected void setDirty(boolean dirty) { if (this.dirty != dirty) { this.dirty = dirty; firePropertyChange(IWorkbenchPartConstants.PROP_DIRTY); } } @Override public boolean isDirty() { return dirty; } @Override public boolean isSaveAsAllowed() { // TODO Auto-generated method stub return false; } private Signature model = null; private dk.itu.big_red.model.Control currentControl; private Tree controls; private TreeItem currentControlItem; private Button addControl, removeControl; private Text name, label; private SignatureEditorPolygonCanvas appearance; private Button ovalMode, polygonMode, resizable; private Button activeKind, atomicKind, passiveKind; private Label appearanceDescription, kindLabel, labelLabel, outlineLabel, fillLabel, nameLabel, appearanceLabel; private ColorSelector outline, fill; protected void setControl(Control c) { if (currentControl != null) currentControl.removePropertyChangeListener(this); currentControl = c; c.addPropertyChangeListener(this); controlToFields(); } private boolean uiUpdateInProgress = false; protected void controlToFields() { uiUpdateInProgress = true; boolean polygon = (currentControl.getShape() == Shape.POLYGON); label.setText(currentControl.getLabel()); name.setText(currentControl.getName()); appearance.setMode(polygon ? Shape.POLYGON : Shape.OVAL); if (polygon) appearance.setPoints(currentControl.getPoints()); appearance.setPorts(currentControl.getPorts()); resizable.setSelection(currentControl.isResizable()); currentControlItem.setText(currentControl.getName()); ovalMode.setSelection(!polygon); polygonMode.setSelection(polygon); outline.setColorValue(currentControl.getOutlineColour().getRGB()); fill.setColorValue(currentControl.getFillColour().getRGB()); activeKind.setSelection(currentControl.getKind() == Kind.ACTIVE); atomicKind.setSelection(currentControl.getKind() == Kind.ATOMIC); passiveKind.setSelection(currentControl.getKind() == Kind.PASSIVE); uiUpdateInProgress = false; } /** * Indicates whether or not changes made to the UI should be propagated * to the current {@link Control}. * @return <code>true</code> if the {@link Control} is valid and is not * itself currently changing the UI, or <code>false</code> otherwise */ private boolean shouldPropagateUI() { return (!uiUpdateInProgress && currentControl != null); } private static Font smiff; @Override public void createPartControl(Composite parent) { GridLayout layout = new GridLayout(2, false); parent.setLayout(layout); Composite left = new Composite(parent, 0); left.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); GridLayout leftLayout = new GridLayout(1, false); left.setLayout(leftLayout); controls = new Tree(left, SWT.SINGLE | SWT.BORDER | SWT.VIRTUAL); GridData controlsLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true); controlsLayoutData.widthHint = 100; controls.setLayoutData(controlsLayoutData); controls.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { currentControlItem = controls.getSelection()[0]; setControl((Control)UI.data(currentControlItem, controlKey)); name.setFocus(); setEnablement(true); } @Override public void widgetDefaultSelected(SelectionEvent e) { widgetSelected(e); } }); Composite controlButtons = new Composite(left, SWT.NONE); RowLayout controlButtonsLayout = new RowLayout(); controlButtons.setLayout(controlButtonsLayout); controlButtons.setLayoutData(new GridData(SWT.END, SWT.TOP, true, false)); addControl = new Button(controlButtons, SWT.NONE); addControl.setImage(UI.getImage(ISharedImages.IMG_OBJ_ADD)); addControl.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { Control c = new Control(); model.addControl(c); currentControlItem = UI.data(new TreeItem(controls, SWT.NONE), controlKey, c); setControl(c); controls.select(currentControlItem); name.setFocus(); setEnablement(true); setDirty(true); } @Override public void widgetDefaultSelected(SelectionEvent e) { return; } }); removeControl = new Button(controlButtons, SWT.NONE); removeControl.setImage(UI.getImage(ISharedImages.IMG_ELCL_REMOVE)); removeControl.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { model.removeControl(currentControl); currentControlItem.dispose(); if (controls.getItemCount() > 0) { controls.select(controls.getItem(0)); currentControlItem = controls.getItem(0); currentControl = (Control)UI.data(currentControlItem, controlKey); controlToFields(); name.setFocus(); } else setEnablement(false); setDirty(true); } @Override public void widgetDefaultSelected(SelectionEvent e) { widgetSelected(e); } }); Composite right = new Composite(parent, 0); right.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); GridLayout rightLayout = new GridLayout(2, false); right.setLayout(rightLayout); abstract class TextListener implements SelectionListener, FocusListener { abstract void go(); @Override public void focusGained(FocusEvent e) { /* nothing */ } @Override public void focusLost(FocusEvent e) { if (shouldPropagateUI()) go(); } @Override public void widgetSelected(SelectionEvent e) { /* nothing */ } @Override public void widgetDefaultSelected(SelectionEvent e) { if (shouldPropagateUI()) go(); } } TextListener nameListener = new TextListener() { @Override void go() { currentControl.setName(name.getText()); } }; nameLabel = UI.newLabel(right, SWT.NONE, "Name:"); name = new Text(right, SWT.BORDER); name.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false)); name.addSelectionListener(nameListener); name.addFocusListener(nameListener); TextListener labelListener = new TextListener() { @Override void go() { currentControl.setLabel(label.getText()); } }; labelLabel = UI.newLabel(right, SWT.NONE, "Label:"); label = new Text(right, SWT.BORDER); label.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false)); label.addSelectionListener(labelListener); label.addFocusListener(labelListener); kindLabel = UI.newLabel(right, SWT.NONE, "Kind:"); Composite kindGroup = new Composite(right, SWT.NONE); kindGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); kindGroup.setLayout(new RowLayout(SWT.HORIZONTAL)); atomicKind = UI.newButton(kindGroup, SWT.RADIO, "Atomic"); atomicKind.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (shouldPropagateUI()) currentControl.setKind(Kind.ATOMIC); } }); - activeKind = UI.newButton(kindGroup, SWT.RADIO, "Passive"); + activeKind = UI.newButton(kindGroup, SWT.RADIO, "Active"); activeKind.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (shouldPropagateUI()) currentControl.setKind(Kind.ACTIVE); } }); passiveKind = UI.newButton(kindGroup, SWT.RADIO, "Passive"); passiveKind.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (shouldPropagateUI()) currentControl.setKind(Kind.PASSIVE); } }); appearanceLabel = UI.newLabel(right, SWT.NONE, "Appearance:"); GridData appearanceLabelLayoutData = new GridData(SWT.FILL, SWT.FILL, false, true); appearanceLabel.setLayoutData(appearanceLabelLayoutData); Composite appearanceGroup = new Composite(right, SWT.NONE); GridData appearanceGroupLayoutData = new GridData(SWT.FILL, SWT.FILL, false, true); appearanceGroup.setLayoutData(appearanceGroupLayoutData); GridLayout appearanceGroupLayout = new GridLayout(1, false); appearanceGroup.setLayout(appearanceGroupLayout); /* XXX: the addition of this row leads to really weird oversizing of * the polygon canvas! */ Composite firstLine = new Composite(appearanceGroup, SWT.NONE); firstLine.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); firstLine.setLayout(new RowLayout(SWT.HORIZONTAL)); ovalMode = UI.newButton(firstLine, SWT.RADIO, "Oval"); ovalMode.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (shouldPropagateUI()) currentControl.setShape(Shape.OVAL); } }); polygonMode = UI.newButton(firstLine, SWT.RADIO, "Polygon"); polygonMode.setSelection(true); polygonMode.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (shouldPropagateUI()) currentControl.setShape(Shape.POLYGON); } }); resizable = UI.newButton(firstLine, SWT.CHECK, "Resizable?"); resizable.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (shouldPropagateUI()) currentControl.setResizable(resizable.getSelection()); } }); appearance = new SignatureEditorPolygonCanvas(appearanceGroup, SWT.BORDER); GridData appearanceLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true); appearanceLayoutData.widthHint = 100; appearanceLayoutData.heightHint = 100; appearance.setLayoutData(appearanceLayoutData); appearance.setBackground(ColorConstants.listBackground); appearance.addPortListener(new PortListener() { @Override public void portChange(PortEvent e) { if (!shouldPropagateUI()) return; for (PortSpec p : Lists.copy(currentControl.getPorts())) currentControl.removePort(p.getName()); for (PortSpec p : appearance.getPorts()) currentControl.addPort(p); } }); appearance.addPointListener(new PointListener() { @Override public void pointChange(PointEvent e) { if (!shouldPropagateUI()) return; currentControl.setPoints(appearance.getPoints().getCopy()); } }); if (smiff == null) smiff = UI.tweakFont(appearanceLabel.getFont(), 8, SWT.ITALIC); appearanceDescription = UI.newLabel(appearanceGroup, SWT.CENTER | SWT.WRAP, "Click to add a new point. Double-click a point to delete it. " + "Move elements by clicking and dragging. " + "Right-click for more options."); GridData appearanceDescriptionData = new GridData(); appearanceDescriptionData.verticalAlignment = SWT.TOP; appearanceDescriptionData.horizontalAlignment = SWT.FILL; appearanceDescriptionData.widthHint = 0; appearanceDescription.setLayoutData(appearanceDescriptionData); appearanceDescription.setFont(smiff); outlineLabel = UI.newLabel(right, SWT.NONE, "Outline:"); outline = new ColorSelector(right); outline.getButton().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); outline.addListener(new IPropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent event) { if (!shouldPropagateUI()) return; try { model.tryApplyChange( currentControl.changeOutlineColour( new Colour(outline.getColorValue()))); } catch (ChangeRejectedException cre) { cre.printStackTrace(); } } }); fillLabel = UI.newLabel(right, SWT.NONE, "Fill:"); fill = new ColorSelector(right); fill.getButton().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); fill.addListener(new IPropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent event) { if (!shouldPropagateUI()) return; try { model.tryApplyChange( currentControl.changeFillColour( new Colour(fill.getColorValue()))); } catch (ChangeRejectedException cre) { cre.printStackTrace(); } } }); setEnablement(false); initialiseSignatureEditor(); } private void setEnablement(boolean enabled) { UI.setEnabled(enabled, name, label, appearance, appearanceDescription, resizable, atomicKind, activeKind, passiveKind, outline.getButton(), outlineLabel, fill.getButton(), ovalMode, fillLabel, polygonMode, kindLabel, nameLabel, appearanceLabel, labelLabel); } private static final String controlKey = ID + ".control"; private void initialiseSignatureEditor() { IEditorInput input = getEditorInput(); setPartName(input.getName()); if (input instanceof FileEditorInput) { FileEditorInput fi = (FileEditorInput)input; try { model = SignatureXMLImport.importFile(fi.getFile()); } catch (Exception e) { e.printStackTrace(); model = new Signature(); } } for (dk.itu.big_red.model.Control c : model.getControls()) UI.data(new TreeItem(controls, 0), controlKey, c).setText(c.getName()); } @Override public void setFocus() { // TODO Auto-generated method stub } @Override public void commandStackChanged(EventObject event) { // TODO Auto-generated method stub } @Override public void selectionChanged(IWorkbenchPart part, ISelection selection) { // TODO Auto-generated method stub } @Override public void propertyChange(java.beans.PropertyChangeEvent evt) { if (evt.getSource().equals(currentControl)) { if (uiUpdateInProgress) return; uiUpdateInProgress = true; try { String propertyName = evt.getPropertyName(); Object newValue = evt.getNewValue(); if (propertyName.equals(Control.PROPERTY_LABEL)) { label.setText((String)newValue); } else if (propertyName.equals(Control.PROPERTY_NAME)) { name.setText((String)newValue); currentControlItem.setText((String)newValue); } else if (propertyName.equals(Control.PROPERTY_SHAPE)) { appearance.setMode((Shape)newValue); ovalMode.setSelection(Shape.OVAL.equals(newValue)); polygonMode.setSelection(Shape.POLYGON.equals(newValue)); } else if (propertyName.equals(Control.PROPERTY_POINTS)) { if (appearance.getMode() == Shape.POLYGON) appearance.setPoints((PointList)newValue); } else if (propertyName.equals(Control.PROPERTY_PORT)) { /* XXX: add and remove rather than overwriting */ appearance.setPorts(currentControl.getPorts()); } else if (propertyName.equals(Control.PROPERTY_RESIZABLE)) { resizable.setSelection((Boolean)newValue); } else if (propertyName.equals(Colourable.PROPERTY_FILL)) { fill.setColorValue(((Colour)newValue).getRGB()); } else if (propertyName.equals(Colourable.PROPERTY_OUTLINE)) { outline.setColorValue(((Colour)newValue).getRGB()); } else if (propertyName.equals(Control.PROPERTY_KIND)) { activeKind.setSelection(Kind.ACTIVE.equals(newValue)); atomicKind.setSelection(Kind.ATOMIC.equals(newValue)); passiveKind.setSelection(Kind.PASSIVE.equals(newValue)); } } finally { uiUpdateInProgress = false; } } setDirty(true); } }
true
true
public void createPartControl(Composite parent) { GridLayout layout = new GridLayout(2, false); parent.setLayout(layout); Composite left = new Composite(parent, 0); left.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); GridLayout leftLayout = new GridLayout(1, false); left.setLayout(leftLayout); controls = new Tree(left, SWT.SINGLE | SWT.BORDER | SWT.VIRTUAL); GridData controlsLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true); controlsLayoutData.widthHint = 100; controls.setLayoutData(controlsLayoutData); controls.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { currentControlItem = controls.getSelection()[0]; setControl((Control)UI.data(currentControlItem, controlKey)); name.setFocus(); setEnablement(true); } @Override public void widgetDefaultSelected(SelectionEvent e) { widgetSelected(e); } }); Composite controlButtons = new Composite(left, SWT.NONE); RowLayout controlButtonsLayout = new RowLayout(); controlButtons.setLayout(controlButtonsLayout); controlButtons.setLayoutData(new GridData(SWT.END, SWT.TOP, true, false)); addControl = new Button(controlButtons, SWT.NONE); addControl.setImage(UI.getImage(ISharedImages.IMG_OBJ_ADD)); addControl.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { Control c = new Control(); model.addControl(c); currentControlItem = UI.data(new TreeItem(controls, SWT.NONE), controlKey, c); setControl(c); controls.select(currentControlItem); name.setFocus(); setEnablement(true); setDirty(true); } @Override public void widgetDefaultSelected(SelectionEvent e) { return; } }); removeControl = new Button(controlButtons, SWT.NONE); removeControl.setImage(UI.getImage(ISharedImages.IMG_ELCL_REMOVE)); removeControl.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { model.removeControl(currentControl); currentControlItem.dispose(); if (controls.getItemCount() > 0) { controls.select(controls.getItem(0)); currentControlItem = controls.getItem(0); currentControl = (Control)UI.data(currentControlItem, controlKey); controlToFields(); name.setFocus(); } else setEnablement(false); setDirty(true); } @Override public void widgetDefaultSelected(SelectionEvent e) { widgetSelected(e); } }); Composite right = new Composite(parent, 0); right.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); GridLayout rightLayout = new GridLayout(2, false); right.setLayout(rightLayout); abstract class TextListener implements SelectionListener, FocusListener { abstract void go(); @Override public void focusGained(FocusEvent e) { /* nothing */ } @Override public void focusLost(FocusEvent e) { if (shouldPropagateUI()) go(); } @Override public void widgetSelected(SelectionEvent e) { /* nothing */ } @Override public void widgetDefaultSelected(SelectionEvent e) { if (shouldPropagateUI()) go(); } } TextListener nameListener = new TextListener() { @Override void go() { currentControl.setName(name.getText()); } }; nameLabel = UI.newLabel(right, SWT.NONE, "Name:"); name = new Text(right, SWT.BORDER); name.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false)); name.addSelectionListener(nameListener); name.addFocusListener(nameListener); TextListener labelListener = new TextListener() { @Override void go() { currentControl.setLabel(label.getText()); } }; labelLabel = UI.newLabel(right, SWT.NONE, "Label:"); label = new Text(right, SWT.BORDER); label.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false)); label.addSelectionListener(labelListener); label.addFocusListener(labelListener); kindLabel = UI.newLabel(right, SWT.NONE, "Kind:"); Composite kindGroup = new Composite(right, SWT.NONE); kindGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); kindGroup.setLayout(new RowLayout(SWT.HORIZONTAL)); atomicKind = UI.newButton(kindGroup, SWT.RADIO, "Atomic"); atomicKind.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (shouldPropagateUI()) currentControl.setKind(Kind.ATOMIC); } }); activeKind = UI.newButton(kindGroup, SWT.RADIO, "Passive"); activeKind.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (shouldPropagateUI()) currentControl.setKind(Kind.ACTIVE); } }); passiveKind = UI.newButton(kindGroup, SWT.RADIO, "Passive"); passiveKind.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (shouldPropagateUI()) currentControl.setKind(Kind.PASSIVE); } }); appearanceLabel = UI.newLabel(right, SWT.NONE, "Appearance:"); GridData appearanceLabelLayoutData = new GridData(SWT.FILL, SWT.FILL, false, true); appearanceLabel.setLayoutData(appearanceLabelLayoutData); Composite appearanceGroup = new Composite(right, SWT.NONE); GridData appearanceGroupLayoutData = new GridData(SWT.FILL, SWT.FILL, false, true); appearanceGroup.setLayoutData(appearanceGroupLayoutData); GridLayout appearanceGroupLayout = new GridLayout(1, false); appearanceGroup.setLayout(appearanceGroupLayout); /* XXX: the addition of this row leads to really weird oversizing of * the polygon canvas! */ Composite firstLine = new Composite(appearanceGroup, SWT.NONE); firstLine.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); firstLine.setLayout(new RowLayout(SWT.HORIZONTAL)); ovalMode = UI.newButton(firstLine, SWT.RADIO, "Oval"); ovalMode.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (shouldPropagateUI()) currentControl.setShape(Shape.OVAL); } }); polygonMode = UI.newButton(firstLine, SWT.RADIO, "Polygon"); polygonMode.setSelection(true); polygonMode.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (shouldPropagateUI()) currentControl.setShape(Shape.POLYGON); } }); resizable = UI.newButton(firstLine, SWT.CHECK, "Resizable?"); resizable.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (shouldPropagateUI()) currentControl.setResizable(resizable.getSelection()); } }); appearance = new SignatureEditorPolygonCanvas(appearanceGroup, SWT.BORDER); GridData appearanceLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true); appearanceLayoutData.widthHint = 100; appearanceLayoutData.heightHint = 100; appearance.setLayoutData(appearanceLayoutData); appearance.setBackground(ColorConstants.listBackground); appearance.addPortListener(new PortListener() { @Override public void portChange(PortEvent e) { if (!shouldPropagateUI()) return; for (PortSpec p : Lists.copy(currentControl.getPorts())) currentControl.removePort(p.getName()); for (PortSpec p : appearance.getPorts()) currentControl.addPort(p); } }); appearance.addPointListener(new PointListener() { @Override public void pointChange(PointEvent e) { if (!shouldPropagateUI()) return; currentControl.setPoints(appearance.getPoints().getCopy()); } }); if (smiff == null) smiff = UI.tweakFont(appearanceLabel.getFont(), 8, SWT.ITALIC); appearanceDescription = UI.newLabel(appearanceGroup, SWT.CENTER | SWT.WRAP, "Click to add a new point. Double-click a point to delete it. " + "Move elements by clicking and dragging. " + "Right-click for more options."); GridData appearanceDescriptionData = new GridData(); appearanceDescriptionData.verticalAlignment = SWT.TOP; appearanceDescriptionData.horizontalAlignment = SWT.FILL; appearanceDescriptionData.widthHint = 0; appearanceDescription.setLayoutData(appearanceDescriptionData); appearanceDescription.setFont(smiff); outlineLabel = UI.newLabel(right, SWT.NONE, "Outline:"); outline = new ColorSelector(right); outline.getButton().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); outline.addListener(new IPropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent event) { if (!shouldPropagateUI()) return; try { model.tryApplyChange( currentControl.changeOutlineColour( new Colour(outline.getColorValue()))); } catch (ChangeRejectedException cre) { cre.printStackTrace(); } } }); fillLabel = UI.newLabel(right, SWT.NONE, "Fill:"); fill = new ColorSelector(right); fill.getButton().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); fill.addListener(new IPropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent event) { if (!shouldPropagateUI()) return; try { model.tryApplyChange( currentControl.changeFillColour( new Colour(fill.getColorValue()))); } catch (ChangeRejectedException cre) { cre.printStackTrace(); } } }); setEnablement(false); initialiseSignatureEditor(); }
public void createPartControl(Composite parent) { GridLayout layout = new GridLayout(2, false); parent.setLayout(layout); Composite left = new Composite(parent, 0); left.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); GridLayout leftLayout = new GridLayout(1, false); left.setLayout(leftLayout); controls = new Tree(left, SWT.SINGLE | SWT.BORDER | SWT.VIRTUAL); GridData controlsLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true); controlsLayoutData.widthHint = 100; controls.setLayoutData(controlsLayoutData); controls.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { currentControlItem = controls.getSelection()[0]; setControl((Control)UI.data(currentControlItem, controlKey)); name.setFocus(); setEnablement(true); } @Override public void widgetDefaultSelected(SelectionEvent e) { widgetSelected(e); } }); Composite controlButtons = new Composite(left, SWT.NONE); RowLayout controlButtonsLayout = new RowLayout(); controlButtons.setLayout(controlButtonsLayout); controlButtons.setLayoutData(new GridData(SWT.END, SWT.TOP, true, false)); addControl = new Button(controlButtons, SWT.NONE); addControl.setImage(UI.getImage(ISharedImages.IMG_OBJ_ADD)); addControl.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { Control c = new Control(); model.addControl(c); currentControlItem = UI.data(new TreeItem(controls, SWT.NONE), controlKey, c); setControl(c); controls.select(currentControlItem); name.setFocus(); setEnablement(true); setDirty(true); } @Override public void widgetDefaultSelected(SelectionEvent e) { return; } }); removeControl = new Button(controlButtons, SWT.NONE); removeControl.setImage(UI.getImage(ISharedImages.IMG_ELCL_REMOVE)); removeControl.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { model.removeControl(currentControl); currentControlItem.dispose(); if (controls.getItemCount() > 0) { controls.select(controls.getItem(0)); currentControlItem = controls.getItem(0); currentControl = (Control)UI.data(currentControlItem, controlKey); controlToFields(); name.setFocus(); } else setEnablement(false); setDirty(true); } @Override public void widgetDefaultSelected(SelectionEvent e) { widgetSelected(e); } }); Composite right = new Composite(parent, 0); right.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); GridLayout rightLayout = new GridLayout(2, false); right.setLayout(rightLayout); abstract class TextListener implements SelectionListener, FocusListener { abstract void go(); @Override public void focusGained(FocusEvent e) { /* nothing */ } @Override public void focusLost(FocusEvent e) { if (shouldPropagateUI()) go(); } @Override public void widgetSelected(SelectionEvent e) { /* nothing */ } @Override public void widgetDefaultSelected(SelectionEvent e) { if (shouldPropagateUI()) go(); } } TextListener nameListener = new TextListener() { @Override void go() { currentControl.setName(name.getText()); } }; nameLabel = UI.newLabel(right, SWT.NONE, "Name:"); name = new Text(right, SWT.BORDER); name.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false)); name.addSelectionListener(nameListener); name.addFocusListener(nameListener); TextListener labelListener = new TextListener() { @Override void go() { currentControl.setLabel(label.getText()); } }; labelLabel = UI.newLabel(right, SWT.NONE, "Label:"); label = new Text(right, SWT.BORDER); label.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false)); label.addSelectionListener(labelListener); label.addFocusListener(labelListener); kindLabel = UI.newLabel(right, SWT.NONE, "Kind:"); Composite kindGroup = new Composite(right, SWT.NONE); kindGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); kindGroup.setLayout(new RowLayout(SWT.HORIZONTAL)); atomicKind = UI.newButton(kindGroup, SWT.RADIO, "Atomic"); atomicKind.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (shouldPropagateUI()) currentControl.setKind(Kind.ATOMIC); } }); activeKind = UI.newButton(kindGroup, SWT.RADIO, "Active"); activeKind.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (shouldPropagateUI()) currentControl.setKind(Kind.ACTIVE); } }); passiveKind = UI.newButton(kindGroup, SWT.RADIO, "Passive"); passiveKind.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (shouldPropagateUI()) currentControl.setKind(Kind.PASSIVE); } }); appearanceLabel = UI.newLabel(right, SWT.NONE, "Appearance:"); GridData appearanceLabelLayoutData = new GridData(SWT.FILL, SWT.FILL, false, true); appearanceLabel.setLayoutData(appearanceLabelLayoutData); Composite appearanceGroup = new Composite(right, SWT.NONE); GridData appearanceGroupLayoutData = new GridData(SWT.FILL, SWT.FILL, false, true); appearanceGroup.setLayoutData(appearanceGroupLayoutData); GridLayout appearanceGroupLayout = new GridLayout(1, false); appearanceGroup.setLayout(appearanceGroupLayout); /* XXX: the addition of this row leads to really weird oversizing of * the polygon canvas! */ Composite firstLine = new Composite(appearanceGroup, SWT.NONE); firstLine.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); firstLine.setLayout(new RowLayout(SWT.HORIZONTAL)); ovalMode = UI.newButton(firstLine, SWT.RADIO, "Oval"); ovalMode.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (shouldPropagateUI()) currentControl.setShape(Shape.OVAL); } }); polygonMode = UI.newButton(firstLine, SWT.RADIO, "Polygon"); polygonMode.setSelection(true); polygonMode.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (shouldPropagateUI()) currentControl.setShape(Shape.POLYGON); } }); resizable = UI.newButton(firstLine, SWT.CHECK, "Resizable?"); resizable.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (shouldPropagateUI()) currentControl.setResizable(resizable.getSelection()); } }); appearance = new SignatureEditorPolygonCanvas(appearanceGroup, SWT.BORDER); GridData appearanceLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true); appearanceLayoutData.widthHint = 100; appearanceLayoutData.heightHint = 100; appearance.setLayoutData(appearanceLayoutData); appearance.setBackground(ColorConstants.listBackground); appearance.addPortListener(new PortListener() { @Override public void portChange(PortEvent e) { if (!shouldPropagateUI()) return; for (PortSpec p : Lists.copy(currentControl.getPorts())) currentControl.removePort(p.getName()); for (PortSpec p : appearance.getPorts()) currentControl.addPort(p); } }); appearance.addPointListener(new PointListener() { @Override public void pointChange(PointEvent e) { if (!shouldPropagateUI()) return; currentControl.setPoints(appearance.getPoints().getCopy()); } }); if (smiff == null) smiff = UI.tweakFont(appearanceLabel.getFont(), 8, SWT.ITALIC); appearanceDescription = UI.newLabel(appearanceGroup, SWT.CENTER | SWT.WRAP, "Click to add a new point. Double-click a point to delete it. " + "Move elements by clicking and dragging. " + "Right-click for more options."); GridData appearanceDescriptionData = new GridData(); appearanceDescriptionData.verticalAlignment = SWT.TOP; appearanceDescriptionData.horizontalAlignment = SWT.FILL; appearanceDescriptionData.widthHint = 0; appearanceDescription.setLayoutData(appearanceDescriptionData); appearanceDescription.setFont(smiff); outlineLabel = UI.newLabel(right, SWT.NONE, "Outline:"); outline = new ColorSelector(right); outline.getButton().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); outline.addListener(new IPropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent event) { if (!shouldPropagateUI()) return; try { model.tryApplyChange( currentControl.changeOutlineColour( new Colour(outline.getColorValue()))); } catch (ChangeRejectedException cre) { cre.printStackTrace(); } } }); fillLabel = UI.newLabel(right, SWT.NONE, "Fill:"); fill = new ColorSelector(right); fill.getButton().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); fill.addListener(new IPropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent event) { if (!shouldPropagateUI()) return; try { model.tryApplyChange( currentControl.changeFillColour( new Colour(fill.getColorValue()))); } catch (ChangeRejectedException cre) { cre.printStackTrace(); } } }); setEnablement(false); initialiseSignatureEditor(); }
diff --git a/addon-web-mvc-controller/src/main/java/org/springframework/roo/addon/web/mvc/controller/DefaultXmlRoundTripFileManager.java b/addon-web-mvc-controller/src/main/java/org/springframework/roo/addon/web/mvc/controller/DefaultXmlRoundTripFileManager.java index 2e04e2f16..639043a77 100644 --- a/addon-web-mvc-controller/src/main/java/org/springframework/roo/addon/web/mvc/controller/DefaultXmlRoundTripFileManager.java +++ b/addon-web-mvc-controller/src/main/java/org/springframework/roo/addon/web/mvc/controller/DefaultXmlRoundTripFileManager.java @@ -1,74 +1,75 @@ package org.springframework.roo.addon.web.mvc.controller; import java.io.File; import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.Service; import org.springframework.roo.process.manager.FileManager; import org.springframework.roo.support.util.Assert; import org.springframework.roo.support.util.DomUtils; import org.springframework.roo.support.util.FileCopyUtils; import org.springframework.roo.support.util.HexUtils; import org.springframework.roo.support.util.XmlRoundTripUtils; import org.springframework.roo.support.util.XmlUtils; import org.w3c.dom.Document; /** * Default implementation of {@link XmlRoundTripFileManager}. * * @author James Tyrrell * @since 1.2.0 */ @Component @Service public class DefaultXmlRoundTripFileManager implements XmlRoundTripFileManager { // Fields @Reference private FileManager fileManager; private HashMap<String, String> fileContentsMap = new HashMap<String, String>(); private static MessageDigest sha = null; static { try { sha = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException ignored) {} } public void writeToDiskIfNecessary(String filename, Document proposed) { Assert.notNull(filename, "The file name is required"); Assert.notNull(proposed, "The proposed document is required"); if (fileManager.exists(filename)) { String proposedContents = XmlUtils.nodeToString(proposed); try { if (sha != null) { String contents = FileCopyUtils.copyToString(new File(filename)) + proposedContents; byte[] digest = sha.digest(contents.getBytes()); String contentsSha = HexUtils.toHex(digest); String lastContents = fileContentsMap.get(filename); if (lastContents != null && contentsSha.equals(lastContents)) { return; } fileContentsMap.put(filename, contentsSha); } } catch (IOException ignored) {} final Document original = XmlUtils.readXml(fileManager.getInputStream(filename)); if (XmlRoundTripUtils.compareDocuments(original, proposed)) { + String updateContents = XmlUtils.nodeToString(original); DomUtils.removeTextNodes(original); - fileManager.createOrUpdateTextFileIfRequired(filename, proposedContents, false); + fileManager.createOrUpdateTextFileIfRequired(filename, updateContents, false); } } else { String contents = XmlUtils.nodeToString(proposed); if (sha != null) { byte[] digest = sha.digest((contents + contents).getBytes()); String contentsSha = HexUtils.toHex(digest); fileContentsMap.put(filename, contentsSha); } fileManager.createOrUpdateTextFileIfRequired(filename, contents, false); } } }
false
true
public void writeToDiskIfNecessary(String filename, Document proposed) { Assert.notNull(filename, "The file name is required"); Assert.notNull(proposed, "The proposed document is required"); if (fileManager.exists(filename)) { String proposedContents = XmlUtils.nodeToString(proposed); try { if (sha != null) { String contents = FileCopyUtils.copyToString(new File(filename)) + proposedContents; byte[] digest = sha.digest(contents.getBytes()); String contentsSha = HexUtils.toHex(digest); String lastContents = fileContentsMap.get(filename); if (lastContents != null && contentsSha.equals(lastContents)) { return; } fileContentsMap.put(filename, contentsSha); } } catch (IOException ignored) {} final Document original = XmlUtils.readXml(fileManager.getInputStream(filename)); if (XmlRoundTripUtils.compareDocuments(original, proposed)) { DomUtils.removeTextNodes(original); fileManager.createOrUpdateTextFileIfRequired(filename, proposedContents, false); } } else { String contents = XmlUtils.nodeToString(proposed); if (sha != null) { byte[] digest = sha.digest((contents + contents).getBytes()); String contentsSha = HexUtils.toHex(digest); fileContentsMap.put(filename, contentsSha); } fileManager.createOrUpdateTextFileIfRequired(filename, contents, false); } }
public void writeToDiskIfNecessary(String filename, Document proposed) { Assert.notNull(filename, "The file name is required"); Assert.notNull(proposed, "The proposed document is required"); if (fileManager.exists(filename)) { String proposedContents = XmlUtils.nodeToString(proposed); try { if (sha != null) { String contents = FileCopyUtils.copyToString(new File(filename)) + proposedContents; byte[] digest = sha.digest(contents.getBytes()); String contentsSha = HexUtils.toHex(digest); String lastContents = fileContentsMap.get(filename); if (lastContents != null && contentsSha.equals(lastContents)) { return; } fileContentsMap.put(filename, contentsSha); } } catch (IOException ignored) {} final Document original = XmlUtils.readXml(fileManager.getInputStream(filename)); if (XmlRoundTripUtils.compareDocuments(original, proposed)) { String updateContents = XmlUtils.nodeToString(original); DomUtils.removeTextNodes(original); fileManager.createOrUpdateTextFileIfRequired(filename, updateContents, false); } } else { String contents = XmlUtils.nodeToString(proposed); if (sha != null) { byte[] digest = sha.digest((contents + contents).getBytes()); String contentsSha = HexUtils.toHex(digest); fileContentsMap.put(filename, contentsSha); } fileManager.createOrUpdateTextFileIfRequired(filename, contents, false); } }
diff --git a/src/main/java/org/sonar/ide/intellij/worker/RefreshSourceWorker.java b/src/main/java/org/sonar/ide/intellij/worker/RefreshSourceWorker.java index ee9da54..db6e999 100644 --- a/src/main/java/org/sonar/ide/intellij/worker/RefreshSourceWorker.java +++ b/src/main/java/org/sonar/ide/intellij/worker/RefreshSourceWorker.java @@ -1,45 +1,45 @@ package org.sonar.ide.intellij.worker; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import org.sonar.ide.intellij.listener.RefreshSourceListener; import org.sonar.wsclient.services.Query; import org.sonar.wsclient.services.Source; import org.sonar.wsclient.services.SourceQuery; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; public class RefreshSourceWorker extends RefreshSonarFileWorker<Source> { private List<RefreshSourceListener> listeners = new ArrayList<RefreshSourceListener>(); public RefreshSourceWorker(Project project, VirtualFile virtualFile) { super(project, virtualFile); } public void addListener(RefreshSourceListener listener) { listeners.add(listener); } @Override protected Query<Source> getQuery(String resourceKey) { return SourceQuery.create(resourceKey); } @Override protected void done() { try { List<Source> sources = get(); - Source source = sources == null ? null : sources.get(0); + Source source = (sources == null || sources.isEmpty()) ? null : sources.get(0); for (RefreshSourceListener listener : this.listeners) { listener.doneRefreshSource(this.virtualFile, source); } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } }
true
true
protected void done() { try { List<Source> sources = get(); Source source = sources == null ? null : sources.get(0); for (RefreshSourceListener listener : this.listeners) { listener.doneRefreshSource(this.virtualFile, source); } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } }
protected void done() { try { List<Source> sources = get(); Source source = (sources == null || sources.isEmpty()) ? null : sources.get(0); for (RefreshSourceListener listener : this.listeners) { listener.doneRefreshSource(this.virtualFile, source); } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } }
diff --git a/src/org/apache/ws/sandbox/security/conversation/ConversationManager.java b/src/org/apache/ws/sandbox/security/conversation/ConversationManager.java index e9af65ed0..678621458 100644 --- a/src/org/apache/ws/sandbox/security/conversation/ConversationManager.java +++ b/src/org/apache/ws/sandbox/security/conversation/ConversationManager.java @@ -1,477 +1,477 @@ /* * Copyright 2003-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ws.security.conversation; import org.apache.axis.components.logger.LogFactory; import org.apache.commons.logging.Log; import org.apache.ws.security.SOAPConstants; import org.apache.ws.security.WSConstants; import org.apache.ws.security.WSDocInfo; import org.apache.ws.security.WSEncryptionPart; import org.apache.ws.security.WSPasswordCallback; import org.apache.ws.security.WSSConfig; import org.apache.ws.security.WSSecurityException; import org.apache.ws.security.conversation.message.info.DerivedKeyInfo; import org.apache.ws.security.conversation.message.token.DerivedKeyToken; import org.apache.ws.security.message.EnvelopeIdResolver; import org.apache.ws.security.message.WSEncryptBody; import org.apache.ws.security.message.token.Reference; import org.apache.ws.security.message.token.SecurityTokenReference; import org.apache.ws.security.transform.STRTransform; import org.apache.ws.security.util.WSSecurityUtil; import org.apache.xml.security.c14n.Canonicalizer; import org.apache.xml.security.exceptions.XMLSecurityException; import org.apache.xml.security.keys.KeyInfo; import org.apache.xml.security.signature.XMLSignature; import org.apache.xml.security.signature.XMLSignatureException; import org.apache.xml.security.transforms.TransformationException; import org.apache.xml.security.transforms.Transforms; import org.w3c.dom.Document; import org.w3c.dom.Element; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import javax.security.auth.callback.Callback; import java.util.Vector; /** * This class helps handlers to carry on conversation. * <p/> * It performes functionalities * 1) Adding derived Keys * 2) Signing using derived keys * 3) Encrypting using derive keys * <p/> * Actually the class is the collection of methods that are useful * for carrying out conversation. * * @author Dimuthu Leelarathne. ([email protected]) */ public class ConversationManager { private static Log log = LogFactory.getLog(ConversationManager.class.getName()); private int generation = 0; protected String canonAlgo = Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS; /** * Adds Derived key tokens to the header of the SOAP message, given the * following parameters. * @param doc * @param uuid * @param dkcbHandler * @param stRef2Base -SecurityTOkenReference to the token, from which the derived * key is derived from * @return * @throws ConversationException */ public DerivedKeyInfo createDerivedKeyToken(Document doc, String uuid, DerivedKeyCallbackHandler dkcbHandler,SecurityTokenReference stRef2Base, int keyLen ) throws ConversationException { String genID = ConversationUtil.genericID(); /* * This metod is 4-step procedure. */ // step 1 : Creating wsse:Reference to DerivedKeyToken Reference ref = new Reference(WSSConfig.getDefaultWSConfig(), doc); ref.setURI("#" + genID); ref.setValueType("http://schemas.xmlsoap.org/ws/2004/04/security/sc/dk"); SecurityTokenReference stRef = new SecurityTokenReference(WSSConfig.getDefaultWSConfig(), doc); stRef.setReference(ref); WSSecurityUtil.setNamespace(stRef.getElement(), WSConstants.WSSE_NS, WSConstants.WSSE_PREFIX); // step 2 :Create the DerriveToken DerivedKeyToken dtoken = new DerivedKeyToken(doc); if(stRef2Base != null){ dtoken.setSecuityTokenReference(doc, stRef2Base); } dtoken.setLabel(doc, "WS-SecureConversationWS-SecureConversation"); dtoken.setNonce(doc, ConversationUtil.generateNonce(128)); dtoken.setID(genID); //System.out.println("Fix me here ...."); if(keyLen!=-1){ dtoken.setLength(doc,keyLen); } //step 3 :add the derived key token infomation into the dkcbHandler DerivedKeyInfo dkInfo = null; try { dkInfo = new DerivedKeyInfo(dtoken); dkInfo.setSecTokRef2DkToken(stRef); dkcbHandler.addDerivedKey(uuid, dkInfo); } catch (WSSecurityException e) { e.printStackTrace(); throw new ConversationException("ConversationManager:: Cannot add Derived key token to the envelope"); } return dkInfo; } public void addDkToken(Document doc, DerivedKeyInfo info){ DerivedKeyTokenAdder adder = new DerivedKeyTokenAdder(); adder.build(doc, info.getDkTok()); } /** * Manages derived key encryption. * * @param encUser * @param actor * @param mu * @param doc * @param secRef - SecurityTokenReference pointing to the derived Key * @param dkcbHandler * @throws ConversationException */ public void performDK_ENCR(String encUser, String actor, boolean mu, Document doc, SecurityTokenReference secRef, DerivedKeyCallbackHandler dkcbHandler, Vector parts, String symAlgo) throws ConversationException { WSEncryptBody wsEncrypt = new WSEncryptBody(actor, mu); /* * Here we want to add a wsse:SecurityTokenReference element into <KeyInfo>. * Rest is as same as EMBEDDED_KEYNAME , i.e. we want to encrypt the message * using a symmetric key and the result would be an <EncryptedData> element. * Steps are * step 1: Adding SecurityTokenReference pointing to DkToken * step 2: Adding the key into wsEncrypt * step 3: Setting the user. */ wsEncrypt.setKeyIdentifierType(WSConstants.EMBED_SECURITY_TOKEN_REF); /* * step 1: Adding SecurityTokenReference pointing to DkToken. */ wsEncrypt.setSecurityTokenReference(secRef); /* * step 2: Generating the key, and setting it in the the wsEncrypt */ WSPasswordCallback pwCb = new WSPasswordCallback(encUser, WSPasswordCallback.UNKNOWN); Callback[] callbacks = new Callback[1]; callbacks[0] = (Callback) pwCb; try { dkcbHandler.handle(callbacks); } catch (java.lang.Exception e) { e.printStackTrace(); throw new ConversationException("ConversationManager :: PasswordCallback failed"); } wsEncrypt.setKey(pwCb.getKey()); /* * step 3: set the user. */ wsEncrypt.setUserInfo(encUser); /* * step 4 : Setting encryption parts */ wsEncrypt.setParts(parts); wsEncrypt.setSymmetricEncAlgorithm(symAlgo); try { wsEncrypt.build(doc, null); } catch (WSSecurityException e) { e.printStackTrace(); throw new ConversationException("ConversationManager :: Encryption: error during message processing"); } } /** * Manages derived key signature. * * @param doc * @param dkcbHandler * @param uuid * @param dkSigInfo * @throws ConversationException */ public void performDK_Sign(Document doc, DerivedKeyCallbackHandler dkcbHandler, String uuid, DerivedKeyInfo dkSigInfo, Vector parts) throws ConversationException { // Signing.... // HMAC_SignVerify sign = new HMAC_SignVerify(); String sigAlgo = XMLSignature.ALGO_ID_MAC_HMAC_SHA1; String sigUser = ConversationUtil.generateIdentifier(uuid, dkSigInfo.getId()); System.out.println("Signature user is ::"+sigUser); WSPasswordCallback pwCb = new WSPasswordCallback(sigUser, WSPasswordCallback.UNKNOWN); Callback[] callbacks = new Callback[1]; callbacks[0] = (Callback) pwCb; try { dkcbHandler.handle(callbacks); } catch (java.lang.Exception e) { throw new ConversationException("ConversationManager :: Password callback failed"); } try { Reference ref = dkSigInfo.getSecTokRef2DkToken().getReference(); this.build(doc, ref, pwCb.getKey(), parts); } catch (WSSecurityException e1) { e1.printStackTrace(); throw new ConversationException("ConversationManager :: Error performing signature."); } } /** * The method is coded such that it can be plugged into WSSignEnvelope. * Performs HMAC_SHA1 signature. * needed. * * @param doc * @param ref * @param sk * @param parts * @return * @throws WSSecurityException */ public Document build(Document doc, Reference ref, byte[] sk, Vector parts) throws WSSecurityException { boolean doDebug = log.isDebugEnabled(); if (doDebug) { log.debug("Beginning signing..."); } if (ref == null) { throw new WSSecurityException(WSSecurityException.FAILURE, - "Invalid Data", + "invalidData", new Object[]{"For symmeric key signatures - Reference object must be provided"}); } if (sk == null) { throw new WSSecurityException(WSSecurityException.FAILURE, - "Invalid Data", + "invalidData", new Object[]{"For symmeric key signatures - Reference object must be provided"}); } String sigAlgo = XMLSignature.ALGO_ID_MAC_HMAC_SHA1; log.debug("Key is "+new String(sk)); SecretKey sharedKey = new SecretKeySpec(sk, sigAlgo); //TODO :: Check for the characteristics (eg: legnth of the key) of the key if it applies. /* * Gather some info about the document to process and store it for * retrival */ WSDocInfo wsDocInfo = new WSDocInfo(doc.hashCode()); Element envelope = doc.getDocumentElement(); SOAPConstants soapConstants = WSSecurityUtil.getSOAPConstants(envelope); Element securityHeader = WSSecurityUtil.findWsseSecurityHeaderBlock(WSSConfig.getDefaultWSConfig(), doc, doc.getDocumentElement(), true); XMLSignature sig = null; try { sig = new XMLSignature(doc, null, sigAlgo, canonAlgo); } catch (XMLSecurityException e) { throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noXMLSig"); } KeyInfo info = sig.getKeyInfo(); String keyInfoUri = "KeyId-" + info.hashCode(); info.setId(keyInfoUri); SecurityTokenReference secRef = new SecurityTokenReference(WSSConfig.getDefaultWSConfig(), doc); String strUri = "STRId-" + secRef.hashCode(); secRef.setID(strUri); if (parts == null) { parts = new Vector(); WSEncryptionPart encP = new WSEncryptionPart(soapConstants.getBodyQName().getLocalPart(), soapConstants.getEnvelopeURI(), "Content"); parts.add(encP); } /* * The below "for" loop (which perform transforms) is * copied from * build(Document doc, Crypto crypto) method in * org.apache.ws.security.message.WSEncryptBody.java */ Transforms transforms = null; for (int part = 0; part < parts.size(); part++) { WSEncryptionPart encPart = (WSEncryptionPart) parts.get(part); String elemName = encPart.getName(); String nmSpace = encPart.getNamespace(); /* * Set up the elements to sign. There are two resevered element * names: "Token" and "STRTransform" "Token": Setup the Signature * to either sign the information that points to the security token * or the token itself. If its a direct reference sign the token, * otherwise sign the KeyInfo Element. "STRTransform": Setup the * ds:Reference to use STR Transform * */ try { if (elemName.equals("Token")) { transforms = new Transforms(doc); transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS); sig.addDocument("#" + keyInfoUri, transforms); } else if (elemName.equals("STRTransform")) { // STRTransform Element ctx = createSTRParameter(doc); transforms = new Transforms(doc); transforms.addTransform(STRTransform.implementedTransformURI, ctx); sig.addDocument("#" + strUri, transforms); } else { Element body = (Element) WSSecurityUtil.findElement(envelope, elemName, nmSpace); if (body == null) { throw new WSSecurityException(WSSecurityException.FAILURE, "noEncElement", new Object[]{nmSpace + ", " + elemName}); } transforms = new Transforms(doc); transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS); sig.addDocument("#" + setWsuId(body), transforms); } } catch (TransformationException e1) { throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, e1); } catch (XMLSignatureException e1) { throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, e1); } } sig.addResourceResolver(EnvelopeIdResolver.getInstance(WSSConfig.getDefaultWSConfig())); /* * Prepending order * -Append the signature element. * -Apped the KeyInfo element */ WSSecurityUtil.appendChildElement(doc, securityHeader, sig.getElement()); /* * Put the "Reference object" into secRef in KeyInfo */ secRef.setReference(ref); info.addUnknownElement(secRef.getElement()); try { sig.sign(sharedKey); } catch (XMLSignatureException e1) { throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, null, null, e1); } if (doDebug) { log.debug("Signing complete."); } return (doc); } /* * Extracted from org.apache.ws.security.message.WSSignEnvelope.java */ private Element createSTRParameter(Document doc) { Element transformParam = doc.createElementNS(WSConstants.WSSE_NS, WSConstants.WSSE_PREFIX + ":TransformationParameters"); WSSecurityUtil.setNamespace(transformParam, WSConstants.WSSE_NS, WSConstants.WSSE_PREFIX); Element canonElem = doc.createElementNS(WSConstants.SIG_NS, WSConstants.SIG_PREFIX + ":CanonicalizationMethod"); WSSecurityUtil.setNamespace(canonElem, WSConstants.SIG_NS, WSConstants.SIG_PREFIX); canonElem.setAttributeNS(null, "Algorithm", Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS); transformParam.appendChild(canonElem); return transformParam; } /* * Extracted from org.apache.ws.security.message.WSSignEnvelope.java */ protected String setWsuId(Element bodyElement) { String prefix = WSSecurityUtil.setNamespace(bodyElement, WSConstants.WSU_NS, WSConstants.WSU_PREFIX); String id = bodyElement.getAttributeNS(WSConstants.WSU_NS, "Id"); if ((id == null) || (id.length() == 0)) { id = "id-" + Integer.toString(bodyElement.hashCode()); bodyElement.setAttributeNS(WSConstants.WSU_NS, prefix + ":Id", id); } return id; } /** * @param i */ public void setGenerationInfo(int i) { generation = i; } }
false
true
public Document build(Document doc, Reference ref, byte[] sk, Vector parts) throws WSSecurityException { boolean doDebug = log.isDebugEnabled(); if (doDebug) { log.debug("Beginning signing..."); } if (ref == null) { throw new WSSecurityException(WSSecurityException.FAILURE, "Invalid Data", new Object[]{"For symmeric key signatures - Reference object must be provided"}); } if (sk == null) { throw new WSSecurityException(WSSecurityException.FAILURE, "Invalid Data", new Object[]{"For symmeric key signatures - Reference object must be provided"}); } String sigAlgo = XMLSignature.ALGO_ID_MAC_HMAC_SHA1; log.debug("Key is "+new String(sk)); SecretKey sharedKey = new SecretKeySpec(sk, sigAlgo); //TODO :: Check for the characteristics (eg: legnth of the key) of the key if it applies. /* * Gather some info about the document to process and store it for * retrival */ WSDocInfo wsDocInfo = new WSDocInfo(doc.hashCode()); Element envelope = doc.getDocumentElement(); SOAPConstants soapConstants = WSSecurityUtil.getSOAPConstants(envelope); Element securityHeader = WSSecurityUtil.findWsseSecurityHeaderBlock(WSSConfig.getDefaultWSConfig(), doc, doc.getDocumentElement(), true); XMLSignature sig = null; try { sig = new XMLSignature(doc, null, sigAlgo, canonAlgo); } catch (XMLSecurityException e) { throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noXMLSig"); } KeyInfo info = sig.getKeyInfo(); String keyInfoUri = "KeyId-" + info.hashCode(); info.setId(keyInfoUri); SecurityTokenReference secRef = new SecurityTokenReference(WSSConfig.getDefaultWSConfig(), doc); String strUri = "STRId-" + secRef.hashCode(); secRef.setID(strUri); if (parts == null) { parts = new Vector(); WSEncryptionPart encP = new WSEncryptionPart(soapConstants.getBodyQName().getLocalPart(), soapConstants.getEnvelopeURI(), "Content"); parts.add(encP); } /* * The below "for" loop (which perform transforms) is * copied from * build(Document doc, Crypto crypto) method in * org.apache.ws.security.message.WSEncryptBody.java */ Transforms transforms = null; for (int part = 0; part < parts.size(); part++) { WSEncryptionPart encPart = (WSEncryptionPart) parts.get(part); String elemName = encPart.getName(); String nmSpace = encPart.getNamespace(); /* * Set up the elements to sign. There are two resevered element * names: "Token" and "STRTransform" "Token": Setup the Signature * to either sign the information that points to the security token * or the token itself. If its a direct reference sign the token, * otherwise sign the KeyInfo Element. "STRTransform": Setup the * ds:Reference to use STR Transform * */ try { if (elemName.equals("Token")) { transforms = new Transforms(doc); transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS); sig.addDocument("#" + keyInfoUri, transforms); } else if (elemName.equals("STRTransform")) { // STRTransform Element ctx = createSTRParameter(doc); transforms = new Transforms(doc); transforms.addTransform(STRTransform.implementedTransformURI, ctx); sig.addDocument("#" + strUri, transforms); } else { Element body = (Element) WSSecurityUtil.findElement(envelope, elemName, nmSpace); if (body == null) { throw new WSSecurityException(WSSecurityException.FAILURE, "noEncElement", new Object[]{nmSpace + ", " + elemName}); } transforms = new Transforms(doc); transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS); sig.addDocument("#" + setWsuId(body), transforms); } } catch (TransformationException e1) { throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, e1); } catch (XMLSignatureException e1) { throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, e1); } } sig.addResourceResolver(EnvelopeIdResolver.getInstance(WSSConfig.getDefaultWSConfig())); /* * Prepending order * -Append the signature element. * -Apped the KeyInfo element */ WSSecurityUtil.appendChildElement(doc, securityHeader, sig.getElement()); /* * Put the "Reference object" into secRef in KeyInfo */ secRef.setReference(ref); info.addUnknownElement(secRef.getElement()); try { sig.sign(sharedKey); } catch (XMLSignatureException e1) { throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, null, null, e1); } if (doDebug) { log.debug("Signing complete."); } return (doc); }
public Document build(Document doc, Reference ref, byte[] sk, Vector parts) throws WSSecurityException { boolean doDebug = log.isDebugEnabled(); if (doDebug) { log.debug("Beginning signing..."); } if (ref == null) { throw new WSSecurityException(WSSecurityException.FAILURE, "invalidData", new Object[]{"For symmeric key signatures - Reference object must be provided"}); } if (sk == null) { throw new WSSecurityException(WSSecurityException.FAILURE, "invalidData", new Object[]{"For symmeric key signatures - Reference object must be provided"}); } String sigAlgo = XMLSignature.ALGO_ID_MAC_HMAC_SHA1; log.debug("Key is "+new String(sk)); SecretKey sharedKey = new SecretKeySpec(sk, sigAlgo); //TODO :: Check for the characteristics (eg: legnth of the key) of the key if it applies. /* * Gather some info about the document to process and store it for * retrival */ WSDocInfo wsDocInfo = new WSDocInfo(doc.hashCode()); Element envelope = doc.getDocumentElement(); SOAPConstants soapConstants = WSSecurityUtil.getSOAPConstants(envelope); Element securityHeader = WSSecurityUtil.findWsseSecurityHeaderBlock(WSSConfig.getDefaultWSConfig(), doc, doc.getDocumentElement(), true); XMLSignature sig = null; try { sig = new XMLSignature(doc, null, sigAlgo, canonAlgo); } catch (XMLSecurityException e) { throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noXMLSig"); } KeyInfo info = sig.getKeyInfo(); String keyInfoUri = "KeyId-" + info.hashCode(); info.setId(keyInfoUri); SecurityTokenReference secRef = new SecurityTokenReference(WSSConfig.getDefaultWSConfig(), doc); String strUri = "STRId-" + secRef.hashCode(); secRef.setID(strUri); if (parts == null) { parts = new Vector(); WSEncryptionPart encP = new WSEncryptionPart(soapConstants.getBodyQName().getLocalPart(), soapConstants.getEnvelopeURI(), "Content"); parts.add(encP); } /* * The below "for" loop (which perform transforms) is * copied from * build(Document doc, Crypto crypto) method in * org.apache.ws.security.message.WSEncryptBody.java */ Transforms transforms = null; for (int part = 0; part < parts.size(); part++) { WSEncryptionPart encPart = (WSEncryptionPart) parts.get(part); String elemName = encPart.getName(); String nmSpace = encPart.getNamespace(); /* * Set up the elements to sign. There are two resevered element * names: "Token" and "STRTransform" "Token": Setup the Signature * to either sign the information that points to the security token * or the token itself. If its a direct reference sign the token, * otherwise sign the KeyInfo Element. "STRTransform": Setup the * ds:Reference to use STR Transform * */ try { if (elemName.equals("Token")) { transforms = new Transforms(doc); transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS); sig.addDocument("#" + keyInfoUri, transforms); } else if (elemName.equals("STRTransform")) { // STRTransform Element ctx = createSTRParameter(doc); transforms = new Transforms(doc); transforms.addTransform(STRTransform.implementedTransformURI, ctx); sig.addDocument("#" + strUri, transforms); } else { Element body = (Element) WSSecurityUtil.findElement(envelope, elemName, nmSpace); if (body == null) { throw new WSSecurityException(WSSecurityException.FAILURE, "noEncElement", new Object[]{nmSpace + ", " + elemName}); } transforms = new Transforms(doc); transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS); sig.addDocument("#" + setWsuId(body), transforms); } } catch (TransformationException e1) { throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, e1); } catch (XMLSignatureException e1) { throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, e1); } } sig.addResourceResolver(EnvelopeIdResolver.getInstance(WSSConfig.getDefaultWSConfig())); /* * Prepending order * -Append the signature element. * -Apped the KeyInfo element */ WSSecurityUtil.appendChildElement(doc, securityHeader, sig.getElement()); /* * Put the "Reference object" into secRef in KeyInfo */ secRef.setReference(ref); info.addUnknownElement(secRef.getElement()); try { sig.sign(sharedKey); } catch (XMLSignatureException e1) { throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, null, null, e1); } if (doDebug) { log.debug("Signing complete."); } return (doc); }
diff --git a/src/web/org/openmrs/web/filter/initialization/InitializationFilter.java b/src/web/org/openmrs/web/filter/initialization/InitializationFilter.java index 43698bc1..c238b579 100644 --- a/src/web/org/openmrs/web/filter/initialization/InitializationFilter.java +++ b/src/web/org/openmrs/web/filter/initialization/InitializationFilter.java @@ -1,896 +1,896 @@ /** * The contents of this file are subject to the OpenMRS Public License * Version 1.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://license.openmrs.org * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * Copyright (C) OpenMRS, LLC. All Rights Reserved. */ package org.openmrs.web.filter.initialization; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.Writer; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Random; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import liquibase.ChangeSet; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.log4j.Appender; import org.apache.log4j.Logger; import org.openmrs.ImplementationId; import org.openmrs.api.PasswordException; import org.openmrs.api.context.Context; import org.openmrs.module.web.WebModuleUtil; import org.openmrs.scheduler.SchedulerConstants; import org.openmrs.scheduler.SchedulerUtil; import org.openmrs.util.DatabaseUpdateException; import org.openmrs.util.DatabaseUpdater; import org.openmrs.util.InputRequiredException; import org.openmrs.util.MemoryAppender; import org.openmrs.util.OpenmrsConstants; import org.openmrs.util.OpenmrsUtil; import org.openmrs.util.DatabaseUpdater.ChangeSetExecutorCallback; import org.openmrs.web.Listener; import org.openmrs.web.WebConstants; import org.openmrs.web.filter.StartupFilter; import org.springframework.web.context.ContextLoader; /** * This is the first filter that is processed. It is only active when starting OpenMRS for the very * first time. It will redirect all requests to the {@link WebConstants#SETUP_PAGE_URL} if the * {@link Listener} wasn't able to find any runtime properties */ public class InitializationFilter extends StartupFilter { protected final Log log = LogFactory.getLog(getClass()); private static final String LIQUIBASE_SCHEMA_DATA = "liquibase-schema-only.xml"; private static final String LIQUIBASE_CORE_DATA = "liquibase-core-data.xml"; private static final String LIQUIBASE_DEMO_DATA = "liquibase-demo-data.xml"; /** * The velocity macro page to redirect to if an error occurs or on initial startup */ private final String DEFAULT_PAGE = "databasesetup.vm"; /** * The model object that holds all the properties that the rendered templates use. All * attributes on this object are made available to all templates via reflection in the * {@link #renderTemplate(String, Map, Writer)} method. */ private InitializationWizardModel wizardModel = null; private InitializationCompletion initJob; /** * Variable set at the end of the wizard when spring is being restarted */ private boolean initializationComplete = false; /** * Called by {@link #doFilter(ServletRequest, ServletResponse, FilterChain)} on GET requests * * @param httpRequest * @param httpResponse */ protected void doGet(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException, ServletException { Writer writer = httpResponse.getWriter(); Map<String, Object> referenceMap = new HashMap<String, Object>(); File runtimeProperties = getRuntimePropertiesFile(); if (!runtimeProperties.exists()) { try { runtimeProperties.createNewFile(); } catch (IOException io) { wizardModel.canCreate = false; wizardModel.cannotCreateErrorMessage = io.getMessage(); } // check this before deleting the file again wizardModel.canWrite = runtimeProperties.canWrite(); // delete the file again after testing the create/write // so that if the user stops the webapp before finishing // this wizard, they can still get back into it runtimeProperties.delete(); } else { wizardModel.canWrite = runtimeProperties.canWrite(); } wizardModel.runtimePropertiesPath = runtimeProperties.getAbsolutePath(); // do step one of the wizard renderTemplate(DEFAULT_PAGE, referenceMap, writer); } /** * Called by {@link #doFilter(ServletRequest, ServletResponse, FilterChain)} on POST requests * * @param httpRequest * @param httpResponse */ protected void doPost(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException, ServletException { String page = httpRequest.getParameter("page"); Map<String, Object> referenceMap = new HashMap<String, Object>(); Writer writer = httpResponse.getWriter(); // TODO make these page names variables. // step one if ("databasesetup.vm".equals(page)) { wizardModel.databaseConnection = httpRequest.getParameter("database_connection"); checkForEmptyValue(wizardModel.databaseConnection, errors, "Database connection string"); //TODO make each bit of page logic a (unit testable) method // asked the user for their desired database name if ("yes".equals(httpRequest.getParameter("current_openmrs_database"))) { wizardModel.databaseName = httpRequest.getParameter("openmrs_current_database_name"); checkForEmptyValue(wizardModel.databaseName, errors, "Current database name"); wizardModel.hasCurrentOpenmrsDatabase = true; // TODO check to see if this is an active database } else { // mark this wizard as a "to create database" (done at the end) wizardModel.hasCurrentOpenmrsDatabase = false; wizardModel.createTables = true; wizardModel.databaseName = httpRequest.getParameter("openmrs_new_database_name"); checkForEmptyValue(wizardModel.databaseName, errors, "New database name"); // TODO create database now to check if its possible? wizardModel.createDatabaseUsername = httpRequest.getParameter("create_database_username"); checkForEmptyValue(wizardModel.createDatabaseUsername, errors, "A user that has 'CREATE DATABASE' privileges"); wizardModel.createDatabasePassword = httpRequest.getParameter("create_database_password"); checkForEmptyValue(wizardModel.createDatabasePassword, errors, "Password for user with 'CREATE DATABASE' privileges"); } if (errors.isEmpty()) { page = "databasetablesanduser.vm"; } renderTemplate(page, referenceMap, writer); } // step two else if ("databasetablesanduser.vm".equals(page)) { if ("Back".equals(httpRequest.getParameter("back"))) { renderTemplate("databasesetup.vm", referenceMap, writer); return; } if (wizardModel.hasCurrentOpenmrsDatabase) { wizardModel.createTables = "yes".equals(httpRequest.getParameter("create_tables")); } wizardModel.addDemoData = "yes".equals(httpRequest.getParameter("add_demo_data")); if ("yes".equals(httpRequest.getParameter("current_database_user"))) { wizardModel.currentDatabaseUsername = httpRequest.getParameter("current_database_username"); checkForEmptyValue(wizardModel.currentDatabaseUsername, errors, "Curent user account"); wizardModel.currentDatabasePassword = httpRequest.getParameter("current_database_password"); checkForEmptyValue(wizardModel.currentDatabasePassword, errors, "Current user account password"); wizardModel.hasCurrentDatabaseUser = true; wizardModel.createDatabaseUser = false; } else { wizardModel.hasCurrentDatabaseUser = false; wizardModel.createDatabaseUser = true; // asked for the root mysql username/password wizardModel.createUserUsername = httpRequest.getParameter("create_user_username"); checkForEmptyValue(wizardModel.createUserUsername, errors, "A user that has 'CREATE USER' privileges"); wizardModel.createUserPassword = httpRequest.getParameter("create_user_password"); checkForEmptyValue(wizardModel.createUserPassword, errors, "Password for user that has 'CREATE USER' privileges"); } if (errors.isEmpty()) { // go to next page page = "otherruntimeproperties.vm"; } renderTemplate(page, referenceMap, writer); } // step three else if ("otherruntimeproperties.vm".equals(page)) { if ("Back".equals(httpRequest.getParameter("back"))) { renderTemplate("databasetablesanduser.vm", referenceMap, writer); return; } wizardModel.moduleWebAdmin = "yes".equals(httpRequest.getParameter("module_web_admin")); wizardModel.autoUpdateDatabase = "yes".equals(httpRequest.getParameter("auto_update_database")); if (wizardModel.createTables) { // go to next page if they are creating tables page = "adminusersetup.vm"; } else { // skip a page page = "implementationidsetup.vm"; } renderTemplate(page, referenceMap, writer); } // optional step four else if ("adminusersetup.vm".equals(page)) { if ("Back".equals(httpRequest.getParameter("back"))) { renderTemplate("otherruntimeproperties.vm", referenceMap, writer); return; } wizardModel.adminUserPassword = httpRequest.getParameter("new_admin_password"); String adminUserConfirm = httpRequest.getParameter("new_admin_password_confirm"); // throw back to admin user if passwords don't match if (!wizardModel.adminUserPassword.equals(adminUserConfirm)) { errors.add("Admin passwords don't match"); renderTemplate("adminusersetup.vm", referenceMap, writer); return; } // throw back if the user didn't put in a password if (wizardModel.adminUserPassword.equals("")) { errors.add("An admin password is required"); renderTemplate("adminusersetup.vm", referenceMap, writer); return; } try { OpenmrsUtil.validatePassword("admin", wizardModel.adminUserPassword, "admin"); } catch (PasswordException p) { errors .add("The password is not long enough, does not contain both uppercase characters and a number, or matches the username."); renderTemplate("adminusersetup.vm", referenceMap, writer); return; } if (errors.isEmpty()) { // go to next page page = "implementationidsetup.vm"; } renderTemplate(page, referenceMap, writer); } // optional step five else if ("implementationidsetup.vm".equals(page)) { if ("Back".equals(httpRequest.getParameter("back"))) { if (wizardModel.createTables) renderTemplate("adminusersetup.vm", referenceMap, writer); else renderTemplate("otherruntimeproperties.vm", referenceMap, writer); return; } wizardModel.implementationIdName = httpRequest.getParameter("implementation_name"); wizardModel.implementationId = httpRequest.getParameter("implementation_id"); wizardModel.implementationIdPassPhrase = httpRequest.getParameter("pass_phrase"); wizardModel.implementationIdDescription = httpRequest.getParameter("description"); // throw back if the user-specified ID is invalid (contains ^ or |). if (wizardModel.implementationId.indexOf('^') != -1 || wizardModel.implementationId.indexOf('|') != -1) { errors.add("Implementation ID cannot contain '^' or '|'"); renderTemplate("implementationidsetup.vm", referenceMap, writer); return; } if (errors.isEmpty()) { // go to next page page = "wizardcomplete.vm"; } renderTemplate(page, referenceMap, writer); } else if ("wizardcomplete.vm".equals(page)) { if ("Back".equals(httpRequest.getParameter("back"))) { renderTemplate("implementationidsetup.vm", referenceMap, writer); return; } // TODO send user to confirmation page with results of wizard, location of runtime props, before starting install? initJob = new InitializationCompletion(); initJob.start(); renderTemplate("progress.vm", referenceMap, writer); } else if ("progress.vm".equals(page)) { if (initJob != null) { if (initJob.hasErrors()) { initJob.waitForCompletion(); page = initJob.getErrorPage(); errors.addAll(initJob.getErrors()); renderTemplate(page, referenceMap, writer); } else if (initJob.isCompleted()) { initializationComplete = true; httpResponse.sendRedirect("/" + WebConstants.WEBAPP_NAME); } else { wizardModel.actionCounter = initJob.getStepsComplete(); wizardModel.lastActionMessage = initJob.getMessage(); Appender appender = Logger.getRootLogger().getAppender("MEMORY_APPENDER"); if (appender instanceof MemoryAppender) { MemoryAppender memoryAppender = (MemoryAppender) appender; wizardModel.logLines = memoryAppender.getLogLines(); } page = "progress.vm"; renderTemplate(page, referenceMap, writer); } } } } /** * Verify the database connection works. * * @param connectionUsername * @param connectionPassword * @param databaseConnectionFinalUrl * @return true/false whether it was verified or not */ private boolean verifyConnection(String connectionUsername, String connectionPassword, String databaseConnectionFinalUrl) { try { // verify connection // TODO how to get the driver for the other dbs... Class.forName("com.mysql.jdbc.Driver").newInstance(); DriverManager.getConnection(databaseConnectionFinalUrl, connectionUsername, connectionPassword); return true; } catch (Exception e) { errors.add("User account " + connectionUsername + " does not work. " + e.getMessage() + " See the error log for more details"); // TODO internationalize this log.warn("Error while checking the connection user account", e); return false; } } /** * Convenience method to load the runtime properties in the application data directory * * @return */ private File getRuntimePropertiesFile() { String filename = WebConstants.WEBAPP_NAME + "-runtime.properties"; File file = new File(OpenmrsUtil.getApplicationDataDirectory(), filename); log.debug("Using file: " + file.getAbsolutePath()); return file; } /** * @see org.openmrs.web.filter.StartupFilter#getTemplatePrefix() */ protected String getTemplatePrefix() { return "org/openmrs/web/filter/initialization/"; } /** * @see org.openmrs.web.filter.StartupFilter#getModel() */ protected Object getModel() { return wizardModel; } /** * @see org.openmrs.web.filter.StartupFilter#skipFilter() */ public boolean skipFilter() { return Listener.runtimePropertiesFound() || isInitializationComplete(); } /** * @see javax.servlet.Filter#init(javax.servlet.FilterConfig) */ public void init(FilterConfig filterConfig) throws ServletException { super.init(filterConfig); wizardModel = new InitializationWizardModel(); } /** * @param silent if this statement fails do not display stack trace or record an error in the * wizard object. * @param user username to connect with * @param pw password to connect with * @param sql String containing sql and question marks * @param args the strings to fill into the question marks in the given sql * @return result of executeUpdate or -1 for error */ private int executeStatement(boolean silent, String user, String pw, String sql, String... args) { Connection connection = null; try { String replacedSql = sql; // TODO how to get the driver for the other dbs... if (wizardModel.databaseConnection.contains("mysql")) { Class.forName("com.mysql.jdbc.Driver").newInstance(); } else { replacedSql = replacedSql.replaceAll("`", "\""); } String tempDatabaseConnection = ""; if (sql.contains("create database")) { tempDatabaseConnection = wizardModel.databaseConnection.replace("@DBNAME@", ""); // make this dbname agnostic so we can create the db } else { tempDatabaseConnection = wizardModel.databaseConnection.replace("@DBNAME@", wizardModel.databaseName); } connection = DriverManager.getConnection(tempDatabaseConnection, user, pw); for (String arg : args) { arg = arg.replace(";", "&#094"); // to prevent any sql injection replacedSql = replacedSql.replaceFirst("\\?", arg); } // run the sql statement Statement statement = connection.createStatement(); return statement.executeUpdate(replacedSql); } catch (SQLException sqlex) { if (!silent) { // log and add error log.warn("error executing sql: " + sql, sqlex); errors.add("Error executing sql: " + sql + " - " + sqlex.getMessage()); } } catch (InstantiationException e) { log.error("Error generated", e); } catch (IllegalAccessException e) { log.error("Error generated", e); } catch (ClassNotFoundException e) { log.error("Error generated", e); } finally { try { if (connection != null) { connection.close(); } } catch (Throwable t) { log.warn("Error while closing connection", t); } } return -1; } /** * Convenience variable to know if this wizard has completed successfully and that this wizard * does not need to be executed again * * @return true if this has been run already */ private boolean isInitializationComplete() { return initializationComplete; } /** * Check if the given value is null or a zero-length String * * @param value the string to check * @param errors the list of errors to append the errorMessage to if value is empty * @param errorMessage the string error message to append if value is empty * @return true if the value is non-empty */ private boolean checkForEmptyValue(String value, List<String> errors, String errorMessage) { if (value != null && !value.equals("")) { return true; } errors.add(errorMessage + " required."); return false; } /** * Separate thread that will run through all tasks to complete the initialization. The database * is created, user's created, etc here */ private class InitializationCompletion { private Thread thread; private int steps = 0; private String message = ""; private List<String> errors = new ArrayList<String>(); private String errorPage = null; private boolean erroneous = false; private boolean completed = false; public void reportError(String error, String errorPage) { errors.add(error); this.errorPage = errorPage; erroneous = true; } public boolean hasErrors() { return erroneous; } public String getErrorPage() { return errorPage; } public List<String> getErrors() { return errors; } /** * Start the completion stage. This fires up the thread to do all the work. */ public void start() { setStepsComplete(0); setCompleted(false); thread.start(); } public void waitForCompletion() { try { thread.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block log.error("Error generated", e); } } protected void setCompleted(boolean completed) { this.completed = completed; } public boolean isCompleted() { return completed; } protected void setStepsComplete(int steps) { this.steps = steps; } protected int getStepsComplete() { return steps; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; setStepsComplete(getStepsComplete() + 1); } /** * This class does all the work of creating the desired database, user, updates, etc */ public InitializationCompletion() { Runnable r = new Runnable() { /** * TODO split this up into multiple testable methods * * @see java.lang.Runnable#run() */ public void run() { try { String connectionUsername; String connectionPassword; if (!wizardModel.hasCurrentOpenmrsDatabase) { setMessage("Create database"); // connect via jdbc and create a database String sql = "create database `?` default character set utf8"; int result = executeStatement(false, wizardModel.createDatabaseUsername, wizardModel.createDatabasePassword, sql, wizardModel.databaseName); // throw the user back to the main screen if this error occurs if (result < 0) { reportError(null, DEFAULT_PAGE); return; } else { wizardModel.workLog.add("Created database " + wizardModel.databaseName); } } if (wizardModel.createDatabaseUser) { setMessage("Create database user"); connectionUsername = wizardModel.databaseName + "_user"; if (connectionUsername.length() > 16) connectionUsername = wizardModel.databaseName.substring(0, 11) + "_user"; // trim off enough to leave space for _user at the end connectionPassword = ""; // generate random password from this subset of alphabet // intentionally left out these characters: ufsb$() to prevent certain words forming randomly String chars = "acdeghijklmnopqrtvwxyzACDEGHIJKLMNOPQRTVWXYZ0123456789.|~@#^&"; Random r = new Random(); for (int x = 0; x < 12; x++) { connectionPassword += chars.charAt(r.nextInt(chars.length())); } // connect via jdbc with root user and create an openmrs user String sql = "drop user '?'@'localhost'"; executeStatement(true, wizardModel.createUserUsername, wizardModel.createUserPassword, sql, connectionUsername); sql = "create user '?'@'localhost' identified by '?'"; if (-1 != executeStatement(false, wizardModel.createUserUsername, wizardModel.createUserPassword, sql, connectionUsername, connectionPassword)) { wizardModel.workLog.add("Created user " + connectionUsername); } else { // if error occurs stop reportError(null, DEFAULT_PAGE); return; } // grant the roles sql = "GRANT ALL ON `?`.* TO '?'@'localhost'"; int result = executeStatement(false, wizardModel.createUserUsername, wizardModel.createUserPassword, sql, wizardModel.databaseName, connectionUsername); // throw the user back to the main screen if this error occurs if (result < 0) { reportError(null, DEFAULT_PAGE); return; } else { wizardModel.workLog.add("Granted user " + connectionUsername + " all privileges to database " + wizardModel.databaseName); } } else { connectionUsername = wizardModel.currentDatabaseUsername; connectionPassword = wizardModel.currentDatabasePassword; } String finalDatabaseConnectionString = wizardModel.databaseConnection.replace("@DBNAME@", wizardModel.databaseName); // verify that the database connection works if (!verifyConnection(connectionUsername, connectionPassword, finalDatabaseConnectionString)) { setMessage("Verify that the database connection works"); // redirect to setup page if we got an error reportError(null, DEFAULT_PAGE); return; } // save the properties for startup purposes Properties runtimeProperties = new Properties(); runtimeProperties.put("connection.url", finalDatabaseConnectionString); runtimeProperties.put("connection.username", connectionUsername); runtimeProperties.put("connection.password", connectionPassword); runtimeProperties.put("module.allow_web_admin", wizardModel.moduleWebAdmin.toString()); runtimeProperties.put("auto_update_database", wizardModel.autoUpdateDatabase.toString()); runtimeProperties.put(SchedulerConstants.SCHEDULER_USERNAME_PROPERTY, "admin"); runtimeProperties.put(SchedulerConstants.SCHEDULER_PASSWORD_PROPERTY, wizardModel.adminUserPassword); Context.setRuntimeProperties(runtimeProperties); /** * A callback class that prints out info about liquibase changesets */ class PrintingChangeSetExecutorCallback implements ChangeSetExecutorCallback { private int i = 1; private String message; public PrintingChangeSetExecutorCallback(String message) { this.message = message; } /** * @see org.openmrs.util.DatabaseUpdater.ChangeSetExecutorCallback#executing(liquibase.ChangeSet, * int) */ public void executing(ChangeSet changeSet, int numChangeSetsToRun) { setMessage(message + " (" + i++ + "/" + numChangeSetsToRun + "): Author: " + changeSet.getAuthor() + " Comments: " + changeSet.getComments() + " Description: " + changeSet.getDescription()); } } if (wizardModel.createTables) { // use liquibase to create core data + tables try { setMessage("Executing " + LIQUIBASE_SCHEMA_DATA); DatabaseUpdater.executeChangelog(LIQUIBASE_SCHEMA_DATA, null, new PrintingChangeSetExecutorCallback("OpenMRS schema file")); DatabaseUpdater.executeChangelog(LIQUIBASE_CORE_DATA, null, new PrintingChangeSetExecutorCallback("OpenMRS core data file")); wizardModel.workLog.add("Created database tables and added core data"); } catch (Exception e) { reportError(e.getMessage() + " See the error log for more details", null); log.warn("Error while trying to create tables and demo data", e); } } // add demo data only if creating tables fresh and user selected the option add demo data if (wizardModel.createTables && wizardModel.addDemoData) { try { setMessage("Adding demo data"); DatabaseUpdater.executeChangelog(LIQUIBASE_DEMO_DATA, null, new PrintingChangeSetExecutorCallback("OpenMRS demo patients, users, and forms")); wizardModel.workLog.add("Added demo data"); } catch (Exception e) { reportError(e.getMessage() + " See the error log for more details", null); log.warn("Error while trying to add demo data", e); } } // update the database to the latest version try { setMessage("Updating the database to the latest version"); DatabaseUpdater.executeChangelog(null, null, new PrintingChangeSetExecutorCallback( "Updating database tables to latest version ")); } catch (Exception e) { reportError(e.getMessage() + " Error while trying to update to the latest database version", DEFAULT_PAGE); log.warn("Error while trying to update to the latest database version", e); return; } setMessage("Starting OpenMRS"); // start spring // after this point, all errors need to also call: contextLoader.closeWebApplicationContext(event.getServletContext()) // logic copied from org.springframework.web.context.ContextLoaderListener ContextLoader contextLoader = new ContextLoader(); contextLoader.initWebApplicationContext(filterConfig.getServletContext()); // start openmrs try { Context.openSession(); Context.startup(runtimeProperties); } catch (DatabaseUpdateException updateEx) { log.warn("Error while running the database update file", updateEx); reportError( updateEx.getMessage() + " There was an error while running the database update file: " + updateEx.getMessage(), DEFAULT_PAGE); return; } catch (InputRequiredException inputRequiredEx) { // TODO display a page looping over the required input and ask the user for each. // When done and the user and put in their say, call DatabaseUpdater.update(Map); // with the user's question/answer pairs log .warn("Unable to continue because user input is required for the db updates and we cannot do anything about that right now"); reportError( "Unable to continue because user input is required for the db updates and we cannot do anything about that right now", DEFAULT_PAGE); return; } // TODO catch openmrs errors here and drop the user back out to the setup screen if (!wizardModel.implementationId.equals("")) { try { Context.addProxyPrivilege(OpenmrsConstants.PRIV_MANAGE_GLOBAL_PROPERTIES); Context.addProxyPrivilege(OpenmrsConstants.PRIV_MANAGE_CONCEPT_SOURCES); Context.addProxyPrivilege(OpenmrsConstants.PRIV_VIEW_CONCEPT_SOURCES); Context.addProxyPrivilege(OpenmrsConstants.PRIV_MANAGE_IMPLEMENTATION_ID); ImplementationId implId = new ImplementationId(); implId.setName(wizardModel.implementationIdName); implId.setImplementationId(wizardModel.implementationId); implId.setPassphrase(wizardModel.implementationIdPassPhrase); implId.setDescription(wizardModel.implementationIdDescription); Context.getAdministrationService().setImplementationId(implId); } catch (Throwable t) { reportError(t.getMessage() + " Implementation ID could not be set.", DEFAULT_PAGE); log.warn("Implementation ID could not be set.", t); Context.shutdown(); WebModuleUtil.shutdownModules(filterConfig.getServletContext()); contextLoader.closeWebApplicationContext(filterConfig.getServletContext()); return; } finally { Context.removeProxyPrivilege(OpenmrsConstants.PRIV_MANAGE_GLOBAL_PROPERTIES); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_MANAGE_CONCEPT_SOURCES); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_CONCEPT_SOURCES); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_MANAGE_IMPLEMENTATION_ID); } } try { // change the admin user password from "test" to what they input above if (wizardModel.createTables) { Context.authenticate("admin", "test"); Context.getUserService().changePassword("test", wizardModel.adminUserPassword); Context.logout(); } // load modules Listener.loadAndStartCoreModules(filterConfig.getServletContext()); // web load modules Listener.performWebStartOfModules(filterConfig.getServletContext()); // start the scheduled tasks SchedulerUtil.startup(runtimeProperties); } catch (Throwable t) { Context.shutdown(); WebModuleUtil.shutdownModules(filterConfig.getServletContext()); contextLoader.closeWebApplicationContext(filterConfig.getServletContext()); reportError(t.getMessage() + " Unable to complete the startup.", DEFAULT_PAGE); log.warn("Unable to complete the startup.", t); return; } // output properties to the openmrs runtime properties file so that this wizard is not run again FileOutputStream fos = null; try { fos = new FileOutputStream(getRuntimePropertiesFile()); - runtimeProperties.store(fos, "Auto generated by OpenMRS initialization wizard"); + OpenmrsUtil.storeProperties(runtimeProperties, fos, "Auto generated by OpenMRS initialization wizard"); wizardModel.workLog.add("Saved runtime properties file " + getRuntimePropertiesFile()); // don't need to catch errors here because we tested it at the beginning of the wizard } finally { if (fos != null) { fos.close(); } } // set this so that the wizard isn't run again on next page load Context.closeSession(); } catch (IOException e) { reportError(e.getMessage() + " Unable to complete the startup.", DEFAULT_PAGE); } finally { setCompleted(true); } } }; thread = new Thread(r); } } }
true
true
public InitializationCompletion() { Runnable r = new Runnable() { /** * TODO split this up into multiple testable methods * * @see java.lang.Runnable#run() */ public void run() { try { String connectionUsername; String connectionPassword; if (!wizardModel.hasCurrentOpenmrsDatabase) { setMessage("Create database"); // connect via jdbc and create a database String sql = "create database `?` default character set utf8"; int result = executeStatement(false, wizardModel.createDatabaseUsername, wizardModel.createDatabasePassword, sql, wizardModel.databaseName); // throw the user back to the main screen if this error occurs if (result < 0) { reportError(null, DEFAULT_PAGE); return; } else { wizardModel.workLog.add("Created database " + wizardModel.databaseName); } } if (wizardModel.createDatabaseUser) { setMessage("Create database user"); connectionUsername = wizardModel.databaseName + "_user"; if (connectionUsername.length() > 16) connectionUsername = wizardModel.databaseName.substring(0, 11) + "_user"; // trim off enough to leave space for _user at the end connectionPassword = ""; // generate random password from this subset of alphabet // intentionally left out these characters: ufsb$() to prevent certain words forming randomly String chars = "acdeghijklmnopqrtvwxyzACDEGHIJKLMNOPQRTVWXYZ0123456789.|~@#^&"; Random r = new Random(); for (int x = 0; x < 12; x++) { connectionPassword += chars.charAt(r.nextInt(chars.length())); } // connect via jdbc with root user and create an openmrs user String sql = "drop user '?'@'localhost'"; executeStatement(true, wizardModel.createUserUsername, wizardModel.createUserPassword, sql, connectionUsername); sql = "create user '?'@'localhost' identified by '?'"; if (-1 != executeStatement(false, wizardModel.createUserUsername, wizardModel.createUserPassword, sql, connectionUsername, connectionPassword)) { wizardModel.workLog.add("Created user " + connectionUsername); } else { // if error occurs stop reportError(null, DEFAULT_PAGE); return; } // grant the roles sql = "GRANT ALL ON `?`.* TO '?'@'localhost'"; int result = executeStatement(false, wizardModel.createUserUsername, wizardModel.createUserPassword, sql, wizardModel.databaseName, connectionUsername); // throw the user back to the main screen if this error occurs if (result < 0) { reportError(null, DEFAULT_PAGE); return; } else { wizardModel.workLog.add("Granted user " + connectionUsername + " all privileges to database " + wizardModel.databaseName); } } else { connectionUsername = wizardModel.currentDatabaseUsername; connectionPassword = wizardModel.currentDatabasePassword; } String finalDatabaseConnectionString = wizardModel.databaseConnection.replace("@DBNAME@", wizardModel.databaseName); // verify that the database connection works if (!verifyConnection(connectionUsername, connectionPassword, finalDatabaseConnectionString)) { setMessage("Verify that the database connection works"); // redirect to setup page if we got an error reportError(null, DEFAULT_PAGE); return; } // save the properties for startup purposes Properties runtimeProperties = new Properties(); runtimeProperties.put("connection.url", finalDatabaseConnectionString); runtimeProperties.put("connection.username", connectionUsername); runtimeProperties.put("connection.password", connectionPassword); runtimeProperties.put("module.allow_web_admin", wizardModel.moduleWebAdmin.toString()); runtimeProperties.put("auto_update_database", wizardModel.autoUpdateDatabase.toString()); runtimeProperties.put(SchedulerConstants.SCHEDULER_USERNAME_PROPERTY, "admin"); runtimeProperties.put(SchedulerConstants.SCHEDULER_PASSWORD_PROPERTY, wizardModel.adminUserPassword); Context.setRuntimeProperties(runtimeProperties); /** * A callback class that prints out info about liquibase changesets */ class PrintingChangeSetExecutorCallback implements ChangeSetExecutorCallback { private int i = 1; private String message; public PrintingChangeSetExecutorCallback(String message) { this.message = message; } /** * @see org.openmrs.util.DatabaseUpdater.ChangeSetExecutorCallback#executing(liquibase.ChangeSet, * int) */ public void executing(ChangeSet changeSet, int numChangeSetsToRun) { setMessage(message + " (" + i++ + "/" + numChangeSetsToRun + "): Author: " + changeSet.getAuthor() + " Comments: " + changeSet.getComments() + " Description: " + changeSet.getDescription()); } } if (wizardModel.createTables) { // use liquibase to create core data + tables try { setMessage("Executing " + LIQUIBASE_SCHEMA_DATA); DatabaseUpdater.executeChangelog(LIQUIBASE_SCHEMA_DATA, null, new PrintingChangeSetExecutorCallback("OpenMRS schema file")); DatabaseUpdater.executeChangelog(LIQUIBASE_CORE_DATA, null, new PrintingChangeSetExecutorCallback("OpenMRS core data file")); wizardModel.workLog.add("Created database tables and added core data"); } catch (Exception e) { reportError(e.getMessage() + " See the error log for more details", null); log.warn("Error while trying to create tables and demo data", e); } } // add demo data only if creating tables fresh and user selected the option add demo data if (wizardModel.createTables && wizardModel.addDemoData) { try { setMessage("Adding demo data"); DatabaseUpdater.executeChangelog(LIQUIBASE_DEMO_DATA, null, new PrintingChangeSetExecutorCallback("OpenMRS demo patients, users, and forms")); wizardModel.workLog.add("Added demo data"); } catch (Exception e) { reportError(e.getMessage() + " See the error log for more details", null); log.warn("Error while trying to add demo data", e); } } // update the database to the latest version try { setMessage("Updating the database to the latest version"); DatabaseUpdater.executeChangelog(null, null, new PrintingChangeSetExecutorCallback( "Updating database tables to latest version ")); } catch (Exception e) { reportError(e.getMessage() + " Error while trying to update to the latest database version", DEFAULT_PAGE); log.warn("Error while trying to update to the latest database version", e); return; } setMessage("Starting OpenMRS"); // start spring // after this point, all errors need to also call: contextLoader.closeWebApplicationContext(event.getServletContext()) // logic copied from org.springframework.web.context.ContextLoaderListener ContextLoader contextLoader = new ContextLoader(); contextLoader.initWebApplicationContext(filterConfig.getServletContext()); // start openmrs try { Context.openSession(); Context.startup(runtimeProperties); } catch (DatabaseUpdateException updateEx) { log.warn("Error while running the database update file", updateEx); reportError( updateEx.getMessage() + " There was an error while running the database update file: " + updateEx.getMessage(), DEFAULT_PAGE); return; } catch (InputRequiredException inputRequiredEx) { // TODO display a page looping over the required input and ask the user for each. // When done and the user and put in their say, call DatabaseUpdater.update(Map); // with the user's question/answer pairs log .warn("Unable to continue because user input is required for the db updates and we cannot do anything about that right now"); reportError( "Unable to continue because user input is required for the db updates and we cannot do anything about that right now", DEFAULT_PAGE); return; } // TODO catch openmrs errors here and drop the user back out to the setup screen if (!wizardModel.implementationId.equals("")) { try { Context.addProxyPrivilege(OpenmrsConstants.PRIV_MANAGE_GLOBAL_PROPERTIES); Context.addProxyPrivilege(OpenmrsConstants.PRIV_MANAGE_CONCEPT_SOURCES); Context.addProxyPrivilege(OpenmrsConstants.PRIV_VIEW_CONCEPT_SOURCES); Context.addProxyPrivilege(OpenmrsConstants.PRIV_MANAGE_IMPLEMENTATION_ID); ImplementationId implId = new ImplementationId(); implId.setName(wizardModel.implementationIdName); implId.setImplementationId(wizardModel.implementationId); implId.setPassphrase(wizardModel.implementationIdPassPhrase); implId.setDescription(wizardModel.implementationIdDescription); Context.getAdministrationService().setImplementationId(implId); } catch (Throwable t) { reportError(t.getMessage() + " Implementation ID could not be set.", DEFAULT_PAGE); log.warn("Implementation ID could not be set.", t); Context.shutdown(); WebModuleUtil.shutdownModules(filterConfig.getServletContext()); contextLoader.closeWebApplicationContext(filterConfig.getServletContext()); return; } finally { Context.removeProxyPrivilege(OpenmrsConstants.PRIV_MANAGE_GLOBAL_PROPERTIES); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_MANAGE_CONCEPT_SOURCES); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_CONCEPT_SOURCES); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_MANAGE_IMPLEMENTATION_ID); } } try { // change the admin user password from "test" to what they input above if (wizardModel.createTables) { Context.authenticate("admin", "test"); Context.getUserService().changePassword("test", wizardModel.adminUserPassword); Context.logout(); } // load modules Listener.loadAndStartCoreModules(filterConfig.getServletContext()); // web load modules Listener.performWebStartOfModules(filterConfig.getServletContext()); // start the scheduled tasks SchedulerUtil.startup(runtimeProperties); } catch (Throwable t) { Context.shutdown(); WebModuleUtil.shutdownModules(filterConfig.getServletContext()); contextLoader.closeWebApplicationContext(filterConfig.getServletContext()); reportError(t.getMessage() + " Unable to complete the startup.", DEFAULT_PAGE); log.warn("Unable to complete the startup.", t); return; } // output properties to the openmrs runtime properties file so that this wizard is not run again FileOutputStream fos = null; try { fos = new FileOutputStream(getRuntimePropertiesFile()); runtimeProperties.store(fos, "Auto generated by OpenMRS initialization wizard"); wizardModel.workLog.add("Saved runtime properties file " + getRuntimePropertiesFile()); // don't need to catch errors here because we tested it at the beginning of the wizard } finally { if (fos != null) { fos.close(); } } // set this so that the wizard isn't run again on next page load Context.closeSession(); } catch (IOException e) { reportError(e.getMessage() + " Unable to complete the startup.", DEFAULT_PAGE); } finally { setCompleted(true); } } }; thread = new Thread(r); }
public InitializationCompletion() { Runnable r = new Runnable() { /** * TODO split this up into multiple testable methods * * @see java.lang.Runnable#run() */ public void run() { try { String connectionUsername; String connectionPassword; if (!wizardModel.hasCurrentOpenmrsDatabase) { setMessage("Create database"); // connect via jdbc and create a database String sql = "create database `?` default character set utf8"; int result = executeStatement(false, wizardModel.createDatabaseUsername, wizardModel.createDatabasePassword, sql, wizardModel.databaseName); // throw the user back to the main screen if this error occurs if (result < 0) { reportError(null, DEFAULT_PAGE); return; } else { wizardModel.workLog.add("Created database " + wizardModel.databaseName); } } if (wizardModel.createDatabaseUser) { setMessage("Create database user"); connectionUsername = wizardModel.databaseName + "_user"; if (connectionUsername.length() > 16) connectionUsername = wizardModel.databaseName.substring(0, 11) + "_user"; // trim off enough to leave space for _user at the end connectionPassword = ""; // generate random password from this subset of alphabet // intentionally left out these characters: ufsb$() to prevent certain words forming randomly String chars = "acdeghijklmnopqrtvwxyzACDEGHIJKLMNOPQRTVWXYZ0123456789.|~@#^&"; Random r = new Random(); for (int x = 0; x < 12; x++) { connectionPassword += chars.charAt(r.nextInt(chars.length())); } // connect via jdbc with root user and create an openmrs user String sql = "drop user '?'@'localhost'"; executeStatement(true, wizardModel.createUserUsername, wizardModel.createUserPassword, sql, connectionUsername); sql = "create user '?'@'localhost' identified by '?'"; if (-1 != executeStatement(false, wizardModel.createUserUsername, wizardModel.createUserPassword, sql, connectionUsername, connectionPassword)) { wizardModel.workLog.add("Created user " + connectionUsername); } else { // if error occurs stop reportError(null, DEFAULT_PAGE); return; } // grant the roles sql = "GRANT ALL ON `?`.* TO '?'@'localhost'"; int result = executeStatement(false, wizardModel.createUserUsername, wizardModel.createUserPassword, sql, wizardModel.databaseName, connectionUsername); // throw the user back to the main screen if this error occurs if (result < 0) { reportError(null, DEFAULT_PAGE); return; } else { wizardModel.workLog.add("Granted user " + connectionUsername + " all privileges to database " + wizardModel.databaseName); } } else { connectionUsername = wizardModel.currentDatabaseUsername; connectionPassword = wizardModel.currentDatabasePassword; } String finalDatabaseConnectionString = wizardModel.databaseConnection.replace("@DBNAME@", wizardModel.databaseName); // verify that the database connection works if (!verifyConnection(connectionUsername, connectionPassword, finalDatabaseConnectionString)) { setMessage("Verify that the database connection works"); // redirect to setup page if we got an error reportError(null, DEFAULT_PAGE); return; } // save the properties for startup purposes Properties runtimeProperties = new Properties(); runtimeProperties.put("connection.url", finalDatabaseConnectionString); runtimeProperties.put("connection.username", connectionUsername); runtimeProperties.put("connection.password", connectionPassword); runtimeProperties.put("module.allow_web_admin", wizardModel.moduleWebAdmin.toString()); runtimeProperties.put("auto_update_database", wizardModel.autoUpdateDatabase.toString()); runtimeProperties.put(SchedulerConstants.SCHEDULER_USERNAME_PROPERTY, "admin"); runtimeProperties.put(SchedulerConstants.SCHEDULER_PASSWORD_PROPERTY, wizardModel.adminUserPassword); Context.setRuntimeProperties(runtimeProperties); /** * A callback class that prints out info about liquibase changesets */ class PrintingChangeSetExecutorCallback implements ChangeSetExecutorCallback { private int i = 1; private String message; public PrintingChangeSetExecutorCallback(String message) { this.message = message; } /** * @see org.openmrs.util.DatabaseUpdater.ChangeSetExecutorCallback#executing(liquibase.ChangeSet, * int) */ public void executing(ChangeSet changeSet, int numChangeSetsToRun) { setMessage(message + " (" + i++ + "/" + numChangeSetsToRun + "): Author: " + changeSet.getAuthor() + " Comments: " + changeSet.getComments() + " Description: " + changeSet.getDescription()); } } if (wizardModel.createTables) { // use liquibase to create core data + tables try { setMessage("Executing " + LIQUIBASE_SCHEMA_DATA); DatabaseUpdater.executeChangelog(LIQUIBASE_SCHEMA_DATA, null, new PrintingChangeSetExecutorCallback("OpenMRS schema file")); DatabaseUpdater.executeChangelog(LIQUIBASE_CORE_DATA, null, new PrintingChangeSetExecutorCallback("OpenMRS core data file")); wizardModel.workLog.add("Created database tables and added core data"); } catch (Exception e) { reportError(e.getMessage() + " See the error log for more details", null); log.warn("Error while trying to create tables and demo data", e); } } // add demo data only if creating tables fresh and user selected the option add demo data if (wizardModel.createTables && wizardModel.addDemoData) { try { setMessage("Adding demo data"); DatabaseUpdater.executeChangelog(LIQUIBASE_DEMO_DATA, null, new PrintingChangeSetExecutorCallback("OpenMRS demo patients, users, and forms")); wizardModel.workLog.add("Added demo data"); } catch (Exception e) { reportError(e.getMessage() + " See the error log for more details", null); log.warn("Error while trying to add demo data", e); } } // update the database to the latest version try { setMessage("Updating the database to the latest version"); DatabaseUpdater.executeChangelog(null, null, new PrintingChangeSetExecutorCallback( "Updating database tables to latest version ")); } catch (Exception e) { reportError(e.getMessage() + " Error while trying to update to the latest database version", DEFAULT_PAGE); log.warn("Error while trying to update to the latest database version", e); return; } setMessage("Starting OpenMRS"); // start spring // after this point, all errors need to also call: contextLoader.closeWebApplicationContext(event.getServletContext()) // logic copied from org.springframework.web.context.ContextLoaderListener ContextLoader contextLoader = new ContextLoader(); contextLoader.initWebApplicationContext(filterConfig.getServletContext()); // start openmrs try { Context.openSession(); Context.startup(runtimeProperties); } catch (DatabaseUpdateException updateEx) { log.warn("Error while running the database update file", updateEx); reportError( updateEx.getMessage() + " There was an error while running the database update file: " + updateEx.getMessage(), DEFAULT_PAGE); return; } catch (InputRequiredException inputRequiredEx) { // TODO display a page looping over the required input and ask the user for each. // When done and the user and put in their say, call DatabaseUpdater.update(Map); // with the user's question/answer pairs log .warn("Unable to continue because user input is required for the db updates and we cannot do anything about that right now"); reportError( "Unable to continue because user input is required for the db updates and we cannot do anything about that right now", DEFAULT_PAGE); return; } // TODO catch openmrs errors here and drop the user back out to the setup screen if (!wizardModel.implementationId.equals("")) { try { Context.addProxyPrivilege(OpenmrsConstants.PRIV_MANAGE_GLOBAL_PROPERTIES); Context.addProxyPrivilege(OpenmrsConstants.PRIV_MANAGE_CONCEPT_SOURCES); Context.addProxyPrivilege(OpenmrsConstants.PRIV_VIEW_CONCEPT_SOURCES); Context.addProxyPrivilege(OpenmrsConstants.PRIV_MANAGE_IMPLEMENTATION_ID); ImplementationId implId = new ImplementationId(); implId.setName(wizardModel.implementationIdName); implId.setImplementationId(wizardModel.implementationId); implId.setPassphrase(wizardModel.implementationIdPassPhrase); implId.setDescription(wizardModel.implementationIdDescription); Context.getAdministrationService().setImplementationId(implId); } catch (Throwable t) { reportError(t.getMessage() + " Implementation ID could not be set.", DEFAULT_PAGE); log.warn("Implementation ID could not be set.", t); Context.shutdown(); WebModuleUtil.shutdownModules(filterConfig.getServletContext()); contextLoader.closeWebApplicationContext(filterConfig.getServletContext()); return; } finally { Context.removeProxyPrivilege(OpenmrsConstants.PRIV_MANAGE_GLOBAL_PROPERTIES); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_MANAGE_CONCEPT_SOURCES); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_CONCEPT_SOURCES); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_MANAGE_IMPLEMENTATION_ID); } } try { // change the admin user password from "test" to what they input above if (wizardModel.createTables) { Context.authenticate("admin", "test"); Context.getUserService().changePassword("test", wizardModel.adminUserPassword); Context.logout(); } // load modules Listener.loadAndStartCoreModules(filterConfig.getServletContext()); // web load modules Listener.performWebStartOfModules(filterConfig.getServletContext()); // start the scheduled tasks SchedulerUtil.startup(runtimeProperties); } catch (Throwable t) { Context.shutdown(); WebModuleUtil.shutdownModules(filterConfig.getServletContext()); contextLoader.closeWebApplicationContext(filterConfig.getServletContext()); reportError(t.getMessage() + " Unable to complete the startup.", DEFAULT_PAGE); log.warn("Unable to complete the startup.", t); return; } // output properties to the openmrs runtime properties file so that this wizard is not run again FileOutputStream fos = null; try { fos = new FileOutputStream(getRuntimePropertiesFile()); OpenmrsUtil.storeProperties(runtimeProperties, fos, "Auto generated by OpenMRS initialization wizard"); wizardModel.workLog.add("Saved runtime properties file " + getRuntimePropertiesFile()); // don't need to catch errors here because we tested it at the beginning of the wizard } finally { if (fos != null) { fos.close(); } } // set this so that the wizard isn't run again on next page load Context.closeSession(); } catch (IOException e) { reportError(e.getMessage() + " Unable to complete the startup.", DEFAULT_PAGE); } finally { setCompleted(true); } } }; thread = new Thread(r); }
diff --git a/Compilatron/java/src/Compiler.java b/Compilatron/java/src/Compiler.java index e237afc..aa4cb84 100644 --- a/Compilatron/java/src/Compiler.java +++ b/Compilatron/java/src/Compiler.java @@ -1,418 +1,418 @@ /** * Compiles the SIMPLE program into a memory array that can be run in an SML interpreter. * * @author Foster Mclane and Jonathan Lowe */ import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.ListIterator; import java.util.Scanner; import java.util.Stack; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Compiler { private final static Pattern relation_pattern = Pattern.compile("(.+)(>|<|>=|<=|==|!=)+(.+)"); private final static String operators = "+-*/()"; private final static Pattern expression_pattern = Pattern.compile("([a-zA-Z0-9+\\-*/]+)"); Scanner scanner; int[] memory; ArrayList<Integer> constants; ArrayList<Integer> line_number_list; HashMap<Integer, Integer> line_numbers; HashMap<String, Integer> variables; int last_line_number, pointer, data_pointer; /** * Constructs a new Compiler object given a file * * @param file The SIMPLE file * @throws FileNotFoundException Thrown if the file does not exist */ public Compiler(File file) throws FileNotFoundException { scanner = new Scanner(file); memory = new int[100]; constants = new ArrayList<Integer>(); line_number_list = new ArrayList<Integer>(); line_numbers = new HashMap<Integer, Integer>(); variables = new HashMap<String, Integer>(); last_line_number = -1; pointer = 0; data_pointer = 99; } /** * Return the current SIMPLE line number * * @return The line number */ public int getLineNumber() { return last_line_number; } /** * Return the current SML pointer * * @return The memory pointer */ public int getPointer() { return pointer; } /** * Compile the SIMPLE into an SML memory array * * @return The SML memory array * * @throws OutOfMemoryException Ran out of SML memory * @throws ArgumentException If without a goto * @throws InvalidVariableException Variable doesn't start with a letter * @throws NumberFormatException Invalid number * @throws SyntaxException SIMPLE syntax error * @throws GotoException Goto nonexistent line * @throws LineNumberException Line numbers don't increase * @throws UndefinedVariableException Variable accessed before it exists */ public int[] compile() throws OutOfMemoryException, ArgumentException, InvalidVariableException, NumberFormatException, SyntaxException, GotoException, LineNumberException, UndefinedVariableException { while(scanner.hasNextLine()) { if(pointer >= data_pointer) throw new OutOfMemoryException(); String[] command = scanner.nextLine().split(" "); //Everything is separated by spaces //Ignore comment lines if(command[0].equalsIgnoreCase("rem") || command[1].equalsIgnoreCase("rem")) continue; //Double check line numbers int line_number = Integer.parseInt(command[0]); if(line_number <= last_line_number) throw new LineNumberException(); //Add it to the hashmap and line number array if(!line_number_list.contains(line_number)) line_number_list.add(line_number); line_numbers.put(line_number, pointer); last_line_number = line_number; //Make a new variable and remember it if(command[1].equalsIgnoreCase("input")) { if(!Character.isLetter(command[2].charAt(0))) throw new InvalidVariableException(); variables.put(command[2], data_pointer); memory[pointer] = 1000 + data_pointer; pointer++; data_pointer--; } //Simply print variable else if(command[1].equalsIgnoreCase("print")) { if(!variables.containsKey(command[2])) throw new UndefinedVariableException(); memory[pointer] = 1100 + variables.get(command[2]); pointer++; } //If a variable doesn't exist, create it then parse the expression else if(command[1].equalsIgnoreCase("let")) { String[] params = command[2].split("=", 2); if(params.length < 2) throw new SyntaxException(); if(!Character.isLetter(params[0].charAt(0))) throw new InvalidVariableException(); if(!variables.containsKey(params[0])) { variables.put(params[0], data_pointer); data_pointer--; } parseExpression(params[1], variables.get(params[0])); } //Put a new goto else if(command[1].equalsIgnoreCase("goto")) { int goto_line = Integer.parseInt(command[2]); if(!line_number_list.contains(goto_line)) line_number_list.add(goto_line); memory[pointer] = 14000 + line_number_list.indexOf(goto_line); pointer++; } //Yay for if's else if(command[1].equalsIgnoreCase("if")) { if(!command[3].equalsIgnoreCase("goto")) throw new ArgumentException(); int goto_line = Integer.parseInt(command[4]); if(!line_number_list.contains(goto_line)) line_number_list.add(goto_line); parseRelation(command[2], line_number_list.indexOf(goto_line)); //Call parse relation } //Put a halt else if(command[1].equalsIgnoreCase("end")) { memory[pointer] = 4300; pointer++; } } //Make sure we still have room for constants if(pointer + constants.size() > data_pointer) throw new OutOfMemoryException(); - //Space the constants on the end of the program + //Add the constants to the end of the program for(int i = 0; i < constants.size(); i++) memory[pointer + i] = constants.get(i); for(int i = 0; i < 100; i++) { int opcode = memory[i] / 100; switch(opcode) { //Constants case 120: case 121: case 130: case 131: case 132: case 133: //Take the 1 flag from the front then increment the constant index to point to the constant at the end of the program //Equivalent to (opcode - 100) * 100 + pointer + memory[i] % 100 memory[i] = memory[i] - 10000 + pointer; break; - //Line numbers + //Line numbers case 140: case 141: case 142: //Check that the line number exists Integer line_number_pointer = line_numbers.get(line_number_list.get(memory[i] % 100)); if(line_number_pointer == null) throw new GotoException(); memory[i] = (opcode - 100) * 100 + line_number_pointer; break; } } pointer += constants.size(); return memory; } private void parseRelation(String relation, int goto_symbol) throws OutOfMemoryException, SyntaxException, NumberFormatException, UndefinedVariableException { //Check relations based on regexes Matcher matcher = relation_pattern.matcher(relation); if(!matcher.matches()) throw new SyntaxException(); parseExpression(matcher.group(1), data_pointer); data_pointer--; parseExpression(matcher.group(3), data_pointer); memory[pointer] = 2000 + data_pointer; pointer++; if(matcher.group(2).charAt(0) == '>') { memory[pointer] = 3100 + data_pointer + 1; //First number pointer++; memory[pointer] = 14100 + goto_symbol; //Branch negative to "goto" if(matcher.group(2).length() > 1 && matcher.group(2).charAt(1) == '=') { pointer++; memory[pointer] = 4100 + goto_symbol; //Also branch zero if equal to } } else if(matcher.group(2).charAt(0) == '<') { memory[pointer - 1] = 2000 + data_pointer + 1; memory[pointer] = 3100 + data_pointer; pointer++; memory[pointer] = 14100 + goto_symbol; if(matcher.group(2).length() > 1 && matcher.group(2).charAt(1) == '=') { pointer++; memory[pointer] = 14100 + goto_symbol; } } else if(matcher.group(2).equals("==")) { memory[pointer] = 3100 + data_pointer + 1; pointer++; memory[pointer] = 14200 + goto_symbol; } else if(matcher.group(2).equals("!=")) { if(!constants.contains(-1)) constants.add(-1); memory[pointer] = 3100 + data_pointer + 1; pointer++; memory[pointer] = 14100 + goto_symbol; pointer++; memory[pointer] = 13300 + constants.indexOf(-1); pointer++; memory[pointer] = 14100 + goto_symbol; } pointer++; data_pointer--; } private void parseExpression(String expression, int value_pointer) throws OutOfMemoryException, SyntaxException, NumberFormatException, UndefinedVariableException { //Check expressions based on regexes Matcher matcher = expression_pattern.matcher(expression); if(!matcher.matches()) throw new SyntaxException(); LinkedList<String> postfix_list = convertToPostfix(expression); ListIterator<String> postfix = postfix_list.listIterator(); if(postfix_list.size() == 1) { String value = postfix.next(); int value_symbol; if(Character.isLetter(value.charAt(0))) { //Check if variable exists before using it if(!variables.containsKey(value)) throw new UndefinedVariableException(); value_symbol = variables.get(value); } else { int number = Integer.parseInt(value); if(!constants.contains(number)) constants.add(number); //This is a constant so mark it value_symbol = 10000 + constants.indexOf(number); } memory[pointer] = 2000 + value_symbol; pointer++; memory[pointer] = 2100 + value_pointer; pointer++; return; } int temp_data_pointer = data_pointer; while(postfix.hasNext()) { int operator = operators.indexOf(postfix.next()); if(operator != -1) { if(temp_data_pointer < pointer) throw new OutOfMemoryException(); postfix.previous(); String operand = postfix.previous(); int operand_symbol; if(operand.charAt(0) == '.') { operand_symbol = Integer.parseInt(operand.substring(1)); } else if(Character.isLetter(operand.charAt(0))) { if(!variables.containsKey(operand)) throw new UndefinedVariableException(); operand_symbol = variables.get(operand); } else { int number = Integer.parseInt(operand); if(!constants.contains(number)) constants.add(number); //This is a constant so mark it operand_symbol = 10000 + constants.indexOf(number); } String load = postfix.previous(); int load_symbol; if(load.charAt(0) == '.') { load_symbol = Integer.parseInt(load.substring(1)); } else if(Character.isLetter(load.charAt(0))) { if(!variables.containsKey(load)) throw new UndefinedVariableException(); load_symbol = variables.get(load); } else { int number = Integer.parseInt(load); if(!constants.contains(number)) constants.add(number); //This is a constant so mark it load_symbol = 10000 + constants.indexOf(number); } memory[pointer] = 2000 + load_symbol; pointer++; switch(operator) { case 0: memory[pointer] = 3000 + operand_symbol; break; case 1: memory[pointer] = 3100 + operand_symbol; break; case 2: memory[pointer] = 3300 + operand_symbol; break; case 3: memory[pointer] = 3200 + operand_symbol; break; } pointer++; postfix.remove(); postfix.next(); postfix.remove(); postfix.next(); postfix.remove(); if(postfix.hasNext()) { memory[pointer] = 2100 + temp_data_pointer; postfix.add("." + temp_data_pointer); temp_data_pointer--; } else { memory[pointer] = 2100 + value_pointer; } pointer++; } } } private LinkedList<String> convertToPostfix(String infix) { LinkedList<String> postfix = new LinkedList<String>(); Stack<Character> operator_stack = new Stack<Character>(); char[] chars = infix.toCharArray(); for(int i = 0; i < chars.length; i++) { String term = new String(); //Get full term while(operators.indexOf(chars[i]) == -1 || i == 0 || (operators.indexOf(chars[i - 1]) != -1 && operators.indexOf(chars[i]) == 1)) { term += chars[i]; i++; if(i >= chars.length) { postfix.add(term); while(!operator_stack.empty()) postfix.add(Character.toString(operator_stack.pop())); return postfix; } } postfix.add(term); if(operator_stack.empty()) { operator_stack.push(chars[i]); } else { while(operators.indexOf(chars[i]) <= operators.indexOf(operator_stack.peek())) { postfix.add(Character.toString(operator_stack.pop())); } operator_stack.push(chars[i]); } } return postfix; } }
false
true
public int[] compile() throws OutOfMemoryException, ArgumentException, InvalidVariableException, NumberFormatException, SyntaxException, GotoException, LineNumberException, UndefinedVariableException { while(scanner.hasNextLine()) { if(pointer >= data_pointer) throw new OutOfMemoryException(); String[] command = scanner.nextLine().split(" "); //Everything is separated by spaces //Ignore comment lines if(command[0].equalsIgnoreCase("rem") || command[1].equalsIgnoreCase("rem")) continue; //Double check line numbers int line_number = Integer.parseInt(command[0]); if(line_number <= last_line_number) throw new LineNumberException(); //Add it to the hashmap and line number array if(!line_number_list.contains(line_number)) line_number_list.add(line_number); line_numbers.put(line_number, pointer); last_line_number = line_number; //Make a new variable and remember it if(command[1].equalsIgnoreCase("input")) { if(!Character.isLetter(command[2].charAt(0))) throw new InvalidVariableException(); variables.put(command[2], data_pointer); memory[pointer] = 1000 + data_pointer; pointer++; data_pointer--; } //Simply print variable else if(command[1].equalsIgnoreCase("print")) { if(!variables.containsKey(command[2])) throw new UndefinedVariableException(); memory[pointer] = 1100 + variables.get(command[2]); pointer++; } //If a variable doesn't exist, create it then parse the expression else if(command[1].equalsIgnoreCase("let")) { String[] params = command[2].split("=", 2); if(params.length < 2) throw new SyntaxException(); if(!Character.isLetter(params[0].charAt(0))) throw new InvalidVariableException(); if(!variables.containsKey(params[0])) { variables.put(params[0], data_pointer); data_pointer--; } parseExpression(params[1], variables.get(params[0])); } //Put a new goto else if(command[1].equalsIgnoreCase("goto")) { int goto_line = Integer.parseInt(command[2]); if(!line_number_list.contains(goto_line)) line_number_list.add(goto_line); memory[pointer] = 14000 + line_number_list.indexOf(goto_line); pointer++; } //Yay for if's else if(command[1].equalsIgnoreCase("if")) { if(!command[3].equalsIgnoreCase("goto")) throw new ArgumentException(); int goto_line = Integer.parseInt(command[4]); if(!line_number_list.contains(goto_line)) line_number_list.add(goto_line); parseRelation(command[2], line_number_list.indexOf(goto_line)); //Call parse relation } //Put a halt else if(command[1].equalsIgnoreCase("end")) { memory[pointer] = 4300; pointer++; } } //Make sure we still have room for constants if(pointer + constants.size() > data_pointer) throw new OutOfMemoryException(); //Space the constants on the end of the program for(int i = 0; i < constants.size(); i++) memory[pointer + i] = constants.get(i); for(int i = 0; i < 100; i++) { int opcode = memory[i] / 100; switch(opcode) { //Constants case 120: case 121: case 130: case 131: case 132: case 133: //Take the 1 flag from the front then increment the constant index to point to the constant at the end of the program //Equivalent to (opcode - 100) * 100 + pointer + memory[i] % 100 memory[i] = memory[i] - 10000 + pointer; break; //Line numbers case 140: case 141: case 142: //Check that the line number exists Integer line_number_pointer = line_numbers.get(line_number_list.get(memory[i] % 100)); if(line_number_pointer == null) throw new GotoException(); memory[i] = (opcode - 100) * 100 + line_number_pointer; break; } } pointer += constants.size(); return memory; }
public int[] compile() throws OutOfMemoryException, ArgumentException, InvalidVariableException, NumberFormatException, SyntaxException, GotoException, LineNumberException, UndefinedVariableException { while(scanner.hasNextLine()) { if(pointer >= data_pointer) throw new OutOfMemoryException(); String[] command = scanner.nextLine().split(" "); //Everything is separated by spaces //Ignore comment lines if(command[0].equalsIgnoreCase("rem") || command[1].equalsIgnoreCase("rem")) continue; //Double check line numbers int line_number = Integer.parseInt(command[0]); if(line_number <= last_line_number) throw new LineNumberException(); //Add it to the hashmap and line number array if(!line_number_list.contains(line_number)) line_number_list.add(line_number); line_numbers.put(line_number, pointer); last_line_number = line_number; //Make a new variable and remember it if(command[1].equalsIgnoreCase("input")) { if(!Character.isLetter(command[2].charAt(0))) throw new InvalidVariableException(); variables.put(command[2], data_pointer); memory[pointer] = 1000 + data_pointer; pointer++; data_pointer--; } //Simply print variable else if(command[1].equalsIgnoreCase("print")) { if(!variables.containsKey(command[2])) throw new UndefinedVariableException(); memory[pointer] = 1100 + variables.get(command[2]); pointer++; } //If a variable doesn't exist, create it then parse the expression else if(command[1].equalsIgnoreCase("let")) { String[] params = command[2].split("=", 2); if(params.length < 2) throw new SyntaxException(); if(!Character.isLetter(params[0].charAt(0))) throw new InvalidVariableException(); if(!variables.containsKey(params[0])) { variables.put(params[0], data_pointer); data_pointer--; } parseExpression(params[1], variables.get(params[0])); } //Put a new goto else if(command[1].equalsIgnoreCase("goto")) { int goto_line = Integer.parseInt(command[2]); if(!line_number_list.contains(goto_line)) line_number_list.add(goto_line); memory[pointer] = 14000 + line_number_list.indexOf(goto_line); pointer++; } //Yay for if's else if(command[1].equalsIgnoreCase("if")) { if(!command[3].equalsIgnoreCase("goto")) throw new ArgumentException(); int goto_line = Integer.parseInt(command[4]); if(!line_number_list.contains(goto_line)) line_number_list.add(goto_line); parseRelation(command[2], line_number_list.indexOf(goto_line)); //Call parse relation } //Put a halt else if(command[1].equalsIgnoreCase("end")) { memory[pointer] = 4300; pointer++; } } //Make sure we still have room for constants if(pointer + constants.size() > data_pointer) throw new OutOfMemoryException(); //Add the constants to the end of the program for(int i = 0; i < constants.size(); i++) memory[pointer + i] = constants.get(i); for(int i = 0; i < 100; i++) { int opcode = memory[i] / 100; switch(opcode) { //Constants case 120: case 121: case 130: case 131: case 132: case 133: //Take the 1 flag from the front then increment the constant index to point to the constant at the end of the program //Equivalent to (opcode - 100) * 100 + pointer + memory[i] % 100 memory[i] = memory[i] - 10000 + pointer; break; //Line numbers case 140: case 141: case 142: //Check that the line number exists Integer line_number_pointer = line_numbers.get(line_number_list.get(memory[i] % 100)); if(line_number_pointer == null) throw new GotoException(); memory[i] = (opcode - 100) * 100 + line_number_pointer; break; } } pointer += constants.size(); return memory; }
diff --git a/src/test/java/ch/o2it/weblounge/common/content/PublishingContextImplTest.java b/src/test/java/ch/o2it/weblounge/common/content/PublishingContextImplTest.java index dc688fa66..90242daad 100644 --- a/src/test/java/ch/o2it/weblounge/common/content/PublishingContextImplTest.java +++ b/src/test/java/ch/o2it/weblounge/common/content/PublishingContextImplTest.java @@ -1,162 +1,163 @@ /* * Weblounge: Web Content Management System * Copyright (c) 2009 The Weblounge Team * http://weblounge.o2it.ch * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package ch.o2it.weblounge.common.content; import static org.junit.Assert.fail; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import ch.o2it.weblounge.common.impl.content.PublishingContext; import ch.o2it.weblounge.common.impl.user.UserImpl; import ch.o2it.weblounge.common.user.User; import org.junit.Before; import org.junit.Test; import java.util.Date; /** * Test cases for {@link PublishingContext}. */ public class PublishingContextImplTest { /** The test context */ protected PublishingContext ctx = null; /** Publisher */ protected User publisher = new UserImpl("john", "testland", "John Doe"); /** Publication start date */ protected Date startDate = new Date(1257501172000L); /** Publication end date */ protected Date endDate = new Date(1289087999000L); /** * @throws java.lang.Exception */ @Before public void setUp() throws Exception { ctx = new PublishingContext(); ctx.setPublisher(publisher); ctx.setPublishFrom(startDate); ctx.setPublishTo(endDate); } /** * Test method for * {@link ch.o2it.weblounge.common.impl.content.PublishingContext#getPublisher()} * . */ @Test public void testGetPublisher() { assertEquals(publisher, ctx.getPublisher()); } /** * Test method for * {@link ch.o2it.weblounge.common.impl.content.PublishingContext#getPublishFrom()} * . */ @Test public void testGetPublishFrom() { assertEquals(startDate, ctx.getPublishFrom()); } /** * Test method for * {@link ch.o2it.weblounge.common.impl.content.PublishingContext#getPublishTo()} * . */ @Test public void testGetPublishTo() { assertEquals(endDate, ctx.getPublishTo()); } /** * Test method for * {@link ch.o2it.weblounge.common.impl.content.PublishingContext#isPublished()} * . */ @Test public void testIsPublished() { Date yesterday = new Date(new Date().getTime() - 86400000L); Date tomorrow = new Date(new Date().getTime() + 86400000L); - ctx.setPublishFrom(yesterday); - ctx.setPublishTo(tomorrow); + ctx.setPublished(null, yesterday, tomorrow); +// ctx.setPublishFrom(yesterday); +// ctx.setPublishTo(tomorrow); assertTrue(ctx.isPublished()); ctx.setPublishTo(null); assertTrue(ctx.isPublished()); ctx.setPublishFrom(null); assertTrue(ctx.isPublished()); } /** * Test method for * {@link ch.o2it.weblounge.common.impl.content.PublishingContext#isPublished(java.util.Date)} * . */ @Test public void testIsPublishedDate() { assertTrue(ctx.isPublished(new Date(startDate.getTime() + 1000))); assertTrue(ctx.isPublished(new Date(endDate.getTime() - 1000))); assertFalse(ctx.isPublished(new Date(startDate.getTime() - 86400000L))); assertFalse(ctx.isPublished(new Date(endDate.getTime() + 86400000L))); } /** * Test method for * {@link ch.o2it.weblounge.common.impl.content.PublishingContext#clone()} * . */ @Test public void testClone() { PublishingContext c = null; try { c = (PublishingContext)ctx.clone(); assertEquals(ctx.getPublisher(), c.getPublisher()); assertEquals(ctx.getPublishFrom(), c.getPublishFrom()); assertEquals(ctx.getPublishTo(), c.getPublishTo()); } catch (CloneNotSupportedException e) { fail("Creating clone of publishing context failed"); } } /** * Test method for * {@link ch.o2it.weblounge.common.impl.content.PublishingContext#setPublished(User, Date, Date)} * . */ @Test public void testSetPublished() { try { Date yesterday = new Date(new Date().getTime() - 86400000L); Date tomorrow = new Date(new Date().getTime() + 86400000L); ctx.setPublished(publisher, tomorrow, yesterday); fail("Setting a start date that is after the end date should not be possible"); } catch (IllegalArgumentException e) { // Expected } } }
true
true
public void testIsPublished() { Date yesterday = new Date(new Date().getTime() - 86400000L); Date tomorrow = new Date(new Date().getTime() + 86400000L); ctx.setPublishFrom(yesterday); ctx.setPublishTo(tomorrow); assertTrue(ctx.isPublished()); ctx.setPublishTo(null); assertTrue(ctx.isPublished()); ctx.setPublishFrom(null); assertTrue(ctx.isPublished()); }
public void testIsPublished() { Date yesterday = new Date(new Date().getTime() - 86400000L); Date tomorrow = new Date(new Date().getTime() + 86400000L); ctx.setPublished(null, yesterday, tomorrow); // ctx.setPublishFrom(yesterday); // ctx.setPublishTo(tomorrow); assertTrue(ctx.isPublished()); ctx.setPublishTo(null); assertTrue(ctx.isPublished()); ctx.setPublishFrom(null); assertTrue(ctx.isPublished()); }
diff --git a/tests/frontend/org/voltdb/jni/TestExecutionEngine.java b/tests/frontend/org/voltdb/jni/TestExecutionEngine.java index f7d844cd8..4763b092d 100755 --- a/tests/frontend/org/voltdb/jni/TestExecutionEngine.java +++ b/tests/frontend/org/voltdb/jni/TestExecutionEngine.java @@ -1,344 +1,348 @@ /* This file is part of VoltDB. * Copyright (C) 2008-2010 VoltDB Inc. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.voltdb.jni; import java.nio.channels.SocketChannel; import java.util.HashMap; import java.util.HashSet; import java.util.concurrent.atomic.AtomicReference; import junit.framework.TestCase; import org.voltdb.EELibraryLoader; import org.voltdb.SysProcSelector; import org.voltdb.TableStreamType; import org.voltdb.VoltDB; import org.voltdb.VoltTable; import org.voltdb.VoltType; import org.voltdb.catalog.Catalog; import org.voltdb.catalog.LoadCatalogToString; import org.voltdb.exceptions.EEException; import org.voltdb.messaging.MockMailbox; import org.voltdb.messaging.VoltMessage; import org.voltdb.utils.DBBPool; import org.voltdb.utils.DBBPool.BBContainer; import org.voltdb.utils.Pair; /** * Tests native execution engine JNI interface. */ public class TestExecutionEngine extends TestCase { public void testLoadCatalogs() throws Exception { Catalog catalog = new Catalog(); catalog.execute(LoadCatalogToString.THE_CATALOG); sourceEngine.loadCatalog(catalog.serialize()); } public void testLoadBadCatalogs() throws Exception { /* * Tests if the intended EE exception will be thrown when bad catalog is * loaded. We are really expecting an ERROR message on the terminal in * this case. */ String badCatalog = LoadCatalogToString.THE_CATALOG.replaceFirst("set", "bad"); try { sourceEngine.loadCatalog(badCatalog); } catch (final EEException e) { return; } assertFalse(true); } public void testMultiSiteInSamePhysicalNodeWithExecutionSite() throws Exception { // TODO } private void loadTestTables(Catalog catalog) throws Exception { final boolean allowExport = false; int WAREHOUSE_TABLEID = warehouseTableId(catalog); int STOCK_TABLEID = stockTableId(catalog); VoltTable warehousedata = new VoltTable( new VoltTable.ColumnInfo("W_ID", VoltType.INTEGER), new VoltTable.ColumnInfo("W_NAME", VoltType.STRING) ); for (int i = 0; i < 200; ++i) { warehousedata.addRow(i, "str" + i); } System.out.println(warehousedata.toString()); sourceEngine.loadTable(WAREHOUSE_TABLEID, warehousedata, 0, 0, Long.MAX_VALUE, allowExport); VoltTable stockdata = new VoltTable( new VoltTable.ColumnInfo("S_I_ID", VoltType.INTEGER), new VoltTable.ColumnInfo("S_W_ID", VoltType.INTEGER), new VoltTable.ColumnInfo("S_QUANTITY", VoltType.INTEGER) ); for (int i = 0; i < 1000; ++i) { stockdata.addRow(i, i % 200, i * i); } sourceEngine.loadTable(STOCK_TABLEID, stockdata, 0, 0, Long.MAX_VALUE, allowExport); } public void testLoadTable() throws Exception { Catalog catalog = new Catalog(); catalog.execute(LoadCatalogToString.THE_CATALOG); sourceEngine.loadCatalog(catalog.serialize()); int WAREHOUSE_TABLEID = warehouseTableId(catalog); int STOCK_TABLEID = stockTableId(catalog); loadTestTables(catalog); assertEquals(200, sourceEngine.serializeTable(WAREHOUSE_TABLEID).getRowCount()); assertEquals(1000, sourceEngine.serializeTable(STOCK_TABLEID).getRowCount()); } public void testStreamTables() throws Exception { final Catalog catalog = new Catalog(); catalog.execute(LoadCatalogToString.THE_CATALOG); sourceEngine.loadCatalog(catalog.serialize()); ExecutionEngine destinationEngine = new ExecutionEngineJNI(null, CLUSTER_ID, NODE_ID, 0, 0, ""); destinationEngine.loadCatalog(catalog.serialize()); int WAREHOUSE_TABLEID = warehouseTableId(catalog); int STOCK_TABLEID = stockTableId(catalog); loadTestTables(catalog); sourceEngine.activateTableStream( WAREHOUSE_TABLEID, TableStreamType.RECOVERY ); sourceEngine.activateTableStream( STOCK_TABLEID, TableStreamType.RECOVERY ); BBContainer origin = DBBPool.allocateDirect(1024 * 1024 * 2); try { origin.b.clear(); long address = org.voltdb.utils.DBBPool.getBufferAddress(origin.b); BBContainer container = new BBContainer(origin.b, address){ @Override public void discard() { }}; int serialized = sourceEngine.tableStreamSerializeMore( container, WAREHOUSE_TABLEID, TableStreamType.RECOVERY); assertTrue(serialized > 0); container.b.limit(serialized); destinationEngine.processRecoveryMessage( container.b, container.address); serialized = sourceEngine.tableStreamSerializeMore( container, WAREHOUSE_TABLEID, TableStreamType.RECOVERY); assertEquals( 21, serialized); + int id = container.b.get(); + assert(id >= 0); // assertEquals( RecoveryMessageType.Complete.ordinal(), container.b.get()); assertEquals( WAREHOUSE_TABLEID, container.b.getInt()); assertEquals( sourceEngine.tableHashCode(WAREHOUSE_TABLEID), destinationEngine.tableHashCode(WAREHOUSE_TABLEID)); container.b.clear(); serialized = sourceEngine.tableStreamSerializeMore( container, STOCK_TABLEID, TableStreamType.RECOVERY); assertTrue(serialized > 0); container.b.limit(serialized); destinationEngine.processRecoveryMessage( container.b, container.address); serialized = sourceEngine.tableStreamSerializeMore( container, STOCK_TABLEID, TableStreamType.RECOVERY); assertEquals( 21, serialized); + id = container.b.get(); + assert(id >= 0); // assertEquals( RecoveryMessageType.Complete.ordinal(), container.b.get()); assertEquals( STOCK_TABLEID, container.b.getInt()); assertEquals( sourceEngine.tableHashCode(STOCK_TABLEID), destinationEngine.tableHashCode(STOCK_TABLEID)); } finally { origin.discard(); } } // public void testRecoveryProcessors() throws Exception { // final int sourceId = 0; // final int destinationId = 32; // final AtomicReference<Boolean> sourceCompleted = new AtomicReference<Boolean>(false); // final AtomicReference<Boolean> destinationCompleted = new AtomicReference<Boolean>(false); // final Catalog catalog = new Catalog(); // catalog.execute(LoadCatalogToString.THE_CATALOG); // sourceEngine.loadCatalog(catalog.serialize()); // final ExecutionEngine destinationEngine = // new ExecutionEngineJNI(null, CLUSTER_ID, NODE_ID, destinationId, destinationId, ""); // destinationEngine.loadCatalog(catalog.serialize()); // // int WAREHOUSE_TABLEID = warehouseTableId(catalog); // int STOCK_TABLEID = stockTableId(catalog); // // loadTestTables(catalog); // // final HashMap<Pair<String, Integer>, HashSet<Integer>> tablesAndDestinations = // new HashMap<Pair<String, Integer>, HashSet<Integer>>(); // HashSet<Integer> destinations = new HashSet<Integer>(); // destinations.add(destinationId); // tablesAndDestinations.put(Pair.of( "STOCK", STOCK_TABLEID), destinations); // tablesAndDestinations.put(Pair.of( "WAREHOUSE", WAREHOUSE_TABLEID), destinations); // // final MockMailbox sourceMailbox = new MockMailbox(); // MockMailbox.registerMailbox( sourceId, sourceMailbox); // // final Runnable onSourceCompletion = new Runnable() { // @Override // public void run() { // sourceCompleted.set(true); // } // }; // // final MessageHandler mh = new MessageHandler() { // // @Override // public void handleMessage(VoltMessage message) { // fail(); // } // }; // // Thread sourceThread = new Thread("Source thread") { // @Override // public void run() { // try { // VoltMessage message = sourceMailbox.recvBlocking(); // assertTrue(message != null); // assertTrue(message instanceof RecoveryMessage); // RecoveryMessage rm = (RecoveryMessage)message; // SocketChannel sc = RecoverySiteProcessorSource.createRecoveryConnection(rm.address(), rm.port()); // final RecoverySiteProcessorSource sourceProcessor = // new RecoverySiteProcessorSource( // rm.txnId(), // rm.sourceSite(), // tablesAndDestinations, // sourceEngine, // sourceMailbox, // sourceId, // onSourceCompletion, // mh, // sc); // sourceProcessor.doRecoveryWork(0); // } catch (java.io.IOException e) { // e.printStackTrace(); // return; // } // } // }; // sourceThread.start(); // // final HashMap<Pair<String, Integer>, Integer> tablesAndSources = // new HashMap<Pair<String, Integer>, Integer>(); // tablesAndSources.put(Pair.of( "STOCK", STOCK_TABLEID), sourceId); // tablesAndSources.put(Pair.of( "WAREHOUSE", WAREHOUSE_TABLEID), sourceId); // // final MockMailbox destinationMailbox = new MockMailbox(); // MockMailbox.registerMailbox( destinationId, destinationMailbox); // // final Runnable onDestinationCompletion = new Runnable() { // @Override // public void run() { // destinationCompleted.set(true); // } // }; // // Thread destinationThread = new Thread("Destination thread") { // @Override // public void run() { // RecoverySiteProcessorDestination destinationProcess = // new RecoverySiteProcessorDestination( // tablesAndSources, // destinationEngine, // destinationMailbox, // destinationId, // 0, // onDestinationCompletion, // mh); // /* // * Do a lot of craziness so we can intercept the mailbox calls // * and discard the buffer so it is returned to the source // */ // destinationProcess.doRecoveryWork(-1); // destinationProcess.doRecoveryWork(0); // assert(destinationCompleted.get()); // } // }; // destinationThread.start(); // // destinationThread.join(); // sourceThread.join(); // // assertEquals( sourceEngine.tableHashCode(STOCK_TABLEID), destinationEngine.tableHashCode(STOCK_TABLEID)); // assertEquals( sourceEngine.tableHashCode(WAREHOUSE_TABLEID), destinationEngine.tableHashCode(WAREHOUSE_TABLEID)); // // assertEquals(200, sourceEngine.serializeTable(WAREHOUSE_TABLEID).getRowCount()); // assertEquals(1000, sourceEngine.serializeTable(STOCK_TABLEID).getRowCount()); // assertEquals(200, destinationEngine.serializeTable(WAREHOUSE_TABLEID).getRowCount()); // assertEquals(1000, destinationEngine.serializeTable(STOCK_TABLEID).getRowCount()); // } private int warehouseTableId(Catalog catalog) { return catalog.getClusters().get("cluster").getDatabases().get("database").getTables().get("WAREHOUSE").getRelativeIndex(); } private int stockTableId(Catalog catalog) { return catalog.getClusters().get("cluster").getDatabases().get("database").getTables().get("STOCK").getRelativeIndex(); } public void testGetStats() throws Exception { final Catalog catalog = new Catalog(); catalog.execute(LoadCatalogToString.THE_CATALOG); sourceEngine.loadCatalog(catalog.serialize()); final int WAREHOUSE_TABLEID = catalog.getClusters().get("cluster").getDatabases().get("database").getTables().get("WAREHOUSE").getRelativeIndex(); final int STOCK_TABLEID = catalog.getClusters().get("cluster").getDatabases().get("database").getTables().get("STOCK").getRelativeIndex(); final int locators[] = new int[] { WAREHOUSE_TABLEID, STOCK_TABLEID }; final VoltTable results[] = sourceEngine.getStats(SysProcSelector.TABLE, locators, false, 0L); assertNotNull(results); assertEquals(1, results.length); assertNotNull(results[0]); final VoltTable resultTable = results[0]; assertEquals(2, resultTable.getRowCount()); while (resultTable.advanceRow()) { String tn = resultTable.getString("TABLE_NAME"); assertTrue(tn.equals("WAREHOUSE") || tn.equals("STOCK")); } } private ExecutionEngine sourceEngine; private static final int CLUSTER_ID = 2; private static final int NODE_ID = 1; @Override protected void setUp() throws Exception { super.setUp(); EELibraryLoader.loadExecutionEngineLibrary(true); // VoltDB.instance().readBuildInfo(); sourceEngine = new ExecutionEngineJNI(null, CLUSTER_ID, NODE_ID, 0, 0, ""); } @Override protected void tearDown() throws Exception { super.tearDown(); sourceEngine.release(); sourceEngine = null; } }
false
true
public void testStreamTables() throws Exception { final Catalog catalog = new Catalog(); catalog.execute(LoadCatalogToString.THE_CATALOG); sourceEngine.loadCatalog(catalog.serialize()); ExecutionEngine destinationEngine = new ExecutionEngineJNI(null, CLUSTER_ID, NODE_ID, 0, 0, ""); destinationEngine.loadCatalog(catalog.serialize()); int WAREHOUSE_TABLEID = warehouseTableId(catalog); int STOCK_TABLEID = stockTableId(catalog); loadTestTables(catalog); sourceEngine.activateTableStream( WAREHOUSE_TABLEID, TableStreamType.RECOVERY ); sourceEngine.activateTableStream( STOCK_TABLEID, TableStreamType.RECOVERY ); BBContainer origin = DBBPool.allocateDirect(1024 * 1024 * 2); try { origin.b.clear(); long address = org.voltdb.utils.DBBPool.getBufferAddress(origin.b); BBContainer container = new BBContainer(origin.b, address){ @Override public void discard() { }}; int serialized = sourceEngine.tableStreamSerializeMore( container, WAREHOUSE_TABLEID, TableStreamType.RECOVERY); assertTrue(serialized > 0); container.b.limit(serialized); destinationEngine.processRecoveryMessage( container.b, container.address); serialized = sourceEngine.tableStreamSerializeMore( container, WAREHOUSE_TABLEID, TableStreamType.RECOVERY); assertEquals( 21, serialized); // assertEquals( RecoveryMessageType.Complete.ordinal(), container.b.get()); assertEquals( WAREHOUSE_TABLEID, container.b.getInt()); assertEquals( sourceEngine.tableHashCode(WAREHOUSE_TABLEID), destinationEngine.tableHashCode(WAREHOUSE_TABLEID)); container.b.clear(); serialized = sourceEngine.tableStreamSerializeMore( container, STOCK_TABLEID, TableStreamType.RECOVERY); assertTrue(serialized > 0); container.b.limit(serialized); destinationEngine.processRecoveryMessage( container.b, container.address); serialized = sourceEngine.tableStreamSerializeMore( container, STOCK_TABLEID, TableStreamType.RECOVERY); assertEquals( 21, serialized); // assertEquals( RecoveryMessageType.Complete.ordinal(), container.b.get()); assertEquals( STOCK_TABLEID, container.b.getInt()); assertEquals( sourceEngine.tableHashCode(STOCK_TABLEID), destinationEngine.tableHashCode(STOCK_TABLEID)); } finally { origin.discard(); } }
public void testStreamTables() throws Exception { final Catalog catalog = new Catalog(); catalog.execute(LoadCatalogToString.THE_CATALOG); sourceEngine.loadCatalog(catalog.serialize()); ExecutionEngine destinationEngine = new ExecutionEngineJNI(null, CLUSTER_ID, NODE_ID, 0, 0, ""); destinationEngine.loadCatalog(catalog.serialize()); int WAREHOUSE_TABLEID = warehouseTableId(catalog); int STOCK_TABLEID = stockTableId(catalog); loadTestTables(catalog); sourceEngine.activateTableStream( WAREHOUSE_TABLEID, TableStreamType.RECOVERY ); sourceEngine.activateTableStream( STOCK_TABLEID, TableStreamType.RECOVERY ); BBContainer origin = DBBPool.allocateDirect(1024 * 1024 * 2); try { origin.b.clear(); long address = org.voltdb.utils.DBBPool.getBufferAddress(origin.b); BBContainer container = new BBContainer(origin.b, address){ @Override public void discard() { }}; int serialized = sourceEngine.tableStreamSerializeMore( container, WAREHOUSE_TABLEID, TableStreamType.RECOVERY); assertTrue(serialized > 0); container.b.limit(serialized); destinationEngine.processRecoveryMessage( container.b, container.address); serialized = sourceEngine.tableStreamSerializeMore( container, WAREHOUSE_TABLEID, TableStreamType.RECOVERY); assertEquals( 21, serialized); int id = container.b.get(); assert(id >= 0); // assertEquals( RecoveryMessageType.Complete.ordinal(), container.b.get()); assertEquals( WAREHOUSE_TABLEID, container.b.getInt()); assertEquals( sourceEngine.tableHashCode(WAREHOUSE_TABLEID), destinationEngine.tableHashCode(WAREHOUSE_TABLEID)); container.b.clear(); serialized = sourceEngine.tableStreamSerializeMore( container, STOCK_TABLEID, TableStreamType.RECOVERY); assertTrue(serialized > 0); container.b.limit(serialized); destinationEngine.processRecoveryMessage( container.b, container.address); serialized = sourceEngine.tableStreamSerializeMore( container, STOCK_TABLEID, TableStreamType.RECOVERY); assertEquals( 21, serialized); id = container.b.get(); assert(id >= 0); // assertEquals( RecoveryMessageType.Complete.ordinal(), container.b.get()); assertEquals( STOCK_TABLEID, container.b.getInt()); assertEquals( sourceEngine.tableHashCode(STOCK_TABLEID), destinationEngine.tableHashCode(STOCK_TABLEID)); } finally { origin.discard(); } }
diff --git a/service/src/main/java/org/evasion/cloud/service/security/HTML5CorsFilter.java b/service/src/main/java/org/evasion/cloud/service/security/HTML5CorsFilter.java index f289fbf..53062c3 100644 --- a/service/src/main/java/org/evasion/cloud/service/security/HTML5CorsFilter.java +++ b/service/src/main/java/org/evasion/cloud/service/security/HTML5CorsFilter.java @@ -1,56 +1,60 @@ /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.evasion.cloud.service.security; import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.LoggerFactory; /** * * @author sgl */ public class HTML5CorsFilter implements javax.servlet.Filter { private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(HTML5CorsFilter.class); //private Set<String> whitelist = Sets.newHashSet("[AllowedOrigin1]", "[AllowedOrigin2]"); @Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { LOG.debug("HTML5CorsFilter add HTML5 CORS Headers"); HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) resp; if (request.getMethod().equals("OPTIONS")) { response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE"); response.addHeader("Access-Control-Allow-Headers", "origin, content-type, accept"); response.addHeader("Access-Control-Max-Age", "1800"); } String origin = request.getHeader("Origin"); + // contournement du bug appengine 8625 bug présent uniquement en prod. + if (origin==null){ + origin=""; + } //if (origin != null && whitelist.contains(origin)) { response.addHeader("Access-Control-Allow-Origin", origin); response.addHeader("Access-Control-Allow-Credentials", "true"); //} chain.doFilter(request, response); } @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void destroy() { } }
true
true
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { LOG.debug("HTML5CorsFilter add HTML5 CORS Headers"); HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) resp; if (request.getMethod().equals("OPTIONS")) { response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE"); response.addHeader("Access-Control-Allow-Headers", "origin, content-type, accept"); response.addHeader("Access-Control-Max-Age", "1800"); } String origin = request.getHeader("Origin"); //if (origin != null && whitelist.contains(origin)) { response.addHeader("Access-Control-Allow-Origin", origin); response.addHeader("Access-Control-Allow-Credentials", "true"); //} chain.doFilter(request, response); }
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { LOG.debug("HTML5CorsFilter add HTML5 CORS Headers"); HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) resp; if (request.getMethod().equals("OPTIONS")) { response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE"); response.addHeader("Access-Control-Allow-Headers", "origin, content-type, accept"); response.addHeader("Access-Control-Max-Age", "1800"); } String origin = request.getHeader("Origin"); // contournement du bug appengine 8625 bug présent uniquement en prod. if (origin==null){ origin=""; } //if (origin != null && whitelist.contains(origin)) { response.addHeader("Access-Control-Allow-Origin", origin); response.addHeader("Access-Control-Allow-Credentials", "true"); //} chain.doFilter(request, response); }
diff --git a/src/main/java/no/uis/portal/employee/ExternalExaminerBean.java b/src/main/java/no/uis/portal/employee/ExternalExaminerBean.java index 197b810..76e716a 100644 --- a/src/main/java/no/uis/portal/employee/ExternalExaminerBean.java +++ b/src/main/java/no/uis/portal/employee/ExternalExaminerBean.java @@ -1,115 +1,115 @@ package no.uis.portal.employee; import java.util.ArrayList; import java.util.List; import javax.faces.event.ActionEvent; import no.uis.abam.dom.Assignment; import no.uis.abam.dom.ExternalExaminer; import no.uis.abam.dom.Student; import no.uis.abam.dom.Thesis; import no.uis.abam.dom.ThesisInformation; import com.icesoft.faces.context.DisposableBean; public class ExternalExaminerBean implements DisposableBean{ private boolean showSavedConfirmation; private List<ThesisInformation> thesisInformationList = new ArrayList<ThesisInformation>(); private EmployeeService employeeService; private ExternalExaminer externalExaminer; public ExternalExaminerBean() { } public void actionPrepareAddExternalExaminer(ActionEvent event) { thesisInformationList.clear(); setShowSavedConfirmation(false); setExternalExaminer(new ExternalExaminer()); //TODO: don't get all theses. List<Thesis> thesisList = employeeService.getThesisList(); ThesisInformation thesisInformation; if(thesisList != null) { for (Thesis thesis : thesisList) { thesisInformation = new ThesisInformation(); Assignment assignment = thesis.getAssignedAssignment(); if (assignment == null) { Student student = employeeService.getStudentFromStudentNumber(thesis.getStudentNumber1()); thesisInformation.setAssignmentTitle(student.getCustomAssignment().getTitle()); } else { thesisInformation.setAssignmentTitle(assignment.getTitle()); } - if (!thesis.getStudentNumber2().isEmpty()) + if (thesis.getStudentNumber2() != null && !thesis.getStudentNumber2().isEmpty()) thesisInformation.setCoStudent1Name(employeeService.getStudentFromStudentNumber(thesis.getStudentNumber2()).getName()); - if (!thesis.getStudentNumber3().isEmpty()) + if (thesis.getStudentNumber3() != null && !thesis.getStudentNumber3().isEmpty()) thesisInformation.setCoStudent2Name(employeeService.getStudentFromStudentNumber(thesis.getStudentNumber3()).getName()); ExternalExaminer examiner = thesis.getExternalExaminer(); if (examiner == null) { thesisInformation.setExternalExaminerName(""); } else { thesisInformation.setExternalExaminerName(thesis.getExternalExaminer().getName()); } thesisInformation.setStudentName(employeeService .getStudentFromStudentNumber(thesis.getStudentNumber1()) .getName()); thesisInformation.setThesis(thesis); thesisInformationList.add(thesisInformation); } } } public void actionSaveExaminerToSelectedRows(ActionEvent event) { for (ThesisInformation thesisInformation : thesisInformationList) { if (thesisInformation.isSelected()) { thesisInformation.getThesis().setExternalExaminer(externalExaminer); thesisInformation.setExternalExaminerName(externalExaminer.getName()); employeeService.updateThesis(thesisInformation.getThesis()); } } setShowSavedConfirmation(true); } public boolean isShowSavedConfirmation() { return showSavedConfirmation; } public void setShowSavedConfirmation(boolean showSavedConfirmation) { this.showSavedConfirmation = showSavedConfirmation; } public List<ThesisInformation> getThesisInformationList() { return thesisInformationList; } public void setThesisInformationList( List<ThesisInformation> thesisInformationList) { this.thesisInformationList = thesisInformationList; } public EmployeeService getEmployeeService() { return employeeService; } public void setEmployeeService(EmployeeService employeeService) { this.employeeService = employeeService; } public ExternalExaminer getExternalExaminer() { return externalExaminer; } public void setExternalExaminer(ExternalExaminer externalExaminer) { this.externalExaminer = externalExaminer; } @Override public void dispose() throws Exception { } }
false
true
public void actionPrepareAddExternalExaminer(ActionEvent event) { thesisInformationList.clear(); setShowSavedConfirmation(false); setExternalExaminer(new ExternalExaminer()); //TODO: don't get all theses. List<Thesis> thesisList = employeeService.getThesisList(); ThesisInformation thesisInformation; if(thesisList != null) { for (Thesis thesis : thesisList) { thesisInformation = new ThesisInformation(); Assignment assignment = thesis.getAssignedAssignment(); if (assignment == null) { Student student = employeeService.getStudentFromStudentNumber(thesis.getStudentNumber1()); thesisInformation.setAssignmentTitle(student.getCustomAssignment().getTitle()); } else { thesisInformation.setAssignmentTitle(assignment.getTitle()); } if (!thesis.getStudentNumber2().isEmpty()) thesisInformation.setCoStudent1Name(employeeService.getStudentFromStudentNumber(thesis.getStudentNumber2()).getName()); if (!thesis.getStudentNumber3().isEmpty()) thesisInformation.setCoStudent2Name(employeeService.getStudentFromStudentNumber(thesis.getStudentNumber3()).getName()); ExternalExaminer examiner = thesis.getExternalExaminer(); if (examiner == null) { thesisInformation.setExternalExaminerName(""); } else { thesisInformation.setExternalExaminerName(thesis.getExternalExaminer().getName()); } thesisInformation.setStudentName(employeeService .getStudentFromStudentNumber(thesis.getStudentNumber1()) .getName()); thesisInformation.setThesis(thesis); thesisInformationList.add(thesisInformation); } } }
public void actionPrepareAddExternalExaminer(ActionEvent event) { thesisInformationList.clear(); setShowSavedConfirmation(false); setExternalExaminer(new ExternalExaminer()); //TODO: don't get all theses. List<Thesis> thesisList = employeeService.getThesisList(); ThesisInformation thesisInformation; if(thesisList != null) { for (Thesis thesis : thesisList) { thesisInformation = new ThesisInformation(); Assignment assignment = thesis.getAssignedAssignment(); if (assignment == null) { Student student = employeeService.getStudentFromStudentNumber(thesis.getStudentNumber1()); thesisInformation.setAssignmentTitle(student.getCustomAssignment().getTitle()); } else { thesisInformation.setAssignmentTitle(assignment.getTitle()); } if (thesis.getStudentNumber2() != null && !thesis.getStudentNumber2().isEmpty()) thesisInformation.setCoStudent1Name(employeeService.getStudentFromStudentNumber(thesis.getStudentNumber2()).getName()); if (thesis.getStudentNumber3() != null && !thesis.getStudentNumber3().isEmpty()) thesisInformation.setCoStudent2Name(employeeService.getStudentFromStudentNumber(thesis.getStudentNumber3()).getName()); ExternalExaminer examiner = thesis.getExternalExaminer(); if (examiner == null) { thesisInformation.setExternalExaminerName(""); } else { thesisInformation.setExternalExaminerName(thesis.getExternalExaminer().getName()); } thesisInformation.setStudentName(employeeService .getStudentFromStudentNumber(thesis.getStudentNumber1()) .getName()); thesisInformation.setThesis(thesis); thesisInformationList.add(thesisInformation); } } }
diff --git a/src/main/java/net/canarymod/commandsys/commands/warp/WarpList.java b/src/main/java/net/canarymod/commandsys/commands/warp/WarpList.java index 59fa1cd..84648fe 100644 --- a/src/main/java/net/canarymod/commandsys/commands/warp/WarpList.java +++ b/src/main/java/net/canarymod/commandsys/commands/warp/WarpList.java @@ -1,64 +1,64 @@ package net.canarymod.commandsys.commands.warp; import java.util.List; import net.canarymod.Canary; import net.canarymod.Translator; import net.canarymod.api.Server; import net.canarymod.api.entity.living.humanoid.Player; import net.canarymod.api.world.blocks.CommandBlock; import net.canarymod.chat.Colors; import net.canarymod.chat.MessageReceiver; import net.canarymod.warp.Warp; public class WarpList { public void execute(MessageReceiver caller, String[] parameters) { if(caller instanceof Server || caller instanceof CommandBlock) { caller.notice("**** WARPS ****"); List<Warp> warps = Canary.warps().getAllWarps(); StringBuilder warpList = new StringBuilder(); for (Warp warp : warps) { - warpList.append(warp.getName()).append(","); + warpList.append(warp.getName()).append(", "); } if (warpList.length() > 0) { warpList.deleteCharAt(warpList.length() - 1); Canary.logInfo(warpList.toString()); } else { Canary.logInfo(Translator.translate("no warps")); } } else { Player player = (Player)caller; player.sendMessage(Colors.YELLOW + Translator.translate("warps available")); List<Warp> warps = Canary.warps().getAllWarps(); StringBuilder warpList = new StringBuilder(); for (Warp w : warps) { if (w.getOwner() != null) { if (w.isPlayerHome() && w.getOwner().equals(player.getName())) { - warpList.append(Colors.LIGHT_GREEN).append("(").append(Translator.translate("your home")).append(")").append(Colors.WHITE).append(","); + warpList.append(Colors.LIGHT_GREEN).append("(").append(Translator.translate("your home")).append(")").append(Colors.WHITE).append(", "); } else if (!w.isPlayerHome() && w.getOwner().equals(player.getName()) || (player.isAdmin())) { - warpList.append(Colors.ORANGE).append(w.getName()).append("(").append(Translator.translate("private")).append(")").append(Colors.WHITE).append(","); + warpList.append(Colors.ORANGE).append(w.getName()).append("(").append(Translator.translate("private")).append(")").append(Colors.WHITE).append(", "); } } else if (w.isGroupRestricted() && w.isGroupAllowed(player.getGroup())) { - warpList.append(Colors.YELLOW).append(w.getName()).append("(").append(Translator.translate("group")).append(")").append(Colors.WHITE).append(","); + warpList.append(Colors.YELLOW).append(w.getName()).append("(").append(Translator.translate("group")).append(")").append(Colors.WHITE).append(", "); } else if (!w.isGroupRestricted()) { - warpList.append(w.getName()).append(","); + warpList.append(w.getName()).append(", "); } } if (warpList.length() > 0) { warpList.deleteCharAt(warpList.length()-1); - player.sendMessage(warpList.toString()); + player.sendMessage(warpList.toString().trim()); } else { player.notice(Translator.translate("no warps")); } } } }
false
true
public void execute(MessageReceiver caller, String[] parameters) { if(caller instanceof Server || caller instanceof CommandBlock) { caller.notice("**** WARPS ****"); List<Warp> warps = Canary.warps().getAllWarps(); StringBuilder warpList = new StringBuilder(); for (Warp warp : warps) { warpList.append(warp.getName()).append(","); } if (warpList.length() > 0) { warpList.deleteCharAt(warpList.length() - 1); Canary.logInfo(warpList.toString()); } else { Canary.logInfo(Translator.translate("no warps")); } } else { Player player = (Player)caller; player.sendMessage(Colors.YELLOW + Translator.translate("warps available")); List<Warp> warps = Canary.warps().getAllWarps(); StringBuilder warpList = new StringBuilder(); for (Warp w : warps) { if (w.getOwner() != null) { if (w.isPlayerHome() && w.getOwner().equals(player.getName())) { warpList.append(Colors.LIGHT_GREEN).append("(").append(Translator.translate("your home")).append(")").append(Colors.WHITE).append(","); } else if (!w.isPlayerHome() && w.getOwner().equals(player.getName()) || (player.isAdmin())) { warpList.append(Colors.ORANGE).append(w.getName()).append("(").append(Translator.translate("private")).append(")").append(Colors.WHITE).append(","); } } else if (w.isGroupRestricted() && w.isGroupAllowed(player.getGroup())) { warpList.append(Colors.YELLOW).append(w.getName()).append("(").append(Translator.translate("group")).append(")").append(Colors.WHITE).append(","); } else if (!w.isGroupRestricted()) { warpList.append(w.getName()).append(","); } } if (warpList.length() > 0) { warpList.deleteCharAt(warpList.length()-1); player.sendMessage(warpList.toString()); } else { player.notice(Translator.translate("no warps")); } } }
public void execute(MessageReceiver caller, String[] parameters) { if(caller instanceof Server || caller instanceof CommandBlock) { caller.notice("**** WARPS ****"); List<Warp> warps = Canary.warps().getAllWarps(); StringBuilder warpList = new StringBuilder(); for (Warp warp : warps) { warpList.append(warp.getName()).append(", "); } if (warpList.length() > 0) { warpList.deleteCharAt(warpList.length() - 1); Canary.logInfo(warpList.toString()); } else { Canary.logInfo(Translator.translate("no warps")); } } else { Player player = (Player)caller; player.sendMessage(Colors.YELLOW + Translator.translate("warps available")); List<Warp> warps = Canary.warps().getAllWarps(); StringBuilder warpList = new StringBuilder(); for (Warp w : warps) { if (w.getOwner() != null) { if (w.isPlayerHome() && w.getOwner().equals(player.getName())) { warpList.append(Colors.LIGHT_GREEN).append("(").append(Translator.translate("your home")).append(")").append(Colors.WHITE).append(", "); } else if (!w.isPlayerHome() && w.getOwner().equals(player.getName()) || (player.isAdmin())) { warpList.append(Colors.ORANGE).append(w.getName()).append("(").append(Translator.translate("private")).append(")").append(Colors.WHITE).append(", "); } } else if (w.isGroupRestricted() && w.isGroupAllowed(player.getGroup())) { warpList.append(Colors.YELLOW).append(w.getName()).append("(").append(Translator.translate("group")).append(")").append(Colors.WHITE).append(", "); } else if (!w.isGroupRestricted()) { warpList.append(w.getName()).append(", "); } } if (warpList.length() > 0) { warpList.deleteCharAt(warpList.length()-1); player.sendMessage(warpList.toString().trim()); } else { player.notice(Translator.translate("no warps")); } } }
diff --git a/src/main/java/org/basex/test/w3c/W3CTS.java b/src/main/java/org/basex/test/w3c/W3CTS.java index 9c6d52402..b974df276 100644 --- a/src/main/java/org/basex/test/w3c/W3CTS.java +++ b/src/main/java/org/basex/test/w3c/W3CTS.java @@ -1,875 +1,875 @@ package org.basex.test.w3c; import static org.basex.core.Text.*; import static org.basex.util.Token.*; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.HashMap; import java.util.regex.Pattern; import org.basex.core.Context; import org.basex.core.Prop; import org.basex.core.cmd.Check; import org.basex.core.cmd.Close; import org.basex.core.cmd.CreateDB; import org.basex.core.cmd.DropDB; import org.basex.data.Data; import org.basex.data.DataText; import org.basex.data.Nodes; import org.basex.data.SerializerProp; import org.basex.data.XMLSerializer; import org.basex.io.ArrayOutput; import org.basex.io.IO; import org.basex.io.TextInput; import org.basex.query.QueryException; import org.basex.query.QueryProcessor; import org.basex.query.expr.Expr; import org.basex.query.func.FNSimple; import org.basex.query.func.FunDef; import org.basex.query.item.DBNode; import org.basex.query.item.Item; import org.basex.query.item.NodeType; import org.basex.query.item.Str; import org.basex.query.item.Uri; import org.basex.query.item.Value; import org.basex.query.iter.ItemCache; import org.basex.util.Args; import org.basex.util.Performance; import org.basex.util.TokenBuilder; import org.basex.util.TokenList; import org.basex.util.Util; /** * XQuery Test Suite wrapper. * * @author BaseX Team 2005-11, BSD License * @author Christian Gruen */ public abstract class W3CTS { // Try "ulimit -n 65536" if Linux tells you "Too many open files." /** Inspect flag. */ private static final byte[] INSPECT = token("Inspect"); /** Fragment flag. */ private static final byte[] FRAGMENT = token("Fragment"); /** XML flag. */ private static final byte[] XML = token("XML"); /** XML flag. */ private static final byte[] IGNORE = token("Ignore"); /** Replacement pattern. */ private static final Pattern SLASH = Pattern.compile("/", Pattern.LITERAL); /** Database context. */ protected final Context context = new Context(); /** Path to the XQuery Test Suite. */ protected String path = ""; /** Data reference. */ protected Data data; /** History path. */ private final String pathhis; /** Log file. */ private final String pathlog; /** Test suite input. */ private final String input; /** Test suite id. */ private final String testid; /** Query path. */ private String queries; /** Expected results. */ private String expected; /** Reported results. */ private String results; /** Reports. */ private String report; /** Test sources. */ private String sources; /** Maximum length of result output. */ private int maxout = 500; /** Query filter string. */ private String single; /** Flag for printing current time functions into log file. */ private boolean currTime; /** Flag for creating report files. */ private boolean reporting; /** Verbose flag. */ private boolean verbose; /** Debug flag. */ private boolean debug; /** Minimum conformance. */ private boolean minimum; /** Print compilation steps. */ private boolean compile; /** test-group to use. */ private String group; /** Cached source files. */ private final HashMap<String, String> srcs = new HashMap<String, String>(); /** Cached module files. */ private final HashMap<String, String> mods = new HashMap<String, String>(); /** Cached collections. */ private final HashMap<String, byte[][]> colls = new HashMap<String, byte[][]>(); /** OK log. */ private final StringBuilder logOK = new StringBuilder(); /** OK log. */ private final StringBuilder logOK2 = new StringBuilder(); /** Error log. */ private final StringBuilder logErr = new StringBuilder(); /** Error log. */ private final StringBuilder logErr2 = new StringBuilder(); /** File log. */ private final StringBuilder logReport = new StringBuilder(); /** Error counter. */ private int err; /** Error2 counter. */ private int err2; /** OK counter. */ private int ok; /** OK2 counter. */ private int ok2; /** * Constructor. * @param nm name of test */ public W3CTS(final String nm) { input = nm + "Catalog" + IO.XMLSUFFIX; testid = nm.substring(0, 4); pathhis = testid.toLowerCase() + ".hist"; pathlog = testid.toLowerCase() + ".log"; } /** * Runs the test suite. * @param args command-line arguments * @throws Exception exception */ void run(final String[] args) throws Exception { final Args arg = new Args(args, this, " Test Suite [options] [pat]" + NL + " [pat] perform only tests with the specified pattern" + NL + " -c print compilation steps" + NL + " -d show debugging info" + NL + " -h show this help" + NL + " -m minimum conformance" + NL + " -g <test-group> test group to test" + NL + " -C include tests that depend on the current time" + NL + " -p change path" + NL + " -r create report" + NL + " -v verbose output"); while(arg.more()) { if(arg.dash()) { final char c = arg.next(); if(c == 'r') { reporting = true; currTime = true; } else if(c == 'C') { currTime = true; } else if(c == 'c') { compile = true; } else if(c == 'd') { debug = true; } else if(c == 'm') { minimum = true; } else if(c == 'g') { group = arg.string(); } else if(c == 'p') { path = arg.string() + "/"; } else if(c == 'v') { verbose = true; } else { arg.check(false); } } else { single = arg.string(); maxout = Integer.MAX_VALUE; } } if(!arg.finish()) return; queries = path + "Queries/XQuery/"; expected = path + "ExpectedTestResults/"; results = path + "ReportingResults/Results/"; report = path + "ReportingResults/"; sources = path + "TestSources/"; final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); final String dat = sdf.format(Calendar.getInstance().getTime()); final Performance perf = new Performance(); context.prop.set(Prop.CHOP, false); new Check(path + input).execute(context); data = context.data; final Nodes root = new Nodes(0, data); Util.outln(NL + Util.name(this) + " Test Suite " + text("/*:test-suite/@version", root)); Util.outln(NL + "Caching Sources..."); for(final int s : nodes("//*:source", root).list) { final Nodes srcRoot = new Nodes(s, data); final String val = (path + text("@FileName", srcRoot)).replace('\\', '/'); srcs.put(text("@ID", srcRoot), val); } Util.outln("Caching Modules..."); for(final int s : nodes("//*:module", root).list) { final Nodes srcRoot = new Nodes(s, data); final String val = (path + text("@FileName", srcRoot)).replace('\\', '/'); mods.put(text("@ID", srcRoot), val); } Util.outln("Caching Collections..."); for(final int c : nodes("//*:collection", root).list) { final Nodes nodes = new Nodes(c, data); final String cname = text("@ID", nodes); final TokenList dl = new TokenList(); final Nodes doc = nodes("*:input-document", nodes); for(int d = 0; d < doc.size(); ++d) { dl.add(token(sources + string(data.atom(doc.list[d])) + IO.XMLSUFFIX)); } colls.put(cname, dl.toArray()); } init(root); if(reporting) { Util.outln("Delete old results..."); delete(new File[] { new File(results) }); } if(verbose) Util.outln(); final Nodes nodes = minimum ? nodes("//*:test-group[starts-with(@name, 'Minim')]//*:test-case", root) : group != null ? nodes("//*:test-group[@name eq '" + group + "']//*:test-case", root) : nodes("//*:test-case", root); long total = nodes.size(); Util.out("Parsing " + total + " Queries"); for(int t = 0; t < total; ++t) { if(!parse(new Nodes(nodes.list[t], data))) break; if(!verbose && t % 500 == 0) Util.out("."); } Util.outln(); total = ok + ok2 + err + err2; final String time = perf.getTimer(); Util.outln("Writing log file..." + NL); BufferedWriter bw = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(path + pathlog), UTF8)); bw.write("TEST RESULTS =================================================="); bw.write(NL + NL + "Total #Queries: " + total + NL); bw.write("Correct / Empty Results: " + ok + " / " + ok2 + NL); bw.write("Conformance (w/Empty Results): "); bw.write(pc(ok, total) + " / " + pc(ok + ok2, total) + NL); bw.write("Wrong Results / Errors: " + err + " / " + err2 + NL); bw.write("WRONG ========================================================="); bw.write(NL + NL + logErr + NL); bw.write("WRONG (ERRORS) ================================================"); bw.write(NL + NL + logErr2 + NL); bw.write("CORRECT? (EMPTY) =============================================="); bw.write(NL + NL + logOK2 + NL); bw.write("CORRECT ======================================================="); bw.write(NL + NL + logOK + NL); bw.write("==============================================================="); bw.close(); bw = new BufferedWriter(new FileWriter(path + pathhis, true)); bw.write(dat + "\t" + ok + "\t" + ok2 + "\t" + err + "\t" + err2 + NL); bw.close(); if(reporting) { bw = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(report + NAME + IO.XMLSUFFIX), UTF8)); write(bw, report + NAME + "Pre" + IO.XMLSUFFIX); bw.write(logReport.toString()); write(bw, report + NAME + "Pos" + IO.XMLSUFFIX); bw.close(); } Util.outln("Total #Queries: " + total); Util.outln("Correct / Empty results: " + ok + " / " + ok2); Util.out("Conformance (w/empty results): "); Util.outln(pc(ok, total) + " / " + pc(ok + ok2, total)); Util.outln("Total Time: " + time); context.close(); } /** * Calculates the percentage of correct queries. * @param v value * @param t total value * @return percentage */ private String pc(final int v, final long t) { return (t == 0 ? 100 : v * 10000 / t / 100d) + "%"; } /** * Parses the specified test case. * @param root root node * @throws Exception exception * @return true if the query, specified by {@link #single}, was evaluated */ private boolean parse(final Nodes root) throws Exception { final String pth = text("@FilePath", root); final String outname = text("@name", root); if(single != null && !outname.startsWith(single)) return true; final Performance perf = new Performance(); if(verbose) Util.out("- " + outname); boolean inspect = false; boolean correct = true; final Nodes nodes = states(root); for(int n = 0; n < nodes.size(); ++n) { final Nodes state = new Nodes(nodes.list[n], nodes.data); final String inname = text("*:query/@name", state); context.query = IO.get(queries + pth + inname + IO.XQSUFFIX); final String in = read(context.query); String er = null; ItemCache iter = null; boolean doc = true; final Nodes cont = nodes("*:contextItem", state); Nodes curr = null; if(cont.size() != 0) { final Data d = Check.check(context, srcs.get(string(data.atom(cont.list[0])))); curr = new Nodes(d.doc(), d); curr.root = true; } context.prop.set(Prop.QUERYINFO, compile); final QueryProcessor xq = new QueryProcessor(in, curr, context); context.prop.set(Prop.QUERYINFO, false); // limit result sizes to 1MB final ArrayOutput ao = new ArrayOutput(); final TokenBuilder files = new TokenBuilder(); try { files.add(file(nodes("*:input-file", state), nodes("*:input-file/@variable", state), xq, n == 0)); files.add(file(nodes("*:defaultCollection", state), null, xq, n == 0)); var(nodes("*:input-URI", state), nodes("*:input-URI/@variable", state), xq); eval(nodes("*:input-query/@name", state), nodes("*:input-query/@variable", state), pth, xq); parse(xq, state); for(final int p : nodes("*:module", root).list) { - final String ns = text("@namespace", new Nodes(p, data)); - final String f = mods.get(string(data.atom(p))) + IO.XQSUFFIX; - xq.module(ns, f); + final String uri = text("@namespace", new Nodes(p, data)); + final String file = mods.get(string(data.atom(p))) + IO.XQSUFFIX; + xq.module(file, uri); } // evaluate and serialize query final SerializerProp sp = new SerializerProp(); sp.set(SerializerProp.S_INDENT, context.prop.is(Prop.CHOP) ? DataText.YES : DataText.NO); final XMLSerializer xml = new XMLSerializer(ao, sp); iter = xq.value().cache(); for(Item it; (it = iter.next()) != null;) { doc &= it.type == NodeType.DOC; it.serialize(xml); } xml.close(); } catch(final Exception ex) { if(!(ex instanceof QueryException || ex instanceof IOException)) { System.err.println("\n*** " + outname + " ***"); System.err.println(in + "\n"); ex.printStackTrace(); } er = ex.getMessage(); if(er.startsWith(STOPPED)) er = er.substring(er.indexOf('\n') + 1); if(er.startsWith("[")) er = er.replaceAll("\\[(.*?)\\] (.*)", "$1 $2"); // unexpected error - dump stack trace } // print compilation steps if(compile) { Util.errln("---------------------------------------------------------"); Util.err(xq.info()); Util.errln(in); } final Nodes expOut = nodes("*:output-file/text()", state); final TokenList result = new TokenList(); for(int o = 0; o < expOut.size(); ++o) { final String resFile = string(data.atom(expOut.list[o])); final IO exp = IO.get(expected + pth + resFile); result.add(read(exp)); } final Nodes cmpFiles = nodes("*:output-file/@compare", state); boolean xml = false; boolean frag = false; boolean ignore = false; for(int o = 0; o < cmpFiles.size(); ++o) { final byte[] type = data.atom(cmpFiles.list[o]); xml |= eq(type, XML); frag |= eq(type, FRAGMENT); ignore |= eq(type, IGNORE); } String expError = text("*:expected-error/text()", state); final StringBuilder log = new StringBuilder(pth + inname + IO.XQSUFFIX); if(files.size() != 0) { log.append(" ["); log.append(files); log.append("]"); } log.append(NL); /** Remove comments. */ log.append(norm(in)); log.append(NL); final String logStr = log.toString(); // skip queries with variable results final boolean print = currTime || !logStr.contains("current-"); boolean correctError = false; if(er != null && (expOut.size() == 0 || !expError.isEmpty())) { expError = error(pth + outname, expError); final String code = er.substring(0, Math.min(8, er.length())); for(final String e : SLASH.split(expError)) { if(code.equals(e)) { correctError = true; break; } } } if(correctError) { if(print) { logOK.append(logStr); logOK.append("[Right] "); logOK.append(norm(er)); logOK.append(NL); logOK.append(NL); addLog(pth, outname + ".log", er); } ++ok; } else if(er == null) { int s = -1; final int rs = result.size(); while(!ignore && ++s < rs) { inspect |= s < cmpFiles.list.length && eq(data.atom(cmpFiles.list[s]), INSPECT); final byte[] res = result.get(s), actual = ao.toArray(); if(res.length == ao.size() && eq(res, actual)) break; if(xml || frag) { iter.reset(); try { final ItemCache ic = toIter(string(res).replaceAll( "^<\\?xml.*?\\?>", "").trim(), frag); if(FNSimple.deep(null, iter, ic)) break; ic.reset(); final ItemCache ia = toIter(string(actual), frag); if(FNSimple.deep(null, ia, ic)) break; if(debug) { iter.reset(); ic.reset(); final XMLSerializer ser = new XMLSerializer(System.out); Util.outln(NL + "=== " + testid + " ==="); for(Item it; (it = ic.next()) != null;) it.serialize(ser); Util.outln(NL + "=== " + NAME + " ==="); for(Item it; (it = iter.next()) != null;) it.serialize(ser); Util.outln(); } } catch(final IOException ex) { } catch(final Throwable ex) { System.err.println("\n" + outname + ":"); ex.printStackTrace(); } } } if((rs > 0 || !expError.isEmpty()) && s == rs && !inspect) { if(print) { if(expOut.size() == 0) result.add(error(pth + outname, expError)); logErr.append(logStr); logErr.append("[" + testid + " ] "); logErr.append(norm(string(result.get(0)))); logErr.append(NL); logErr.append("[Wrong] "); logErr.append(norm(ao.toString())); logErr.append(NL); logErr.append(NL); addLog(pth, outname + (xml ? IO.XMLSUFFIX : ".txt"), ao.toString()); } correct = false; ++err; } else { if(print) { logOK.append(logStr); logOK.append("[Right] "); logOK.append(norm(ao.toString())); logOK.append(NL); logOK.append(NL); addLog(pth, outname + (xml ? IO.XMLSUFFIX : ".txt"), ao.toString()); } ++ok; } } else { if(expOut.size() == 0 || !expError.isEmpty()) { if(print) { logOK2.append(logStr); logOK2.append("[" + testid + " ] "); logOK2.append(norm(expError)); logOK2.append(NL); logOK2.append("[Rght?] "); logOK2.append(norm(er)); logOK2.append(NL); logOK2.append(NL); addLog(pth, outname + ".log", er); } ++ok2; } else { if(print) { logErr2.append(logStr); logErr2.append("[" + testid + " ] "); logErr2.append(norm(string(result.get(0)))); logErr2.append(NL); logErr2.append("[Wrong] "); logErr2.append(norm(er)); logErr2.append(NL); logErr2.append(NL); addLog(pth, outname + ".log", er); } correct = false; ++err2; } } if(curr != null) Close.close(curr.data, context); xq.close(); } if(reporting) { logReport.append(" <test-case name=\""); logReport.append(outname); logReport.append("\" result='"); logReport.append(correct ? "pass" : "fail"); if(inspect) logReport.append("' todo='inspect"); logReport.append("'/>"); logReport.append(NL); } if(verbose) { final long t = perf.getTime(); if(t > 100000000) Util.out(": " + Performance.getTimer(t, 1)); Util.outln(); } return single == null || !outname.equals(single); } /** * Creates an item iterator for the given XML fragment. * @param xml fragment * @param frag fragment flag * @return iterator */ private ItemCache toIter(final String xml, final boolean frag) { final ItemCache it = new ItemCache(); try { String str = frag ? "<X>" + xml + "</X>" : xml; final Data d = CreateDB.xml(IO.get(str), context); for(int p = frag ? 2 : 0; p < d.meta.size; p += d.size(p, d.kind(p))) it.add(new DBNode(d, p)); } catch(final IOException ex) { return new ItemCache(new Item[] { Str.get(Long.toString(System.nanoTime())) }, 1); } return it; } /** * Removes comments from the specified string. * @param in input string * @return result */ private String norm(final String in) { return QueryProcessor.removeComments(in, maxout); } /** * Initializes the input files, specified by the context nodes. * @param nod variables * @param var documents * @param qp query processor * @param first call * @return string with input files * @throws Exception exception */ private byte[] file(final Nodes nod, final Nodes var, final QueryProcessor qp, final boolean first) throws Exception { final TokenBuilder tb = new TokenBuilder(); for(int c = 0; c < nod.size(); ++c) { final byte[] nm = data.atom(nod.list[c]); String src = srcs.get(string(nm)); if(tb.size() != 0) tb.add(", "); tb.add(nm); Expr expr = null; if(src == null) { // assign collection expr = coll(nm, qp); } else { // assign document final String dbname = IO.get(src).dbname(); FunDef def = FunDef.DOC; // updates: drop updated document or open updated database if(updating()) { if(first) { new DropDB(dbname).execute(context); } else { def = FunDef.OPEN; src = dbname; } } expr = def.get(null, Str.get(src)); } if(var != null) qp.bind(string(data.atom(var.list[c])), expr); } return tb.finish(); } /** * Assigns the nodes to the specified variables. * @param nod nodes * @param var variables * @param qp query processor * @throws QueryException query exception */ private void var(final Nodes nod, final Nodes var, final QueryProcessor qp) throws QueryException { for(int c = 0; c < nod.size(); ++c) { final byte[] nm = data.atom(nod.list[c]); final String src = srcs.get(string(nm)); final Item it = src == null ? coll(nm, qp) : Str.get(src); qp.bind(string(data.atom(var.list[c])), it); } } /** * Assigns a collection. * @param name collection name * @param qp query processor * @return expression * @throws QueryException query exception */ private Uri coll(final byte[] name, final QueryProcessor qp) throws QueryException { qp.ctx.resource.addCollection(name, colls.get(string(name))); return Uri.uri(name); } /** * Evaluates the the input files and assigns the result to the specified * variables. * @param nod variables * @param var documents * @param pth file path * @param qp query processor * @throws Exception exception */ private void eval(final Nodes nod, final Nodes var, final String pth, final QueryProcessor qp) throws Exception { for(int c = 0; c < nod.size(); ++c) { final String file = pth + string(data.atom(nod.list[c])) + IO.XQSUFFIX; final String in = read(IO.get(queries + file)); final QueryProcessor xq = new QueryProcessor(in, context); final Value val = xq.value(); qp.bind(string(data.atom(var.list[c])), val); xq.close(); } } /** * Adds a log file. * @param pth file path * @param nm file name * @param msg message * @throws Exception exception */ private void addLog(final String pth, final String nm, final String msg) throws Exception { if(reporting) { final File file = new File(results + pth); if(!file.exists()) file.mkdirs(); final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(results + pth + nm), UTF8)); bw.write(msg); bw.close(); } } /** * Returns an error message. * @param nm test name * @param error XQTS error * @return error message */ private String error(final String nm, final String error) { final String error2 = expected + nm + ".log"; final IO file = IO.get(error2); return file.exists() ? error + "/" + read(file) : error; } /** * Returns the resulting query text (text node or attribute value). * @param qu query * @param root root node * @return attribute value * @throws Exception exception */ protected String text(final String qu, final Nodes root) throws Exception { final Nodes n = nodes(qu, root); final TokenBuilder tb = new TokenBuilder(); for(int i = 0; i < n.size(); ++i) { if(i != 0) tb.add('/'); tb.add(data.atom(n.list[i])); } return tb.toString(); } /** * Returns the resulting auxiliary uri in multiple strings. * @param role role * @param root root node * @return attribute value * @throws Exception exception */ protected String[] aux(final String role, final Nodes root) throws Exception { return text("*:aux-URI[@role = '" + role + "']", root).split("/"); } /** * Returns the resulting query nodes. * @param qu query * @param root root node * @return attribute value * @throws Exception exception */ protected Nodes nodes(final String qu, final Nodes root) throws Exception { return new QueryProcessor(qu, root, context).queryNodes(); } /** * Recursively deletes a directory. * @param pth deletion path */ void delete(final File[] pth) { for(final File f : pth) { if(f.isDirectory()) delete(f.listFiles()); f.delete(); } } /** * Adds the specified file to the writer. * @param bw writer * @param f file path * @throws Exception exception */ private void write(final BufferedWriter bw, final String f) throws Exception { final BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f), UTF8)); String line; while((line = br.readLine()) != null) { bw.write(line); bw.write(NL); } br.close(); } /** * Returns the contents of the specified file. * @param f file to be read * @return content */ private String read(final IO f) { try { return TextInput.content(f).toString().replaceAll("\r\n?", "\n"); } catch(final IOException ex) { Util.errln(ex); return ""; } } /** * Initializes the test. * @param root root nodes reference * @throws Exception exception */ @SuppressWarnings("unused") protected void init(final Nodes root) throws Exception { } /** * Performs test specific parsings. * @param qp query processor * @param root root nodes reference * @throws Exception exception */ @SuppressWarnings("unused") protected void parse(final QueryProcessor qp, final Nodes root) throws Exception { } /** * Returns all query states. * @param root root node * @return states * @throws Exception exception */ @SuppressWarnings("unused") protected Nodes states(final Nodes root) throws Exception { return root; } /** * Updating flag. * @return flag */ protected boolean updating() { return false; } }
true
true
private boolean parse(final Nodes root) throws Exception { final String pth = text("@FilePath", root); final String outname = text("@name", root); if(single != null && !outname.startsWith(single)) return true; final Performance perf = new Performance(); if(verbose) Util.out("- " + outname); boolean inspect = false; boolean correct = true; final Nodes nodes = states(root); for(int n = 0; n < nodes.size(); ++n) { final Nodes state = new Nodes(nodes.list[n], nodes.data); final String inname = text("*:query/@name", state); context.query = IO.get(queries + pth + inname + IO.XQSUFFIX); final String in = read(context.query); String er = null; ItemCache iter = null; boolean doc = true; final Nodes cont = nodes("*:contextItem", state); Nodes curr = null; if(cont.size() != 0) { final Data d = Check.check(context, srcs.get(string(data.atom(cont.list[0])))); curr = new Nodes(d.doc(), d); curr.root = true; } context.prop.set(Prop.QUERYINFO, compile); final QueryProcessor xq = new QueryProcessor(in, curr, context); context.prop.set(Prop.QUERYINFO, false); // limit result sizes to 1MB final ArrayOutput ao = new ArrayOutput(); final TokenBuilder files = new TokenBuilder(); try { files.add(file(nodes("*:input-file", state), nodes("*:input-file/@variable", state), xq, n == 0)); files.add(file(nodes("*:defaultCollection", state), null, xq, n == 0)); var(nodes("*:input-URI", state), nodes("*:input-URI/@variable", state), xq); eval(nodes("*:input-query/@name", state), nodes("*:input-query/@variable", state), pth, xq); parse(xq, state); for(final int p : nodes("*:module", root).list) { final String ns = text("@namespace", new Nodes(p, data)); final String f = mods.get(string(data.atom(p))) + IO.XQSUFFIX; xq.module(ns, f); } // evaluate and serialize query final SerializerProp sp = new SerializerProp(); sp.set(SerializerProp.S_INDENT, context.prop.is(Prop.CHOP) ? DataText.YES : DataText.NO); final XMLSerializer xml = new XMLSerializer(ao, sp); iter = xq.value().cache(); for(Item it; (it = iter.next()) != null;) { doc &= it.type == NodeType.DOC; it.serialize(xml); } xml.close(); } catch(final Exception ex) { if(!(ex instanceof QueryException || ex instanceof IOException)) { System.err.println("\n*** " + outname + " ***"); System.err.println(in + "\n"); ex.printStackTrace(); } er = ex.getMessage(); if(er.startsWith(STOPPED)) er = er.substring(er.indexOf('\n') + 1); if(er.startsWith("[")) er = er.replaceAll("\\[(.*?)\\] (.*)", "$1 $2"); // unexpected error - dump stack trace } // print compilation steps if(compile) { Util.errln("---------------------------------------------------------"); Util.err(xq.info()); Util.errln(in); } final Nodes expOut = nodes("*:output-file/text()", state); final TokenList result = new TokenList(); for(int o = 0; o < expOut.size(); ++o) { final String resFile = string(data.atom(expOut.list[o])); final IO exp = IO.get(expected + pth + resFile); result.add(read(exp)); } final Nodes cmpFiles = nodes("*:output-file/@compare", state); boolean xml = false; boolean frag = false; boolean ignore = false; for(int o = 0; o < cmpFiles.size(); ++o) { final byte[] type = data.atom(cmpFiles.list[o]); xml |= eq(type, XML); frag |= eq(type, FRAGMENT); ignore |= eq(type, IGNORE); } String expError = text("*:expected-error/text()", state); final StringBuilder log = new StringBuilder(pth + inname + IO.XQSUFFIX); if(files.size() != 0) { log.append(" ["); log.append(files); log.append("]"); } log.append(NL); /** Remove comments. */ log.append(norm(in)); log.append(NL); final String logStr = log.toString(); // skip queries with variable results final boolean print = currTime || !logStr.contains("current-"); boolean correctError = false; if(er != null && (expOut.size() == 0 || !expError.isEmpty())) { expError = error(pth + outname, expError); final String code = er.substring(0, Math.min(8, er.length())); for(final String e : SLASH.split(expError)) { if(code.equals(e)) { correctError = true; break; } } } if(correctError) { if(print) { logOK.append(logStr); logOK.append("[Right] "); logOK.append(norm(er)); logOK.append(NL); logOK.append(NL); addLog(pth, outname + ".log", er); } ++ok; } else if(er == null) { int s = -1; final int rs = result.size(); while(!ignore && ++s < rs) { inspect |= s < cmpFiles.list.length && eq(data.atom(cmpFiles.list[s]), INSPECT); final byte[] res = result.get(s), actual = ao.toArray(); if(res.length == ao.size() && eq(res, actual)) break; if(xml || frag) { iter.reset(); try { final ItemCache ic = toIter(string(res).replaceAll( "^<\\?xml.*?\\?>", "").trim(), frag); if(FNSimple.deep(null, iter, ic)) break; ic.reset(); final ItemCache ia = toIter(string(actual), frag); if(FNSimple.deep(null, ia, ic)) break; if(debug) { iter.reset(); ic.reset(); final XMLSerializer ser = new XMLSerializer(System.out); Util.outln(NL + "=== " + testid + " ==="); for(Item it; (it = ic.next()) != null;) it.serialize(ser); Util.outln(NL + "=== " + NAME + " ==="); for(Item it; (it = iter.next()) != null;) it.serialize(ser); Util.outln(); } } catch(final IOException ex) { } catch(final Throwable ex) { System.err.println("\n" + outname + ":"); ex.printStackTrace(); } } } if((rs > 0 || !expError.isEmpty()) && s == rs && !inspect) { if(print) { if(expOut.size() == 0) result.add(error(pth + outname, expError)); logErr.append(logStr); logErr.append("[" + testid + " ] "); logErr.append(norm(string(result.get(0)))); logErr.append(NL); logErr.append("[Wrong] "); logErr.append(norm(ao.toString())); logErr.append(NL); logErr.append(NL); addLog(pth, outname + (xml ? IO.XMLSUFFIX : ".txt"), ao.toString()); } correct = false; ++err; } else { if(print) { logOK.append(logStr); logOK.append("[Right] "); logOK.append(norm(ao.toString())); logOK.append(NL); logOK.append(NL); addLog(pth, outname + (xml ? IO.XMLSUFFIX : ".txt"), ao.toString()); } ++ok; } } else { if(expOut.size() == 0 || !expError.isEmpty()) { if(print) { logOK2.append(logStr); logOK2.append("[" + testid + " ] "); logOK2.append(norm(expError)); logOK2.append(NL); logOK2.append("[Rght?] "); logOK2.append(norm(er)); logOK2.append(NL); logOK2.append(NL); addLog(pth, outname + ".log", er); } ++ok2; } else { if(print) { logErr2.append(logStr); logErr2.append("[" + testid + " ] "); logErr2.append(norm(string(result.get(0)))); logErr2.append(NL); logErr2.append("[Wrong] "); logErr2.append(norm(er)); logErr2.append(NL); logErr2.append(NL); addLog(pth, outname + ".log", er); } correct = false; ++err2; } } if(curr != null) Close.close(curr.data, context); xq.close(); } if(reporting) { logReport.append(" <test-case name=\""); logReport.append(outname); logReport.append("\" result='"); logReport.append(correct ? "pass" : "fail"); if(inspect) logReport.append("' todo='inspect"); logReport.append("'/>"); logReport.append(NL); } if(verbose) { final long t = perf.getTime(); if(t > 100000000) Util.out(": " + Performance.getTimer(t, 1)); Util.outln(); } return single == null || !outname.equals(single); }
private boolean parse(final Nodes root) throws Exception { final String pth = text("@FilePath", root); final String outname = text("@name", root); if(single != null && !outname.startsWith(single)) return true; final Performance perf = new Performance(); if(verbose) Util.out("- " + outname); boolean inspect = false; boolean correct = true; final Nodes nodes = states(root); for(int n = 0; n < nodes.size(); ++n) { final Nodes state = new Nodes(nodes.list[n], nodes.data); final String inname = text("*:query/@name", state); context.query = IO.get(queries + pth + inname + IO.XQSUFFIX); final String in = read(context.query); String er = null; ItemCache iter = null; boolean doc = true; final Nodes cont = nodes("*:contextItem", state); Nodes curr = null; if(cont.size() != 0) { final Data d = Check.check(context, srcs.get(string(data.atom(cont.list[0])))); curr = new Nodes(d.doc(), d); curr.root = true; } context.prop.set(Prop.QUERYINFO, compile); final QueryProcessor xq = new QueryProcessor(in, curr, context); context.prop.set(Prop.QUERYINFO, false); // limit result sizes to 1MB final ArrayOutput ao = new ArrayOutput(); final TokenBuilder files = new TokenBuilder(); try { files.add(file(nodes("*:input-file", state), nodes("*:input-file/@variable", state), xq, n == 0)); files.add(file(nodes("*:defaultCollection", state), null, xq, n == 0)); var(nodes("*:input-URI", state), nodes("*:input-URI/@variable", state), xq); eval(nodes("*:input-query/@name", state), nodes("*:input-query/@variable", state), pth, xq); parse(xq, state); for(final int p : nodes("*:module", root).list) { final String uri = text("@namespace", new Nodes(p, data)); final String file = mods.get(string(data.atom(p))) + IO.XQSUFFIX; xq.module(file, uri); } // evaluate and serialize query final SerializerProp sp = new SerializerProp(); sp.set(SerializerProp.S_INDENT, context.prop.is(Prop.CHOP) ? DataText.YES : DataText.NO); final XMLSerializer xml = new XMLSerializer(ao, sp); iter = xq.value().cache(); for(Item it; (it = iter.next()) != null;) { doc &= it.type == NodeType.DOC; it.serialize(xml); } xml.close(); } catch(final Exception ex) { if(!(ex instanceof QueryException || ex instanceof IOException)) { System.err.println("\n*** " + outname + " ***"); System.err.println(in + "\n"); ex.printStackTrace(); } er = ex.getMessage(); if(er.startsWith(STOPPED)) er = er.substring(er.indexOf('\n') + 1); if(er.startsWith("[")) er = er.replaceAll("\\[(.*?)\\] (.*)", "$1 $2"); // unexpected error - dump stack trace } // print compilation steps if(compile) { Util.errln("---------------------------------------------------------"); Util.err(xq.info()); Util.errln(in); } final Nodes expOut = nodes("*:output-file/text()", state); final TokenList result = new TokenList(); for(int o = 0; o < expOut.size(); ++o) { final String resFile = string(data.atom(expOut.list[o])); final IO exp = IO.get(expected + pth + resFile); result.add(read(exp)); } final Nodes cmpFiles = nodes("*:output-file/@compare", state); boolean xml = false; boolean frag = false; boolean ignore = false; for(int o = 0; o < cmpFiles.size(); ++o) { final byte[] type = data.atom(cmpFiles.list[o]); xml |= eq(type, XML); frag |= eq(type, FRAGMENT); ignore |= eq(type, IGNORE); } String expError = text("*:expected-error/text()", state); final StringBuilder log = new StringBuilder(pth + inname + IO.XQSUFFIX); if(files.size() != 0) { log.append(" ["); log.append(files); log.append("]"); } log.append(NL); /** Remove comments. */ log.append(norm(in)); log.append(NL); final String logStr = log.toString(); // skip queries with variable results final boolean print = currTime || !logStr.contains("current-"); boolean correctError = false; if(er != null && (expOut.size() == 0 || !expError.isEmpty())) { expError = error(pth + outname, expError); final String code = er.substring(0, Math.min(8, er.length())); for(final String e : SLASH.split(expError)) { if(code.equals(e)) { correctError = true; break; } } } if(correctError) { if(print) { logOK.append(logStr); logOK.append("[Right] "); logOK.append(norm(er)); logOK.append(NL); logOK.append(NL); addLog(pth, outname + ".log", er); } ++ok; } else if(er == null) { int s = -1; final int rs = result.size(); while(!ignore && ++s < rs) { inspect |= s < cmpFiles.list.length && eq(data.atom(cmpFiles.list[s]), INSPECT); final byte[] res = result.get(s), actual = ao.toArray(); if(res.length == ao.size() && eq(res, actual)) break; if(xml || frag) { iter.reset(); try { final ItemCache ic = toIter(string(res).replaceAll( "^<\\?xml.*?\\?>", "").trim(), frag); if(FNSimple.deep(null, iter, ic)) break; ic.reset(); final ItemCache ia = toIter(string(actual), frag); if(FNSimple.deep(null, ia, ic)) break; if(debug) { iter.reset(); ic.reset(); final XMLSerializer ser = new XMLSerializer(System.out); Util.outln(NL + "=== " + testid + " ==="); for(Item it; (it = ic.next()) != null;) it.serialize(ser); Util.outln(NL + "=== " + NAME + " ==="); for(Item it; (it = iter.next()) != null;) it.serialize(ser); Util.outln(); } } catch(final IOException ex) { } catch(final Throwable ex) { System.err.println("\n" + outname + ":"); ex.printStackTrace(); } } } if((rs > 0 || !expError.isEmpty()) && s == rs && !inspect) { if(print) { if(expOut.size() == 0) result.add(error(pth + outname, expError)); logErr.append(logStr); logErr.append("[" + testid + " ] "); logErr.append(norm(string(result.get(0)))); logErr.append(NL); logErr.append("[Wrong] "); logErr.append(norm(ao.toString())); logErr.append(NL); logErr.append(NL); addLog(pth, outname + (xml ? IO.XMLSUFFIX : ".txt"), ao.toString()); } correct = false; ++err; } else { if(print) { logOK.append(logStr); logOK.append("[Right] "); logOK.append(norm(ao.toString())); logOK.append(NL); logOK.append(NL); addLog(pth, outname + (xml ? IO.XMLSUFFIX : ".txt"), ao.toString()); } ++ok; } } else { if(expOut.size() == 0 || !expError.isEmpty()) { if(print) { logOK2.append(logStr); logOK2.append("[" + testid + " ] "); logOK2.append(norm(expError)); logOK2.append(NL); logOK2.append("[Rght?] "); logOK2.append(norm(er)); logOK2.append(NL); logOK2.append(NL); addLog(pth, outname + ".log", er); } ++ok2; } else { if(print) { logErr2.append(logStr); logErr2.append("[" + testid + " ] "); logErr2.append(norm(string(result.get(0)))); logErr2.append(NL); logErr2.append("[Wrong] "); logErr2.append(norm(er)); logErr2.append(NL); logErr2.append(NL); addLog(pth, outname + ".log", er); } correct = false; ++err2; } } if(curr != null) Close.close(curr.data, context); xq.close(); } if(reporting) { logReport.append(" <test-case name=\""); logReport.append(outname); logReport.append("\" result='"); logReport.append(correct ? "pass" : "fail"); if(inspect) logReport.append("' todo='inspect"); logReport.append("'/>"); logReport.append(NL); } if(verbose) { final long t = perf.getTime(); if(t > 100000000) Util.out(": " + Performance.getTimer(t, 1)); Util.outln(); } return single == null || !outname.equals(single); }
diff --git a/org/xbill/DNS/WKSRecord.java b/org/xbill/DNS/WKSRecord.java index 1f3757c..18b1dce 100644 --- a/org/xbill/DNS/WKSRecord.java +++ b/org/xbill/DNS/WKSRecord.java @@ -1,717 +1,722 @@ // Copyright (c) 1999-2004 Brian Wellington ([email protected]) package org.xbill.DNS; import java.net.*; import java.io.*; import java.util.*; import org.xbill.DNS.utils.*; /** * Well Known Services - Lists services offered by this host. * * @author Brian Wellington */ public class WKSRecord extends Record { public static class Protocol { /** * IP protocol identifiers. This is basically copied out of RFC 1010. */ private Protocol() {} /** Internet Control Message */ public static final int ICMP = 1; /** Internet Group Management */ public static final int IGMP = 2; /** Gateway-to-Gateway */ public static final int GGP = 3; /** Stream */ public static final int ST = 5; /** Transmission Control */ public static final int TCP = 6; /** UCL */ public static final int UCL = 7; /** Exterior Gateway Protocol */ public static final int EGP = 8; /** any private interior gateway */ public static final int IGP = 9; /** BBN RCC Monitoring */ public static final int BBN_RCC_MON = 10; /** Network Voice Protocol */ public static final int NVP_II = 11; /** PUP */ public static final int PUP = 12; /** ARGUS */ public static final int ARGUS = 13; /** EMCON */ public static final int EMCON = 14; /** Cross Net Debugger */ public static final int XNET = 15; /** Chaos */ public static final int CHAOS = 16; /** User Datagram */ public static final int UDP = 17; /** Multiplexing */ public static final int MUX = 18; /** DCN Measurement Subsystems */ public static final int DCN_MEAS = 19; /** Host Monitoring */ public static final int HMP = 20; /** Packet Radio Measurement */ public static final int PRM = 21; /** XEROX NS IDP */ public static final int XNS_IDP = 22; /** Trunk-1 */ public static final int TRUNK_1 = 23; /** Trunk-2 */ public static final int TRUNK_2 = 24; /** Leaf-1 */ public static final int LEAF_1 = 25; /** Leaf-2 */ public static final int LEAF_2 = 26; /** Reliable Data Protocol */ public static final int RDP = 27; /** Internet Reliable Transaction */ public static final int IRTP = 28; /** ISO Transport Protocol Class 4 */ public static final int ISO_TP4 = 29; /** Bulk Data Transfer Protocol */ public static final int NETBLT = 30; /** MFE Network Services Protocol */ public static final int MFE_NSP = 31; /** MERIT Internodal Protocol */ public static final int MERIT_INP = 32; /** Sequential Exchange Protocol */ public static final int SEP = 33; /** CFTP */ public static final int CFTP = 62; /** SATNET and Backroom EXPAK */ public static final int SAT_EXPAK = 64; /** MIT Subnet Support */ public static final int MIT_SUBNET = 65; /** MIT Remote Virtual Disk Protocol */ public static final int RVD = 66; /** Internet Pluribus Packet Core */ public static final int IPPC = 67; /** SATNET Monitoring */ public static final int SAT_MON = 69; /** Internet Packet Core Utility */ public static final int IPCV = 71; /** Backroom SATNET Monitoring */ public static final int BR_SAT_MON = 76; /** WIDEBAND Monitoring */ public static final int WB_MON = 78; /** WIDEBAND EXPAK */ public static final int WB_EXPAK = 79; private static Mnemonic protocols = new Mnemonic("IP protocol", Mnemonic.CASE_LOWER); static { protocols.setMaximum(0xFF); protocols.setNumericAllowed(true); protocols.add(ICMP, "icmp"); protocols.add(IGMP, "igmp"); protocols.add(GGP, "ggp"); protocols.add(ST, "st"); protocols.add(TCP, "tcp"); protocols.add(UCL, "ucl"); protocols.add(EGP, "egp"); protocols.add(IGP, "igp"); protocols.add(BBN_RCC_MON, "bbn-rcc-mon"); protocols.add(NVP_II, "nvp-ii"); protocols.add(PUP, "pup"); protocols.add(ARGUS, "argus"); protocols.add(EMCON, "emcon"); protocols.add(XNET, "xnet"); protocols.add(CHAOS, "chaos"); protocols.add(UDP, "udp"); protocols.add(MUX, "mux"); protocols.add(DCN_MEAS, "dcn-meas"); protocols.add(HMP, "hmp"); protocols.add(PRM, "prm"); protocols.add(XNS_IDP, "xns-idp"); protocols.add(TRUNK_1, "trunk-1"); protocols.add(TRUNK_2, "trunk-2"); protocols.add(LEAF_1, "leaf-1"); protocols.add(LEAF_2, "leaf-2"); protocols.add(RDP, "rdp"); protocols.add(IRTP, "irtp"); protocols.add(ISO_TP4, "iso-tp4"); protocols.add(NETBLT, "netblt"); protocols.add(MFE_NSP, "mfe-nsp"); protocols.add(MERIT_INP, "merit-inp"); protocols.add(SEP, "sep"); protocols.add(CFTP, "cftp"); protocols.add(SAT_EXPAK, "sat-expak"); protocols.add(MIT_SUBNET, "mit-subnet"); protocols.add(RVD, "rvd"); protocols.add(IPPC, "ippc"); protocols.add(SAT_MON, "sat-mon"); protocols.add(IPCV, "ipcv"); protocols.add(BR_SAT_MON, "br-sat-mon"); protocols.add(WB_MON, "wb-mon"); protocols.add(WB_EXPAK, "wb-expak"); } /** * Converts an IP protocol value into its textual representation */ public static String string(int type) { return protocols.getText(type); } /** * Converts a textual representation of an IP protocol into its * numeric code. Integers in the range 0..255 are also accepted. * @param s The textual representation of the protocol * @return The protocol code, or -1 on error. */ public static int value(String s) { return protocols.getValue(s); } } public static class Service { /** * TCP/UDP services. This is basically copied out of RFC 1010, * with MIT-ML-DEV removed, as it is not unique, and the description * of SWIFT-RVF fixed. */ private Service() {} /** Remote Job Entry */ public static final int RJE = 5; /** Echo */ public static final int ECHO = 7; /** Discard */ public static final int DISCARD = 9; /** Active Users */ public static final int USERS = 11; /** Daytime */ public static final int DAYTIME = 13; /** Quote of the Day */ public static final int QUOTE = 17; /** Character Generator */ public static final int CHARGEN = 19; /** File Transfer [Default Data] */ public static final int FTP_DATA = 20; /** File Transfer [Control] */ public static final int FTP = 21; /** Telnet */ public static final int TELNET = 23; /** Simple Mail Transfer */ public static final int SMTP = 25; /** NSW User System FE */ public static final int NSW_FE = 27; /** MSG ICP */ public static final int MSG_ICP = 29; /** MSG Authentication */ public static final int MSG_AUTH = 31; /** Display Support Protocol */ public static final int DSP = 33; /** Time */ public static final int TIME = 37; /** Resource Location Protocol */ public static final int RLP = 39; /** Graphics */ public static final int GRAPHICS = 41; /** Host Name Server */ public static final int NAMESERVER = 42; /** Who Is */ public static final int NICNAME = 43; /** MPM FLAGS Protocol */ public static final int MPM_FLAGS = 44; /** Message Processing Module [recv] */ public static final int MPM = 45; /** MPM [default send] */ public static final int MPM_SND = 46; /** NI FTP */ public static final int NI_FTP = 47; /** Login Host Protocol */ public static final int LOGIN = 49; /** IMP Logical Address Maintenance */ public static final int LA_MAINT = 51; /** Domain Name Server */ public static final int DOMAIN = 53; /** ISI Graphics Language */ public static final int ISI_GL = 55; /** NI MAIL */ public static final int NI_MAIL = 61; /** VIA Systems - FTP */ public static final int VIA_FTP = 63; /** TACACS-Database Service */ public static final int TACACS_DS = 65; /** Bootstrap Protocol Server */ public static final int BOOTPS = 67; /** Bootstrap Protocol Client */ public static final int BOOTPC = 68; /** Trivial File Transfer */ public static final int TFTP = 69; /** Remote Job Service */ public static final int NETRJS_1 = 71; /** Remote Job Service */ public static final int NETRJS_2 = 72; /** Remote Job Service */ public static final int NETRJS_3 = 73; /** Remote Job Service */ public static final int NETRJS_4 = 74; /** Finger */ public static final int FINGER = 79; /** HOSTS2 Name Server */ public static final int HOSTS2_NS = 81; /** SU/MIT Telnet Gateway */ public static final int SU_MIT_TG = 89; /** MIT Dover Spooler */ public static final int MIT_DOV = 91; /** Device Control Protocol */ public static final int DCP = 93; /** SUPDUP */ public static final int SUPDUP = 95; /** Swift Remote Virtual File Protocol */ public static final int SWIFT_RVF = 97; /** TAC News */ public static final int TACNEWS = 98; /** Metagram Relay */ public static final int METAGRAM = 99; /** NIC Host Name Server */ public static final int HOSTNAME = 101; /** ISO-TSAP */ public static final int ISO_TSAP = 102; /** X400 */ public static final int X400 = 103; /** X400-SND */ public static final int X400_SND = 104; /** Mailbox Name Nameserver */ public static final int CSNET_NS = 105; /** Remote Telnet Service */ public static final int RTELNET = 107; /** Post Office Protocol - Version 2 */ public static final int POP_2 = 109; /** SUN Remote Procedure Call */ public static final int SUNRPC = 111; /** Authentication Service */ public static final int AUTH = 113; /** Simple File Transfer Protocol */ public static final int SFTP = 115; /** UUCP Path Service */ public static final int UUCP_PATH = 117; /** Network News Transfer Protocol */ public static final int NNTP = 119; /** HYDRA Expedited Remote Procedure */ public static final int ERPC = 121; /** Network Time Protocol */ public static final int NTP = 123; /** Locus PC-Interface Net Map Server */ public static final int LOCUS_MAP = 125; /** Locus PC-Interface Conn Server */ public static final int LOCUS_CON = 127; /** Password Generator Protocol */ public static final int PWDGEN = 129; /** CISCO FNATIVE */ public static final int CISCO_FNA = 130; /** CISCO TNATIVE */ public static final int CISCO_TNA = 131; /** CISCO SYSMAINT */ public static final int CISCO_SYS = 132; /** Statistics Service */ public static final int STATSRV = 133; /** INGRES-NET Service */ public static final int INGRES_NET = 134; /** Location Service */ public static final int LOC_SRV = 135; /** PROFILE Naming System */ public static final int PROFILE = 136; /** NETBIOS Name Service */ public static final int NETBIOS_NS = 137; /** NETBIOS Datagram Service */ public static final int NETBIOS_DGM = 138; /** NETBIOS Session Service */ public static final int NETBIOS_SSN = 139; /** EMFIS Data Service */ public static final int EMFIS_DATA = 140; /** EMFIS Control Service */ public static final int EMFIS_CNTL = 141; /** Britton-Lee IDM */ public static final int BL_IDM = 142; /** Survey Measurement */ public static final int SUR_MEAS = 243; /** LINK */ public static final int LINK = 245; private static Mnemonic services = new Mnemonic("TCP/UDP service", Mnemonic.CASE_LOWER); static { services.setMaximum(0xFFFF); services.setNumericAllowed(true); services.add(RJE, "rje"); services.add(ECHO, "echo"); services.add(DISCARD, "discard"); services.add(USERS, "users"); services.add(DAYTIME, "daytime"); services.add(QUOTE, "quote"); services.add(CHARGEN, "chargen"); services.add(FTP_DATA, "ftp-data"); services.add(FTP, "ftp"); services.add(TELNET, "telnet"); services.add(SMTP, "smtp"); services.add(NSW_FE, "nsw-fe"); services.add(MSG_ICP, "msg-icp"); services.add(MSG_AUTH, "msg-auth"); services.add(DSP, "dsp"); services.add(TIME, "time"); services.add(RLP, "rlp"); services.add(GRAPHICS, "graphics"); services.add(NAMESERVER, "nameserver"); services.add(NICNAME, "nicname"); services.add(MPM_FLAGS, "mpm-flags"); services.add(MPM, "mpm"); services.add(MPM_SND, "mpm-snd"); services.add(NI_FTP, "ni-ftp"); services.add(LOGIN, "login"); services.add(LA_MAINT, "la-maint"); services.add(DOMAIN, "domain"); services.add(ISI_GL, "isi-gl"); services.add(NI_MAIL, "ni-mail"); services.add(VIA_FTP, "via-ftp"); services.add(TACACS_DS, "tacacs-ds"); services.add(BOOTPS, "bootps"); services.add(BOOTPC, "bootpc"); services.add(TFTP, "tftp"); services.add(NETRJS_1, "netrjs-1"); services.add(NETRJS_2, "netrjs-2"); services.add(NETRJS_3, "netrjs-3"); services.add(NETRJS_4, "netrjs-4"); services.add(FINGER, "finger"); services.add(HOSTS2_NS, "hosts2-ns"); services.add(SU_MIT_TG, "su-mit-tg"); services.add(MIT_DOV, "mit-dov"); services.add(DCP, "dcp"); services.add(SUPDUP, "supdup"); services.add(SWIFT_RVF, "swift-rvf"); services.add(TACNEWS, "tacnews"); services.add(METAGRAM, "metagram"); services.add(HOSTNAME, "hostname"); services.add(ISO_TSAP, "iso-tsap"); services.add(X400, "x400"); services.add(X400_SND, "x400-snd"); services.add(CSNET_NS, "csnet-ns"); services.add(RTELNET, "rtelnet"); services.add(POP_2, "pop-2"); services.add(SUNRPC, "sunrpc"); services.add(AUTH, "auth"); services.add(SFTP, "sftp"); services.add(UUCP_PATH, "uucp-path"); services.add(NNTP, "nntp"); services.add(ERPC, "erpc"); services.add(NTP, "ntp"); services.add(LOCUS_MAP, "locus-map"); services.add(LOCUS_CON, "locus-con"); services.add(PWDGEN, "pwdgen"); services.add(CISCO_FNA, "cisco-fna"); services.add(CISCO_TNA, "cisco-tna"); services.add(CISCO_SYS, "cisco-sys"); services.add(STATSRV, "statsrv"); services.add(INGRES_NET, "ingres-net"); services.add(LOC_SRV, "loc-srv"); services.add(PROFILE, "profile"); services.add(NETBIOS_NS, "netbios-ns"); services.add(NETBIOS_DGM, "netbios-dgm"); services.add(NETBIOS_SSN, "netbios-ssn"); services.add(EMFIS_DATA, "emfis-data"); services.add(EMFIS_CNTL, "emfis-cntl"); services.add(BL_IDM, "bl-idm"); services.add(SUR_MEAS, "sur-meas"); services.add(LINK, "link"); } /** * Converts a TCP/UDP service port number into its textual * representation. */ public static String string(int type) { return services.getText(type); } /** * Converts a textual representation of a TCP/UDP service into its * port number. Integers in the range 0..65535 are also accepted. * @param s The textual representation of the service. * @return The port number, or -1 on error. */ public static int value(String s) { return services.getValue(s); } } private byte [] address; private int protocol; private int [] services; WKSRecord() {} Record getObject() { return new WKSRecord(); } /** * Creates a WKS Record from the given data * @param address The IP address * @param protocol The IP protocol number * @param keyTag The ID of the associated KEYRecord, if present * @param alg The algorithm of the associated KEYRecord, if present * @param cert Binary data representing the certificate */ public WKSRecord(Name name, int dclass, long ttl, InetAddress address, int protocol, int [] services) { super(name, Type.WKS, dclass, ttl); this.address = address.getAddress(); this.protocol = checkU8("protocol", protocol); for (int i = 0; i < services.length; i++) { checkU16("service", services[i]); } this.services = new int[services.length]; System.arraycopy(services, 0, this.services, 0, services.length); Arrays.sort(this.services); } void rrFromWire(DNSInput in) throws IOException { address = in.readByteArray(4); protocol = in.readU8(); byte [] array = in.readByteArray(); List list = new ArrayList(); for (int i = 0; i < array.length; i++) { for (int j = 0; j < 8; j++) { int octet = array[i] & 0xFF; if ((octet & (1 << (7 - j))) != 0) { list.add(new Integer(i * 8 + j)); } } } services = new int[list.size()]; for (int i = 0; i < list.size(); i++) { services[i] = ((Integer) list.get(i)).intValue(); } } void rdataFromString(Tokenizer st, Name origin) throws IOException { String s = st.getString(); int [] array = Address.toArray(s); if (array == null) throw st.exception("invalid address"); + address = new byte[4]; + for (int i = 0; i < 4; i++) { + address[i] = (byte)array[i]; + } s = st.getString(); protocol = Protocol.value(s); if (protocol < 0) { throw st.exception("Invalid IP protocol: " + s); } List list = new ArrayList(); while (true) { Tokenizer.Token t = st.get(); if (!t.isString()) break; int service = Service.value(t.value); if (service < 0) { throw st.exception("Invalid TCP/UDP service: " + t.value); } list.add(new Integer(service)); } + st.unget(); services = new int[list.size()]; for (int i = 0; i < list.size(); i++) { services[i] = ((Integer) list.get(i)).intValue(); } } /** * Converts rdata to a String */ String rrToString() { StringBuffer sb = new StringBuffer(); sb.append(Address.toDottedQuad(address)); sb.append(" "); sb.append(protocol); for (int i = 0; i < services.length; i++) { sb.append(" " + services[i]); } return sb.toString(); } /** * Returns the IP address. */ public InetAddress getAddress() { try { return Address.getByName(Address.toDottedQuad(address)); } catch (UnknownHostException e) { throw new IllegalStateException("dotted quad lookup failure"); } } /** * Returns the IP protocol. */ public int getProtocol() { return protocol; } /** * Returns the services provided by the host on the specified address. */ public int [] getServices() { return services; } void rrToWire(DNSOutput out, Compression c, boolean canonical) { out.writeByteArray(address); out.writeU8(protocol); int highestPort = services[services.length - 1]; byte [] array = new byte[highestPort / 8 + 1]; for (int i = 0; i < services.length; i++) { int port = services[i]; array[port / 8] |= (1 << (7 - port % 8)); } out.writeByteArray(array); } }
false
true
void rdataFromString(Tokenizer st, Name origin) throws IOException { String s = st.getString(); int [] array = Address.toArray(s); if (array == null) throw st.exception("invalid address"); s = st.getString(); protocol = Protocol.value(s); if (protocol < 0) { throw st.exception("Invalid IP protocol: " + s); } List list = new ArrayList(); while (true) { Tokenizer.Token t = st.get(); if (!t.isString()) break; int service = Service.value(t.value); if (service < 0) { throw st.exception("Invalid TCP/UDP service: " + t.value); } list.add(new Integer(service)); } services = new int[list.size()]; for (int i = 0; i < list.size(); i++) { services[i] = ((Integer) list.get(i)).intValue(); } }
void rdataFromString(Tokenizer st, Name origin) throws IOException { String s = st.getString(); int [] array = Address.toArray(s); if (array == null) throw st.exception("invalid address"); address = new byte[4]; for (int i = 0; i < 4; i++) { address[i] = (byte)array[i]; } s = st.getString(); protocol = Protocol.value(s); if (protocol < 0) { throw st.exception("Invalid IP protocol: " + s); } List list = new ArrayList(); while (true) { Tokenizer.Token t = st.get(); if (!t.isString()) break; int service = Service.value(t.value); if (service < 0) { throw st.exception("Invalid TCP/UDP service: " + t.value); } list.add(new Integer(service)); } st.unget(); services = new int[list.size()]; for (int i = 0; i < list.size(); i++) { services[i] = ((Integer) list.get(i)).intValue(); } }
diff --git a/src/states/CastleState.java b/src/states/CastleState.java index 18dd751..271364e 100644 --- a/src/states/CastleState.java +++ b/src/states/CastleState.java @@ -1,127 +1,127 @@ package states; import java.util.ArrayList; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Image; import org.newdawn.slick.Music; import org.newdawn.slick.SlickException; import org.newdawn.slick.state.StateBasedGame; import org.newdawn.slick.tiled.TiledMap; import core.MainGame; import weapons.*; import dudes.GoblinArcher; import dudes.Knight; import dudes.Monster; public class CastleState extends AreaState { public CastleState(int stateID) { super(stateID); } public void init(GameContainer container, StateBasedGame game) throws SlickException { super.init(container, game); loop = new Music("Assets/Sound/Loops/CastleState.wav"); bgImage = new TiledMap("Assets/World/castlemap1.tmx"); areaLength = 200; // SpiderWeb sw1 = new SpiderWeb(new float[] {container.getWidth()-200f, container.getHeight()-200f}); // SpiderWeb sw2 = new SpiderWeb(new float[] {container.getWidth()-300f, container.getHeight()-150f}); // // obstacles.add(sw1); // obstacles.add(sw2); ArrayList<Monster> group_1 = new ArrayList<Monster>(); Knight g1_knight1 = new Knight(container.getWidth(), container.getHeight() - 80, 2, container); Knight g1_knight3 = new Knight(container.getWidth(), container.getHeight() - 240, 2, container); g1_knight1.init(); g1_knight3.init(); group_1.add(g1_knight1); group_1.add(g1_knight3); ArrayList<Monster> group_2 = new ArrayList<Monster>(); - Knight g2_knight1 = new Knight(container.getWidth(), + Knight g2_knight1 = new Knight(container.getWidth()-64, container.getHeight() - 80, 2, container); - Knight g2_knight2 = new Knight(container.getWidth(), + Knight g2_knight2 = new Knight(container.getWidth()-64, container.getHeight() - 160, 2, container); Knight g2_knight3 = new Knight(container.getWidth(), container.getHeight() - 240, 2, container); - GoblinArcher g2_goblin1 = new GoblinArcher(container.getWidth()+80, + GoblinArcher g2_goblin1 = new GoblinArcher(container.getWidth() , container.getHeight() - 80, 2, container); - GoblinArcher g2_goblin2 = new GoblinArcher(container.getWidth()+80, + GoblinArcher g2_goblin2 = new GoblinArcher(container.getWidth() , container.getHeight() - 160, 2, container); g2_knight1.init(); g2_knight2.init(); g2_knight3.init(); g2_goblin1.init(); g2_goblin2.init(); group_2.add(g2_knight1); group_2.add(g2_knight2); group_2.add(g2_knight3); group_2.add(g2_goblin1); group_2.add(g2_goblin2); ArrayList<Monster> group_3 = new ArrayList<Monster>(); - Knight g3_knight1 = new Knight(container.getWidth(), + Knight g3_knight1 = new Knight(container.getWidth()-64, container.getHeight() - 80, 2, container); - Knight g3_knight2 = new Knight(container.getWidth(), + Knight g3_knight2 = new Knight(container.getWidth()-64, container.getHeight() - 160, 2, container); Knight g3_knight3 = new Knight(0, container.getHeight() - 240, 2, container); Knight g3_knight4 = new Knight(0, container.getHeight() - 80, 2, container); GoblinArcher g3_goblin1 = new GoblinArcher(container.getWidth(), container.getHeight() - 80, 2, container); GoblinArcher g3_goblin2 = new GoblinArcher(container.getWidth(), container.getHeight() - 160, 2, container); g3_knight1.init(); g3_knight2.init(); g3_knight3.init(); g3_knight4.init(); g3_goblin1.init(); g3_goblin2.init(); group_3.add(g3_knight1); group_3.add(g3_knight2); group_3.add(g3_knight3); group_3.add(g3_knight4); group_3.add(g3_goblin1); group_3.add(g3_goblin2); monsters.add(group_1); monsters.add(group_2); monsters.add(group_3); battleStops = new int[3]; battleStops[0] = 1000; battleStops[1] = 2000; battleStops[2] = 3000; princess = new Image("Assets/Outdated/npcs/daughterFront.png"); //princess.draw(container.getWidth(), container.getHeight() - 80); } /*@Override public ArrayList<Weapon> makeInitItems() throws SlickException { ArrayList<Weapon> o = new ArrayList<Weapon>(); Weapon k1 = new Sword(1200f, MainGame.GAME_HEIGHT - 100); Weapon k2 = new Bear(1300f, MainGame.GAME_HEIGHT - 100); k1.createGroundSprite(); k2.createGroundSprite(); o.add(k1); o.add(k2); return o; }*/ @Override public int getID(){ return 4; } }
false
true
public void init(GameContainer container, StateBasedGame game) throws SlickException { super.init(container, game); loop = new Music("Assets/Sound/Loops/CastleState.wav"); bgImage = new TiledMap("Assets/World/castlemap1.tmx"); areaLength = 200; // SpiderWeb sw1 = new SpiderWeb(new float[] {container.getWidth()-200f, container.getHeight()-200f}); // SpiderWeb sw2 = new SpiderWeb(new float[] {container.getWidth()-300f, container.getHeight()-150f}); // // obstacles.add(sw1); // obstacles.add(sw2); ArrayList<Monster> group_1 = new ArrayList<Monster>(); Knight g1_knight1 = new Knight(container.getWidth(), container.getHeight() - 80, 2, container); Knight g1_knight3 = new Knight(container.getWidth(), container.getHeight() - 240, 2, container); g1_knight1.init(); g1_knight3.init(); group_1.add(g1_knight1); group_1.add(g1_knight3); ArrayList<Monster> group_2 = new ArrayList<Monster>(); Knight g2_knight1 = new Knight(container.getWidth(), container.getHeight() - 80, 2, container); Knight g2_knight2 = new Knight(container.getWidth(), container.getHeight() - 160, 2, container); Knight g2_knight3 = new Knight(container.getWidth(), container.getHeight() - 240, 2, container); GoblinArcher g2_goblin1 = new GoblinArcher(container.getWidth()+80, container.getHeight() - 80, 2, container); GoblinArcher g2_goblin2 = new GoblinArcher(container.getWidth()+80, container.getHeight() - 160, 2, container); g2_knight1.init(); g2_knight2.init(); g2_knight3.init(); g2_goblin1.init(); g2_goblin2.init(); group_2.add(g2_knight1); group_2.add(g2_knight2); group_2.add(g2_knight3); group_2.add(g2_goblin1); group_2.add(g2_goblin2); ArrayList<Monster> group_3 = new ArrayList<Monster>(); Knight g3_knight1 = new Knight(container.getWidth(), container.getHeight() - 80, 2, container); Knight g3_knight2 = new Knight(container.getWidth(), container.getHeight() - 160, 2, container); Knight g3_knight3 = new Knight(0, container.getHeight() - 240, 2, container); Knight g3_knight4 = new Knight(0, container.getHeight() - 80, 2, container); GoblinArcher g3_goblin1 = new GoblinArcher(container.getWidth(), container.getHeight() - 80, 2, container); GoblinArcher g3_goblin2 = new GoblinArcher(container.getWidth(), container.getHeight() - 160, 2, container); g3_knight1.init(); g3_knight2.init(); g3_knight3.init(); g3_knight4.init(); g3_goblin1.init(); g3_goblin2.init(); group_3.add(g3_knight1); group_3.add(g3_knight2); group_3.add(g3_knight3); group_3.add(g3_knight4); group_3.add(g3_goblin1); group_3.add(g3_goblin2); monsters.add(group_1); monsters.add(group_2); monsters.add(group_3); battleStops = new int[3]; battleStops[0] = 1000; battleStops[1] = 2000; battleStops[2] = 3000; princess = new Image("Assets/Outdated/npcs/daughterFront.png"); //princess.draw(container.getWidth(), container.getHeight() - 80); }
public void init(GameContainer container, StateBasedGame game) throws SlickException { super.init(container, game); loop = new Music("Assets/Sound/Loops/CastleState.wav"); bgImage = new TiledMap("Assets/World/castlemap1.tmx"); areaLength = 200; // SpiderWeb sw1 = new SpiderWeb(new float[] {container.getWidth()-200f, container.getHeight()-200f}); // SpiderWeb sw2 = new SpiderWeb(new float[] {container.getWidth()-300f, container.getHeight()-150f}); // // obstacles.add(sw1); // obstacles.add(sw2); ArrayList<Monster> group_1 = new ArrayList<Monster>(); Knight g1_knight1 = new Knight(container.getWidth(), container.getHeight() - 80, 2, container); Knight g1_knight3 = new Knight(container.getWidth(), container.getHeight() - 240, 2, container); g1_knight1.init(); g1_knight3.init(); group_1.add(g1_knight1); group_1.add(g1_knight3); ArrayList<Monster> group_2 = new ArrayList<Monster>(); Knight g2_knight1 = new Knight(container.getWidth()-64, container.getHeight() - 80, 2, container); Knight g2_knight2 = new Knight(container.getWidth()-64, container.getHeight() - 160, 2, container); Knight g2_knight3 = new Knight(container.getWidth(), container.getHeight() - 240, 2, container); GoblinArcher g2_goblin1 = new GoblinArcher(container.getWidth() , container.getHeight() - 80, 2, container); GoblinArcher g2_goblin2 = new GoblinArcher(container.getWidth() , container.getHeight() - 160, 2, container); g2_knight1.init(); g2_knight2.init(); g2_knight3.init(); g2_goblin1.init(); g2_goblin2.init(); group_2.add(g2_knight1); group_2.add(g2_knight2); group_2.add(g2_knight3); group_2.add(g2_goblin1); group_2.add(g2_goblin2); ArrayList<Monster> group_3 = new ArrayList<Monster>(); Knight g3_knight1 = new Knight(container.getWidth()-64, container.getHeight() - 80, 2, container); Knight g3_knight2 = new Knight(container.getWidth()-64, container.getHeight() - 160, 2, container); Knight g3_knight3 = new Knight(0, container.getHeight() - 240, 2, container); Knight g3_knight4 = new Knight(0, container.getHeight() - 80, 2, container); GoblinArcher g3_goblin1 = new GoblinArcher(container.getWidth(), container.getHeight() - 80, 2, container); GoblinArcher g3_goblin2 = new GoblinArcher(container.getWidth(), container.getHeight() - 160, 2, container); g3_knight1.init(); g3_knight2.init(); g3_knight3.init(); g3_knight4.init(); g3_goblin1.init(); g3_goblin2.init(); group_3.add(g3_knight1); group_3.add(g3_knight2); group_3.add(g3_knight3); group_3.add(g3_knight4); group_3.add(g3_goblin1); group_3.add(g3_goblin2); monsters.add(group_1); monsters.add(group_2); monsters.add(group_3); battleStops = new int[3]; battleStops[0] = 1000; battleStops[1] = 2000; battleStops[2] = 3000; princess = new Image("Assets/Outdated/npcs/daughterFront.png"); //princess.draw(container.getWidth(), container.getHeight() - 80); }
diff --git a/src/main/us/exultant/mdm/commands/MdmStatusCommand.java b/src/main/us/exultant/mdm/commands/MdmStatusCommand.java index fa34107..8690406 100644 --- a/src/main/us/exultant/mdm/commands/MdmStatusCommand.java +++ b/src/main/us/exultant/mdm/commands/MdmStatusCommand.java @@ -1,106 +1,106 @@ /* * Copyright 2012, 2013 Eric Myhre <http://exultant.us> * * This file is part of mdm <https://github.com/heavenlyhash/mdm/>. * * mdm is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, version 3 of the License, or * (at your option) 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package us.exultant.mdm.commands; import java.io.*; import java.util.*; import org.eclipse.jgit.errors.*; import org.eclipse.jgit.lib.*; import us.exultant.ahs.util.*; import us.exultant.mdm.*; public class MdmStatusCommand extends MdmCommand { public MdmStatusCommand(Repository repo, PrintStream os) { super(repo, os); } public MdmStatusCommand(Repository repo) { super(repo); } private PrintStream os = System.out; public void setPrintStream(PrintStream os) { this.os = os; } public MdmExitMessage call() throws IOException, ConfigInvalidException { try { assertInRepo(); } catch (MdmExitMessage e) { return e; } MdmModuleSet moduleSet = new MdmModuleSet(repo); Map<String,MdmModule> modules = moduleSet.getDependencyModules(); if (modules.size() == 0) { os.println(" --- no managed dependencies --- "); - return null; + return new MdmExitMessage(0); } Collection<String> row1 = new ArrayList<>(modules.keySet()); row1.add("dependency:"); int width1 = Strings.chooseFieldWidth(row1); os.printf("%-"+width1+"s \t %s\n", "dependency:", "version:"); os.printf("%-"+width1+"s \t %s\n", "-----------", "--------"); for (MdmModule mod : modules.values()) { StatusTuple status = status(mod); os.printf(" %-"+width1+"s \t %s\n", mod.getHandle(), status.version); for (String warning : status.warnings) os.printf(" %-"+width1+"s \t %s\n", "", " !! "+warning); } return new MdmExitMessage(0); } public StatusTuple status(MdmModule module) { StatusTuple s = new StatusTuple(); if (!module.getHandle().equals(module.getPath())) s.errors.add("Handle and path are not the same. This is very strange and may cause issues with other git tools."); if (module.getUrlHistoric() == null) s.errors.add("No url for remote repo is set in gitmodules."); if (module.getType() == MdmModuleType.DEPENDENCY) { if (module.getVersionName() == null) s.errors.add("Version name not specified in gitmodules file!"); if (module.getHeadId() == null) { s.version = "-- uninitialized --"; } else { s.version = (module.getVersionActual() == null) ? "__UNKNOWN_VERSION__" : module.getVersionActual(); if (module.getVersionName() != null && !module.getVersionName().equals(module.getVersionActual())) s.warnings.add("intended version is "+module.getVersionName()+", run `mdm update` to get it"); if (!module.getIndexId().equals(module.getHeadId())) s.warnings.add("commit currently checked out does not match hash in parent project"); if (module.hasDirtyFiles()) s.warnings.add("there are uncommitted changes in this submodule"); } } return s; } public class StatusTuple { public String version; /** Major notifications about the state of a module -- things that mean your build probably won't work. */ public List<String> warnings = new ArrayList<>(); /** Errors so bad that we can't even tell what's supposed to be going on with this module. */ public List<String> errors = new ArrayList<>(); } }
true
true
public MdmExitMessage call() throws IOException, ConfigInvalidException { try { assertInRepo(); } catch (MdmExitMessage e) { return e; } MdmModuleSet moduleSet = new MdmModuleSet(repo); Map<String,MdmModule> modules = moduleSet.getDependencyModules(); if (modules.size() == 0) { os.println(" --- no managed dependencies --- "); return null; } Collection<String> row1 = new ArrayList<>(modules.keySet()); row1.add("dependency:"); int width1 = Strings.chooseFieldWidth(row1); os.printf("%-"+width1+"s \t %s\n", "dependency:", "version:"); os.printf("%-"+width1+"s \t %s\n", "-----------", "--------"); for (MdmModule mod : modules.values()) { StatusTuple status = status(mod); os.printf(" %-"+width1+"s \t %s\n", mod.getHandle(), status.version); for (String warning : status.warnings) os.printf(" %-"+width1+"s \t %s\n", "", " !! "+warning); } return new MdmExitMessage(0); }
public MdmExitMessage call() throws IOException, ConfigInvalidException { try { assertInRepo(); } catch (MdmExitMessage e) { return e; } MdmModuleSet moduleSet = new MdmModuleSet(repo); Map<String,MdmModule> modules = moduleSet.getDependencyModules(); if (modules.size() == 0) { os.println(" --- no managed dependencies --- "); return new MdmExitMessage(0); } Collection<String> row1 = new ArrayList<>(modules.keySet()); row1.add("dependency:"); int width1 = Strings.chooseFieldWidth(row1); os.printf("%-"+width1+"s \t %s\n", "dependency:", "version:"); os.printf("%-"+width1+"s \t %s\n", "-----------", "--------"); for (MdmModule mod : modules.values()) { StatusTuple status = status(mod); os.printf(" %-"+width1+"s \t %s\n", mod.getHandle(), status.version); for (String warning : status.warnings) os.printf(" %-"+width1+"s \t %s\n", "", " !! "+warning); } return new MdmExitMessage(0); }
diff --git a/source/src/org/playframework/playclipse/editors/html/HTMLEditor.java b/source/src/org/playframework/playclipse/editors/html/HTMLEditor.java index a277a78..e8431c4 100644 --- a/source/src/org/playframework/playclipse/editors/html/HTMLEditor.java +++ b/source/src/org/playframework/playclipse/editors/html/HTMLEditor.java @@ -1,326 +1,326 @@ package org.playframework.playclipse.editors.html; import java.util.ArrayList; import java.util.HashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.TextAttribute; import org.eclipse.jface.text.hyperlink.IHyperlink; import org.eclipse.jface.text.source.Annotation; import org.eclipse.jface.text.source.ISourceViewer; import org.eclipse.jface.text.source.IVerticalRuler; import org.eclipse.jface.text.source.projection.ProjectionAnnotation; import org.eclipse.jface.text.source.projection.ProjectionAnnotationModel; import org.eclipse.jface.text.source.projection.ProjectionSupport; import org.eclipse.jface.text.source.projection.ProjectionViewer; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.widgets.Composite; import org.playframework.playclipse.editors.Editor; public class HTMLEditor extends Editor { private ProjectionSupport projectionSupport; public HTMLEditor() { super(); setSourceViewerConfiguration(new HTMLConfiguration(this)); } public String[] getTypes() { return new String[] {"default", "doctype", "html", "string", "tag", "expression", "action", "skipped", "keyword"}; } public TextAttribute getStyle(String type) { if(type.equals("doctype")) { return style(new RGB(127, 127, 127)); } if(type.equals("html")) { return style(new RGB(58, 147, 18)); } if(type.equals("string")) { return style(new RGB(5, 152, 220)); } if(type.equals("tag")) { return style(new RGB(129, 0, 153)); } if(type.equals("expression")) { return style(new RGB(255, 144, 0)); } if(type.equals("action")) { return style(new RGB(255, 0, 192)); } if(type.equals("skipped")) { return style(new RGB(90, 90, 90)); } if(type.equals("keyword")) { return style(new RGB(255, 0, 0)); } return style(new RGB(0, 0, 0)); } // Auto-close public String autoClose(char pc, char c, char nc) { if(c == '<') { return ">"; } if(c == '>' && nc == '>') { return SKIP; } if(c == '{') { return "}"; } if(c == '}' && nc == '}') { return SKIP; } if(c == '(') { return ")"; } if(c == ')' && nc == ')') { return SKIP; } if(c == '[') { return "]"; } if(c == ']' && nc == ']') { return SKIP; } if(c == '\'') { if(nc == '\'') { return SKIP; } return "\'"; } if(c == '\"') { if(nc == '\"') { return SKIP; } return "\""; } return null; }; // Template public void templates(String contentType, String ctx) { if(contentType == "default" || contentType == "html" || contentType == "string") { template("$", "Insert dynamic expression", "$${${}}${cursor}"); template("tag", "Insert tag without body", "#{${name} ${}/}${cursor}"); template("action", "Insert action", "@{${}}${cursor}"); template("tag", "Insert tag with body", "##{${name} ${}}${cursor}#{/${name}}"); } if(contentType == "default") { template("if", "Insert a #if tag", "#{if ${}}\n ${cursor}\n#{/if}"); template("extends", "Insert a #extends tag", "#{extends '${}' /}${cursor}"); template("list", "Insert a #list tag", "#{list ${}, as:'${i}'}\n ${cursor}\n#{/list>"); template("doctype", "Insert an HTML5 doctype element", "<!DOCTYPE html>"); } // Magic Matcher isTag = Pattern.compile("<([a-zA-Z]+)>").matcher(ctx); if(isTag.matches()) { String closeTag = "</" + isTag.group(1) + ">"; template(ctx, "Close the " + ctx + " HTML tag", "${cursor}"+closeTag); } } // Hyperlink Pattern extend_s = Pattern.compile("#\\{extends\\s+'([^']+)'"); Pattern include = Pattern.compile("#\\{include\\s+'([^']+)'"); Pattern action = Pattern.compile("@\\{([^}]+)\\}"); Pattern action_in_tag = Pattern.compile("#\\{.+(@.+[)])"); Pattern tag = Pattern.compile("#\\{([-a-zA-Z0-9.]+) "); public IHyperlink detectHyperlink(ITextViewer textViewer, IRegion region) { BestMatch match = findBestMatch(region.getOffset(), include, extend_s, action, action_in_tag, tag); if(match != null) { if(match.is(action)) { return match.hyperlink("action", 0, 0); } if(match.is(tag)) { return match.hyperlink("tag", 2, -1); } if(match.is(extend_s)) { return match.hyperlink("extends", match.matcher.start(1) - match.matcher.start(), -1); } if(match.is(include)) { return match.hyperlink("include", match.matcher.start(1) - match.matcher.start(), -1); } if(match.is(action_in_tag)) { return match.hyperlink("action_in_tag", match.matcher.start(1) - match.matcher.start(), 0); } } return null; } // Scanner boolean consumeString = false; char openedString = ' '; String oldState = "default"; String oldStringState = "default"; @Override protected void reset() { super.reset(); consumeString = false; oldState = "default"; } @Override public String scan() { if(isNext("*{") && state != "skipped") { oldState = state; return found("skipped", 0); } if(state == "skipped") { if(isNext("}*")) { return found(oldState, 2); } } if(state == "default" || state == "html" || state == "string") { if(isNext("#{")) { oldState = state; return found("tag", 0); } if(isNext("${")) { oldState = state; return found("expression", 0); } if(isNext("@{")) { oldState = state; return found("action", 0); } } if(state == "tag" || state == "expression" || state == "action") { if(isNext("}")) { return found(oldState, 1); } } if(state == "default") { if(isNext("<!DOCTYPE")) { return found("doctype", 0); } if(isNext("<")) { return found("html", 0); } if(isNext("var ")) { return found("keyword", 0); } if(isNext("def ")) { return found("keyword", 0); } if(isNext("return ")) { return found("keyword", 0); } if(isNext("function(")) { return found("keyword", 0); } if(isNext("function ")) { return found("keyword", 0); } if(isNext("if(")) { return found("keyword", 0); } if(isNext("if ")) { return found("keyword", 0); } if(isNext("else ")) { return found("keyword", 0); } if(isNext("switch(")) { return found("keyword", 0); } if(isNext("switch ")) { return found("keyword", 0); } } if(state == "keyword") { if(isNext(" ") || isNext("(")) { return found("default", 0); } } if(state == "doctype" || state == "html") { if(isNext(">")) { return found("default", 1); } } - if(state == "html" || state == "default") { + if(state == "html") { if(isNext("\"")) { openedString = '\"'; consumeString = false; oldStringState = state; return found("string", 0); } if(isNext("'")) { openedString = '\''; consumeString = false; oldStringState = state; return found("string", 0); } } if(state == "string") { if(isNext(""+openedString) && consumeString) { return found(oldStringState, 1); } consumeString = true; } return null; } // Folding private Annotation[] oldAnnotations; private ProjectionAnnotationModel annotationModel; public void updateFoldingStructure(ArrayList<Position> positions) { Annotation[] annotations = new Annotation[positions.size()]; //this will hold the new annotations along //with their corresponding positions HashMap<ProjectionAnnotation, Position> newAnnotations = new HashMap<ProjectionAnnotation, Position>(); for (int i = 0; i < positions.size(); i++) { ProjectionAnnotation annotation = new ProjectionAnnotation(); newAnnotations.put(annotation, positions.get(i)); annotations[i] = annotation; } annotationModel.modifyAnnotations(oldAnnotations, newAnnotations, null); oldAnnotations = annotations; } @Override public void createPartControl(Composite parent) { super.createPartControl(parent); ProjectionViewer viewer =(ProjectionViewer)getSourceViewer(); projectionSupport = new ProjectionSupport(viewer, getAnnotationAccess(), getSharedColors()); projectionSupport.install(); //turn projection mode on viewer.doOperation(ProjectionViewer.TOGGLE); annotationModel = viewer.getProjectionAnnotationModel(); } @Override protected ISourceViewer createSourceViewer(Composite parent, IVerticalRuler ruler, int styles) { ISourceViewer viewer = new ProjectionViewer(parent, ruler, getOverviewRuler(), isOverviewRulerVisible(), styles); // ensure decoration support has been created and configured. getSourceViewerDecorationSupport(viewer); return viewer; } }
true
true
public String scan() { if(isNext("*{") && state != "skipped") { oldState = state; return found("skipped", 0); } if(state == "skipped") { if(isNext("}*")) { return found(oldState, 2); } } if(state == "default" || state == "html" || state == "string") { if(isNext("#{")) { oldState = state; return found("tag", 0); } if(isNext("${")) { oldState = state; return found("expression", 0); } if(isNext("@{")) { oldState = state; return found("action", 0); } } if(state == "tag" || state == "expression" || state == "action") { if(isNext("}")) { return found(oldState, 1); } } if(state == "default") { if(isNext("<!DOCTYPE")) { return found("doctype", 0); } if(isNext("<")) { return found("html", 0); } if(isNext("var ")) { return found("keyword", 0); } if(isNext("def ")) { return found("keyword", 0); } if(isNext("return ")) { return found("keyword", 0); } if(isNext("function(")) { return found("keyword", 0); } if(isNext("function ")) { return found("keyword", 0); } if(isNext("if(")) { return found("keyword", 0); } if(isNext("if ")) { return found("keyword", 0); } if(isNext("else ")) { return found("keyword", 0); } if(isNext("switch(")) { return found("keyword", 0); } if(isNext("switch ")) { return found("keyword", 0); } } if(state == "keyword") { if(isNext(" ") || isNext("(")) { return found("default", 0); } } if(state == "doctype" || state == "html") { if(isNext(">")) { return found("default", 1); } } if(state == "html" || state == "default") { if(isNext("\"")) { openedString = '\"'; consumeString = false; oldStringState = state; return found("string", 0); } if(isNext("'")) { openedString = '\''; consumeString = false; oldStringState = state; return found("string", 0); } } if(state == "string") { if(isNext(""+openedString) && consumeString) { return found(oldStringState, 1); } consumeString = true; } return null; }
public String scan() { if(isNext("*{") && state != "skipped") { oldState = state; return found("skipped", 0); } if(state == "skipped") { if(isNext("}*")) { return found(oldState, 2); } } if(state == "default" || state == "html" || state == "string") { if(isNext("#{")) { oldState = state; return found("tag", 0); } if(isNext("${")) { oldState = state; return found("expression", 0); } if(isNext("@{")) { oldState = state; return found("action", 0); } } if(state == "tag" || state == "expression" || state == "action") { if(isNext("}")) { return found(oldState, 1); } } if(state == "default") { if(isNext("<!DOCTYPE")) { return found("doctype", 0); } if(isNext("<")) { return found("html", 0); } if(isNext("var ")) { return found("keyword", 0); } if(isNext("def ")) { return found("keyword", 0); } if(isNext("return ")) { return found("keyword", 0); } if(isNext("function(")) { return found("keyword", 0); } if(isNext("function ")) { return found("keyword", 0); } if(isNext("if(")) { return found("keyword", 0); } if(isNext("if ")) { return found("keyword", 0); } if(isNext("else ")) { return found("keyword", 0); } if(isNext("switch(")) { return found("keyword", 0); } if(isNext("switch ")) { return found("keyword", 0); } } if(state == "keyword") { if(isNext(" ") || isNext("(")) { return found("default", 0); } } if(state == "doctype" || state == "html") { if(isNext(">")) { return found("default", 1); } } if(state == "html") { if(isNext("\"")) { openedString = '\"'; consumeString = false; oldStringState = state; return found("string", 0); } if(isNext("'")) { openedString = '\''; consumeString = false; oldStringState = state; return found("string", 0); } } if(state == "string") { if(isNext(""+openedString) && consumeString) { return found(oldStringState, 1); } consumeString = true; } return null; }