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/app/rules/RuleUtils.java b/app/rules/RuleUtils.java
index de74894..0ac6e9d 100644
--- a/app/rules/RuleUtils.java
+++ b/app/rules/RuleUtils.java
@@ -1,206 +1,205 @@
package rules;
import java.io.File;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import models.FileMove;
import models.Rule;
import models.User;
import play.Logger;
import com.google.appengine.repackaged.com.google.common.base.Pair;
import com.google.common.collect.Lists;
import dropbox.Dropbox;
import dropbox.client.DropboxClient;
import dropbox.client.DropboxClientFactory;
import dropbox.client.FileMoveCollisionException;
import dropbox.client.InvalidTokenException;
public class RuleUtils {
private static final int MAX_TRIES = 10;
/**
* Return a regex pattern that will match the given glob pattern.
*
* Only ? and * are supported.
* TODO use a memoizer to cache compiled patterns.
* TODO Collapse consecutive *'s.
*/
public static Pattern getGlobPattern(String glob) {
if (glob == null) {
return Pattern.compile("");
}
StringBuilder out = new StringBuilder();
for(int i = 0; i < glob.length(); ++i) {
final char c = glob.charAt(i);
switch(c) {
case '*':
out.append(".*");
break;
case '?':
out.append(".");
break;
case '.':
out.append("\\.");
break;
case '\\':
out.append("\\\\");
break;
default:
out.append(c);
}
}
return Pattern.compile(out.toString(), Pattern.CASE_INSENSITIVE);
}
public static String getExt(String fileName) {
return splitName(fileName).second;
}
/**
* Split given fileName into name and extension.
*
* If the file name starts with a period but does not contain any other
* periods we say that it doesn't have an extension.
*
* Otherwise all text after the last period in the filename is taken to be
* the extension even if it contains spaces.
*
* Examples:
* ".bashrc" has no extension
* ".foo.pdf" has the extension pdf
* "file.ext ension" has extension "ext ension"
*
* @return a {@link Pair} where first is file name and second is extension.
* Extension may be null
* Extension does not contain the leading period (.)
*/
public static Pair<String, String> splitName(String fileName) {
if (fileName == null) {
return new Pair<String, String>(null, null);
}
int extBegin = fileName.lastIndexOf(".");
if (extBegin <= 0) {
return new Pair<String, String>(fileName, null);
}
String name = fileName.substring(0, extBegin);
String ext = fileName.substring(extBegin + 1);
if (ext.isEmpty()) {
ext = null;
}
return new Pair<String, String>(name, ext);
}
/**
* Process all rules for the current user and move files to new location
* as approriate.
*
* @return list of file moves performed
*/
public static List<FileMove> runRules(User user) {
user.updateLastSyncDate();
List<FileMove> fileMoves = Lists.newArrayList();
DropboxClient client = DropboxClientFactory.create(user);
try {
Set<String> files = client.listDir(Dropbox.getSortboxPath());
if (files.isEmpty()) {
Logger.info("Ran rules for %s, no files to process.", user);
return fileMoves;
}
List<Rule> rules = Rule.findByUserId(user.id);
Logger.info("Running rules for %s", user);
for (String file : files) {
String base = basename(file);
for (Rule r : rules) {
if (r.matches(base)) {
Logger.info("Moving file '%s' to '%s'. Rule id: %s",
file, r.dest, r.id);
boolean success = true;
String resolvedName = null;
int tries = 0;
while (tries < MAX_TRIES) {
try {
String suffix = null;
if (!success) {
suffix = " conflict"
+ (tries > 1 ? " " + tries : "");
}
resolvedName = insertIntoName(base, suffix);
String dest = r.dest
+ (r.dest.endsWith("/") ? "" : "/")
+ resolvedName;
client.move(file, dest);
break;
} catch (FileMoveCollisionException e) {
success = false;
}
tries++;
}
if (success) {
// If we moved the file to the correct destination
// on first try resolved name is same as original
// name so leave it as null.
resolvedName = null;
} else if (tries >= MAX_TRIES) {
// If we failed to move the file to any location
// leave this field
// as null to indicate complete failure.
resolvedName = null;
- Logger.error(
- "Cannot move file '%s' to '%s' after %d tries. Skipping.",
- file, r.dest, MAX_TRIES);
+ Logger.error("Cannot move file '%s' to '%s' after %d tries. Skipping.",
+ file, r.dest, MAX_TRIES);
}
fileMoves.add(new FileMove(user.id, base, r.dest,
success, resolvedName));
break;
}
}
}
Logger.info("Done running rules for %s. %d moves performed", user,
fileMoves.size());
if (!fileMoves.isEmpty()) {
user.incrementFileMoves(fileMoves.size());
FileMove.save(fileMoves);
}
return fileMoves;
} catch (InvalidTokenException e) {
Logger.error(e, "Disabling periodic sort, invalid OAuth token for user: %s", user);
user.periodicSort = false;
user.save();
}
return Collections.emptyList();
}
public static String insertIntoName(String fileName, String suffix) {
assert ! fileName.contains("/") : "Cannot process paths, can only process basenames.";
Pair<String, String> fileAndExt = splitName(fileName);
return fileAndExt.first +
(suffix == null ? "" : suffix) +
(fileAndExt.second == null ? "" : "." + fileAndExt.second);
}
public static String basename(String path) {
return path == null ? null : new File(path).getName();
}
private RuleUtils() {}
}
| true | true | public static List<FileMove> runRules(User user) {
user.updateLastSyncDate();
List<FileMove> fileMoves = Lists.newArrayList();
DropboxClient client = DropboxClientFactory.create(user);
try {
Set<String> files = client.listDir(Dropbox.getSortboxPath());
if (files.isEmpty()) {
Logger.info("Ran rules for %s, no files to process.", user);
return fileMoves;
}
List<Rule> rules = Rule.findByUserId(user.id);
Logger.info("Running rules for %s", user);
for (String file : files) {
String base = basename(file);
for (Rule r : rules) {
if (r.matches(base)) {
Logger.info("Moving file '%s' to '%s'. Rule id: %s",
file, r.dest, r.id);
boolean success = true;
String resolvedName = null;
int tries = 0;
while (tries < MAX_TRIES) {
try {
String suffix = null;
if (!success) {
suffix = " conflict"
+ (tries > 1 ? " " + tries : "");
}
resolvedName = insertIntoName(base, suffix);
String dest = r.dest
+ (r.dest.endsWith("/") ? "" : "/")
+ resolvedName;
client.move(file, dest);
break;
} catch (FileMoveCollisionException e) {
success = false;
}
tries++;
}
if (success) {
// If we moved the file to the correct destination
// on first try resolved name is same as original
// name so leave it as null.
resolvedName = null;
} else if (tries >= MAX_TRIES) {
// If we failed to move the file to any location
// leave this field
// as null to indicate complete failure.
resolvedName = null;
Logger.error(
"Cannot move file '%s' to '%s' after %d tries. Skipping.",
file, r.dest, MAX_TRIES);
}
fileMoves.add(new FileMove(user.id, base, r.dest,
success, resolvedName));
break;
}
}
}
Logger.info("Done running rules for %s. %d moves performed", user,
fileMoves.size());
if (!fileMoves.isEmpty()) {
user.incrementFileMoves(fileMoves.size());
FileMove.save(fileMoves);
}
return fileMoves;
} catch (InvalidTokenException e) {
Logger.error(e, "Disabling periodic sort, invalid OAuth token for user: %s", user);
user.periodicSort = false;
user.save();
}
return Collections.emptyList();
}
| public static List<FileMove> runRules(User user) {
user.updateLastSyncDate();
List<FileMove> fileMoves = Lists.newArrayList();
DropboxClient client = DropboxClientFactory.create(user);
try {
Set<String> files = client.listDir(Dropbox.getSortboxPath());
if (files.isEmpty()) {
Logger.info("Ran rules for %s, no files to process.", user);
return fileMoves;
}
List<Rule> rules = Rule.findByUserId(user.id);
Logger.info("Running rules for %s", user);
for (String file : files) {
String base = basename(file);
for (Rule r : rules) {
if (r.matches(base)) {
Logger.info("Moving file '%s' to '%s'. Rule id: %s",
file, r.dest, r.id);
boolean success = true;
String resolvedName = null;
int tries = 0;
while (tries < MAX_TRIES) {
try {
String suffix = null;
if (!success) {
suffix = " conflict"
+ (tries > 1 ? " " + tries : "");
}
resolvedName = insertIntoName(base, suffix);
String dest = r.dest
+ (r.dest.endsWith("/") ? "" : "/")
+ resolvedName;
client.move(file, dest);
break;
} catch (FileMoveCollisionException e) {
success = false;
}
tries++;
}
if (success) {
// If we moved the file to the correct destination
// on first try resolved name is same as original
// name so leave it as null.
resolvedName = null;
} else if (tries >= MAX_TRIES) {
// If we failed to move the file to any location
// leave this field
// as null to indicate complete failure.
resolvedName = null;
Logger.error("Cannot move file '%s' to '%s' after %d tries. Skipping.",
file, r.dest, MAX_TRIES);
}
fileMoves.add(new FileMove(user.id, base, r.dest,
success, resolvedName));
break;
}
}
}
Logger.info("Done running rules for %s. %d moves performed", user,
fileMoves.size());
if (!fileMoves.isEmpty()) {
user.incrementFileMoves(fileMoves.size());
FileMove.save(fileMoves);
}
return fileMoves;
} catch (InvalidTokenException e) {
Logger.error(e, "Disabling periodic sort, invalid OAuth token for user: %s", user);
user.periodicSort = false;
user.save();
}
return Collections.emptyList();
}
|
diff --git a/jsf/plugins/org.eclipse.jst.jsf.core/src/org/eclipse/jst/jsf/designtime/internal/jsp/JSPModelProcessor.java b/jsf/plugins/org.eclipse.jst.jsf.core/src/org/eclipse/jst/jsf/designtime/internal/jsp/JSPModelProcessor.java
index 45d3407c7..2dfdb9d58 100644
--- a/jsf/plugins/org.eclipse.jst.jsf.core/src/org/eclipse/jst/jsf/designtime/internal/jsp/JSPModelProcessor.java
+++ b/jsf/plugins/org.eclipse.jst.jsf.core/src/org/eclipse/jst/jsf/designtime/internal/jsp/JSPModelProcessor.java
@@ -1,679 +1,683 @@
/*******************************************************************************
* Copyright (c) 2006 Oracle Corporation.
* 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:
* Cameron Bateman/Oracle - initial API and implementation
*
********************************************************************************/
package org.eclipse.jst.jsf.designtime.internal.jsp;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.jst.jsf.common.JSFCommonPlugin;
import org.eclipse.jst.jsf.common.internal.resource.IResourceLifecycleListener;
import org.eclipse.jst.jsf.common.internal.resource.LifecycleListener;
import org.eclipse.jst.jsf.common.internal.resource.ResourceLifecycleEvent;
import org.eclipse.jst.jsf.common.internal.resource.ResourceLifecycleEvent.EventType;
import org.eclipse.jst.jsf.common.internal.resource.ResourceLifecycleEvent.ReasonType;
import org.eclipse.jst.jsf.common.metadata.Trait;
import org.eclipse.jst.jsf.common.metadata.internal.TraitValueHelper;
import org.eclipse.jst.jsf.common.metadata.query.ITaglibDomainMetaDataModelContext;
import org.eclipse.jst.jsf.common.metadata.query.TaglibDomainMetaDataQueryHelper;
import org.eclipse.jst.jsf.context.resolver.structureddocument.IStructuredDocumentContextResolverFactory;
import org.eclipse.jst.jsf.context.resolver.structureddocument.ITaglibContextResolver;
import org.eclipse.jst.jsf.context.structureddocument.IStructuredDocumentContext;
import org.eclipse.jst.jsf.context.structureddocument.IStructuredDocumentContextFactory;
import org.eclipse.jst.jsf.context.symbol.IComponentSymbol;
import org.eclipse.jst.jsf.context.symbol.ISymbol;
import org.eclipse.jst.jsf.context.symbol.SymbolFactory;
import org.eclipse.jst.jsf.context.symbol.source.AbstractContextSymbolFactory;
import org.eclipse.jst.jsf.context.symbol.source.ISymbolConstants;
import org.eclipse.jst.jsf.core.internal.JSFCorePlugin;
import org.eclipse.jst.jsf.designtime.DesignTimeApplicationManager;
import org.eclipse.jst.jsf.designtime.context.DTFacesContext;
import org.eclipse.jst.jsp.core.internal.domdocument.DOMModelForJSP;
import org.eclipse.wst.sse.core.StructuredModelManager;
import org.eclipse.wst.sse.core.internal.provisional.IModelManager;
import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
import org.eclipse.wst.xml.core.internal.provisional.document.IDOMDocument;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* Processes a JSP model to determine information of interest about it such
* as what tags are currently in use. Listens to the model and updates it's
* information when the model changes.
*
* @author cbateman
*
*/
public class JSPModelProcessor
{
private final static Map<IFile, JSPModelProcessor> RESOURCE_MAP =
new HashMap<IFile, JSPModelProcessor>();
private final static java.util.concurrent.locks.Lock CRITICAL_SECTION =
new ReentrantLock();
private static LifecycleListener LIFECYCLE_LISTENER;
/**
* @param file The file to get the model processor for
* @return the processor for a particular model, creating it if it does not
* already exist
* @throws CoreException if an attempt to get the model associated with file
* fails due to reasons other than I/O problems
*/
public static JSPModelProcessor get(IFile file) throws CoreException
{
CRITICAL_SECTION.lock();
try
{
if (!file.isAccessible())
{
throw new CoreException(new Status(IStatus.ERROR, JSFCorePlugin.PLUGIN_ID, "File must be accessible"));
}
JSPModelProcessor processor = RESOURCE_MAP.get(file);
if (processor == null)
{
if (LIFECYCLE_LISTENER == null)
{
LIFECYCLE_LISTENER = new LifecycleListener(file);
}
else
{
LIFECYCLE_LISTENER.addResource(file);
}
processor = new JSPModelProcessor(file,LIFECYCLE_LISTENER);
RESOURCE_MAP.put(file, processor);
}
return processor;
}
finally
{
CRITICAL_SECTION.unlock();
}
}
/**
* Disposes of the JSPModelProcessor associated with model
* @param file the model processor to be disposed
*/
private static void dispose(IFile file)
{
CRITICAL_SECTION.lock();
try
{
JSPModelProcessor processor = RESOURCE_MAP.get(file);
if (processor != null)
{
RESOURCE_MAP.remove(file);
if (!processor.isDisposed())
{
processor.dispose();
LIFECYCLE_LISTENER.removeResource(file);
}
}
if (RESOURCE_MAP.size() == 0)
{
// if we no longer have any resources being tracked,
// then dispose the lifecycle listener
LIFECYCLE_LISTENER.dispose();
LIFECYCLE_LISTENER = null;
}
}
finally
{
CRITICAL_SECTION.unlock();
}
}
private final IFile _file;
private LifecycleListener _lifecycleListener;
private IResourceLifecycleListener _resListener;
private boolean _isDisposed;
private Map<Object, ISymbol> _requestMap;
private Map<Object, ISymbol> _sessionMap;
private Map<Object, ISymbol> _applicationMap;
private Map<Object, ISymbol> _noneMap;
private long _lastModificationStamp;
// used to avoid infinite recursion in refresh. Must never be null
private final CountingMutex _lastModificationStampMonitor = new CountingMutex();
/**
* Construct a new JSPModelProcessor for model
*
* @param model
*/
private JSPModelProcessor(final IFile file, final LifecycleListener lifecycleListener)
{
//_model = getModelForFile(file);
//_modelListener = new ModelListener();
//_model.addModelLifecycleListener(_modelListener);
_file = file;
_lifecycleListener = lifecycleListener;
_resListener = new IResourceLifecycleListener()
{
public EventResult acceptEvent(ResourceLifecycleEvent event)
{
final EventResult result = EventResult.getDefaultEventResult();
// not interested
if (!_file.equals(event.getAffectedResource()))
{
return result;
}
if (event.getEventType() == EventType.RESOURCE_INACCESSIBLE)
{
dispose(_file);
}
else if (event.getEventType() == EventType.RESOURCE_CHANGED)
{
// if the file has changed contents on disk, then
// invoke an unforced refresh of the JSP file
if (event.getReasonType() == ReasonType.RESOURCE_CHANGED_CONTENTS)
{
refresh(false);
}
}
return result;
}
};
lifecycleListener.addListener(_resListener);
// a negative value guarantees that refresh(false) will
// force a refresh on the first run
_lastModificationStamp = -1;
}
private DOMModelForJSP getModelForFile(final IFile file)
throws CoreException, IOException
{
final IModelManager modelManager =
StructuredModelManager.getModelManager();
IStructuredModel model = modelManager.getModelForRead(file);
if (model instanceof DOMModelForJSP)
{
return (DOMModelForJSP) model;
}
else if (model != null)
{
// only release from read if we don't find a DOMModelForJSP
// if the model is correct, it will be released in dispose
model.releaseFromRead();
}
throw new CoreException
(new Status(IStatus.ERROR
, "org.eclipse.blah"
, 0 //$NON-NLS-1$
,"model not of expected type"
, new Throwable())); //$NON-NLS-1$
}
private void dispose()
{
if (!_isDisposed)
{
// ensure the resource listener is disposed
_lifecycleListener.removeListener(_resListener);
_resListener = null;
_lifecycleListener = null;
if (_requestMap != null)
{
_requestMap.clear();
_requestMap = null;
}
if (_sessionMap != null)
{
_sessionMap.clear();
_sessionMap = null;
}
if (_applicationMap != null)
{
_applicationMap.clear();
_applicationMap = null;
}
if (_noneMap != null)
{
_noneMap.clear();
_noneMap = null;
}
// mark as disposed
_isDisposed = true;
}
}
/**
* @return true if this model processor has been disposed. Disposed
* processors should not be used.
*/
public boolean isDisposed()
{
return _isDisposed;
}
/**
* If isModelDirty() returns true, then it means that a call
* to refresh(false) will trigger a reprocess of the underlying document.
*
* @return true if the underlying JSP model is considered to be dirty
*/
public boolean isModelDirty()
{
final long currentModificationStamp = _file.getModificationStamp();
return _lastModificationStamp != currentModificationStamp;
}
/**
* Updates the internal model
* @param forceRefresh -- if true, always refreshes, if false,
* then it only refreshes if the file's modification has changed
* since the last refresh
* @throws IllegalStateException if isDisposed() == true
*/
public void refresh(final boolean forceRefresh)
{
if (isDisposed())
{
throw new IllegalStateException("Processor is disposed for file: "+_file.toString());
}
synchronized(_lastModificationStampMonitor)
{
if (_lastModificationStampMonitor.isSignalled())
{
// if this calls succeeds, then this thread has obtained the
// lock already and has called through here before.
// return immediately to ensure that we don't recurse infinitely
return;
}
DOMModelForJSP model = null;
try
{
_lastModificationStampMonitor.setSignalled(true);
// only refresh if forced or if the underlying file has changed
// since the last run
if (forceRefresh
|| isModelDirty())
{
model = getModelForFile(_file);
refreshInternal(model);
_lastModificationStamp = _file.getModificationStamp();
}
}
catch (CoreException e) {
JSFCorePlugin.log(new RuntimeException(e), "Error refreshing internal model");
} catch (IOException e) {
JSFCorePlugin.log(new RuntimeException(e), "Error refreshing internal model");
}
// make sure that we unsignal the monitor before releasing the
// mutex
finally
{
+ if (model != null)
+ {
+ model.releaseFromRead();
+ }
_lastModificationStampMonitor.setSignalled(false);
}
}
}
private void refreshInternal(DOMModelForJSP model)
{
final IStructuredDocumentContext context =
IStructuredDocumentContextFactory.INSTANCE.getContext(model.getStructuredDocument(), -1);
final ITaglibContextResolver taglibResolver =
IStructuredDocumentContextResolverFactory.INSTANCE.getTaglibContextResolver(context);
IDOMDocument document = model.getDocument();
getApplicationMap().clear();
getRequestMap().clear();
getSessionMap().clear();
//long curTime = System.currentTimeMillis();
recurseChildNodes(model, document.getChildNodes(), taglibResolver);
//long netTime = System.currentTimeMillis() - curTime;
//System.out.println("Net time to recurse document: "+netTime);
}
private void recurseChildNodes(final DOMModelForJSP model,
final NodeList nodes,
final ITaglibContextResolver taglibResolver)
{
for (int i = 0; i < nodes.getLength(); i++)
{
final Node child = nodes.item(i);
// process attributes at this node before recursing
processAttributes(model, child, taglibResolver);
recurseChildNodes(model, child.getChildNodes(), taglibResolver);
}
}
private void processAttributes(final DOMModelForJSP model, final Node node,
final ITaglibContextResolver taglibResolver)
{
if (taglibResolver.hasTag(node))
{
final String uri =
taglibResolver.getTagURIForNodeName(node);
final String elementName = node.getLocalName();
for (int i = 0; i < node.getAttributes().getLength(); i++)
{
final Node attribute = node.getAttributes().item(i);
processSymbolContrib(model, uri, elementName, attribute);
processSetsLocale(uri, elementName, attribute);
}
}
}
private void processSymbolContrib(final DOMModelForJSP model, final String uri, final String elementName, Node attribute)
{
final SymbolContribAggregator aggregator =
SymbolContribAggregator.
create(_file.getProject(), uri, elementName, attribute.getLocalName());
if (aggregator != null)
{
final AbstractContextSymbolFactory factory = aggregator.getFactory();
final String symbolName = attribute.getNodeValue();
if (factory != null)
{
// long curTime = System.currentTimeMillis();
final List problems = new ArrayList();
ISymbol symbol =
factory.create(symbolName,
ISymbolConstants.SYMBOL_SCOPE_REQUEST, //TODO:
IStructuredDocumentContextFactory.INSTANCE.
getContext(model.getStructuredDocument(),
attribute),
problems);
// long netTime = System.currentTimeMillis() - curTime;
// System.out.println("Time to process loadBundle: "+netTime);
if (symbol != null)
{
updateMap(symbol, aggregator.getScope());
}
}
else
{
IComponentSymbol componentSymbol =
SymbolFactory.eINSTANCE.createIComponentSymbol();
componentSymbol.setName(symbolName);
updateMap(componentSymbol, aggregator.getScope());
}
}
}
private void processSetsLocale(final String uri, final String elementName, Node attribute)
{
LocaleSetAggregator aggregator = LocaleSetAggregator.create(_file.getProject(), uri, elementName, attribute.getLocalName());
if (aggregator != null)
{
DesignTimeApplicationManager dtAppMgr =
DesignTimeApplicationManager.getInstance(_file.getProject());
DTFacesContext facesContext = dtAppMgr.getFacesContext(_file);
if (facesContext != null)
{
facesContext.setLocaleString(attribute.getNodeValue());
}
}
}
/**
* @param scopeName - one of "request", "session" or "application"
* @return an unmodifable map containing all known symbols for
* that scope. If scopeName is not found, returns the empty map.
*/
public Map<Object, ISymbol> getMapForScope(String scopeName)
{
final Map<Object, ISymbol> map = getMapForScopeInternal(scopeName);
if (map != null)
{
return Collections.unmodifiableMap(map);
}
return Collections.EMPTY_MAP;
}
private void updateMap(ISymbol symbol, String scopeName)
{
final Map<Object, ISymbol> map = getMapForScopeInternal(scopeName);
if (map != null)
{
map.put(symbol.getName(), symbol);
}
else
{
Platform.getLog(JSFCorePlugin.getDefault().getBundle()).log(new Status(IStatus.ERROR, JSFCorePlugin.PLUGIN_ID, 0, "Scope not found: "+scopeName, new Throwable())); //$NON-NLS-1$
}
}
private Map<Object, ISymbol> getMapForScopeInternal(String scopeName)
{
if (ISymbolConstants.SYMBOL_SCOPE_REQUEST_STRING.equals(scopeName))
{
return getRequestMap();
}
else if (ISymbolConstants.SYMBOL_SCOPE_SESSION_STRING.equals(scopeName))
{
return getSessionMap();
}
else if (ISymbolConstants.SYMBOL_SCOPE_APPLICATION_STRING.equals(scopeName))
{
return getApplicationMap();
}
else if (ISymbolConstants.SYMBOL_SCOPE_NONE_STRING.equals(scopeName))
{
return getNoneMap();
}
Platform.getLog(JSFCorePlugin.getDefault().getBundle()).log(new Status(IStatus.ERROR, JSFCorePlugin.PLUGIN_ID, 0, "Scope not found: "+scopeName, new Throwable())); //$NON-NLS-1$
return null;
}
private Map getRequestMap()
{
if (_requestMap == null)
{
_requestMap = new HashMap<Object, ISymbol>();
}
return _requestMap;
}
private Map<Object, ISymbol> getSessionMap()
{
if (_sessionMap == null)
{
_sessionMap = new HashMap<Object, ISymbol>();
}
return _sessionMap;
}
private Map<Object, ISymbol> getApplicationMap()
{
if (_applicationMap == null)
{
_applicationMap = new HashMap<Object, ISymbol>();
}
return _applicationMap;
}
private Map<Object, ISymbol> getNoneMap()
{
if (_noneMap == null)
{
_noneMap = new HashMap<Object, ISymbol>();
}
return _noneMap;
}
/**
* Aggregates the sets-locale meta-data
*
* @author cbateman
*/
private static class LocaleSetAggregator
{
private final static String SETS_LOCALE = "sets-locale"; //$NON-NLS-1$
static LocaleSetAggregator create(IProject project,
final String uri,
final String elementName, final String attributeName)
{
final ITaglibDomainMetaDataModelContext mdContext = TaglibDomainMetaDataQueryHelper.createMetaDataModelContext(project, uri);
Trait trait = TaglibDomainMetaDataQueryHelper.getTrait(mdContext, elementName+"/"+attributeName, SETS_LOCALE); //$NON-NLS-1$
if (TraitValueHelper.getValueAsBoolean(trait))
{
return new LocaleSetAggregator();
}
return null;
}
}
/**
* Aggregates all the symbol contributor meta-data into a single object
*
* @author cbateman
*
*/
private static class SymbolContribAggregator
{
private final static String CONTRIBUTES_VALUE_BINDING =
"contributes-value-binding"; //$NON-NLS-1$
private final static String VALUE_BINDING_SCOPE = "value-binding-scope"; //$NON-NLS-1$
private final static String VALUE_BINDING_SYMBOL_FACTORY =
"value-binding-symbol-factory"; //$NON-NLS-1$
/**
* @param attributeName
* @return a new instance only if attributeName is a symbol contributor
*/
static SymbolContribAggregator create(final IProject project,
final String uri,
final String elementName,
final String attributeName)
{
final String entityKey = elementName+"/"+attributeName; //$NON-NLS-1$
final ITaglibDomainMetaDataModelContext mdContext = TaglibDomainMetaDataQueryHelper.createMetaDataModelContext(project, uri);
Trait trait = TaglibDomainMetaDataQueryHelper.getTrait(mdContext, entityKey, CONTRIBUTES_VALUE_BINDING);
boolean contribsValueBindings = TraitValueHelper.getValueAsBoolean(trait);
if (contribsValueBindings)
{
String scope = null;
String symbolFactory = null;
trait = TaglibDomainMetaDataQueryHelper.getTrait(mdContext, entityKey, VALUE_BINDING_SCOPE);
scope = TraitValueHelper.getValueAsString(trait);
if (scope != null && !scope.equals("")) //$NON-NLS-1$
{
trait = TaglibDomainMetaDataQueryHelper.getTrait(mdContext, entityKey, VALUE_BINDING_SYMBOL_FACTORY);
symbolFactory = TraitValueHelper.getValueAsString(trait);
}
return new SymbolContribAggregator(scope, symbolFactory);
}
return null;
}
private final Map _metadata = new HashMap(4);
SymbolContribAggregator(final String scope, final String factory)
{
_metadata.put("scope", scope); //$NON-NLS-1$
_metadata.put("factory", factory); //$NON-NLS-1$
}
/**
* @return the scope
*/
public String getScope()
{
return (String) _metadata.get("scope"); //$NON-NLS-1$
}
/**
* @return the factory
*/
public AbstractContextSymbolFactory getFactory()
{
return JSFCommonPlugin.getSymbolFactories().get(_metadata.get("factory")); //$NON-NLS-1$
}
}
private static class CountingMutex extends Object
{
private boolean _signalled = false;
/**
* @return true if the state of mutex is signalled
*/
public synchronized boolean isSignalled() {
return _signalled;
}
/**
* @param signalled
*/
public synchronized void setSignalled(boolean signalled) {
this._signalled = signalled;
}
}
}
| true | true | public void refresh(final boolean forceRefresh)
{
if (isDisposed())
{
throw new IllegalStateException("Processor is disposed for file: "+_file.toString());
}
synchronized(_lastModificationStampMonitor)
{
if (_lastModificationStampMonitor.isSignalled())
{
// if this calls succeeds, then this thread has obtained the
// lock already and has called through here before.
// return immediately to ensure that we don't recurse infinitely
return;
}
DOMModelForJSP model = null;
try
{
_lastModificationStampMonitor.setSignalled(true);
// only refresh if forced or if the underlying file has changed
// since the last run
if (forceRefresh
|| isModelDirty())
{
model = getModelForFile(_file);
refreshInternal(model);
_lastModificationStamp = _file.getModificationStamp();
}
}
catch (CoreException e) {
JSFCorePlugin.log(new RuntimeException(e), "Error refreshing internal model");
} catch (IOException e) {
JSFCorePlugin.log(new RuntimeException(e), "Error refreshing internal model");
}
// make sure that we unsignal the monitor before releasing the
// mutex
finally
{
_lastModificationStampMonitor.setSignalled(false);
}
}
}
| public void refresh(final boolean forceRefresh)
{
if (isDisposed())
{
throw new IllegalStateException("Processor is disposed for file: "+_file.toString());
}
synchronized(_lastModificationStampMonitor)
{
if (_lastModificationStampMonitor.isSignalled())
{
// if this calls succeeds, then this thread has obtained the
// lock already and has called through here before.
// return immediately to ensure that we don't recurse infinitely
return;
}
DOMModelForJSP model = null;
try
{
_lastModificationStampMonitor.setSignalled(true);
// only refresh if forced or if the underlying file has changed
// since the last run
if (forceRefresh
|| isModelDirty())
{
model = getModelForFile(_file);
refreshInternal(model);
_lastModificationStamp = _file.getModificationStamp();
}
}
catch (CoreException e) {
JSFCorePlugin.log(new RuntimeException(e), "Error refreshing internal model");
} catch (IOException e) {
JSFCorePlugin.log(new RuntimeException(e), "Error refreshing internal model");
}
// make sure that we unsignal the monitor before releasing the
// mutex
finally
{
if (model != null)
{
model.releaseFromRead();
}
_lastModificationStampMonitor.setSignalled(false);
}
}
}
|
diff --git a/manticore/bundles/net.i2cat.mantychore.actionsets.junos/src/main/java/net/i2cat/mantychore/actionsets/junos/OSPFActionSet.java b/manticore/bundles/net.i2cat.mantychore.actionsets.junos/src/main/java/net/i2cat/mantychore/actionsets/junos/OSPFActionSet.java
index afa1f167c..4acf9e758 100644
--- a/manticore/bundles/net.i2cat.mantychore.actionsets.junos/src/main/java/net/i2cat/mantychore/actionsets/junos/OSPFActionSet.java
+++ b/manticore/bundles/net.i2cat.mantychore.actionsets.junos/src/main/java/net/i2cat/mantychore/actionsets/junos/OSPFActionSet.java
@@ -1,27 +1,27 @@
package net.i2cat.mantychore.actionsets.junos;
import net.i2cat.mantychore.actionsets.junos.actions.ospf.ActivateOSPFAction;
import net.i2cat.mantychore.actionsets.junos.actions.ospf.ConfigureOSPFAction;
import net.i2cat.mantychore.actionsets.junos.actions.ospf.DeactivateOSPFAction;
import net.i2cat.mantychore.actionsets.junos.actions.ospf.DisableOSPFInInterfaceAction;
import net.i2cat.mantychore.actionsets.junos.actions.ospf.EnableOSPFInInterfaceAction;
import net.i2cat.mantychore.actionsets.junos.actions.ospf.GetOSPFConfigAction;
import org.opennaas.core.resources.action.ActionSet;
public class OSPFActionSet extends ActionSet {
public OSPFActionSet() {
super.setActionSetId("OSPFActionSet");
- this.putAction(ActionConstants.OSPF_GET_CONFIGURATION, ConfigureOSPFAction.class);
- this.putAction(ActionConstants.OSPF_CONFIGURE, GetOSPFConfigAction.class);
+ this.putAction(ActionConstants.OSPF_GET_CONFIGURATION, GetOSPFConfigAction.class);
+ this.putAction(ActionConstants.OSPF_CONFIGURE, ConfigureOSPFAction.class);
this.putAction(ActionConstants.OSPF_ACTIVATE, ActivateOSPFAction.class);
this.putAction(ActionConstants.OSPF_DEACTIVATE, DeactivateOSPFAction.class);
this.putAction(ActionConstants.OSPF_ENABLE_INTERFACE, EnableOSPFInInterfaceAction.class);
this.putAction(ActionConstants.OSPF_DISABLE_INTERFACE, DisableOSPFInInterfaceAction.class);
/* add refresh actions */
this.refreshActions.add(ActionConstants.OSPF_GET_CONFIGURATION);
}
}
| true | true | public OSPFActionSet() {
super.setActionSetId("OSPFActionSet");
this.putAction(ActionConstants.OSPF_GET_CONFIGURATION, ConfigureOSPFAction.class);
this.putAction(ActionConstants.OSPF_CONFIGURE, GetOSPFConfigAction.class);
this.putAction(ActionConstants.OSPF_ACTIVATE, ActivateOSPFAction.class);
this.putAction(ActionConstants.OSPF_DEACTIVATE, DeactivateOSPFAction.class);
this.putAction(ActionConstants.OSPF_ENABLE_INTERFACE, EnableOSPFInInterfaceAction.class);
this.putAction(ActionConstants.OSPF_DISABLE_INTERFACE, DisableOSPFInInterfaceAction.class);
/* add refresh actions */
this.refreshActions.add(ActionConstants.OSPF_GET_CONFIGURATION);
}
| public OSPFActionSet() {
super.setActionSetId("OSPFActionSet");
this.putAction(ActionConstants.OSPF_GET_CONFIGURATION, GetOSPFConfigAction.class);
this.putAction(ActionConstants.OSPF_CONFIGURE, ConfigureOSPFAction.class);
this.putAction(ActionConstants.OSPF_ACTIVATE, ActivateOSPFAction.class);
this.putAction(ActionConstants.OSPF_DEACTIVATE, DeactivateOSPFAction.class);
this.putAction(ActionConstants.OSPF_ENABLE_INTERFACE, EnableOSPFInInterfaceAction.class);
this.putAction(ActionConstants.OSPF_DISABLE_INTERFACE, DisableOSPFInInterfaceAction.class);
/* add refresh actions */
this.refreshActions.add(ActionConstants.OSPF_GET_CONFIGURATION);
}
|
diff --git a/QuizWebsite/src/servlets/CurrentUserProfileServlet.java b/QuizWebsite/src/servlets/CurrentUserProfileServlet.java
index 94dfab3..8a35ddb 100644
--- a/QuizWebsite/src/servlets/CurrentUserProfileServlet.java
+++ b/QuizWebsite/src/servlets/CurrentUserProfileServlet.java
@@ -1,150 +1,150 @@
package servlets;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import quiz.*;
import user.*;
import database.DataBaseObject;
/**
* Servlet implementation class CurrentUserProfileServlet
*/
@WebServlet("/CurrentUserProfileServlet")
public class CurrentUserProfileServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public CurrentUserProfileServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
private void getMessages(HttpServletRequest request, Connection conn, User user) {
try {
Statement stmt = conn.createStatement();
String query = "SELECT * FROM Message WHERE recipient='" + user.getName() + "' AND beenRead=" + false + ";";
ResultSet rs = stmt.executeQuery(query);
if (rs == null) {
request.setAttribute("unreadMsg", 0);
} else {
int num = 0;
if (rs.last()) {
num = rs.getRow();
}
request.setAttribute("unreadMsg", num);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
private void getFriendActivity(HttpServletRequest request, Connection conn, User user) {
List<Activity> activities = new ArrayList<Activity>();
try {
Statement stmt = conn.createStatement();
String query = "SELECT * FROM Message inner join Friend_Request on Message.id=Friend_Request.id WHERE sender='" + user.getName() +
"' OR recipient='" + user.getName() + "' AND isAccepted=true;";
ResultSet rs = stmt.executeQuery(query);
if (rs != null) {
int count = 0;
while (rs.next() && count < QuizConstants.N_TOP_RATED) {
String username = rs.getString("sender").equals(user.getName()) ? rs.getString("recipient") : rs.getString("sender");
User friend = getFriend(conn, username);
if (friend != null) {
int infoCounter = 0;
Statement quizStmt = conn.createStatement();
String quizResults = "SELECT * from Quiz_Result WHERE username='" + friend.getName() + "' order by id DESC;";
ResultSet results = quizStmt.executeQuery(quizResults);
while (results.next() && infoCounter < QuizConstants.N_TOP_RATED) {
- activities.add(new Activity(friend, friend.getName() + "recently took a quiz.", results.getInt("quiz_id")));
+ activities.add(new Activity(friend, friend.getName() + " recently took a quiz.", results.getInt("quiz_id")));
infoCounter++;
}
infoCounter = 0;
String authored = "SELECT * FROM Quiz WHERE author='" + friend.getName() + "' order by id DESC;";
results = quizStmt.executeQuery(authored);
while (results.next() && infoCounter < QuizConstants.N_TOP_RATED) {
String[] attrs = DataBaseObject.getRow(results, QuizConstants.QUIZ_N_COLS);
Quiz quiz = new Quiz(attrs, conn);
String msg = friend.getName() + " recently authored " + quiz.getName();
Activity act = new Activity(friend, msg, quiz.getID());
activities.add(act);
infoCounter++;
}
}
count++;
}
}
request.setAttribute("activities", activities);
} catch (SQLException e) {
e.printStackTrace();
}
}
private User getFriend(Connection conn, String username) {
Statement stmt;
try {
stmt = conn.createStatement();
String query = "SELECT * FROM User WHERE username='" + username + "';";
ResultSet rs = stmt.executeQuery(query);
if (rs.next()) {
return new User(DataBaseObject.getRow(rs, QuizConstants.USER_N_COLUMNS), conn);
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection conn = (Connection) getServletContext().getAttribute("database");
RequestDispatcher dispatch;
User user = (User) request.getSession().getAttribute("user");
HomePageQueries.getUserRecentQuizzes(request, conn, user, QuizConstants.N_TOP_RATED);
getMessages(request, conn, user);
HomePageQueries.getPopQuizzes(request, conn);
HomePageQueries.getRecentQuizzes(request, conn);
HomePageQueries.getAuthoring(request, conn, user);
HomePageQueries.getAnnouncements(request);
getFriendActivity(request, conn, user);
HomePageQueries.getAchievements(request, conn, user);
dispatch = request.getRequestDispatcher("user_home.jsp");
dispatch.forward(request, response);
}
}
| true | true | private void getFriendActivity(HttpServletRequest request, Connection conn, User user) {
List<Activity> activities = new ArrayList<Activity>();
try {
Statement stmt = conn.createStatement();
String query = "SELECT * FROM Message inner join Friend_Request on Message.id=Friend_Request.id WHERE sender='" + user.getName() +
"' OR recipient='" + user.getName() + "' AND isAccepted=true;";
ResultSet rs = stmt.executeQuery(query);
if (rs != null) {
int count = 0;
while (rs.next() && count < QuizConstants.N_TOP_RATED) {
String username = rs.getString("sender").equals(user.getName()) ? rs.getString("recipient") : rs.getString("sender");
User friend = getFriend(conn, username);
if (friend != null) {
int infoCounter = 0;
Statement quizStmt = conn.createStatement();
String quizResults = "SELECT * from Quiz_Result WHERE username='" + friend.getName() + "' order by id DESC;";
ResultSet results = quizStmt.executeQuery(quizResults);
while (results.next() && infoCounter < QuizConstants.N_TOP_RATED) {
activities.add(new Activity(friend, friend.getName() + "recently took a quiz.", results.getInt("quiz_id")));
infoCounter++;
}
infoCounter = 0;
String authored = "SELECT * FROM Quiz WHERE author='" + friend.getName() + "' order by id DESC;";
results = quizStmt.executeQuery(authored);
while (results.next() && infoCounter < QuizConstants.N_TOP_RATED) {
String[] attrs = DataBaseObject.getRow(results, QuizConstants.QUIZ_N_COLS);
Quiz quiz = new Quiz(attrs, conn);
String msg = friend.getName() + " recently authored " + quiz.getName();
Activity act = new Activity(friend, msg, quiz.getID());
activities.add(act);
infoCounter++;
}
}
count++;
}
}
request.setAttribute("activities", activities);
} catch (SQLException e) {
e.printStackTrace();
}
}
| private void getFriendActivity(HttpServletRequest request, Connection conn, User user) {
List<Activity> activities = new ArrayList<Activity>();
try {
Statement stmt = conn.createStatement();
String query = "SELECT * FROM Message inner join Friend_Request on Message.id=Friend_Request.id WHERE sender='" + user.getName() +
"' OR recipient='" + user.getName() + "' AND isAccepted=true;";
ResultSet rs = stmt.executeQuery(query);
if (rs != null) {
int count = 0;
while (rs.next() && count < QuizConstants.N_TOP_RATED) {
String username = rs.getString("sender").equals(user.getName()) ? rs.getString("recipient") : rs.getString("sender");
User friend = getFriend(conn, username);
if (friend != null) {
int infoCounter = 0;
Statement quizStmt = conn.createStatement();
String quizResults = "SELECT * from Quiz_Result WHERE username='" + friend.getName() + "' order by id DESC;";
ResultSet results = quizStmt.executeQuery(quizResults);
while (results.next() && infoCounter < QuizConstants.N_TOP_RATED) {
activities.add(new Activity(friend, friend.getName() + " recently took a quiz.", results.getInt("quiz_id")));
infoCounter++;
}
infoCounter = 0;
String authored = "SELECT * FROM Quiz WHERE author='" + friend.getName() + "' order by id DESC;";
results = quizStmt.executeQuery(authored);
while (results.next() && infoCounter < QuizConstants.N_TOP_RATED) {
String[] attrs = DataBaseObject.getRow(results, QuizConstants.QUIZ_N_COLS);
Quiz quiz = new Quiz(attrs, conn);
String msg = friend.getName() + " recently authored " + quiz.getName();
Activity act = new Activity(friend, msg, quiz.getID());
activities.add(act);
infoCounter++;
}
}
count++;
}
}
request.setAttribute("activities", activities);
} catch (SQLException e) {
e.printStackTrace();
}
}
|
diff --git a/core/src/main/java/hudson/model/Job.java b/core/src/main/java/hudson/model/Job.java
index 8cd854f45..648666ab9 100644
--- a/core/src/main/java/hudson/model/Job.java
+++ b/core/src/main/java/hudson/model/Job.java
@@ -1,661 +1,663 @@
package hudson.model;
import hudson.ExtensionPoint;
import hudson.Util;
import hudson.model.Descriptor.FormException;
import hudson.tasks.BuildTrigger;
import hudson.tasks.LogRotator;
import hudson.util.ChartUtil;
import hudson.util.ColorPalette;
import hudson.util.CopyOnWriteList;
import hudson.util.DataSetBuilder;
import hudson.util.IOException2;
import hudson.util.RunList;
import hudson.util.ShiftedCategoryAxis;
import hudson.util.StackedAreaRenderer2;
import hudson.util.TextFile;
import org.apache.tools.ant.taskdefs.Copy;
import org.apache.tools.ant.types.FileSet;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.StackedAreaRenderer;
import org.jfree.data.category.CategoryDataset;
import org.jfree.ui.RectangleInsets;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import java.awt.Color;
import java.awt.Paint;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
/**
* A job is an runnable entity under the monitoring of Hudson.
*
* <p>
* Every time it "runs", it will be recorded as a {@link Run} object.
*
* @author Kohsuke Kawaguchi
*/
public abstract class Job<JobT extends Job<JobT,RunT>, RunT extends Run<JobT,RunT>>
extends AbstractItem implements ExtensionPoint {
/**
* Next build number.
* Kept in a separate file because this is the only information
* that gets updated often. This allows the rest of the configuration
* to be in the VCS.
* <p>
* In 1.28 and earlier, this field was stored in the project configuration file,
* so even though this is marked as transient, don't move it around.
*/
protected transient int nextBuildNumber = 1;
private LogRotator logRotator;
private boolean keepDependencies;
/**
* List of {@link UserProperty}s configured for this project.
*/
private CopyOnWriteList<JobProperty<? super JobT>> properties = new CopyOnWriteList<JobProperty<? super JobT>>();
protected Job(ItemGroup parent,String name) {
super(parent,name);
getBuildDir().mkdirs();
}
public void onLoad(ItemGroup<? extends Item> parent, String name) throws IOException {
super.onLoad(parent, name);
TextFile f = getNextBuildNumberFile();
if(f.exists()) {
// starting 1.28, we store nextBuildNumber in a separate file.
// but old Hudson didn't do it, so if the file doesn't exist,
// assume that nextBuildNumber was read from config.xml
try {
this.nextBuildNumber = Integer.parseInt(f.readTrim());
} catch (NumberFormatException e) {
throw new IOException2(f+" doesn't contain a number",e);
}
} else {
// this must be the old Hudson. create this file now.
saveNextBuildNumber();
save(); // and delete it from the config.xml
}
if(properties==null) // didn't exist < 1.72
properties = new CopyOnWriteList<JobProperty<? super JobT>>();
}
@Override
public void onCopiedFrom(Item src) {
super.onCopiedFrom(src);
this.nextBuildNumber = 1; // reset the next build number
}
private TextFile getNextBuildNumberFile() {
return new TextFile(new File(this.getRootDir(),"nextBuildNumber"));
}
protected void saveNextBuildNumber() throws IOException {
getNextBuildNumberFile().write(String.valueOf(nextBuildNumber)+'\n');
}
public boolean isInQueue() {
return false;
}
/**
* If true, it will keep all the build logs of dependency components.
*/
public boolean isKeepDependencies() {
return keepDependencies;
}
/**
* Allocates a new buildCommand number.
*/
public synchronized int assignBuildNumber() throws IOException {
int r = nextBuildNumber++;
saveNextBuildNumber();
return r;
}
/**
* Peeks the next build number.
*/
public int getNextBuildNumber() {
return nextBuildNumber;
}
/**
* Returns the log rotator for this job, or null if none.
*/
public LogRotator getLogRotator() {
return logRotator;
}
public void setLogRotator(LogRotator logRotator) {
this.logRotator = logRotator;
}
public Collection<? extends Job> getAllJobs() {
return Collections.<Job>singleton(this);
}
/**
* Gets all the job properties configured for this job.
*/
@SuppressWarnings("unchecked")
public Map<JobPropertyDescriptor,JobProperty<? super JobT>> getProperties() {
return Descriptor.toMap((Iterable)properties);
}
/**
* Gets the specific property, or null if the propert is not configured for this job.
*/
public <T extends JobProperty> T getProperty(Class<T> clazz) {
for (JobProperty p : properties) {
if(clazz.isInstance(p))
return clazz.cast(p);
}
return null;
}
/**
* Renames a job.
*
* <p>
* This method is defined on {@link Job} but really only applicable
* for {@link Job}s that are top-level items.
*/
public void renameTo(String newName) throws IOException {
// always synchronize from bigger objects first
final Hudson parent = Hudson.getInstance();
assert this instanceof TopLevelItem;
synchronized(parent) {
synchronized(this) {
// sanity check
if(newName==null)
throw new IllegalArgumentException("New name is not given");
if(parent.getItem(newName)!=null)
throw new IllegalArgumentException("Job "+newName+" already exists");
// noop?
if(this.name.equals(newName))
return;
String oldName = this.name;
File oldRoot = this.getRootDir();
doSetName(newName);
File newRoot = this.getRootDir();
{// rename data files
boolean interrupted=false;
boolean renamed = false;
// try to rename the job directory.
// this may fail on Windows due to some other processes accessing a file.
// so retry few times before we fall back to copy.
for( int retry=0; retry<5; retry++ ) {
if(oldRoot.renameTo(newRoot)) {
renamed = true;
break; // succeeded
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// process the interruption later
interrupted = true;
}
}
if(interrupted)
Thread.currentThread().interrupt();
if(!renamed) {
// failed to rename. it must be that some lengthy process is going on
// to prevent a rename operation. So do a copy. Ideally we'd like to
// later delete the old copy, but we can't reliably do so, as before the VM
// shuts down there might be a new job created under the old name.
Copy cp = new Copy();
cp.setProject(new org.apache.tools.ant.Project());
cp.setTodir(newRoot);
FileSet src = new FileSet();
src.setDir(getRootDir());
cp.addFileset(src);
cp.setOverwrite(true);
cp.setPreserveLastModified(true);
cp.setFailOnError(false); // keep going even if there's an error
cp.execute();
// try to delete as much as possible
try {
Util.deleteRecursive(oldRoot);
} catch (IOException e) {
// but ignore the error, since we expect that
e.printStackTrace();
}
}
}
parent.onRenamed((TopLevelItem)this,oldName,newName);
// update BuildTrigger of other projects that point to this object.
// can't we generalize this?
for( Project p : parent.getProjects() ) {
BuildTrigger t = (BuildTrigger) p.getPublishers().get(BuildTrigger.DESCRIPTOR);
if(t!=null) {
if(t.onJobRenamed(oldName,newName))
p.save();
}
}
}
}
}
/**
* Returns true if we should display "build now" icon
*/
public abstract boolean isBuildable();
/**
* Gets all the builds.
*
* @return
* never null. The first entry is the latest buildCommand.
*/
public List<RunT> getBuilds() {
return new ArrayList<RunT>(_getRuns().values());
}
/**
* Gets all the builds in a map.
*/
public SortedMap<Integer,RunT> getBuildsAsMap() {
return Collections.unmodifiableSortedMap(_getRuns());
}
/**
* @deprecated
* This is only used to support backward compatibility with
* old URLs.
*/
@Deprecated
public RunT getBuild(String id) {
for (RunT r : _getRuns().values()) {
if(r.getId().equals(id))
return r;
}
return null;
}
/**
* @param n
* The build number.
* @see Run#getNumber()
*/
public RunT getBuildByNumber(int n) {
return _getRuns().get(n);
}
/**
* Gets the youngest build #m that satisfies <tt>n<=m</tt>.
*
* This is useful when you'd like to fetch a build but the exact build might be already
* gone (deleted, rotated, etc.)
*/
public RunT getNearestBuild(int n) {
SortedMap<Integer, ? extends RunT> m = _getRuns().headMap(n);
if(m.isEmpty()) return null;
return m.get(m.lastKey());
}
public Object getDynamic(String token, StaplerRequest req, StaplerResponse rsp) {
try {
// try to interpret the token as build number
return _getRuns().get(Integer.valueOf(token));
} catch (NumberFormatException e) {
return super.getDynamic(token,req,rsp);
}
}
/**
* Directory for storing {@link Run} records.
* <p>
* Some {@link Job}s may not have backing data store for {@link Run}s,
* but those {@link Job}s that use file system for storing data
* should use this directory for consistency.
*
* @see RunMap
*/
protected File getBuildDir() {
return new File(getRootDir(),"builds");
}
/**
* Gets all the runs.
*
* The resulting map must be immutable (by employing copy-on-write semantics.)
*/
protected abstract SortedMap<Integer,? extends RunT> _getRuns();
/**
* Called from {@link Run} to remove it from this job.
*
* The files are deleted already. So all the callee needs to do
* is to remove a reference from this {@link Job}.
*/
protected abstract void removeRun(RunT run);
/**
* Returns the last build.
*/
public RunT getLastBuild() {
SortedMap<Integer,? extends RunT> runs = _getRuns();
if(runs.isEmpty()) return null;
return runs.get(runs.firstKey());
}
/**
* Returns the oldest build in the record.
*/
public RunT getFirstBuild() {
SortedMap<Integer,? extends RunT> runs = _getRuns();
if(runs.isEmpty()) return null;
return runs.get(runs.lastKey());
}
/**
* Returns the last successful build, if any. Otherwise null.
* A stable build would include either {@link Result#SUCCESS} or {@link Result#UNSTABLE}.
* @see #getLastStableBuild()
*/
public RunT getLastSuccessfulBuild() {
RunT r = getLastBuild();
// temporary hack till we figure out what's causing this bug
while(r!=null && (r.isBuilding() || r.getResult()==null || r.getResult().isWorseThan(Result.UNSTABLE)))
r=r.getPreviousBuild();
return r;
}
/**
* Returns the last stable build, if any. Otherwise null.
*/
public RunT getLastStableBuild() {
RunT r = getLastBuild();
while(r!=null && (r.isBuilding() || r.getResult().isWorseThan(Result.SUCCESS)))
r=r.getPreviousBuild();
return r;
}
/**
* Returns the last failed build, if any. Otherwise null.
*/
public RunT getLastFailedBuild() {
RunT r = getLastBuild();
while(r!=null && (r.isBuilding() || r.getResult()!=Result.FAILURE))
r=r.getPreviousBuild();
return r;
}
/**
* Used as the color of the status ball for the project.
*/
public BallColor getIconColor() {
RunT lastBuild = getLastBuild();
while(lastBuild!=null && lastBuild.hasntStartedYet())
lastBuild = lastBuild.getPreviousBuild();
if(lastBuild!=null)
return lastBuild.getIconColor();
else
return BallColor.GREY;
}
//
//
// actions
//
//
/**
* Accepts submission from the configuration page.
*/
public synchronized void doConfigSubmit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
if (!Hudson.adminCheck(req, rsp))
return;
req.setCharacterEncoding("UTF-8");
description = req.getParameter("description");
if (req.getParameter("logrotate") != null)
logRotator = LogRotator.DESCRIPTOR.newInstance(req);
else
logRotator = null;
keepDependencies = req.getParameter("keepDependencies") != null;
try {
properties.clear();
for (JobPropertyDescriptor d : JobPropertyDescriptor.getPropertyDescriptors(getClass())) {
JobProperty prop = d.newInstance(req);
if (prop != null)
properties.add(prop);
}
submit(req,rsp);
save();
String newName = req.getParameter("name");
if(newName!=null && !newName.equals(name)) {
rsp.sendRedirect("rename?newName="+newName);
} else {
rsp.sendRedirect(".");
}
} catch (FormException e) {
sendError(e,req,rsp);
}
}
/**
* Derived class can override this to perform additional config submission work.
*/
protected void submit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException {
}
/**
* Returns the image that shows the current buildCommand status.
*/
public void doBuildStatus( StaplerRequest req, StaplerResponse rsp ) throws IOException {
rsp.sendRedirect2(req.getContextPath()+"/nocacheImages/48x48/"+getBuildStatusUrl());
}
public String getBuildStatusUrl() {
return getIconColor()+".gif";
}
/**
* Returns the graph that shows how long each build took.
*/
public void doBuildTimeGraph( StaplerRequest req, StaplerResponse rsp ) throws IOException {
if(getLastBuild()==null) {
rsp.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
if(req.checkIfModified(getLastBuild().getTimestamp(),rsp))
return;
ChartUtil.generateGraph(req,rsp, createBuildTimeTrendChart(),500,400);
}
/**
* Returns the clickable map for the build time graph.
* Loaded lazily by AJAX.
*/
public void doBuildTimeGraphMap( StaplerRequest req, StaplerResponse rsp ) throws IOException {
if(getLastBuild()==null) {
rsp.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
if(req.checkIfModified(getLastBuild().getTimestamp(),rsp))
return;
ChartUtil.generateClickableMap(req,rsp, createBuildTimeTrendChart(),500,400);
}
private JFreeChart createBuildTimeTrendChart() {
class Label implements Comparable<Label> {
final Run run;
public Label(Run r) {
this.run = r;
}
public int compareTo(Label that) {
return this.run.number-that.run.number;
}
public boolean equals(Object o) {
Label that = (Label) o;
return run ==that.run;
}
public Color getColor() {
// TODO: consider gradation. See http://www.javadrive.jp/java2d/shape/index9.html
Result r = run.getResult();
if(r ==Result.FAILURE || r== Result.ABORTED)
return ColorPalette.RED;
else
return ColorPalette.BLUE;
}
public int hashCode() {
return run.hashCode();
}
public String toString() {
String l = run.getDisplayName();
if(run instanceof Build) {
String s = ((Build)run).getBuiltOnStr();
if(s!=null)
l += ' '+s;
}
return l;
}
}
DataSetBuilder<String,Label> data = new DataSetBuilder<String, Label>();
- for( Run r : getBuilds() )
+ for( Run r : getBuilds() ) {
+ if(r.isBuilding()) continue;
data.add( ((double)r.getDuration())/(1000*60), "mins", new Label(r));
+ }
final CategoryDataset dataset = data.build();
final JFreeChart chart = ChartFactory.createStackedAreaChart(
null, // chart title
null, // unused
"min", // range axis label
dataset, // data
PlotOrientation.VERTICAL, // orientation
false, // include legend
true, // tooltips
false // urls
);
chart.setBackgroundPaint(Color.white);
final CategoryPlot plot = chart.getCategoryPlot();
// plot.setAxisOffset(new Spacer(Spacer.ABSOLUTE, 5.0, 5.0, 5.0, 5.0));
plot.setBackgroundPaint(Color.WHITE);
plot.setOutlinePaint(null);
plot.setForegroundAlpha(0.8f);
// plot.setDomainGridlinesVisible(true);
// plot.setDomainGridlinePaint(Color.white);
plot.setRangeGridlinesVisible(true);
plot.setRangeGridlinePaint(Color.black);
CategoryAxis domainAxis = new ShiftedCategoryAxis(null);
plot.setDomainAxis(domainAxis);
domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_90);
domainAxis.setLowerMargin(0.0);
domainAxis.setUpperMargin(0.0);
domainAxis.setCategoryMargin(0.0);
final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
StackedAreaRenderer ar = new StackedAreaRenderer2() {
@Override
public Paint getItemPaint(int row, int column) {
Label key = (Label) dataset.getColumnKey(column);
return key.getColor();
}
@Override
public String generateURL(CategoryDataset dataset, int row, int column) {
Label label = (Label) dataset.getColumnKey(column);
return String.valueOf(label.run.number);
}
@Override
public String generateToolTip(CategoryDataset dataset, int row, int column) {
Label label = (Label) dataset.getColumnKey(column);
return label.run.getDisplayName() + " : " + label.run.getDurationString();
}
};
plot.setRenderer(ar);
// crop extra space around the graph
plot.setInsets(new RectangleInsets(0,0,0,5.0));
return chart;
}
/**
* Renames this job.
*/
public /*not synchronized. see renameTo()*/ void doDoRename( StaplerRequest req, StaplerResponse rsp ) throws IOException {
if(!Hudson.adminCheck(req,rsp))
return;
String newName = req.getParameter("newName");
renameTo(newName);
rsp.sendRedirect2(req.getContextPath()+'/'+getUrl()); // send to the new job page
}
public void doRssAll( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
rss(req, rsp, " all builds", new RunList(this));
}
public void doRssFailed( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
rss(req, rsp, " failed builds", new RunList(this).failureOnly());
}
private void rss(StaplerRequest req, StaplerResponse rsp, String suffix, RunList runs) throws IOException, ServletException {
RSS.forwardToRss(getDisplayName()+ suffix, getUrl(),
runs.newBuilds(), Run.FEED_ADAPTER, req, rsp );
}
}
| false | true | private JFreeChart createBuildTimeTrendChart() {
class Label implements Comparable<Label> {
final Run run;
public Label(Run r) {
this.run = r;
}
public int compareTo(Label that) {
return this.run.number-that.run.number;
}
public boolean equals(Object o) {
Label that = (Label) o;
return run ==that.run;
}
public Color getColor() {
// TODO: consider gradation. See http://www.javadrive.jp/java2d/shape/index9.html
Result r = run.getResult();
if(r ==Result.FAILURE || r== Result.ABORTED)
return ColorPalette.RED;
else
return ColorPalette.BLUE;
}
public int hashCode() {
return run.hashCode();
}
public String toString() {
String l = run.getDisplayName();
if(run instanceof Build) {
String s = ((Build)run).getBuiltOnStr();
if(s!=null)
l += ' '+s;
}
return l;
}
}
DataSetBuilder<String,Label> data = new DataSetBuilder<String, Label>();
for( Run r : getBuilds() )
data.add( ((double)r.getDuration())/(1000*60), "mins", new Label(r));
final CategoryDataset dataset = data.build();
final JFreeChart chart = ChartFactory.createStackedAreaChart(
null, // chart title
null, // unused
"min", // range axis label
dataset, // data
PlotOrientation.VERTICAL, // orientation
false, // include legend
true, // tooltips
false // urls
);
chart.setBackgroundPaint(Color.white);
final CategoryPlot plot = chart.getCategoryPlot();
// plot.setAxisOffset(new Spacer(Spacer.ABSOLUTE, 5.0, 5.0, 5.0, 5.0));
plot.setBackgroundPaint(Color.WHITE);
plot.setOutlinePaint(null);
plot.setForegroundAlpha(0.8f);
// plot.setDomainGridlinesVisible(true);
// plot.setDomainGridlinePaint(Color.white);
plot.setRangeGridlinesVisible(true);
plot.setRangeGridlinePaint(Color.black);
CategoryAxis domainAxis = new ShiftedCategoryAxis(null);
plot.setDomainAxis(domainAxis);
domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_90);
domainAxis.setLowerMargin(0.0);
domainAxis.setUpperMargin(0.0);
domainAxis.setCategoryMargin(0.0);
final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
StackedAreaRenderer ar = new StackedAreaRenderer2() {
@Override
public Paint getItemPaint(int row, int column) {
Label key = (Label) dataset.getColumnKey(column);
return key.getColor();
}
@Override
public String generateURL(CategoryDataset dataset, int row, int column) {
Label label = (Label) dataset.getColumnKey(column);
return String.valueOf(label.run.number);
}
@Override
public String generateToolTip(CategoryDataset dataset, int row, int column) {
Label label = (Label) dataset.getColumnKey(column);
return label.run.getDisplayName() + " : " + label.run.getDurationString();
}
};
plot.setRenderer(ar);
// crop extra space around the graph
plot.setInsets(new RectangleInsets(0,0,0,5.0));
return chart;
}
| private JFreeChart createBuildTimeTrendChart() {
class Label implements Comparable<Label> {
final Run run;
public Label(Run r) {
this.run = r;
}
public int compareTo(Label that) {
return this.run.number-that.run.number;
}
public boolean equals(Object o) {
Label that = (Label) o;
return run ==that.run;
}
public Color getColor() {
// TODO: consider gradation. See http://www.javadrive.jp/java2d/shape/index9.html
Result r = run.getResult();
if(r ==Result.FAILURE || r== Result.ABORTED)
return ColorPalette.RED;
else
return ColorPalette.BLUE;
}
public int hashCode() {
return run.hashCode();
}
public String toString() {
String l = run.getDisplayName();
if(run instanceof Build) {
String s = ((Build)run).getBuiltOnStr();
if(s!=null)
l += ' '+s;
}
return l;
}
}
DataSetBuilder<String,Label> data = new DataSetBuilder<String, Label>();
for( Run r : getBuilds() ) {
if(r.isBuilding()) continue;
data.add( ((double)r.getDuration())/(1000*60), "mins", new Label(r));
}
final CategoryDataset dataset = data.build();
final JFreeChart chart = ChartFactory.createStackedAreaChart(
null, // chart title
null, // unused
"min", // range axis label
dataset, // data
PlotOrientation.VERTICAL, // orientation
false, // include legend
true, // tooltips
false // urls
);
chart.setBackgroundPaint(Color.white);
final CategoryPlot plot = chart.getCategoryPlot();
// plot.setAxisOffset(new Spacer(Spacer.ABSOLUTE, 5.0, 5.0, 5.0, 5.0));
plot.setBackgroundPaint(Color.WHITE);
plot.setOutlinePaint(null);
plot.setForegroundAlpha(0.8f);
// plot.setDomainGridlinesVisible(true);
// plot.setDomainGridlinePaint(Color.white);
plot.setRangeGridlinesVisible(true);
plot.setRangeGridlinePaint(Color.black);
CategoryAxis domainAxis = new ShiftedCategoryAxis(null);
plot.setDomainAxis(domainAxis);
domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_90);
domainAxis.setLowerMargin(0.0);
domainAxis.setUpperMargin(0.0);
domainAxis.setCategoryMargin(0.0);
final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
StackedAreaRenderer ar = new StackedAreaRenderer2() {
@Override
public Paint getItemPaint(int row, int column) {
Label key = (Label) dataset.getColumnKey(column);
return key.getColor();
}
@Override
public String generateURL(CategoryDataset dataset, int row, int column) {
Label label = (Label) dataset.getColumnKey(column);
return String.valueOf(label.run.number);
}
@Override
public String generateToolTip(CategoryDataset dataset, int row, int column) {
Label label = (Label) dataset.getColumnKey(column);
return label.run.getDisplayName() + " : " + label.run.getDurationString();
}
};
plot.setRenderer(ar);
// crop extra space around the graph
plot.setInsets(new RectangleInsets(0,0,0,5.0));
return chart;
}
|
diff --git a/moria2/modules/moria-web/src/java/no/feide/moria/servlet/StatusServlet.java b/moria2/modules/moria-web/src/java/no/feide/moria/servlet/StatusServlet.java
index 8078e850..4b7d4be0 100644
--- a/moria2/modules/moria-web/src/java/no/feide/moria/servlet/StatusServlet.java
+++ b/moria2/modules/moria-web/src/java/no/feide/moria/servlet/StatusServlet.java
@@ -1,474 +1,474 @@
/*
* Copyright (c) 2004 UNINETT FAS
*
* 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., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* $Id$
*/
package no.feide.moria.servlet;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Map;
import java.util.HashMap;
import java.util.TreeMap;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.Vector;
import javax.net.ssl.HttpsURLConnection;
import java.net.URL;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.MalformedURLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import no.feide.moria.controller.AuthenticationException;
import no.feide.moria.controller.AuthorizationException;
import no.feide.moria.controller.DirectoryUnavailableException;
import no.feide.moria.controller.IllegalInputException;
import no.feide.moria.controller.InoperableStateException;
import no.feide.moria.controller.MoriaController;
import no.feide.moria.log.MessageLogger;
import no.feide.moria.store.MoriaStore;
import no.feide.moria.store.MoriaStoreException;
import no.feide.moria.store.MoriaStoreFactory;
/**
* The StatusServlet shows the status of Moria.
* @version $Revision$
*/
public class StatusServlet
extends MoriaServlet {
/** Used for logging. */
private final MessageLogger log = new MessageLogger(StatusServlet.class);
/**
* List of parameters required by <code>StatusServlet</code>.
* <br>
* <br>
* Current required parameters are:
* <ul>
* <li><code>RequestUtil.PROP_BACKENDSTATUS_STATUS_XML</code>
* </ul>
* @see RequestUtil#PROP_BACKENDSTATUS_STATUS_XML
*/
private static final String[] REQUIRED_PARAMETERS = {
RequestUtil.PROP_BACKENDSTATUS_STATUS_XML,
RequestUtil.PROP_COOKIE_LANG };
/**
*
* @return the required parameters for this servlet.
*/
public static String[] getRequiredParameters() {
return REQUIRED_PARAMETERS;
}
/**
* A hash map containing the attributes for a test-user.
* Each item in the hashmap maps from a user name to an
* backendStatusUser class instance
*/
private HashMap backendDataUsers = null;
/**
* Monitor for the status xml file.
*/
private FileMonitor statusFileMonitor = null;
/**
* The organization the test user comes from.
*/
private static final String STATUS_ATTRIBUTE = "eduPersonAffiliation";
/**
* The name of the service.
*/
private static final String STATUS_PRINCIPAL = "status";
/**
* Implements a simple xml parser that parses the status.xml file
* into a HashMap with BackendStatusUser instances.
*
* @see BackendStatusHandler
* @see BackendStatusUser
*/
public final synchronized HashMap getBackendStatusData() {
if (statusFileMonitor == null || statusFileMonitor.hasChanged()) {
Properties config = getConfig();
if (config != null) {
BackendStatusHandler handler = new BackendStatusHandler();
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
String filename = (String) config.get(RequestUtil.PROP_BACKENDSTATUS_STATUS_XML);
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(new File(filename), handler);
statusFileMonitor = new FileMonitor(filename);
} catch (Throwable t) {
log.logCritical("Error parsing status.xml");
} finally {
backendDataUsers = handler.getAttribs();
}
}
}
return backendDataUsers;
}
private void printTable() {
HashMap backendStatusData = getBackendStatusData();
}
/**
* Checks the config
*
* @param bundle
* @return
*/
private Vector checkConfigStatus(ResourceBundle bundle) {
Vector statusConfig = new Vector();
// InformationServlet
try {
this.getServletConfig(InformationServlet.getRequiredParameters(), log);
} catch (IllegalStateException e) {
String errorMsg = bundle.getString("config_info");
statusConfig.add(errorMsg);
}
// LoginServlet
try {
this.getServletConfig(LoginServlet.getRequiredParameters(), log);
} catch (IllegalStateException e) {
String errorMsg = bundle.getString("config_login");
statusConfig.add(errorMsg);
}
// StatisticsServlet
try {
this.getServletConfig(StatisticsServlet.getRequiredParameters(), log);
} catch (IllegalStateException e) {
String errorMsg = bundle.getString("config_statistics");
statusConfig.add(errorMsg);
}
return statusConfig;
}
/**
* Checks the modules
*
* @param bundle
* @return
*/
private Vector checkModules(ResourceBundle bundle) {
Map statusMap = MoriaController.getStatus();
Vector statusMsg = new Vector();
if (statusMap != null) {
String[] states = {"moria", "init", "am", "dm", "sm", "web"};
Map moduleNames = new HashMap();
moduleNames.put("moria", "Moria");
moduleNames.put("init", "Controller");
moduleNames.put("am", "Authorization manager");
moduleNames.put("dm", "Directory manager");
moduleNames.put("sm", "Store manager");
moduleNames.put("web", "Web application");
for (int i = 0; i < states.length; i++) {
Object stateObject = statusMap.get(states[i]);
Boolean isReady = new Boolean(false);
if (stateObject instanceof Boolean) {
isReady = (Boolean) stateObject;
}
if (states[i].equals("moria") && isReady.booleanValue()) {
statusMsg = new Vector(); // return an empty vector
break;
} else if (!isReady.booleanValue()) {
String errormsg = bundle.getString("module_1") + moduleNames.get(states[i]) + bundle.getString("module_2") + "<br>";
statusMsg.add(errormsg);
}
}
}
return statusMsg;
}
/**
* Checks the SOAP page.
*
* @param bundle
* @return
*/
private Vector checkSoap(ResourceBundle bundle) {
Vector soapMsg = new Vector();
try {
URL url = new URL("https://login.feide.no/moria2/v2_1/Authentication?wsdl");
java.net.Authenticator.setDefault(new Authenticator() {
protected java.net.PasswordAuthentication getPasswordAuthentication()
{
char[] passwd = {'d', 'e', 'm', 'o', '_', 's', 'e', 'r', 'v', 'i', 'c', 'e'};
return new PasswordAuthentication(new String("demo_service"), passwd);
}
});
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int code = connection.getResponseCode();
if (code != HttpsURLConnection.HTTP_OK) {
String err = new String(bundle.getString("soap_error") + new Integer(code).toString());
soapMsg.add(err);
}
//should not happen
} catch(MalformedURLException e) {
String err = bundle.getString("soap_exception1");
soapMsg.add(err);
} catch (IOException e) {
String err = bundle.getString("soap_exception2");
soapMsg.add(err);
}
return soapMsg;
}
public Vector checkBackend(ResourceBundle bundle) {
Vector backendMsg = new Vector();
for (Iterator iterator = backendDataUsers.keySet().iterator(); iterator.hasNext();) {
String key = (String) iterator.next();
BackendStatusUser userData = (BackendStatusUser) backendDataUsers.get(key);
String org = userData.getOrganization();
try {
final Map attributes = MoriaController.directNonInteractiveAuthentication(new String[] {STATUS_ATTRIBUTE},
userData.getName(), userData.getPassword(), STATUS_PRINCIPAL);
} catch (Exception e) {
String err = bundle.getString("ldap_error") + org;
backendMsg.add(err);
}
}
return backendMsg;
}
/**
* Handles the GET requests.
* @param request
* The HTTP request object.
* @param response
* The HTTP response object.
* @throws java.io.IOException
* If an input or output error is detected when the servlet
* handles the GET request.
* @throws javax.servlet.ServletException
* If the request for the GET could not be handled.
* @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse)
*/
public final void doGet(final HttpServletRequest request, final HttpServletResponse response)
throws IOException, ServletException {
getBackendStatusData();
Properties config = getConfig();
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String docType = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n";
/* Resource bundle. */
String language = null;
String langFromCookie = null;
if (config != null && request.getCookies() != null) {
langFromCookie = RequestUtil.getCookieValue((String) config.get(RequestUtil.PROP_COOKIE_LANG), request.getCookies());
}
// Update cookie if language has changed
if (request.getParameter(RequestUtil.PARAM_LANG) != null) {
language = request.getParameter(RequestUtil.PARAM_LANG);
response.addCookie(RequestUtil.createCookie(
(String) config.get(RequestUtil.PROP_COOKIE_LANG),
language,
new Integer((String) config.get(RequestUtil.PROP_COOKIE_LANG_TTL)).intValue()));
}
/* Get bundle, using either cookie or language parameter */
final ResourceBundle bundle = RequestUtil.getBundle(
RequestUtil.BUNDLE_STATUSSERVLET,
language, langFromCookie, null,
request.getHeader("Accept-Language"),
(String) config.get(RequestUtil.PROP_LOGIN_DEFAULT_LANGUAGE));
// Header
out.println("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
out.println(docType + "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=" + bundle.getLocale() + ">");
out.println("<head><link rel=\"icon\" href=\"/favicon.ico\" type=\"image/png\">");
out.println("<style type=\"text/css\">\n@import url(\"../resource/stil.css\");\n</style>");
out.println("<link rel=\"author\" href=\"mailto:" + config.get(RequestUtil.RESOURCE_MAIL)+ "\">");
out.println("<title>" + bundle.getString("header_title") + "</title></head><body>");
//Layout table
out.println("<table summary=\"Layout-tabell\" class=\"invers\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">");
out.println("<tbody><tr valign=\"middle\">");
out.println("<td class=\"logo\" width=\"76\"><a href=" + config.get(RequestUtil.RESOURCE_LINK) + ">");
out.println("<img src=\"../resource/logo.gif\" alt=" + config.get(RequestUtil.PROP_FAQ_OWNER) + " border=\"0\" height=\"41\" width=\"76\"></a></td>");
out.println("<td width=\"0%\"><a class=\"noline\" href=" + config.get(RequestUtil.RESOURCE_LINK) + ">");
out.println(bundle.getString("header_feide") + "</a></td>");
out.println("<td width=\"35%\"> </td>");
// Language selection
TreeMap languages = (TreeMap)RequestUtil.parseConfig(config, RequestUtil.PROP_LANGUAGE, RequestUtil.PROP_COMMON);
Iterator it = languages.keySet().iterator();
while(it.hasNext()) {
String longName = (String) it.next();
String shortName = (String) languages.get(longName);
if (RequestUtil.ATTR_SELECTED_LANG.equals(shortName)) {
out.println("[" + longName + "]");
} else
out.println("<td align=\"centre\"><small><a class=\"invers\" href ="
+ config.get(RequestUtil.PROP_FAQ_STATUS) + "?" + RequestUtil.PARAM_LANG + "=" + shortName + ">" + longName
+ "</a></small></td>");
}
//More Layout
out.println("<td class=\"dekor1\" width=\"100%\"> </td></tr></tbody></table>");
out.println("<div class=\"midt\">");
out.println("<table cellspacing=\"0\">");
out.println("<tbody><tr valign=\"top\">");
out.println("<td class=\"kropp\">");
// Check status
Vector allerrors = new Vector();
allerrors.addAll(checkModules(bundle));
allerrors.addAll(checkConfigStatus(bundle));
allerrors.addAll(checkSoap(bundle));
allerrors.addAll(checkBackend(bundle));
if (allerrors.size()>0) {
for (int i = 0; i < allerrors.size(); i++) {
- out.println((String)(allerrors.get(i)));
+ out.println("<font color=#FFFFFF>" + (String)(allerrors.get(i)) + "</font>" + "<br>");
}
} else if (allerrors.size() == 0) {
- out.println(bundle.getString("ready_msg"));
+ out.println("<font color=#FFFFFF>" + bundle.getString("ready_msg") + "</font>");
}
// Prepare to check test users.
out.println("<p><table border=1><tr><th>" + bundle.getString("table_organization") + "</th><th>" + bundle.getString("table_status") + "</th></tr>");
// Start checking a new user.
for (Iterator iterator = backendDataUsers.keySet().iterator(); iterator.hasNext();) {
String key = (String) iterator.next();
BackendStatusUser userData = (BackendStatusUser) backendDataUsers.get(key);
out.println("<tr><td>" + userData.getOrganization() + "</td>");
try {
final Map attributes = MoriaController.directNonInteractiveAuthentication(new String[] {STATUS_ATTRIBUTE},
userData.getName(), userData.getPassword(), STATUS_PRINCIPAL);
// This test user worked.
out.println("<td>OK</td>");
} catch (AuthenticationException e) {
log.logWarn("Authentication failed for: " + userData.getName() + ", contact: " + userData.getContact());
String message = "<a href=mailto:" + userData.getContact() + "?subject=" + userData.getOrganization()
+ ":%20" + bundle.getString("subject_authentication") + userData.getName() + ">" + bundle.getString("error_help");
out.println("<td>" + bundle.getString("error_authentication") + message + "</a></td></tr>");
} catch (DirectoryUnavailableException e) {
log.logWarn("The directory is unavailable for: " + userData.getName() + ", contact: " + userData.getContact());
String message = "<a href=mailto:" + userData.getContact() + "?subject=" + userData.getOrganization()
+ ":%20" + bundle.getString("subject_directory") + userData.getName() + ">" + bundle.getString("error_help");
out.println("<td>" + bundle.getString("error_directory") + message + "</a></td></tr>");
} catch (AuthorizationException e) {
log.logWarn("Authorization failed for: " + userData.getName() + ", contact: " + userData.getContact());
String message = "<a href=mailto:" + userData.getContact() + "?subject=" + userData.getOrganization()
+ ":%20" + bundle.getString("subject_authorization") + userData.getName() + ">" + bundle.getString("error_help");
out.println("<td>" + bundle.getString("error_authorization") + message + "</a></td></tr>");
} catch (IllegalInputException e) {
log.logWarn("Illegal input for: " + userData.getName() + ", contact: " + userData.getContact());
String message = "<a href=mailto:" + userData.getContact() + "?subject=" + userData.getOrganization()
+ ":%20" + bundle.getString("subject_illegal") + userData.getName() + ">" + bundle.getString("error_help");
out.println("<td>" + bundle.getString("error_illegal") + message + "</a></td></tr>");
} catch (InoperableStateException e) {
log.logWarn("Inoperable state for: " + userData.getName() + ", contact: " + userData.getContact());
//Only print moria-support adress if moria is inoperable
if (userData.getOrganization().equals("Uninett")){
String message = "<a href=mailto:" + userData.getContact() + "?subject=" + userData.getOrganization()
+ ":%20" + bundle.getString("subject_inoperable") + userData.getName() + ">" + bundle.getString("error_help");
out.println("<td>" + bundle.getString("error_inoperable") + message + "</a></td></tr>");
} else {
out.println("<td>" + bundle.getString("error_inoperable"));
}
} finally {
// Finish the table row.
out.println("</tr>");
}
}
// Done with all test users.
out.println("</table></p>");
//Layout
out.println("</tr>");
out.println("</table>");
out.println("</tbody>");
out.println("</div>");
out.println("<p>");
out.println("<table summary=\"Layout-tabell\" class=\"invers\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">");
out.println("<tbody><tr class=\"bunn\" valign=\"middle\">");
out.println("<td class=\"invers\" align=\"left\"><small><a class=\"invers\" href=\"mailto:"
+ config.get(RequestUtil.RESOURCE_MAIL) + "\">" + config.get(RequestUtil.RESOURCE_MAIL) + "</a></small></td>");
out.println("<td class=\"invers\" align=\"right\"><small>" + config.get(RequestUtil.RESOURCE_DATE) + "</small></td>");
out.println("</tr></tbody></table></p>");
// Finish up.
out.println("</body></html>");
}
/**
* Get this servlet's configuration from the web module, given by
* <code>RequestUtil.PROP_CONFIG</code>.
* @return The last valid configuration.
* @throws IllegalStateException
* If unable to read the current configuration from the servlet
* context, and there is no previous configuration. Also thrown
* if any of the required parameters (given by
* <code>REQUIRED_PARAMETERS</code>) are not set.
* @see #REQUIRED_PARAMETERS
* @see RequestUtil#PROP_CONFIG
*/
private Properties getConfig() {
try {
return getServletConfig(getRequiredParameters(), log);
}
catch (IllegalStateException e) {
return null;
}
}
}
| false | true | public final void doGet(final HttpServletRequest request, final HttpServletResponse response)
throws IOException, ServletException {
getBackendStatusData();
Properties config = getConfig();
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String docType = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n";
/* Resource bundle. */
String language = null;
String langFromCookie = null;
if (config != null && request.getCookies() != null) {
langFromCookie = RequestUtil.getCookieValue((String) config.get(RequestUtil.PROP_COOKIE_LANG), request.getCookies());
}
// Update cookie if language has changed
if (request.getParameter(RequestUtil.PARAM_LANG) != null) {
language = request.getParameter(RequestUtil.PARAM_LANG);
response.addCookie(RequestUtil.createCookie(
(String) config.get(RequestUtil.PROP_COOKIE_LANG),
language,
new Integer((String) config.get(RequestUtil.PROP_COOKIE_LANG_TTL)).intValue()));
}
/* Get bundle, using either cookie or language parameter */
final ResourceBundle bundle = RequestUtil.getBundle(
RequestUtil.BUNDLE_STATUSSERVLET,
language, langFromCookie, null,
request.getHeader("Accept-Language"),
(String) config.get(RequestUtil.PROP_LOGIN_DEFAULT_LANGUAGE));
// Header
out.println("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
out.println(docType + "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=" + bundle.getLocale() + ">");
out.println("<head><link rel=\"icon\" href=\"/favicon.ico\" type=\"image/png\">");
out.println("<style type=\"text/css\">\n@import url(\"../resource/stil.css\");\n</style>");
out.println("<link rel=\"author\" href=\"mailto:" + config.get(RequestUtil.RESOURCE_MAIL)+ "\">");
out.println("<title>" + bundle.getString("header_title") + "</title></head><body>");
//Layout table
out.println("<table summary=\"Layout-tabell\" class=\"invers\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">");
out.println("<tbody><tr valign=\"middle\">");
out.println("<td class=\"logo\" width=\"76\"><a href=" + config.get(RequestUtil.RESOURCE_LINK) + ">");
out.println("<img src=\"../resource/logo.gif\" alt=" + config.get(RequestUtil.PROP_FAQ_OWNER) + " border=\"0\" height=\"41\" width=\"76\"></a></td>");
out.println("<td width=\"0%\"><a class=\"noline\" href=" + config.get(RequestUtil.RESOURCE_LINK) + ">");
out.println(bundle.getString("header_feide") + "</a></td>");
out.println("<td width=\"35%\"> </td>");
// Language selection
TreeMap languages = (TreeMap)RequestUtil.parseConfig(config, RequestUtil.PROP_LANGUAGE, RequestUtil.PROP_COMMON);
Iterator it = languages.keySet().iterator();
while(it.hasNext()) {
String longName = (String) it.next();
String shortName = (String) languages.get(longName);
if (RequestUtil.ATTR_SELECTED_LANG.equals(shortName)) {
out.println("[" + longName + "]");
} else
out.println("<td align=\"centre\"><small><a class=\"invers\" href ="
+ config.get(RequestUtil.PROP_FAQ_STATUS) + "?" + RequestUtil.PARAM_LANG + "=" + shortName + ">" + longName
+ "</a></small></td>");
}
//More Layout
out.println("<td class=\"dekor1\" width=\"100%\"> </td></tr></tbody></table>");
out.println("<div class=\"midt\">");
out.println("<table cellspacing=\"0\">");
out.println("<tbody><tr valign=\"top\">");
out.println("<td class=\"kropp\">");
// Check status
Vector allerrors = new Vector();
allerrors.addAll(checkModules(bundle));
allerrors.addAll(checkConfigStatus(bundle));
allerrors.addAll(checkSoap(bundle));
allerrors.addAll(checkBackend(bundle));
if (allerrors.size()>0) {
for (int i = 0; i < allerrors.size(); i++) {
out.println((String)(allerrors.get(i)));
}
} else if (allerrors.size() == 0) {
out.println(bundle.getString("ready_msg"));
}
// Prepare to check test users.
out.println("<p><table border=1><tr><th>" + bundle.getString("table_organization") + "</th><th>" + bundle.getString("table_status") + "</th></tr>");
// Start checking a new user.
for (Iterator iterator = backendDataUsers.keySet().iterator(); iterator.hasNext();) {
String key = (String) iterator.next();
BackendStatusUser userData = (BackendStatusUser) backendDataUsers.get(key);
out.println("<tr><td>" + userData.getOrganization() + "</td>");
try {
final Map attributes = MoriaController.directNonInteractiveAuthentication(new String[] {STATUS_ATTRIBUTE},
userData.getName(), userData.getPassword(), STATUS_PRINCIPAL);
// This test user worked.
out.println("<td>OK</td>");
} catch (AuthenticationException e) {
log.logWarn("Authentication failed for: " + userData.getName() + ", contact: " + userData.getContact());
String message = "<a href=mailto:" + userData.getContact() + "?subject=" + userData.getOrganization()
+ ":%20" + bundle.getString("subject_authentication") + userData.getName() + ">" + bundle.getString("error_help");
out.println("<td>" + bundle.getString("error_authentication") + message + "</a></td></tr>");
} catch (DirectoryUnavailableException e) {
log.logWarn("The directory is unavailable for: " + userData.getName() + ", contact: " + userData.getContact());
String message = "<a href=mailto:" + userData.getContact() + "?subject=" + userData.getOrganization()
+ ":%20" + bundle.getString("subject_directory") + userData.getName() + ">" + bundle.getString("error_help");
out.println("<td>" + bundle.getString("error_directory") + message + "</a></td></tr>");
} catch (AuthorizationException e) {
log.logWarn("Authorization failed for: " + userData.getName() + ", contact: " + userData.getContact());
String message = "<a href=mailto:" + userData.getContact() + "?subject=" + userData.getOrganization()
+ ":%20" + bundle.getString("subject_authorization") + userData.getName() + ">" + bundle.getString("error_help");
out.println("<td>" + bundle.getString("error_authorization") + message + "</a></td></tr>");
} catch (IllegalInputException e) {
log.logWarn("Illegal input for: " + userData.getName() + ", contact: " + userData.getContact());
String message = "<a href=mailto:" + userData.getContact() + "?subject=" + userData.getOrganization()
+ ":%20" + bundle.getString("subject_illegal") + userData.getName() + ">" + bundle.getString("error_help");
out.println("<td>" + bundle.getString("error_illegal") + message + "</a></td></tr>");
} catch (InoperableStateException e) {
log.logWarn("Inoperable state for: " + userData.getName() + ", contact: " + userData.getContact());
//Only print moria-support adress if moria is inoperable
if (userData.getOrganization().equals("Uninett")){
String message = "<a href=mailto:" + userData.getContact() + "?subject=" + userData.getOrganization()
+ ":%20" + bundle.getString("subject_inoperable") + userData.getName() + ">" + bundle.getString("error_help");
out.println("<td>" + bundle.getString("error_inoperable") + message + "</a></td></tr>");
} else {
out.println("<td>" + bundle.getString("error_inoperable"));
}
} finally {
// Finish the table row.
out.println("</tr>");
}
}
// Done with all test users.
out.println("</table></p>");
//Layout
out.println("</tr>");
out.println("</table>");
out.println("</tbody>");
out.println("</div>");
out.println("<p>");
out.println("<table summary=\"Layout-tabell\" class=\"invers\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">");
out.println("<tbody><tr class=\"bunn\" valign=\"middle\">");
out.println("<td class=\"invers\" align=\"left\"><small><a class=\"invers\" href=\"mailto:"
+ config.get(RequestUtil.RESOURCE_MAIL) + "\">" + config.get(RequestUtil.RESOURCE_MAIL) + "</a></small></td>");
out.println("<td class=\"invers\" align=\"right\"><small>" + config.get(RequestUtil.RESOURCE_DATE) + "</small></td>");
out.println("</tr></tbody></table></p>");
// Finish up.
out.println("</body></html>");
}
| public final void doGet(final HttpServletRequest request, final HttpServletResponse response)
throws IOException, ServletException {
getBackendStatusData();
Properties config = getConfig();
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String docType = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n";
/* Resource bundle. */
String language = null;
String langFromCookie = null;
if (config != null && request.getCookies() != null) {
langFromCookie = RequestUtil.getCookieValue((String) config.get(RequestUtil.PROP_COOKIE_LANG), request.getCookies());
}
// Update cookie if language has changed
if (request.getParameter(RequestUtil.PARAM_LANG) != null) {
language = request.getParameter(RequestUtil.PARAM_LANG);
response.addCookie(RequestUtil.createCookie(
(String) config.get(RequestUtil.PROP_COOKIE_LANG),
language,
new Integer((String) config.get(RequestUtil.PROP_COOKIE_LANG_TTL)).intValue()));
}
/* Get bundle, using either cookie or language parameter */
final ResourceBundle bundle = RequestUtil.getBundle(
RequestUtil.BUNDLE_STATUSSERVLET,
language, langFromCookie, null,
request.getHeader("Accept-Language"),
(String) config.get(RequestUtil.PROP_LOGIN_DEFAULT_LANGUAGE));
// Header
out.println("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
out.println(docType + "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=" + bundle.getLocale() + ">");
out.println("<head><link rel=\"icon\" href=\"/favicon.ico\" type=\"image/png\">");
out.println("<style type=\"text/css\">\n@import url(\"../resource/stil.css\");\n</style>");
out.println("<link rel=\"author\" href=\"mailto:" + config.get(RequestUtil.RESOURCE_MAIL)+ "\">");
out.println("<title>" + bundle.getString("header_title") + "</title></head><body>");
//Layout table
out.println("<table summary=\"Layout-tabell\" class=\"invers\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">");
out.println("<tbody><tr valign=\"middle\">");
out.println("<td class=\"logo\" width=\"76\"><a href=" + config.get(RequestUtil.RESOURCE_LINK) + ">");
out.println("<img src=\"../resource/logo.gif\" alt=" + config.get(RequestUtil.PROP_FAQ_OWNER) + " border=\"0\" height=\"41\" width=\"76\"></a></td>");
out.println("<td width=\"0%\"><a class=\"noline\" href=" + config.get(RequestUtil.RESOURCE_LINK) + ">");
out.println(bundle.getString("header_feide") + "</a></td>");
out.println("<td width=\"35%\"> </td>");
// Language selection
TreeMap languages = (TreeMap)RequestUtil.parseConfig(config, RequestUtil.PROP_LANGUAGE, RequestUtil.PROP_COMMON);
Iterator it = languages.keySet().iterator();
while(it.hasNext()) {
String longName = (String) it.next();
String shortName = (String) languages.get(longName);
if (RequestUtil.ATTR_SELECTED_LANG.equals(shortName)) {
out.println("[" + longName + "]");
} else
out.println("<td align=\"centre\"><small><a class=\"invers\" href ="
+ config.get(RequestUtil.PROP_FAQ_STATUS) + "?" + RequestUtil.PARAM_LANG + "=" + shortName + ">" + longName
+ "</a></small></td>");
}
//More Layout
out.println("<td class=\"dekor1\" width=\"100%\"> </td></tr></tbody></table>");
out.println("<div class=\"midt\">");
out.println("<table cellspacing=\"0\">");
out.println("<tbody><tr valign=\"top\">");
out.println("<td class=\"kropp\">");
// Check status
Vector allerrors = new Vector();
allerrors.addAll(checkModules(bundle));
allerrors.addAll(checkConfigStatus(bundle));
allerrors.addAll(checkSoap(bundle));
allerrors.addAll(checkBackend(bundle));
if (allerrors.size()>0) {
for (int i = 0; i < allerrors.size(); i++) {
out.println("<font color=#FFFFFF>" + (String)(allerrors.get(i)) + "</font>" + "<br>");
}
} else if (allerrors.size() == 0) {
out.println("<font color=#FFFFFF>" + bundle.getString("ready_msg") + "</font>");
}
// Prepare to check test users.
out.println("<p><table border=1><tr><th>" + bundle.getString("table_organization") + "</th><th>" + bundle.getString("table_status") + "</th></tr>");
// Start checking a new user.
for (Iterator iterator = backendDataUsers.keySet().iterator(); iterator.hasNext();) {
String key = (String) iterator.next();
BackendStatusUser userData = (BackendStatusUser) backendDataUsers.get(key);
out.println("<tr><td>" + userData.getOrganization() + "</td>");
try {
final Map attributes = MoriaController.directNonInteractiveAuthentication(new String[] {STATUS_ATTRIBUTE},
userData.getName(), userData.getPassword(), STATUS_PRINCIPAL);
// This test user worked.
out.println("<td>OK</td>");
} catch (AuthenticationException e) {
log.logWarn("Authentication failed for: " + userData.getName() + ", contact: " + userData.getContact());
String message = "<a href=mailto:" + userData.getContact() + "?subject=" + userData.getOrganization()
+ ":%20" + bundle.getString("subject_authentication") + userData.getName() + ">" + bundle.getString("error_help");
out.println("<td>" + bundle.getString("error_authentication") + message + "</a></td></tr>");
} catch (DirectoryUnavailableException e) {
log.logWarn("The directory is unavailable for: " + userData.getName() + ", contact: " + userData.getContact());
String message = "<a href=mailto:" + userData.getContact() + "?subject=" + userData.getOrganization()
+ ":%20" + bundle.getString("subject_directory") + userData.getName() + ">" + bundle.getString("error_help");
out.println("<td>" + bundle.getString("error_directory") + message + "</a></td></tr>");
} catch (AuthorizationException e) {
log.logWarn("Authorization failed for: " + userData.getName() + ", contact: " + userData.getContact());
String message = "<a href=mailto:" + userData.getContact() + "?subject=" + userData.getOrganization()
+ ":%20" + bundle.getString("subject_authorization") + userData.getName() + ">" + bundle.getString("error_help");
out.println("<td>" + bundle.getString("error_authorization") + message + "</a></td></tr>");
} catch (IllegalInputException e) {
log.logWarn("Illegal input for: " + userData.getName() + ", contact: " + userData.getContact());
String message = "<a href=mailto:" + userData.getContact() + "?subject=" + userData.getOrganization()
+ ":%20" + bundle.getString("subject_illegal") + userData.getName() + ">" + bundle.getString("error_help");
out.println("<td>" + bundle.getString("error_illegal") + message + "</a></td></tr>");
} catch (InoperableStateException e) {
log.logWarn("Inoperable state for: " + userData.getName() + ", contact: " + userData.getContact());
//Only print moria-support adress if moria is inoperable
if (userData.getOrganization().equals("Uninett")){
String message = "<a href=mailto:" + userData.getContact() + "?subject=" + userData.getOrganization()
+ ":%20" + bundle.getString("subject_inoperable") + userData.getName() + ">" + bundle.getString("error_help");
out.println("<td>" + bundle.getString("error_inoperable") + message + "</a></td></tr>");
} else {
out.println("<td>" + bundle.getString("error_inoperable"));
}
} finally {
// Finish the table row.
out.println("</tr>");
}
}
// Done with all test users.
out.println("</table></p>");
//Layout
out.println("</tr>");
out.println("</table>");
out.println("</tbody>");
out.println("</div>");
out.println("<p>");
out.println("<table summary=\"Layout-tabell\" class=\"invers\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">");
out.println("<tbody><tr class=\"bunn\" valign=\"middle\">");
out.println("<td class=\"invers\" align=\"left\"><small><a class=\"invers\" href=\"mailto:"
+ config.get(RequestUtil.RESOURCE_MAIL) + "\">" + config.get(RequestUtil.RESOURCE_MAIL) + "</a></small></td>");
out.println("<td class=\"invers\" align=\"right\"><small>" + config.get(RequestUtil.RESOURCE_DATE) + "</small></td>");
out.println("</tr></tbody></table></p>");
// Finish up.
out.println("</body></html>");
}
|
diff --git a/src/minecraft/invtweaks/InvTweaksHandlerSorting.java b/src/minecraft/invtweaks/InvTweaksHandlerSorting.java
index 0fa33a5..e3a996e 100644
--- a/src/minecraft/invtweaks/InvTweaksHandlerSorting.java
+++ b/src/minecraft/invtweaks/InvTweaksHandlerSorting.java
@@ -1,757 +1,761 @@
package invtweaks;
import invtweaks.InvTweaksConst;
import invtweaks.InvTweaksItemTree;
import invtweaks.InvTweaksItemTreeItem;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.concurrent.TimeoutException;
import java.util.logging.Logger;
import net.minecraft.client.Minecraft;
import net.minecraft.src.InvTweaksObfuscation;
import net.minecraft.src.Item;
import net.minecraft.src.ItemArmor;
import net.minecraft.src.ItemStack;
import net.minecraft.src.Slot;
/**
* Core of the sorting behaviour. Allows to move items in a container
* (inventory or chest) with respect to the mod's configuration.
*
* @author Jimeo Wan
*
*/
public class InvTweaksHandlerSorting extends InvTweaksObfuscation {
private static final Logger log = Logger.getLogger("InvTweaks");
public static final boolean STACK_NOT_EMPTIED = true;
public static final boolean STACK_EMPTIED = false;
private static int[] DEFAULT_LOCK_PRIORITIES = null;
private static boolean[] DEFAULT_FROZEN_SLOTS = null;
private static final int MAX_CONTAINER_SIZE = 999;
public static final int ALGORITHM_DEFAULT = 0;
public static final int ALGORITHM_VERTICAL = 1;
public static final int ALGORITHM_HORIZONTAL = 2;
public static final int ALGORITHM_INVENTORY = 3;
public static final int ALGORITHM_EVEN_STACKS = 4;
private InvTweaksContainerSectionManager containerMgr;
private int algorithm;
private int size;
private boolean sortArmorParts;
private int clickDelay;
private InvTweaksItemTree tree;
private Vector<InvTweaksConfigSortingRule> rules;
private int[] rulePriority;
private int[] keywordOrder;
private int[] lockPriorities;
private boolean[] frozenSlots;
public InvTweaksHandlerSorting(Minecraft mc, InvTweaksConfig config,
InvTweaksContainerSection section, int algorithm, int rowSize) throws Exception {
super(mc);
// Init constants
if (DEFAULT_LOCK_PRIORITIES == null) {
DEFAULT_LOCK_PRIORITIES = new int[MAX_CONTAINER_SIZE];
for (int i = 0; i < MAX_CONTAINER_SIZE; i++) {
DEFAULT_LOCK_PRIORITIES[i] = 0;
}
}
if (DEFAULT_FROZEN_SLOTS == null) {
DEFAULT_FROZEN_SLOTS = new boolean[MAX_CONTAINER_SIZE];
for (int i = 0; i < MAX_CONTAINER_SIZE; i++) {
DEFAULT_FROZEN_SLOTS[i] = false;
}
}
// Init attributes
this.clickDelay = config.getClickDelay();
this.containerMgr = new InvTweaksContainerSectionManager(mc, section);
this.containerMgr.setClickDelay(this.clickDelay);
this.size = containerMgr.getSize();
this.sortArmorParts = config.getProperty(InvTweaksConfig.PROP_ENABLE_AUTO_EQUIP_ARMOR).equals(InvTweaksConfig.VALUE_TRUE)
&& !isGuiInventoryCreative(getCurrentScreen()); // FIXME Armor parts disappear when sorting in creative mode while holding an item
this.rules = config.getRules();
this.tree = config.getTree();
if (section == InvTweaksContainerSection.INVENTORY) {
this.lockPriorities = config.getLockPriorities();
this.frozenSlots = config.getFrozenSlots();
this.algorithm = ALGORITHM_INVENTORY;
} else {
this.lockPriorities = DEFAULT_LOCK_PRIORITIES;
this.frozenSlots = DEFAULT_FROZEN_SLOTS;
this.algorithm = algorithm;
if (algorithm != ALGORITHM_DEFAULT) {
computeLineSortingRules(rowSize,
algorithm == ALGORITHM_HORIZONTAL);
}
}
this.rulePriority = new int[size];
this.keywordOrder = new int[size];
for (int i = 0; i < size; i++) {
this.rulePriority[i] = -1;
ItemStack stack = containerMgr.getItemStack(i);
if (stack != null) {
this.keywordOrder[i] = getItemOrder(stack);
} else {
this.keywordOrder[i] = -1;
}
}
}
public void sort() throws TimeoutException {
// Do nothing if the inventory is closed
// if (!mc.hrrentScreen instanceof GuiContainer)
// return;
long timer = System.nanoTime();
InvTweaksContainerManager globalContainer = new InvTweaksContainerManager(mc);
globalContainer.setClickDelay(this.clickDelay);
// Put hold item down
if (getHeldStack() != null) {
int emptySlot = globalContainer.getFirstEmptyIndex(InvTweaksContainerSection.INVENTORY);
if (emptySlot != -1) {
globalContainer.putHoldItemDown(InvTweaksContainerSection.INVENTORY, emptySlot);
}
else {
return; // Not enough room to work, abort
}
}
if (algorithm != ALGORITHM_DEFAULT) {
if (algorithm == ALGORITHM_EVEN_STACKS) {
log.info("Distributing items.");
//item and slot counts for each unique item
HashMap itemCounts = new HashMap();
for(int i = 0; i < size; i++) {
um stack = containerMgr.getItemStack(i);
if(stack != null) {
List<Integer> item = Arrays.asList(getItemID(stack),getItemDamage(stack));
int[] count = (int[])itemCounts.get(item);
if(count == null) {
int[] newCount = {getStackSize(stack),1};
itemCounts.put(item,newCount);
} else {
count[0] += getStackSize(stack); //amount of item
count[1]++; //slots with item
}
}
}
//handle each unique item separately
for(Object object:itemCounts.entrySet()) {
Map.Entry entry = (Map.Entry)object;
List<Integer> item = (List<Integer>)entry.getKey();
int[] count = (int[])entry.getValue();
int numPerSlot = count[0]/count[1]; //totalNumber/numberOfSlots
+ // Skip potential null items
+ if(net.minecraft.item.Item.itemsList[item.get(0)] == null) {
+ continue;
+ }
//skip hacked itemstacks that are larger than their max size
//no idea why they would be here, but may as well account for them anyway
- if(numPerSlot <= getMaxStackSize(new um(new uk(item.get(0))))) {
+ if(numPerSlot <= getMaxStackSize(new ItemStack(net.minecraft.item.Item.itemsList[item.get(0)]))) {
//linkedlists to store which stacks have too many/few items
LinkedList smallStacks = new LinkedList();
LinkedList largeStacks = new LinkedList();
for(int i = 0; i < size; i++) {
um stack = containerMgr.getItemStack(i);
if(stack != null && Arrays.asList(getItemID(stack),getItemDamage(stack)).equals(item)) {
int stackSize = getStackSize(stack);
if(stackSize > numPerSlot)
largeStacks.offer(i);
else if(stackSize < numPerSlot)
smallStacks.offer(i);
}
}
//move items from stacks with too many to those with too little
while((!smallStacks.isEmpty())) {
int largeIndex = (Integer)largeStacks.peek();
int largeSize = getStackSize(containerMgr.getItemStack(largeIndex));
int smallIndex = (Integer)smallStacks.peek();
int smallSize = getStackSize(containerMgr.getItemStack(smallIndex));
containerMgr.moveSome(largeIndex, smallIndex, Math.min(numPerSlot-smallSize,largeSize-numPerSlot));
//update stack lists
largeSize = getStackSize(containerMgr.getItemStack(largeIndex));
smallSize = getStackSize(containerMgr.getItemStack(smallIndex));
if(largeSize == numPerSlot)
largeStacks.remove();
if(smallSize == numPerSlot)
smallStacks.remove();
}
//put all leftover into one stack for easy removal
while(largeStacks.size() > 1) {
int largeIndex = (Integer)largeStacks.poll();
int largeSize = getStackSize(containerMgr.getItemStack(largeIndex));
containerMgr.moveSome(largeIndex,(Integer)largeStacks.peek(),largeSize-numPerSlot);
}
}
}
//mark all items as moved. (is there a better way?)
for(int i=0;i<size;i++)
markAsMoved(i,1);
} else if (algorithm == ALGORITHM_INVENTORY) {
//// Move items out of the crafting slots
log.info("Handling crafting slots.");
if (globalContainer.hasSection(InvTweaksContainerSection.CRAFTING_IN)) {
List<Slot> craftingSlots = globalContainer.getSlots(InvTweaksContainerSection.CRAFTING_IN);
int emptyIndex = globalContainer.getFirstEmptyIndex(InvTweaksContainerSection.INVENTORY);
if (emptyIndex != -1) {
for (Slot craftingSlot : craftingSlots) {
if (hasStack(craftingSlot)) {
globalContainer.move(
InvTweaksContainerSection.CRAFTING_IN,
globalContainer.getSlotIndex(getSlotNumber(craftingSlot)),
InvTweaksContainerSection.INVENTORY,
emptyIndex);
emptyIndex = globalContainer.getFirstEmptyIndex(InvTweaksContainerSection.INVENTORY);
if(emptyIndex == -1) {
break;
}
}
}
}
}
//// Merge stacks to fill the ones in locked slots
//// + Move armor parts to the armor slots
log.info("Merging stacks.");
for (int i = size - 1; i >= 0; i--) {
ItemStack from = containerMgr.getItemStack(i);
if (from != null) {
// Move armor parts
Item fromItem = getItem(from);
if (isDamageable(fromItem)) {
if (sortArmorParts) {
if (isItemArmor(fromItem)) {
ItemArmor fromItemArmor = asItemArmor(fromItem);
if (globalContainer.hasSection(InvTweaksContainerSection.ARMOR)) {
List<Slot> armorSlots = globalContainer.getSlots(InvTweaksContainerSection.ARMOR);
for (Slot slot : armorSlots) {
boolean move = false;
if (!hasStack(slot)) {
move = true;
}
else {
int armorLevel = getArmorLevel(asItemArmor(getItem(getStack(slot))));
if (armorLevel < getArmorLevel(fromItemArmor)
|| (armorLevel == getArmorLevel(fromItemArmor)
&& getItemDamage(getStack(slot)) < getItemDamage(from))) {
move = true;
}
}
if (areSlotAndStackCompatible(slot, from) && move) {
globalContainer.move(InvTweaksContainerSection.INVENTORY, i, InvTweaksContainerSection.ARMOR,
globalContainer.getSlotIndex(getSlotNumber(slot)));
}
}
}
}
}
}
// Stackable objects are never damageable
else {
int j = 0;
for (Integer lockPriority : lockPriorities) {
if (lockPriority > 0) {
ItemStack to = containerMgr.getItemStack(j);
if (to != null && areItemsEqual(from, to)) {
move(i, j, Integer.MAX_VALUE);
markAsNotMoved(j);
if (containerMgr.getItemStack(i) == null) {
break;
}
}
}
j++;
}
}
}
}
}
//// Apply rules
log.info("Applying rules.");
// Sorts rule by rule, themselves being already sorted by decreasing priority
Iterator<InvTweaksConfigSortingRule> rulesIt = rules.iterator();
while (rulesIt.hasNext()) {
InvTweaksConfigSortingRule rule = rulesIt.next();
int rulePriority = rule.getPriority();
if (log.getLevel() == InvTweaksConst.DEBUG)
log.info("Rule : "+rule.getKeyword()+"("+rulePriority+")");
// For every item in the inventory
for (int i = 0; i < size; i++) {
ItemStack from = containerMgr.getItemStack(i);
// If the rule is strong enough to move the item and it matches the item, move it
if (hasToBeMoved(i) && lockPriorities[i] < rulePriority) {
List<InvTweaksItemTreeItem> fromItems = tree.getItems(
getItemID(from), getItemDamage(from));
if (tree.matches(fromItems, rule.getKeyword())) {
// Test preffered slots
int[] preferredSlots = rule.getPreferredSlots();
int stackToMove = i;
for (int j = 0; j < preferredSlots.length; j++) {
int k = preferredSlots[j];
// Move the stack!
int moveResult = move(stackToMove, k, rulePriority);
if (moveResult != -1) {
if (moveResult == k) {
break;
}
else {
from = containerMgr.getItemStack(moveResult);
fromItems = tree.getItems(getItemID(from), getItemDamage(from));
if (!tree.matches(fromItems, rule.getKeyword())) {
break;
}
else {
stackToMove = moveResult;
j = -1;
}
}
}
}
}
}
}
}
//// Don't move locked stacks
log.info("Locking stacks.");
for (int i = 0; i < size; i++) {
if (hasToBeMoved(i) && lockPriorities[i] > 0) {
markAsMoved(i, 1);
}
}
}
//// Sort remaining
defaultSorting();
if (log.getLevel() == InvTweaksConst.DEBUG) {
timer = System.nanoTime()-timer;
log.info("Sorting done in " + timer + "ns");
}
//// Put hold item down, just in case
if (getHeldStack() != null) {
int emptySlot = globalContainer.getFirstEmptyIndex(InvTweaksContainerSection.INVENTORY);
if (emptySlot != -1) {
globalContainer.putHoldItemDown(InvTweaksContainerSection.INVENTORY, emptySlot);
}
}
}
private void defaultSorting() throws TimeoutException {
log.info("Default sorting.");
Vector<Integer> remaining = new Vector<Integer>(), nextRemaining = new Vector<Integer>();
for (int i = 0; i < size; i++) {
if (hasToBeMoved(i)) {
remaining.add(i);
nextRemaining.add(i);
}
}
int iterations = 0;
while (remaining.size() > 0 && iterations++ < 50) {
for (int i : remaining) {
if (hasToBeMoved(i)) {
for (int j = 0; j < size; j++) {
if (move(i, j, 1) != -1) {
nextRemaining.remove((Object) j);
break;
}
}
}
else {
nextRemaining.remove((Object) i);
}
}
remaining.clear();
remaining.addAll(nextRemaining);
}
if (iterations == 100) {
log.warning("Sorting takes too long, aborting.");
}
}
/**
* Tries to move a stack from i to j, and swaps them if j is already
* occupied but i is of greater priority (even if they are of same ID).
*
* @param i from slot
* @param j to slot
* @param priority The rule priority. Use 1 if the stack was not moved using a rule.
* @return -1 if it failed,
* j if the stacks were merged into one,
* n if the j stack has been moved to the n slot.
* @throws TimeoutException
*/
private int move(int i, int j, int priority) throws TimeoutException {
ItemStack from = containerMgr.getItemStack(i), to = containerMgr.getItemStack(j);
if (from == null || frozenSlots[j] || frozenSlots[i]) {
return -1;
}
//log.info("Moving " + i + " (" + from + ") to " + j + " (" + to + ") ");
if (lockPriorities[i] <= priority) {
if (i == j) {
markAsMoved(i, priority);
return j;
}
// Move to empty slot
if (to == null && lockPriorities[j] <= priority && !frozenSlots[j]) {
rulePriority[i] = -1;
keywordOrder[i] = -1;
rulePriority[j] = priority;
keywordOrder[j] = getItemOrder(from);
containerMgr.move(i, j);
return j;
}
// Try to swap/merge
else if (to != null) {
boolean canBeSwappedOrMerged = false;
// Can be swapped?
if (lockPriorities[j] <= priority) {
if (rulePriority[j] < priority) {
canBeSwappedOrMerged = true;
} else if (rulePriority[j] == priority) {
if (isOrderedBefore(i, j)) {
canBeSwappedOrMerged = true;
}
}
}
if (!hasDataTags(from) && !hasDataTags(to) && areItemsEqual(from, to)) {
// Can be merged?
if (getStackSize(to) < getMaxStackSize(to)) {
canBeSwappedOrMerged = true;
}
// Safety check (for TooManyItems)
else if (getStackSize(from) > getMaxStackSize(from)) {
canBeSwappedOrMerged = false;
}
}
if (canBeSwappedOrMerged) {
keywordOrder[j] = keywordOrder[i];
rulePriority[j] = priority;
rulePriority[i] = -1;
containerMgr.move(i, j);
ItemStack remains = containerMgr.getItemStack(i);
if (remains != null) {
int dropSlot = i;
if (lockPriorities[j] > lockPriorities[i]) {
for (int k = 0; k < size; k++) {
if (containerMgr.getItemStack(k) == null
&& lockPriorities[k] == 0) {
dropSlot = k;
break;
}
}
}
if (dropSlot != i) {
containerMgr.move(i, dropSlot);
}
rulePriority[dropSlot] = -1;
keywordOrder[dropSlot] = getItemOrder(remains);
return dropSlot;
}
else {
return j;
}
}
}
}
return -1;
}
private void markAsMoved(int i, int priority) {
rulePriority[i] = priority;
}
private void markAsNotMoved(int i) {
rulePriority[i] = -1;
}
private boolean hasToBeMoved(int slot) {
return containerMgr.getItemStack(slot) != null
&& rulePriority[slot] == -1;
}
private boolean isOrderedBefore(int i, int j) {
ItemStack iStack = containerMgr.getItemStack(i), jStack = containerMgr.getItemStack(j);
if (jStack == null) {
return true;
} else if (iStack == null || keywordOrder[i] == -1) {
return false;
} else {
if (keywordOrder[i] == keywordOrder[j]) {
// Items of same keyword orders can have different IDs,
// in the case of categories defined by a range of IDs
if (getItemID(iStack) == getItemID(jStack)) {
if (getItemDamage(iStack) != getItemDamage(jStack)) {
if (isItemStackDamageable(iStack)) {
return getItemDamage(iStack) > getItemDamage(jStack);
}
else {
return getItemDamage(iStack) < getItemDamage(jStack);
}
}
else {
return getStackSize(iStack) > getStackSize(jStack);
}
} else {
return getItemID(iStack) > getItemID(jStack);
}
} else {
return keywordOrder[i] < keywordOrder[j];
}
}
}
private int getItemOrder(ItemStack itemStack) {
List<InvTweaksItemTreeItem> items = tree.getItems(
getItemID(itemStack), getItemDamage(itemStack));
return (items != null && items.size() > 0)
? items.get(0).getOrder()
: Integer.MAX_VALUE;
}
private void computeLineSortingRules(int rowSize, boolean horizontal) {
rules = new Vector<InvTweaksConfigSortingRule>();
Map<InvTweaksItemTreeItem, Integer> stats = computeContainerStats();
List<InvTweaksItemTreeItem> itemOrder = new ArrayList<InvTweaksItemTreeItem>();
int distinctItems = stats.size();
int columnSize = getContainerColumnSize(rowSize);
int spaceWidth;
int spaceHeight;
int availableSlots = size;
int remainingStacks = 0;
for (Integer stacks : stats.values()) {
remainingStacks += stacks;
}
// No need to compute rules for an empty chest
if (distinctItems == 0)
return;
// (Partially) sort stats by decreasing item stack count
List<InvTweaksItemTreeItem> unorderedItems = new ArrayList<InvTweaksItemTreeItem>(stats.keySet());
boolean hasStacksToOrderFirst = true;
while (hasStacksToOrderFirst) {
hasStacksToOrderFirst = false;
for (InvTweaksItemTreeItem item : unorderedItems) {
Integer value = stats.get(item);
if (value > ((horizontal) ? rowSize : columnSize)
&& !itemOrder.contains(item)) {
hasStacksToOrderFirst = true;
itemOrder.add(item);
unorderedItems.remove(item);
break;
}
}
}
Collections.sort(unorderedItems, Collections.reverseOrder());
itemOrder.addAll(unorderedItems);
// Define space size used for each item type.
if (horizontal) {
spaceHeight = 1;
spaceWidth = rowSize/((distinctItems+columnSize-1)/columnSize);
}
else {
spaceWidth = 1;
spaceHeight = columnSize/((distinctItems+rowSize-1)/rowSize);
}
char row = 'a', maxRow = (char) (row - 1 + columnSize);
char column = '1', maxColumn = (char) (column - 1 + rowSize);
// Create rules
Iterator<InvTweaksItemTreeItem> it = itemOrder.iterator();
while (it.hasNext()) {
InvTweaksItemTreeItem item = it.next();
// Adapt rule dimensions to fit the amount
int thisSpaceWidth = spaceWidth,
thisSpaceHeight = spaceHeight;
while (stats.get(item) > thisSpaceHeight*thisSpaceWidth) {
if (horizontal) {
if (column + thisSpaceWidth < maxColumn) {
thisSpaceWidth = maxColumn - column + 1;
}
else if (row + thisSpaceHeight < maxRow) {
thisSpaceHeight++;
}
else {
break;
}
}
else {
if (row + thisSpaceHeight < maxRow) {
thisSpaceHeight = maxRow - row + 1;
}
else if (column + thisSpaceWidth < maxColumn) {
thisSpaceWidth++;
}
else {
break;
}
}
}
// Adjust line/column ends to fill empty space
if (horizontal && (column + thisSpaceWidth == maxColumn)) {
thisSpaceWidth++;
}
else if (!horizontal && row + thisSpaceHeight == maxRow) {
thisSpaceHeight++;
}
// Create rule
String constraint = row + "" + column + "-"
+ (char)(row - 1 + thisSpaceHeight)
+ (char)(column - 1 + thisSpaceWidth);
if (!horizontal) {
constraint += 'v';
}
rules.add(new InvTweaksConfigSortingRule(tree, constraint, item.getName(), size, rowSize));
// Check if ther's still room for more rules
availableSlots -= thisSpaceHeight*thisSpaceWidth;
remainingStacks -= stats.get(item);
if (availableSlots >= remainingStacks) {
// Move origin for next rule
if (horizontal) {
if (column + thisSpaceWidth + spaceWidth <= maxColumn + 1) {
column += thisSpaceWidth;
}
else {
column = '1';
row += thisSpaceHeight;
}
}
else {
if (row + thisSpaceHeight + spaceHeight <= maxRow + 1) {
row += thisSpaceHeight;
}
else {
row = 'a';
column += thisSpaceWidth;
}
}
if (row > maxRow || column > maxColumn)
break;
}
else {
break;
}
}
String defaultRule;
if (horizontal) {
defaultRule = maxRow + "1-a" + maxColumn;
}
else {
defaultRule = "a" + maxColumn + "-" + maxRow + "1v";
}
rules.add(new InvTweaksConfigSortingRule(tree, defaultRule,
tree.getRootCategory().getName(), size, rowSize));
}
private Map<InvTweaksItemTreeItem, Integer> computeContainerStats() {
Map<InvTweaksItemTreeItem, Integer> stats = new HashMap<InvTweaksItemTreeItem, Integer>();
Map<Integer, InvTweaksItemTreeItem> itemSearch = new HashMap<Integer, InvTweaksItemTreeItem>();
for (int i = 0; i < size; i++) {
ItemStack stack = containerMgr.getItemStack(i);
if (stack != null) {
int itemSearchKey = getItemID(stack)*100000 +
((getMaxStackSize(stack) != 1) ? getItemDamage(stack) : 0);
InvTweaksItemTreeItem item = itemSearch.get(itemSearchKey);
if (item == null) {
item = tree.getItems(getItemID(stack),
getItemDamage(stack)).get(0);
itemSearch.put(itemSearchKey, item);
stats.put(item, 1);
}
else {
stats.put(item, stats.get(item) + 1);
}
}
}
return stats;
}
private int getContainerColumnSize(int rowSize) {
return size / rowSize;
}
}
| false | true | public void sort() throws TimeoutException {
// Do nothing if the inventory is closed
// if (!mc.hrrentScreen instanceof GuiContainer)
// return;
long timer = System.nanoTime();
InvTweaksContainerManager globalContainer = new InvTweaksContainerManager(mc);
globalContainer.setClickDelay(this.clickDelay);
// Put hold item down
if (getHeldStack() != null) {
int emptySlot = globalContainer.getFirstEmptyIndex(InvTweaksContainerSection.INVENTORY);
if (emptySlot != -1) {
globalContainer.putHoldItemDown(InvTweaksContainerSection.INVENTORY, emptySlot);
}
else {
return; // Not enough room to work, abort
}
}
if (algorithm != ALGORITHM_DEFAULT) {
if (algorithm == ALGORITHM_EVEN_STACKS) {
log.info("Distributing items.");
//item and slot counts for each unique item
HashMap itemCounts = new HashMap();
for(int i = 0; i < size; i++) {
um stack = containerMgr.getItemStack(i);
if(stack != null) {
List<Integer> item = Arrays.asList(getItemID(stack),getItemDamage(stack));
int[] count = (int[])itemCounts.get(item);
if(count == null) {
int[] newCount = {getStackSize(stack),1};
itemCounts.put(item,newCount);
} else {
count[0] += getStackSize(stack); //amount of item
count[1]++; //slots with item
}
}
}
//handle each unique item separately
for(Object object:itemCounts.entrySet()) {
Map.Entry entry = (Map.Entry)object;
List<Integer> item = (List<Integer>)entry.getKey();
int[] count = (int[])entry.getValue();
int numPerSlot = count[0]/count[1]; //totalNumber/numberOfSlots
//skip hacked itemstacks that are larger than their max size
//no idea why they would be here, but may as well account for them anyway
if(numPerSlot <= getMaxStackSize(new um(new uk(item.get(0))))) {
//linkedlists to store which stacks have too many/few items
LinkedList smallStacks = new LinkedList();
LinkedList largeStacks = new LinkedList();
for(int i = 0; i < size; i++) {
um stack = containerMgr.getItemStack(i);
if(stack != null && Arrays.asList(getItemID(stack),getItemDamage(stack)).equals(item)) {
int stackSize = getStackSize(stack);
if(stackSize > numPerSlot)
largeStacks.offer(i);
else if(stackSize < numPerSlot)
smallStacks.offer(i);
}
}
//move items from stacks with too many to those with too little
while((!smallStacks.isEmpty())) {
int largeIndex = (Integer)largeStacks.peek();
int largeSize = getStackSize(containerMgr.getItemStack(largeIndex));
int smallIndex = (Integer)smallStacks.peek();
int smallSize = getStackSize(containerMgr.getItemStack(smallIndex));
containerMgr.moveSome(largeIndex, smallIndex, Math.min(numPerSlot-smallSize,largeSize-numPerSlot));
//update stack lists
largeSize = getStackSize(containerMgr.getItemStack(largeIndex));
smallSize = getStackSize(containerMgr.getItemStack(smallIndex));
if(largeSize == numPerSlot)
largeStacks.remove();
if(smallSize == numPerSlot)
smallStacks.remove();
}
//put all leftover into one stack for easy removal
while(largeStacks.size() > 1) {
int largeIndex = (Integer)largeStacks.poll();
int largeSize = getStackSize(containerMgr.getItemStack(largeIndex));
containerMgr.moveSome(largeIndex,(Integer)largeStacks.peek(),largeSize-numPerSlot);
}
}
}
//mark all items as moved. (is there a better way?)
for(int i=0;i<size;i++)
markAsMoved(i,1);
} else if (algorithm == ALGORITHM_INVENTORY) {
//// Move items out of the crafting slots
log.info("Handling crafting slots.");
if (globalContainer.hasSection(InvTweaksContainerSection.CRAFTING_IN)) {
List<Slot> craftingSlots = globalContainer.getSlots(InvTweaksContainerSection.CRAFTING_IN);
int emptyIndex = globalContainer.getFirstEmptyIndex(InvTweaksContainerSection.INVENTORY);
if (emptyIndex != -1) {
for (Slot craftingSlot : craftingSlots) {
if (hasStack(craftingSlot)) {
globalContainer.move(
InvTweaksContainerSection.CRAFTING_IN,
globalContainer.getSlotIndex(getSlotNumber(craftingSlot)),
InvTweaksContainerSection.INVENTORY,
emptyIndex);
emptyIndex = globalContainer.getFirstEmptyIndex(InvTweaksContainerSection.INVENTORY);
if(emptyIndex == -1) {
break;
}
}
}
}
}
//// Merge stacks to fill the ones in locked slots
//// + Move armor parts to the armor slots
log.info("Merging stacks.");
for (int i = size - 1; i >= 0; i--) {
ItemStack from = containerMgr.getItemStack(i);
if (from != null) {
// Move armor parts
Item fromItem = getItem(from);
if (isDamageable(fromItem)) {
if (sortArmorParts) {
if (isItemArmor(fromItem)) {
ItemArmor fromItemArmor = asItemArmor(fromItem);
if (globalContainer.hasSection(InvTweaksContainerSection.ARMOR)) {
List<Slot> armorSlots = globalContainer.getSlots(InvTweaksContainerSection.ARMOR);
for (Slot slot : armorSlots) {
boolean move = false;
if (!hasStack(slot)) {
move = true;
}
else {
int armorLevel = getArmorLevel(asItemArmor(getItem(getStack(slot))));
if (armorLevel < getArmorLevel(fromItemArmor)
|| (armorLevel == getArmorLevel(fromItemArmor)
&& getItemDamage(getStack(slot)) < getItemDamage(from))) {
move = true;
}
}
if (areSlotAndStackCompatible(slot, from) && move) {
globalContainer.move(InvTweaksContainerSection.INVENTORY, i, InvTweaksContainerSection.ARMOR,
globalContainer.getSlotIndex(getSlotNumber(slot)));
}
}
}
}
}
}
// Stackable objects are never damageable
else {
int j = 0;
for (Integer lockPriority : lockPriorities) {
if (lockPriority > 0) {
ItemStack to = containerMgr.getItemStack(j);
if (to != null && areItemsEqual(from, to)) {
move(i, j, Integer.MAX_VALUE);
markAsNotMoved(j);
if (containerMgr.getItemStack(i) == null) {
break;
}
}
}
j++;
}
}
}
}
}
//// Apply rules
log.info("Applying rules.");
// Sorts rule by rule, themselves being already sorted by decreasing priority
Iterator<InvTweaksConfigSortingRule> rulesIt = rules.iterator();
while (rulesIt.hasNext()) {
InvTweaksConfigSortingRule rule = rulesIt.next();
int rulePriority = rule.getPriority();
if (log.getLevel() == InvTweaksConst.DEBUG)
log.info("Rule : "+rule.getKeyword()+"("+rulePriority+")");
// For every item in the inventory
for (int i = 0; i < size; i++) {
ItemStack from = containerMgr.getItemStack(i);
// If the rule is strong enough to move the item and it matches the item, move it
if (hasToBeMoved(i) && lockPriorities[i] < rulePriority) {
List<InvTweaksItemTreeItem> fromItems = tree.getItems(
getItemID(from), getItemDamage(from));
if (tree.matches(fromItems, rule.getKeyword())) {
// Test preffered slots
int[] preferredSlots = rule.getPreferredSlots();
int stackToMove = i;
for (int j = 0; j < preferredSlots.length; j++) {
int k = preferredSlots[j];
// Move the stack!
int moveResult = move(stackToMove, k, rulePriority);
if (moveResult != -1) {
if (moveResult == k) {
break;
}
else {
from = containerMgr.getItemStack(moveResult);
fromItems = tree.getItems(getItemID(from), getItemDamage(from));
if (!tree.matches(fromItems, rule.getKeyword())) {
break;
}
else {
stackToMove = moveResult;
j = -1;
}
}
}
}
}
}
}
}
//// Don't move locked stacks
log.info("Locking stacks.");
for (int i = 0; i < size; i++) {
if (hasToBeMoved(i) && lockPriorities[i] > 0) {
markAsMoved(i, 1);
}
}
}
//// Sort remaining
defaultSorting();
if (log.getLevel() == InvTweaksConst.DEBUG) {
timer = System.nanoTime()-timer;
log.info("Sorting done in " + timer + "ns");
}
//// Put hold item down, just in case
if (getHeldStack() != null) {
int emptySlot = globalContainer.getFirstEmptyIndex(InvTweaksContainerSection.INVENTORY);
if (emptySlot != -1) {
globalContainer.putHoldItemDown(InvTweaksContainerSection.INVENTORY, emptySlot);
}
}
}
| public void sort() throws TimeoutException {
// Do nothing if the inventory is closed
// if (!mc.hrrentScreen instanceof GuiContainer)
// return;
long timer = System.nanoTime();
InvTweaksContainerManager globalContainer = new InvTweaksContainerManager(mc);
globalContainer.setClickDelay(this.clickDelay);
// Put hold item down
if (getHeldStack() != null) {
int emptySlot = globalContainer.getFirstEmptyIndex(InvTweaksContainerSection.INVENTORY);
if (emptySlot != -1) {
globalContainer.putHoldItemDown(InvTweaksContainerSection.INVENTORY, emptySlot);
}
else {
return; // Not enough room to work, abort
}
}
if (algorithm != ALGORITHM_DEFAULT) {
if (algorithm == ALGORITHM_EVEN_STACKS) {
log.info("Distributing items.");
//item and slot counts for each unique item
HashMap itemCounts = new HashMap();
for(int i = 0; i < size; i++) {
um stack = containerMgr.getItemStack(i);
if(stack != null) {
List<Integer> item = Arrays.asList(getItemID(stack),getItemDamage(stack));
int[] count = (int[])itemCounts.get(item);
if(count == null) {
int[] newCount = {getStackSize(stack),1};
itemCounts.put(item,newCount);
} else {
count[0] += getStackSize(stack); //amount of item
count[1]++; //slots with item
}
}
}
//handle each unique item separately
for(Object object:itemCounts.entrySet()) {
Map.Entry entry = (Map.Entry)object;
List<Integer> item = (List<Integer>)entry.getKey();
int[] count = (int[])entry.getValue();
int numPerSlot = count[0]/count[1]; //totalNumber/numberOfSlots
// Skip potential null items
if(net.minecraft.item.Item.itemsList[item.get(0)] == null) {
continue;
}
//skip hacked itemstacks that are larger than their max size
//no idea why they would be here, but may as well account for them anyway
if(numPerSlot <= getMaxStackSize(new ItemStack(net.minecraft.item.Item.itemsList[item.get(0)]))) {
//linkedlists to store which stacks have too many/few items
LinkedList smallStacks = new LinkedList();
LinkedList largeStacks = new LinkedList();
for(int i = 0; i < size; i++) {
um stack = containerMgr.getItemStack(i);
if(stack != null && Arrays.asList(getItemID(stack),getItemDamage(stack)).equals(item)) {
int stackSize = getStackSize(stack);
if(stackSize > numPerSlot)
largeStacks.offer(i);
else if(stackSize < numPerSlot)
smallStacks.offer(i);
}
}
//move items from stacks with too many to those with too little
while((!smallStacks.isEmpty())) {
int largeIndex = (Integer)largeStacks.peek();
int largeSize = getStackSize(containerMgr.getItemStack(largeIndex));
int smallIndex = (Integer)smallStacks.peek();
int smallSize = getStackSize(containerMgr.getItemStack(smallIndex));
containerMgr.moveSome(largeIndex, smallIndex, Math.min(numPerSlot-smallSize,largeSize-numPerSlot));
//update stack lists
largeSize = getStackSize(containerMgr.getItemStack(largeIndex));
smallSize = getStackSize(containerMgr.getItemStack(smallIndex));
if(largeSize == numPerSlot)
largeStacks.remove();
if(smallSize == numPerSlot)
smallStacks.remove();
}
//put all leftover into one stack for easy removal
while(largeStacks.size() > 1) {
int largeIndex = (Integer)largeStacks.poll();
int largeSize = getStackSize(containerMgr.getItemStack(largeIndex));
containerMgr.moveSome(largeIndex,(Integer)largeStacks.peek(),largeSize-numPerSlot);
}
}
}
//mark all items as moved. (is there a better way?)
for(int i=0;i<size;i++)
markAsMoved(i,1);
} else if (algorithm == ALGORITHM_INVENTORY) {
//// Move items out of the crafting slots
log.info("Handling crafting slots.");
if (globalContainer.hasSection(InvTweaksContainerSection.CRAFTING_IN)) {
List<Slot> craftingSlots = globalContainer.getSlots(InvTweaksContainerSection.CRAFTING_IN);
int emptyIndex = globalContainer.getFirstEmptyIndex(InvTweaksContainerSection.INVENTORY);
if (emptyIndex != -1) {
for (Slot craftingSlot : craftingSlots) {
if (hasStack(craftingSlot)) {
globalContainer.move(
InvTweaksContainerSection.CRAFTING_IN,
globalContainer.getSlotIndex(getSlotNumber(craftingSlot)),
InvTweaksContainerSection.INVENTORY,
emptyIndex);
emptyIndex = globalContainer.getFirstEmptyIndex(InvTweaksContainerSection.INVENTORY);
if(emptyIndex == -1) {
break;
}
}
}
}
}
//// Merge stacks to fill the ones in locked slots
//// + Move armor parts to the armor slots
log.info("Merging stacks.");
for (int i = size - 1; i >= 0; i--) {
ItemStack from = containerMgr.getItemStack(i);
if (from != null) {
// Move armor parts
Item fromItem = getItem(from);
if (isDamageable(fromItem)) {
if (sortArmorParts) {
if (isItemArmor(fromItem)) {
ItemArmor fromItemArmor = asItemArmor(fromItem);
if (globalContainer.hasSection(InvTweaksContainerSection.ARMOR)) {
List<Slot> armorSlots = globalContainer.getSlots(InvTweaksContainerSection.ARMOR);
for (Slot slot : armorSlots) {
boolean move = false;
if (!hasStack(slot)) {
move = true;
}
else {
int armorLevel = getArmorLevel(asItemArmor(getItem(getStack(slot))));
if (armorLevel < getArmorLevel(fromItemArmor)
|| (armorLevel == getArmorLevel(fromItemArmor)
&& getItemDamage(getStack(slot)) < getItemDamage(from))) {
move = true;
}
}
if (areSlotAndStackCompatible(slot, from) && move) {
globalContainer.move(InvTweaksContainerSection.INVENTORY, i, InvTweaksContainerSection.ARMOR,
globalContainer.getSlotIndex(getSlotNumber(slot)));
}
}
}
}
}
}
// Stackable objects are never damageable
else {
int j = 0;
for (Integer lockPriority : lockPriorities) {
if (lockPriority > 0) {
ItemStack to = containerMgr.getItemStack(j);
if (to != null && areItemsEqual(from, to)) {
move(i, j, Integer.MAX_VALUE);
markAsNotMoved(j);
if (containerMgr.getItemStack(i) == null) {
break;
}
}
}
j++;
}
}
}
}
}
//// Apply rules
log.info("Applying rules.");
// Sorts rule by rule, themselves being already sorted by decreasing priority
Iterator<InvTweaksConfigSortingRule> rulesIt = rules.iterator();
while (rulesIt.hasNext()) {
InvTweaksConfigSortingRule rule = rulesIt.next();
int rulePriority = rule.getPriority();
if (log.getLevel() == InvTweaksConst.DEBUG)
log.info("Rule : "+rule.getKeyword()+"("+rulePriority+")");
// For every item in the inventory
for (int i = 0; i < size; i++) {
ItemStack from = containerMgr.getItemStack(i);
// If the rule is strong enough to move the item and it matches the item, move it
if (hasToBeMoved(i) && lockPriorities[i] < rulePriority) {
List<InvTweaksItemTreeItem> fromItems = tree.getItems(
getItemID(from), getItemDamage(from));
if (tree.matches(fromItems, rule.getKeyword())) {
// Test preffered slots
int[] preferredSlots = rule.getPreferredSlots();
int stackToMove = i;
for (int j = 0; j < preferredSlots.length; j++) {
int k = preferredSlots[j];
// Move the stack!
int moveResult = move(stackToMove, k, rulePriority);
if (moveResult != -1) {
if (moveResult == k) {
break;
}
else {
from = containerMgr.getItemStack(moveResult);
fromItems = tree.getItems(getItemID(from), getItemDamage(from));
if (!tree.matches(fromItems, rule.getKeyword())) {
break;
}
else {
stackToMove = moveResult;
j = -1;
}
}
}
}
}
}
}
}
//// Don't move locked stacks
log.info("Locking stacks.");
for (int i = 0; i < size; i++) {
if (hasToBeMoved(i) && lockPriorities[i] > 0) {
markAsMoved(i, 1);
}
}
}
//// Sort remaining
defaultSorting();
if (log.getLevel() == InvTweaksConst.DEBUG) {
timer = System.nanoTime()-timer;
log.info("Sorting done in " + timer + "ns");
}
//// Put hold item down, just in case
if (getHeldStack() != null) {
int emptySlot = globalContainer.getFirstEmptyIndex(InvTweaksContainerSection.INVENTORY);
if (emptySlot != -1) {
globalContainer.putHoldItemDown(InvTweaksContainerSection.INVENTORY, emptySlot);
}
}
}
|
diff --git a/src/de/_13ducks/cor/game/networks/behaviour/impl/ServerBehaviourMove.java b/src/de/_13ducks/cor/game/networks/behaviour/impl/ServerBehaviourMove.java
index 76f7c91..a0c6497 100644
--- a/src/de/_13ducks/cor/game/networks/behaviour/impl/ServerBehaviourMove.java
+++ b/src/de/_13ducks/cor/game/networks/behaviour/impl/ServerBehaviourMove.java
@@ -1,179 +1,181 @@
/*
* Copyright 2008, 2009, 2010, 2011:
* Tobias Fleig (tfg[AT]online[DOT]de),
* Michael Haas (mekhar[AT]gmx[DOT]de),
* Johannes Kattinger (johanneskattinger[AT]gmx[DOT]de)
*
* - All rights reserved -
*
*
* This file is part of Centuries of Rage.
*
* Centuries of Rage 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.
*
* Centuries of Rage 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 Centuries of Rage. If not, see <http://www.gnu.org/licenses/>.
*
*/
package de._13ducks.cor.game.networks.behaviour.impl;
import de._13ducks.cor.game.FloatingPointPosition;
import de._13ducks.cor.networks.server.behaviour.ServerBehaviour;
import de._13ducks.cor.game.server.ServerCore;
import de._13ducks.cor.game.Unit;
import de._13ducks.cor.game.server.movement.Vector;
/**
* Lowlevel-Movemanagement
*
* Verwaltet die reine Bewegung einer einzelnen Einheit.
* Kümmert sich nicht weiter um Formationen/Kampf oder ähnliches.
* Erhält vom übergeordneten MidLevelManager einen Richtungsvektor und eine Zielkoordinate.
* Läuft dann dort hin. Tut sonst nichts.
* Hat exklusive Kontrolle über die Einheitenposition.
* Weigert sich, sich schneller als die maximale Einheitengeschwindigkeit zu bewegen.
* Dadurch werden Sprünge verhindert.
*/
public class ServerBehaviourMove extends ServerBehaviour {
private Unit caster2;
private FloatingPointPosition target;
private double speed;
private boolean stopUnit = false;
private long lastTick;
private Vector lastVec;
public ServerBehaviourMove(ServerCore.InnerServer newinner, Unit caster) {
super(newinner, caster, 1, 20, true);
caster2 = caster;
}
@Override
public void activate() {
active = true;
trigger();
}
@Override
public void deactivate() {
active = false;
}
@Override
public void execute() {
// Auto-Ende:
if (target == null || speed <= 0) {
deactivate();
return;
}
// Wir laufen also.
// Aktuelle Position berechnen:
- Vector vec = target.subtract(caster2.getPrecisePosition()).toVector();
- vec.normalize();
+ FloatingPointPosition oldPos = caster2.getPrecisePosition();
+ Vector vec = target.subtract(oldPos).toVector();
+ vec.normalizeMe();
if (!vec.equals(lastVec)) {
// An Client senden
rgi.netctrl.broadcastMoveVec(caster2.netID, target, speed);
- lastVec = vec;
+ lastVec = new Vector(vec.getX(), vec.getY());
}
long ticktime = System.currentTimeMillis();
vec.multiply((ticktime - lastTick) / 1000.0 * speed);
- FloatingPointPosition newpos = vec.toFloatingPointPosition();
+ FloatingPointPosition newpos = vec.toFloatingPointPosition().add(oldPos);
// Ziel schon erreicht?
Vector nextVec = target.subtract(newpos).toVector();
if (vec.isOpposite(nextVec)) {
// ZIEL!
// Wir sind warscheinlich drüber - egal einfach auf dem Ziel halten.
+ System.out.println("ZIEL");
caster2.setMainPosition(target);
target = null;
stopUnit = false; // Es ist wohl besser auf dem Ziel zu stoppen als kurz dahinter!
deactivate();
} else {
// Sofort stoppen?
if (stopUnit) {
caster2.setMainPosition(newpos);
target = null;
stopUnit = false;
deactivate();
} else {
// Weiterlaufen
caster2.setMainPosition(newpos);
lastTick = System.currentTimeMillis();
}
}
}
@Override
public void gotSignal(byte[] packet) {
}
@Override
public void pause() {
caster2.pause();
}
@Override
public void unpause() {
caster2.unpause();
}
/**
* Setzt den Zielvektor für diese Einheit.
* Es wird nicht untersucht, ob das Ziel in irgendeiner Weise ok ist, die Einheit beginnt sofort loszulaufen.
* In der Regel sollte noch eine Geschwindigkeit angegeben werden.
* Wehrt sich gegen nicht existente Ziele.
* @param pos die Zielposition, wird auf direktem Weg angesteuert.
*/
public void setTargetVector(FloatingPointPosition pos) {
if (pos == null) {
throw new IllegalArgumentException("Cannot send " + caster2 + " to null");
}
target = pos;
lastTick = System.currentTimeMillis();
lastVec = Vector.NULL;
activate();
}
/**
* Setzt den Zielvektor und die Geschwindigkeit und startet die Bewegung sofort.
* @param pos die Zielposition
* @param speed die Geschwindigkeit
*/
public void setTargetVector(FloatingPointPosition pos, double speed) {
changeSpeed(speed);
setTargetVector(pos);
}
/**
* Ändert die Geschwindigkeit während des Laufens.
* Speed wird verkleinert, wenn der Wert über dem Einheiten-Maximum liegen würde
* @param speed Die Einheitengeschwindigkeit
*/
public void changeSpeed(double speed) {
if (speed > 0 && speed <= caster2.getSpeed()) {
this.speed = speed;
}
trigger();
}
public boolean isMoving() {
return target != null;
}
/**
* Stoppt die Einheit innerhalb eines Ticks.
*/
public void stopImmediately() {
stopUnit = true;
trigger();
}
}
| false | true | public void execute() {
// Auto-Ende:
if (target == null || speed <= 0) {
deactivate();
return;
}
// Wir laufen also.
// Aktuelle Position berechnen:
Vector vec = target.subtract(caster2.getPrecisePosition()).toVector();
vec.normalize();
if (!vec.equals(lastVec)) {
// An Client senden
rgi.netctrl.broadcastMoveVec(caster2.netID, target, speed);
lastVec = vec;
}
long ticktime = System.currentTimeMillis();
vec.multiply((ticktime - lastTick) / 1000.0 * speed);
FloatingPointPosition newpos = vec.toFloatingPointPosition();
// Ziel schon erreicht?
Vector nextVec = target.subtract(newpos).toVector();
if (vec.isOpposite(nextVec)) {
// ZIEL!
// Wir sind warscheinlich drüber - egal einfach auf dem Ziel halten.
caster2.setMainPosition(target);
target = null;
stopUnit = false; // Es ist wohl besser auf dem Ziel zu stoppen als kurz dahinter!
deactivate();
} else {
// Sofort stoppen?
if (stopUnit) {
caster2.setMainPosition(newpos);
target = null;
stopUnit = false;
deactivate();
} else {
// Weiterlaufen
caster2.setMainPosition(newpos);
lastTick = System.currentTimeMillis();
}
}
}
| public void execute() {
// Auto-Ende:
if (target == null || speed <= 0) {
deactivate();
return;
}
// Wir laufen also.
// Aktuelle Position berechnen:
FloatingPointPosition oldPos = caster2.getPrecisePosition();
Vector vec = target.subtract(oldPos).toVector();
vec.normalizeMe();
if (!vec.equals(lastVec)) {
// An Client senden
rgi.netctrl.broadcastMoveVec(caster2.netID, target, speed);
lastVec = new Vector(vec.getX(), vec.getY());
}
long ticktime = System.currentTimeMillis();
vec.multiply((ticktime - lastTick) / 1000.0 * speed);
FloatingPointPosition newpos = vec.toFloatingPointPosition().add(oldPos);
// Ziel schon erreicht?
Vector nextVec = target.subtract(newpos).toVector();
if (vec.isOpposite(nextVec)) {
// ZIEL!
// Wir sind warscheinlich drüber - egal einfach auf dem Ziel halten.
System.out.println("ZIEL");
caster2.setMainPosition(target);
target = null;
stopUnit = false; // Es ist wohl besser auf dem Ziel zu stoppen als kurz dahinter!
deactivate();
} else {
// Sofort stoppen?
if (stopUnit) {
caster2.setMainPosition(newpos);
target = null;
stopUnit = false;
deactivate();
} else {
// Weiterlaufen
caster2.setMainPosition(newpos);
lastTick = System.currentTimeMillis();
}
}
}
|
diff --git a/org.eclipse.mylyn.commons.ui/src/org/eclipse/mylyn/internal/commons/ui/SectionComposite.java b/org.eclipse.mylyn.commons.ui/src/org/eclipse/mylyn/internal/commons/ui/SectionComposite.java
index 29639409..5f646a9d 100644
--- a/org.eclipse.mylyn.commons.ui/src/org/eclipse/mylyn/internal/commons/ui/SectionComposite.java
+++ b/org.eclipse.mylyn.commons.ui/src/org/eclipse/mylyn/internal/commons/ui/SectionComposite.java
@@ -1,114 +1,114 @@
/*******************************************************************************
* Copyright (c) 2010 Tasktop Technologies 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:
* Tasktop Technologies - initial API and implementation
*******************************************************************************/
package org.eclipse.mylyn.internal.commons.ui;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.layout.GridLayoutFactory;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.forms.events.ExpansionAdapter;
import org.eclipse.ui.forms.events.ExpansionEvent;
import org.eclipse.ui.forms.widgets.ExpandableComposite;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.SharedScrolledComposite;
/**
* @author Steffen Pingel
*/
public class SectionComposite extends SharedScrolledComposite {
FormToolkit toolkit;
public Composite content;
public SectionComposite(Composite parent, int style) {
super(parent, style | SWT.V_SCROLL);
addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
if (toolkit != null) {
toolkit.dispose();
toolkit = null;
}
}
});
content = new Composite(this, SWT.NONE);
content.setLayout(GridLayoutFactory.fillDefaults().create());
setContent(content);
content.setBackground(null);
setExpandVertical(true);
setExpandHorizontal(true);
}
@Override
public Composite getContent() {
return content;
}
public ExpandableComposite createSection(String title) {
return createSection(title, SWT.NONE, false);
}
public ExpandableComposite createSection(String title, int expansionStyle) {
return createSection(title, SWT.NONE, false);
}
public ExpandableComposite createSection(String title, int expansionStyle, final boolean grabExcessVerticalSpace) {
final ExpandableComposite section = getToolkit().createExpandableComposite(
getContent(),
ExpandableComposite.TWISTIE | ExpandableComposite.CLIENT_INDENT | ExpandableComposite.COMPACT
| expansionStyle);
section.titleBarTextMarginWidth = 0;
section.setBackground(null);
section.setFont(JFaceResources.getFontRegistry().getBold(JFaceResources.DIALOG_FONT));
section.addExpansionListener(new ExpansionAdapter() {
@Override
public void expansionStateChanged(ExpansionEvent e) {
if ((Boolean) e.data == true && grabExcessVerticalSpace) {
GridData g = (GridData) section.getLayoutData();
g.verticalAlignment = GridData.FILL;
g.grabExcessVerticalSpace = true;
section.setLayoutData(g);
} else {
GridData g = (GridData) section.getLayoutData();
g.verticalAlignment = GridData.BEGINNING;
g.grabExcessVerticalSpace = false;
section.setLayoutData(g);
}
+ layout(true);
reflow(true);
- section.getShell().pack();
}
});
section.setText(title);
if (content.getLayout() instanceof GridLayout) {
GridDataFactory.fillDefaults()
.indent(0, 5)
.grab(true, false)
.span(((GridLayout) content.getLayout()).numColumns, SWT.DEFAULT)
.applyTo(section);
}
return section;
}
public FormToolkit getToolkit() {
checkWidget();
if (toolkit == null) {
toolkit = new FormToolkit(CommonsUiPlugin.getDefault().getFormColors(getDisplay()));
}
return toolkit;
}
}
| false | true | public ExpandableComposite createSection(String title, int expansionStyle, final boolean grabExcessVerticalSpace) {
final ExpandableComposite section = getToolkit().createExpandableComposite(
getContent(),
ExpandableComposite.TWISTIE | ExpandableComposite.CLIENT_INDENT | ExpandableComposite.COMPACT
| expansionStyle);
section.titleBarTextMarginWidth = 0;
section.setBackground(null);
section.setFont(JFaceResources.getFontRegistry().getBold(JFaceResources.DIALOG_FONT));
section.addExpansionListener(new ExpansionAdapter() {
@Override
public void expansionStateChanged(ExpansionEvent e) {
if ((Boolean) e.data == true && grabExcessVerticalSpace) {
GridData g = (GridData) section.getLayoutData();
g.verticalAlignment = GridData.FILL;
g.grabExcessVerticalSpace = true;
section.setLayoutData(g);
} else {
GridData g = (GridData) section.getLayoutData();
g.verticalAlignment = GridData.BEGINNING;
g.grabExcessVerticalSpace = false;
section.setLayoutData(g);
}
reflow(true);
section.getShell().pack();
}
});
section.setText(title);
if (content.getLayout() instanceof GridLayout) {
GridDataFactory.fillDefaults()
.indent(0, 5)
.grab(true, false)
.span(((GridLayout) content.getLayout()).numColumns, SWT.DEFAULT)
.applyTo(section);
}
return section;
}
| public ExpandableComposite createSection(String title, int expansionStyle, final boolean grabExcessVerticalSpace) {
final ExpandableComposite section = getToolkit().createExpandableComposite(
getContent(),
ExpandableComposite.TWISTIE | ExpandableComposite.CLIENT_INDENT | ExpandableComposite.COMPACT
| expansionStyle);
section.titleBarTextMarginWidth = 0;
section.setBackground(null);
section.setFont(JFaceResources.getFontRegistry().getBold(JFaceResources.DIALOG_FONT));
section.addExpansionListener(new ExpansionAdapter() {
@Override
public void expansionStateChanged(ExpansionEvent e) {
if ((Boolean) e.data == true && grabExcessVerticalSpace) {
GridData g = (GridData) section.getLayoutData();
g.verticalAlignment = GridData.FILL;
g.grabExcessVerticalSpace = true;
section.setLayoutData(g);
} else {
GridData g = (GridData) section.getLayoutData();
g.verticalAlignment = GridData.BEGINNING;
g.grabExcessVerticalSpace = false;
section.setLayoutData(g);
}
layout(true);
reflow(true);
}
});
section.setText(title);
if (content.getLayout() instanceof GridLayout) {
GridDataFactory.fillDefaults()
.indent(0, 5)
.grab(true, false)
.span(((GridLayout) content.getLayout()).numColumns, SWT.DEFAULT)
.applyTo(section);
}
return section;
}
|
diff --git a/src/net/makeitonthe/GemXp/XpContainer.java b/src/net/makeitonthe/GemXp/XpContainer.java
index fa7a1f3..8aee25f 100644
--- a/src/net/makeitonthe/GemXp/XpContainer.java
+++ b/src/net/makeitonthe/GemXp/XpContainer.java
@@ -1,426 +1,427 @@
/**
* Small plugin to enable the storage of experience points in an item.
*
* Rewrite of the original PearlXP created by Nebual of nebtown.info in March 2012.
*
* rewrite by: Marex, Zonta.
*
* contact us at : [email protected]
*
* Copyright (C) 2012 belongs to their respective owners
*
* 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.makeitonthe.GemXp;
import java.util.LinkedList;
import java.util.List;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
public class XpContainer extends ItemStack {
/**
* Maximum storage capacity of a item
*/
public static int MAX_STORAGE = 32767; // Max of a short
/**
* Maximum possible tax
*/
public static double MAX_TAX = 99;
/**
* Display name text format
*/
public static String DISPLAY_NAME_FORMAT = "�o�f"; // remove italic + white
/**
* Lore text format
*/
public static String LORE_FORMAT = "�r�7"; // reset format + gray
private static int itemId;
private static int imbuedItemId;
private static int maxExp;
private static String itemName;
private static String itemHint;
private static double xpTax;
private static int stackSize;
private ItemStack itemStack;
public XpContainer(ItemStack stack) {
super(stack);
this.itemStack = stack;
}
/**
* Return true if the ItemStack has the capability of storing experience points
* @return true if it can store XP, false otherwise
*/
public static boolean isAnXpContainer(ItemStack stack) {
int itemId = 0;
boolean container = false;
if (stack != null) {
itemId = stack.getTypeId();
container = itemId == getImbuedItemId() || itemId == getItemId();
}
return container;
}
/**
* Return true if the ItemStack contains experience points
* @return true if it contain XP, false otherwise
*/
public static boolean isAFilledXpContainer(ItemStack stack) {
boolean container = false;
if (stack != null) {
container = (stack.getTypeId() == getImbuedItemId() && stack.getDurability() > 0);
}
return container;
}
/**
* Return true if the ItemStack has the capability of containing experience points
* @return true if it can contain XP, false otherwise
*/
public boolean canContainXp() {
return getTypeId() == getImbuedItemId();
}
/**
* Return true if the ItemStack has the capability of storing experience points
* @return true if it can store XP, false otherwise
*/
public boolean canStoreXp() {
return getTypeId() == getItemId();
}
/* (non-Javadoc)
* @see org.bukkit.inventory.ItemStack#clone()
*/
@Override
public XpContainer clone() {
return new XpContainer( new ItemStack(getItemStack()) );
}
/*
* (non-Javadoc)
* @see org.bukkit.inventory.ItemStack#getAmount()
*/
@Override
public int getAmount() {
return getItemStack().getAmount();
}
/*
* (non-Javadoc)
* @see org.bukkit.inventory.ItemStack#setAmount(int)
*/
@Override
public void setAmount(int i) {
getItemStack().setAmount(i);
}
/**
* Return the amount of experience points stored in the item
* @param item
* @return xp experience points
*/
public int getStoredXp() {
return getDurability();
}
/**
* Set the amount of stored experience points in the itemstack to xp (mutable)
* @param xp new stored experience points
* @param item ItemStack getting modified
*/
public void setStoredXp(int xp) {
// check for overflow
if (xp > getmaxExp()) {
xp = getmaxExp();
}
// Change appearance
if (xp == 0) {
resetContainer();
} else {
initContainer(xp);
}
// Change the stored xp
setDurability((short) xp);
}
/**
* @return the itemId used as the empty containers
*/
public static int getItemId() {
return itemId;
}
/**
* @return the ItemId used as the containers
*/
public static int getImbuedItemId() {
return imbuedItemId;
}
/**
* @return the maximum level cap of the containers
*/
public static int getmaxExp() {
return maxExp;
}
/**
* @return the stack
*/
public ItemStack getItemStack() {
return itemStack;
}
/**
* @return the xpTax
*/
public static double getXpTax() {
return xpTax;
}
/**
* @return the stackSize
*/
@Override
public int getMaxStackSize() {
int max;
if (canContainXp() && getStoredXp() > 0) {
//filled gems
max = stackSize;
} else {
//empty gems
max = getType().getMaxStackSize();
}
return max;
}
/**
* @return the itemName of the containers
*/
protected static String getItemName() {
return itemName;
}
/**
* @return the itemHint
*/
protected static String getItemHint() {
return itemHint;
}
/**
* @param imbuedItemId the imbuedItemId to set
*/
protected static void setImbuedItemId(int imbuedItemId) {
XpContainer.imbuedItemId = imbuedItemId;
}
/**
* @param itemId the itemId to set
*/
protected static void setItemId(int itemId) {
XpContainer.itemId = itemId;
}
/**
* @param maxExp the maximum experience points cap to set
*/
protected static boolean setMaxExp(int maxExp) {
boolean result = false;
// check if maxLevel fits in a short (2^15 - 1)
if (maxExp > MAX_STORAGE) {
XpContainer.maxExp = MAX_STORAGE;
} else {
XpContainer.maxExp = maxExp;
result = true;
}
return result;
}
/**
* @param itemName the itemName to set
*/
protected static void setItemName(String itemName) {
XpContainer.itemName = itemName;
}
/**
* @param itemHint the itemHint to set
*/
protected static void setItemHint(String itemHint) {
XpContainer.itemHint = itemHint;
}
/**
* @param xpTax the xpTax to set
*/
protected static void setXpTax(double xpTax) {
XpContainer.xpTax = xpTax;
}
/**
* @param maxStackSize the maxStackSize to set
*/
protected static void setMaxStackSize(int maxStackSize) {
XpContainer.stackSize = maxStackSize;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
boolean result = false;
if (this == obj)
return true;
if (getClass() != obj.getClass())
return false;
XpContainer other = (XpContainer) obj;
if (other.canContainXp() == this.canContainXp()
&& other.canStoreXp() == this.canStoreXp()
&& other.getStoredXp() == this.getStoredXp()) {
result = true;
}
return result;
}
/**
* Find first not full stack with the same property. Return null if nothing
* found.
*
* @param stack {@link XpContainer} with the property looking for
* @param inv inventory
* @return ItemStack found
*/
public XpContainer findSimilarStack(Inventory inv) {
return findSimilarStack(inv, 0, inv.getSize());
}
/**
* Find the first not full stack of XpContainer with the same property starting at start
* and ending at the index stop.
*
* @param stack {@link XpContainer} with the property looking for
* @param inv inventory
* @param start the index to start the search
* @param stop
* @return the XpContainer found or null if nothing found
*/
public XpContainer findSimilarStack(Inventory inv, int start, int stop) {
ItemStack[] items = inv.getContents();
XpContainer gem = null;
boolean found = false;
if (stop > items.length) stop = items.length;
for (int i = start; i < stop && !found; i++) {
if (items[i] != null) {
gem = new XpContainer(items[i]);
if (gem.getAmount() < gem.getMaxStackSize() && gem.equals(this)) {
found = true;
}
}
}
return found ? gem : null;
}
/**
* Prepare the container by changing is typeid, display name and adding a
* new lore indicating the stored experience points
*
* @param xp experience points stored in the container
*/
private void initContainer(int xp) {
ItemMeta itemMeta = this.getItemMeta();
List<String> lores = itemMeta.getLore();
String lore = LORE_FORMAT + getItemHint() + " " + xp + "xp";
// Change appearance and display name
setTypeId(getImbuedItemId());
itemMeta.setDisplayName(DISPLAY_NAME_FORMAT + getItemName());
// Add description
if (lores != null) {
lores.add(lore);
} else {
// If the list does'nt exist we create it
lores = new LinkedList<String>();
lores.add(lore);
}
+ itemMeta.setLore(lores);
this.setItemMeta(itemMeta);
}
/**
* Reset the appearance of the container
*/
private void resetContainer() {
ItemMeta itemMeta = this.getItemMeta();
// Change appearance
setTypeId(getItemId());
// Reset hints
itemMeta.setDisplayName(null);
itemMeta.setLore(null);
this.setItemMeta(itemMeta);
}
}
| true | true | private void initContainer(int xp) {
ItemMeta itemMeta = this.getItemMeta();
List<String> lores = itemMeta.getLore();
String lore = LORE_FORMAT + getItemHint() + " " + xp + "xp";
// Change appearance and display name
setTypeId(getImbuedItemId());
itemMeta.setDisplayName(DISPLAY_NAME_FORMAT + getItemName());
// Add description
if (lores != null) {
lores.add(lore);
} else {
// If the list does'nt exist we create it
lores = new LinkedList<String>();
lores.add(lore);
}
this.setItemMeta(itemMeta);
}
| private void initContainer(int xp) {
ItemMeta itemMeta = this.getItemMeta();
List<String> lores = itemMeta.getLore();
String lore = LORE_FORMAT + getItemHint() + " " + xp + "xp";
// Change appearance and display name
setTypeId(getImbuedItemId());
itemMeta.setDisplayName(DISPLAY_NAME_FORMAT + getItemName());
// Add description
if (lores != null) {
lores.add(lore);
} else {
// If the list does'nt exist we create it
lores = new LinkedList<String>();
lores.add(lore);
}
itemMeta.setLore(lores);
this.setItemMeta(itemMeta);
}
|
diff --git a/core/src/main/java/hudson/DescriptorExtensionList.java b/core/src/main/java/hudson/DescriptorExtensionList.java
index 65154c377..0856c686d 100644
--- a/core/src/main/java/hudson/DescriptorExtensionList.java
+++ b/core/src/main/java/hudson/DescriptorExtensionList.java
@@ -1,150 +1,150 @@
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, 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 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 hudson;
import hudson.model.Descriptor;
import hudson.model.Describable;
import hudson.model.Hudson;
import hudson.model.ViewDescriptor;
import hudson.model.Descriptor.FormException;
import hudson.util.Memoizer;
import hudson.slaves.NodeDescriptor;
import hudson.tasks.Publisher;
import hudson.tasks.Publisher.DescriptorExtensionListImpl;
import java.util.List;
import java.util.ArrayList;
import java.util.logging.Logger;
import java.util.concurrent.CopyOnWriteArrayList;
import java.lang.reflect.Type;
import java.lang.reflect.ParameterizedType;
import org.jvnet.tiger_types.Types;
import org.kohsuke.stapler.Stapler;
import net.sf.json.JSONObject;
/**
* {@link ExtensionList} for holding a set of {@link Descriptor}s, which is a group of descriptors for
* the same extension point.
*
* Use {@link Hudson#getDescriptorList(Class)} to obtain instances.
*
* @param <D>
* Represents the descriptor type. This is {@code Descriptor<T>} normally but often there are subtypes
* of descriptors, like {@link ViewDescriptor}, {@link NodeDescriptor}, etc, and this parameter points
* to those for better type safety of users.
*
* The actual value of 'D' is not necessary for the operation of this code, so it's purely for convenience
* of the users of this class.
*
* @since 1.286
*/
public class DescriptorExtensionList<T extends Describable<T>, D extends Descriptor<T>> extends ExtensionList<D> {
/**
* Creates a new instance.
*/
public static <T extends Describable<T>,D extends Descriptor<T>>
DescriptorExtensionList<T,D> create(Hudson hudson, Class<T> describableType) {
if(describableType==(Class)Publisher.class) // javac or IntelliJ compiler complains if I don't have this cast
return (DescriptorExtensionList)new DescriptorExtensionListImpl(hudson);
return new DescriptorExtensionList<T,D>(hudson,describableType);
}
/**
* Type of the {@link Describable} that this extension list retains.
*/
private final Class<T> describableType;
protected DescriptorExtensionList(Hudson hudson, Class<T> describableType) {
super(hudson, (Class)Descriptor.class, legacyDescriptors.get(describableType));
this.describableType = describableType;
}
/**
* Finds the descriptor that has the matching fully-qualified class name.
*
* @param fqcn
* Fully qualified name of the descriptor, not the describable.
*/
public D find(String fqcn) {
return Descriptor.find(this,fqcn);
}
/**
* Creates a new instance of a {@link Describable}
* from the structured form submission data posted
* by a radio button group.
*/
public T newInstanceFromRadioList(JSONObject config) throws FormException {
if(config.isNullObject())
return null; // none was selected
int idx = config.getInt("value");
return get(idx).newInstance(Stapler.getCurrentRequest(),config);
}
public T newInstanceFromRadioList(JSONObject parent, String name) throws FormException {
return newInstanceFromRadioList(parent.getJSONObject(name));
}
/**
* Finds a descriptor by their {@link Descriptor#clazz}.
*
* If none is found, null is returned.
*/
public Descriptor<T> findByName(String fullyQualifiedClassName) {
for (Descriptor<T> d : this)
if(d.clazz.getName().equals(fullyQualifiedClassName))
return d;
return null;
}
/**
* Loading the descriptors in this case means filtering the descriptor from the master {@link ExtensionList}.
*/
@Override
protected List<D> load() {
List r = new ArrayList();
for( Descriptor d : hudson.getExtensionList(Descriptor.class) ) {
Type subTyping = Types.getBaseClass(d.getClass(), Descriptor.class);
if (!(subTyping instanceof ParameterizedType)) {
LOGGER.severe(d.getClass()+" doesn't extend Descriptor with a type parameter");
continue; // skip this one
}
- if(Types.getTypeArgument(subTyping,0)==describableType)
+ if(Types.erasure(Types.getTypeArgument(subTyping,0))==(Class)describableType)
r.add(d);
}
return r;
}
/**
* Stores manually registered Descriptor instances.
*/
private static final Memoizer<Class,CopyOnWriteArrayList> legacyDescriptors = new Memoizer<Class,CopyOnWriteArrayList>() {
public CopyOnWriteArrayList compute(Class key) {
return new CopyOnWriteArrayList();
}
};
private static final Logger LOGGER = Logger.getLogger(DescriptorExtensionList.class.getName());
}
| true | true | protected List<D> load() {
List r = new ArrayList();
for( Descriptor d : hudson.getExtensionList(Descriptor.class) ) {
Type subTyping = Types.getBaseClass(d.getClass(), Descriptor.class);
if (!(subTyping instanceof ParameterizedType)) {
LOGGER.severe(d.getClass()+" doesn't extend Descriptor with a type parameter");
continue; // skip this one
}
if(Types.getTypeArgument(subTyping,0)==describableType)
r.add(d);
}
return r;
}
| protected List<D> load() {
List r = new ArrayList();
for( Descriptor d : hudson.getExtensionList(Descriptor.class) ) {
Type subTyping = Types.getBaseClass(d.getClass(), Descriptor.class);
if (!(subTyping instanceof ParameterizedType)) {
LOGGER.severe(d.getClass()+" doesn't extend Descriptor with a type parameter");
continue; // skip this one
}
if(Types.erasure(Types.getTypeArgument(subTyping,0))==(Class)describableType)
r.add(d);
}
return r;
}
|
diff --git a/seqware-queryengine/src/main/java/com/github/seqware/queryengine/system/importers/workers/VCFVariantImportWorker.java b/seqware-queryengine/src/main/java/com/github/seqware/queryengine/system/importers/workers/VCFVariantImportWorker.java
index 6a785004..ad6dbd30 100644
--- a/seqware-queryengine/src/main/java/com/github/seqware/queryengine/system/importers/workers/VCFVariantImportWorker.java
+++ b/seqware-queryengine/src/main/java/com/github/seqware/queryengine/system/importers/workers/VCFVariantImportWorker.java
@@ -1,520 +1,520 @@
package com.github.seqware.queryengine.system.importers.workers;
import com.esotericsoftware.minlog.Log;
import com.github.seqware.queryengine.Constants;
import com.github.seqware.queryengine.factory.CreateUpdateManager;
import com.github.seqware.queryengine.factory.SWQEFactory;
import com.github.seqware.queryengine.impl.HBaseStorage;
import com.github.seqware.queryengine.model.Feature;
import com.github.seqware.queryengine.model.FeatureSet;
import com.github.seqware.queryengine.model.Tag;
import com.github.seqware.queryengine.model.TagSet;
import com.github.seqware.queryengine.system.importers.FeatureImporter;
import com.github.seqware.queryengine.system.importers.SOFeatureImporter;
import com.github.seqware.queryengine.util.SGID;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.compress.compressors.CompressorException;
import org.apache.commons.compress.compressors.CompressorStreamFactory;
import org.apache.log4j.Logger;
//import net.sourceforge.seqware.queryengine.backend.model.Coverage;
//import net.sourceforge.seqware.queryengine.backend.model.Variant;
/**
* Ported VCFVariantImportWorker now using our Hibernate-like entry. Hopefully
* this doesn't slow things down too much. Not tested yet.
*
* @author boconnor
* @author dyuen
*
* TODO: Variant is now our Feature. Coverage does not seem to be in use anyways
*
* FIXME: need to support indels FIXME: need to support alternative alleles,
* each should get its own variant object I think
* @version $Id: $Id
*/
public class VCFVariantImportWorker extends ImportWorker {
/** Constant <code>SECONDARY_INDEX="sIndex.out"</code> */
public static final String SECONDARY_INDEX = "sIndex.out";
/** Constant <code>VCF="VCF"</code> */
public static final String VCF = "VCF";
private CreateUpdateManager modelManager;
private List<TagSet> potentialTagSets = new ArrayList<TagSet>();
private TagSet adHocSet;
private Map<String, Tag> localCache = new HashMap<String, Tag>();
private PrintWriter out = null;
private TagSet vcfTagSet = null;
private boolean warnedAboutIDs = false;
/**
* <p>Constructor for VCFVariantImportWorker.</p>
*/
public VCFVariantImportWorker() {
if (SOFeatureImporter.SECONDARY_INDEX_HACK) {
try {
out = new PrintWriter(new BufferedWriter(new FileWriter(SECONDARY_INDEX, true)));
} catch (IOException ex) {
Logger.getLogger(VCFVariantImportWorker.class.getName()).fatal(null, ex);
System.exit(FeatureImporter.EXIT_CODE_INVALID_ARGS);
}
}
}
public Tag getTagSpec(String key){
return getTagSpec(key, null);
}
/**
* Given a key, locate a potential match inside a list of tag sets,
* otherwise create a new one in the ad hoc set.
*
* Looking through full list each time is slow, using a local cache
*
* @param key a {@link java.lang.String} object.
* @return a {@link com.github.seqware.queryengine.model.Tag} object.
*/
public Tag getTagSpec(String key, String value) {
if (!Constants.TRACK_TAGSET){
Tag.Builder builder = Tag.newBuilder().setKey(key);
if (value != null){
builder.setValue(value);
}
return builder.build();
}
Logger.getLogger(VCFVariantImportWorker.class.getName()).trace("getTagSpec() called on " + key);
// check local cache first
if (this.localCache.containsKey(key)) {
Logger.getLogger(VCFVariantImportWorker.class.getName()).trace(key + " found in localCache ");
return this.localCache.get(key);
}
for (TagSet set : this.potentialTagSets) {
if (set.containsKey(key)) {
Logger.getLogger(VCFVariantImportWorker.class.getName()).trace(key + " found in provided set " + set.getSGID().getRowKey());
Tag tagByKey = set.get(key);
this.localCache.put(key, tagByKey);
return tagByKey;
}
}
Logger.getLogger(VCFVariantImportWorker.class.getName()).trace(key + " not found in potential tag sets");
if (adHocSet.containsKey(key)) {
Logger.getLogger(VCFVariantImportWorker.class.getName()).trace(key + " found in ad hoc tag set " + adHocSet.getSGID().getRowKey());
Tag tagByKey = adHocSet.get(key);
this.localCache.put(key, tagByKey);
return tagByKey;
} else {
Logger.getLogger(VCFVariantImportWorker.class.getName()).trace(key + " added to ad hoc tag set");
Tag build = modelManager.buildTag().setKey(key).build();
adHocSet.add(build);
this.localCache.put(key, build);
return build;
}
}
/**
* <p>processVCFTagSpec.</p>
*
* @param key a {@link java.lang.String} object.
* @param tagset a {@link com.github.seqware.queryengine.model.TagSet} object.
* @param modelManager a {@link com.github.seqware.queryengine.factory.CreateUpdateManager} object.
* @return a {@link com.github.seqware.queryengine.model.Tag} object.
*/
public static Tag processVCFTagSpec(String key, String value, TagSet tagset, CreateUpdateManager modelManager) {
if (!Constants.TRACK_TAGSET){
Tag.Builder builder = Tag.newBuilder().setKey(key);
if (value != null) {
builder.setValue(value);
}
return builder.build();
}
Logger.getLogger(VCFVariantImportWorker.class.getName()).trace("processVCFTagSpec() called on " + key);
if (tagset.containsKey(key)) {
Logger.getLogger(VCFVariantImportWorker.class.getName()).trace(key + " found in VCF set " + tagset.getSGID().getRowKey());
Tag tagByKey = tagset.get(key);
return tagByKey;
}
Logger.getLogger(VCFVariantImportWorker.class.getName()).trace(key + " not found in potential tag sets, adding to VCF tag set");
Tag build = modelManager.buildTag().setKey(key).setValue(value).build();
tagset.add(build);
return build;
}
/** {@inheritDoc} */
@Override
public void run() {
// grab FeatureSet reference
// FeatureSets are totally new, hope this doesn't slow things too much
FeatureSet fSet = SWQEFactory.getQueryInterface().getAtomBySGID(FeatureSet.class, this.featureSetID);
this.modelManager = SWQEFactory.getModelManager();
modelManager.persist(fSet);
if (Constants.TRACK_TAGSET) {
// setup the "VCF" TagSet
this.vcfTagSet = SWQEFactory.getQueryInterface().getLatestAtomByRowKey(VCF, TagSet.class);
if (vcfTagSet == null) {
vcfTagSet = modelManager.buildTagSet().setName(VCF).setFriendlyRowKey(VCF).build();
this.potentialTagSets.add(vcfTagSet);
}
// process potential tag sets
if (this.getTagSetIDs() != null) {
for (SGID tagSetID : this.getTagSetIDs()) {
this.potentialTagSets.add(SWQEFactory.getQueryInterface().getLatestAtomBySGID(tagSetID, TagSet.class));
}
}
this.adHocSet = SWQEFactory.getQueryInterface().getLatestAtomBySGID(this.getAdhoctagset(), TagSet.class);
modelManager.persist(adHocSet);
}
// open the file
BufferedReader inputStream;
try {
// first ask for a token from semaphore
//pmi.getLock();
// Attempting to guess the file format
if (compressed) {
inputStream = handleCompressedInput(input);
} else {
inputStream = new BufferedReader(new FileReader(input));
}
String l;
//Variant m = new Variant();
Feature.Builder fBuilder = modelManager.buildFeature();
// Coverage c = null;
// int currBin = 0;
int count = 0;
// String previousPos = null;
// Pattern p = Pattern.compile("-([ATGCNatgcn]+)");
while ((l = inputStream.readLine()) != null) {
// try to tag our dataset with feature set wide tags
if (l.contains(SOFeatureImporter.PRAGMA_QE_TAG_FORMAT)){
- String[] parts = l.split(SOFeatureImporter.PRAGMA_QE_TAG_FORMAT);
+ String[] parts = l.split(SOFeatureImporter.PRAGMA_QE_TAG_FORMAT+"=");
String tag = parts[parts.length-1];
String[] tagParts = tag.split("=");
assert(tagParts.length == 2);
Tag featureTag = Tag.newBuilder().setKey(tagParts[0]).setValue(tagParts[1]).build();
fSet.associateTag(featureTag);
}
// display progress
count++;
// we need to flush and clear the manager in order to release the memory consumed by the Features themselves
// the featureSet has to be reattached
if (count % this.getBatch_size() == 0) {
modelManager.flush();
modelManager.clear();
if (Constants.TRACK_TAGSET){
modelManager.persist(adHocSet);
}
modelManager.persist(fSet);
}
// ignore commented lines
if (!l.startsWith("#")) {
if (Constants.OUTPUT_METRICS){
Logger.getLogger(HBaseStorage.class.getName()).info("Line " + count + " is " + l.getBytes().length + " bytes long");
}
// pileup string
String[] t = l.split("\t+");
// load the variant object
//m.setContig(t[0]);
fBuilder.setSeqid(t[0]);
// should not rename this actually
// if (!".".equals(t[0]) && !t[0].startsWith("chr")) {
// //m.setContig("chr" + t[0]);
// fBuilder.setSeqid("chr" + t[0]);
// }
// cache our tags till our message is built
Set<Tag> setOfTags = new HashSet<Tag>();
HashMap<String, String> strTags = new HashMap<String, String>();
//TODO: link this up with proper TagSets, these are ad hoc tags
//tagSet.add(Tag.newBuilder().setKey(t[0]).build());
//setOfTags.add(getTagSpec(t[0]));
//m.addTag(t[0], null);
// referenceBase, consensusBase, and calledBase can be ad hoc tags for now
//setOfTags.add(processVCFTagSpec(ImportConstants.VCF_REFERENCE_BASE, t[3].toUpperCase()));
strTags.put(ImportConstants.VCF_REFERENCE_BASE, t[3].toUpperCase());
//setOfTags.add(processVCFTagSpec(ImportConstants.VCF_CONSENSUS_BASE, t[4].toUpperCase()));
//Tag calledTag = processVCFTagSpec(ImportConstants.VCF_CALLED_BASE,t[4].toUpperCase());
//setOfTags.add(calledTag);
strTags.put(ImportConstants.VCF_CALLED_BASE,t[4].toUpperCase());
//m.setReferenceBase(t[3].toUpperCase());
//m.setConsensusBase(t[4].toUpperCase());
//m.setCalledBase(t[4].toUpperCase());
// figure out the consensusCallQuality
if (!".".equals(t[5])) {
fBuilder.setScore(Double.parseDouble(t[5]));
}
//m.setConsensusCallQuality(Float.parseFloat(t[5]));
// parse ID
if (!".".equals(t[2])) {
//setOfTags.add(processVCFTagSpec(ImportConstants.VCF_SECOND_ID,t[2]));
strTags.put(ImportConstants.VCF_SECOND_ID,t[2]);
//m.addTag("ID", t[2]);
}
// This had to be removed when adding tag support, adding every ID field as a tag would effectviely blow out our ad hoc tag sets to the size of a FeatureSet which
// is not currently feasible
// if (!".".equals(t[2])) {
// setOfTags.add(getTagSpec(t[2]).toBuilder().build());
// //m.addTag(t[2], null);
// }
// FIXME: only supports two alleles for now, see http://users.ox.ac.uk/~linc1775/blueprint.htm
// if there are multiple alleles then both the consensus and called bases should be
String calledBase = t[4].toUpperCase() /**
* m.getCalledBase()
*/
;
if (t[4].toUpperCase().length() > 1 && t[4].toUpperCase().contains(",")) {
//setOfTags.remove(calledTag);
if ("C,A".equals(calledBase) || "A,C".equals(calledBase)) {
calledBase = "M";
} else if ("A,G".equals(calledBase) || "G,A".equals(calledBase)) {
calledBase = "R";
} else if ("A,T".equals(calledBase) || "T,A".equals(calledBase)) {
calledBase = "W";
} else if ("C,G".equals(calledBase) || "G,C".equals(calledBase)) {
calledBase = "S";
} else if ("C,T".equals(calledBase) || "T,C".equals(calledBase)) {
calledBase = "Y";
} else if ("G,T".equals(calledBase) || "T,G".equals(calledBase)) {
calledBase = "K";
} else {
// this doesn't work when consensus base comes back like:
// TGCACGTCA,TAA
//throw new Exception("Don't know what "+m.getReferenceBase()+"->"+m.getConsensusBase()+" is!!!");
}
//calledTag = processVCFTagSpec(ImportConstants.VCF_CALLED_BASE, calledBase);
//setOfTags.add(calledTag);
strTags.put(ImportConstants.VCF_CALLED_BASE, calledBase);
//m.setCalledBase(calledBase);
// leave the consensus base as the original call syntax from the VCF file
}
/*
* I've seen another alternative way of representing alleles
* where the FQ and AF1 can be used to caall homozygous From
* http://seqanswers.com/forums/showthread.php?t=11651 In
* English, the first line means "check the FQ"; the FQ is
* negative when the SNP is homozygous, and positive when
* it's mixed, and the bigger the absolute value, the more
* confident the SNP.
*
* So if it's < 0, it does the first part of code (it checks
* against the AF1, and if the AF1 is > 0.5, which it should
* be for a homozygous SNP, it sets $b as the alternate
* letter, if for some reason the AF1 is < .5, it sets $b as
* the old reference letter.)
*
* If the FQ is positive, then the SNP should be mixed, and
* it concatenates the two letters, and checks the hash
* above to know what single letter to set $b to. Then it
* adds $b to the growing sequence.
*
* $q, which is derived from the FQ, ends up being the
* quality score, though it gets tweaked a little; it adds
* 33.449 to the figure, then converts it to a letter,
* capping it at a quality of 126.
*
* $q = int($q + 33 + .499); $q = chr($q <= 126? $q : 126);
*
* Gaps are handled as they were in the old program, where
* they are NOT added in, there is just a window of
* lowercase letters around them. Personally, I made a
* little perl script, and I feed it the genome, and a
* conservatively filtered list of SNPs, and I put the
* changes in that way.
*/
// FIXME: hard-coded for now
fBuilder.setType(ImportConstants.VCF_SNV);
//m.setType(Variant.SNV);
// always save a tag
//setOfTags.add(processVCFTagSpec(ImportConstants.VCF_SNV));
//m.addTag("SNV", null);
if (!".".equals(t[1])) {
Integer pos = Integer.parseInt(t[1]);
fBuilder.setStart(pos - 1);
fBuilder.setStop(pos);
}
//m.setStartPosition(pos - 1);
//m.setStopPosition(pos);
// now parse field 6
//setOfTags.add(processVCFTagSpec(ImportConstants.VCF_FILTER,t[6]));
strTags.put(ImportConstants.VCF_FILTER,t[6]);
//m.addTag(t[6], null);
// added to prototype, record the info field
// don't record the field as a whole, this is useless and big
//setOfTags.add(processVCFTagSpec(ImportConstants.VCF_INFO).toBuilder().setValue(t[7]).build());
// if FQ is < 0 and AF1 < 0.5 then the algorithm is calling homozygous reference so skip
boolean af1LtHalf = false;
boolean fqLt0 = false;
String[] tags = t[7].split(";");
for (String tag : tags) {
if (tag.contains("=")) {
String[] kv = tag.split("=");
strTags.put(kv[0],kv[1]);
//setOfTags.add(getTagSpec(kv[0],kv[1]));
//m.addTag(kv[0], kv[1]);
if ("DP".equals(kv[0])) {
//setOfTags.add(processVCFTagSpec(ImportConstants.VCF_READ_COUNTS,kv[1]));
strTags.put(ImportConstants.VCF_READ_COUNTS,kv[1]);
//m.setReadCount(Integer.parseInt(kv[1]));
}
// see above
if ("FQ".equals(kv[0])) {
float fq = Float.parseFloat(kv[1]);
if (fq < 0) {
//setOfTags.add(processVCFTagSpec(ImportConstants.VCF_HOMOZYGOUS));
strTags.put(ImportConstants.VCF_HOMOZYGOUS, null);
//m.setZygosity(m.VCF_HOMOZYGOUS);
//m.getTags().put("homozygous", null);
fqLt0 = true;
} else {
//setOfTags.add(processVCFTagSpec(ImportConstants.VCF_HETEROZYGOUS));
strTags.put(ImportConstants.VCF_HETEROZYGOUS, null);
//m.setZygosity(m.VCF_HETEROZYGOUS);
//m.getTags().put("heterozygous", null);
}
}
if ("AF1".equals(kv[0])) {
float af1 = Float.parseFloat(kv[1]);
if (af1 < 0.5) {
af1LtHalf = true;
}
}
} else {
// in a file provided, the ID is added as a tag, blowing up our ad hoc tag sets and crashing the region server
// if it is not allocated much memory
if (tag.equals(t[2])) {
if (!this.warnedAboutIDs){
Log.warn("Detected that the ID column is duplicated in the INFO column, skipping: " + tag);
this.warnedAboutIDs = true;
}
} else {
// this is dangerous because it could add an arbitrary number of additional Tags,
// but we need it for testing dbSNP
//setOfTags.add(getTagSpec(tag));
strTags.put(tag, null);
//m.addTag(tag, null);
}
}
}
// yet another way to encode hom/het
// FIXME: this doesn't conform to the standard
if (t.length > 9 && t[8].contains("GT") && t[9].contains("het")) {
///////////////setOfTags.add(processVCFTagSpec(ImportConstants.VCF_HETEROZYGOUS));
//m.setZygosity(m.VCF_HETEROZYGOUS);
//m.getTags().put("heterozygous", null);
} else if (t.length > 9 && t[8].contains("GT") && t[9].contains("hom")) {
/////////////////setOfTags.add(processVCFTagSpec(ImportConstants.VCF_HOMOZYGOUS));
//m.setZygosity(m.VCF_HOMOZYGOUS);
//m.getTags().put("homozygous", null);
}
// if this is true then it's just being called homozygous reference so don't even store
if (af1LtHalf && fqLt0) {
System.out.println("Dropping variant because FQ < 0 and AF1 < 0.5!");
} else {
// our equivalent of store is just making the model manager aware of this by building it
Feature build = fBuilder.build();
/*for (Tag tag : setOfTags) {
build.associateTag(tag);
}*/
for (String key : strTags.keySet()) {
build.fastAssociateTag(key, strTags.get(key));
}
//store.putMismatch(m);
// this is new, add it to a featureSet
fSet.add(build);
// if we use this, we will need to specify a tagset as well
// // hack to spit out secondary index
// if (SOFeatureImporter.SECONDARY_INDEX_HACK){
// if (build.getTagByKey(keyIndex) != null){
// FSGID fsgid = (FSGID) build.getSGID();
// FSGIDPB m2pb = FSGIDIO.m2pb(fsgid);
// String message = TextFormat.printToString(m2pb);
// out.print(message);
// out.println("!");
// }
// }
if (count % this.getBatch_size() == 0) {
System.out.println(new Date().toString() + workerName + " adding mismatch to db: " + build.getSeqid() + ":" + build.getStart() + "-" + build.getStop() + " total records added: " + build.getSeqid() + " total lines so far: " + count);
}
}
// if (count % 10000 == 0) {
// System.out.println(workerName + ": adding mismatch to db: " + m.getContig() + ":" + m.getStartPosition() + "-" + m.getStopPosition()
// + " total records added: " + m.getSeqid() + " total lines so far: " + count);
// }
// now prepare for next mismatch
fBuilder = modelManager.buildFeature();
//m = new Variant();
}
}
if (SOFeatureImporter.SECONDARY_INDEX_HACK) {
out.close();
}
// close file
inputStream.close();
} catch (Exception e) {
Logger.getLogger(VCFVariantImportWorker.class.getName()).fatal("Exception thrown with file: " + input, e);
//e.printStackTrace();
throw new RuntimeException("Error in VCRVariantImportWorker");
} finally {
// new, this is needed to have the model manager write results to the DB in one big batch
modelManager.close();
//pmi.releaseLock();
}
}
/**
* <p>handleCompressedInput.</p>
*
* @param input a {@link java.lang.String} object.
* @return a {@link java.io.BufferedReader} object.
* @throws org.apache.commons.compress.compressors.CompressorException if any.
* @throws java.io.FileNotFoundException if any.
*/
public static BufferedReader handleCompressedInput(String input) throws CompressorException, FileNotFoundException {
BufferedReader inputStream;
if (input.endsWith("bz2") || input.endsWith("bzip2")) {
inputStream = new BufferedReader(new InputStreamReader(new CompressorStreamFactory().createCompressorInputStream("bzip2", new BufferedInputStream(new FileInputStream(input)))));
} else if (input.endsWith("gz") || input.endsWith("gzip")) {
inputStream = new BufferedReader(new InputStreamReader(new CompressorStreamFactory().createCompressorInputStream("gz", new BufferedInputStream(new FileInputStream(input)))));
} else {
throw new RuntimeException("Don't know how to interpret the filename extension for: " + input + " we support 'bz2', 'bzip2', 'gz', and 'gzip'");
}
return inputStream;
}
}
| true | true | public void run() {
// grab FeatureSet reference
// FeatureSets are totally new, hope this doesn't slow things too much
FeatureSet fSet = SWQEFactory.getQueryInterface().getAtomBySGID(FeatureSet.class, this.featureSetID);
this.modelManager = SWQEFactory.getModelManager();
modelManager.persist(fSet);
if (Constants.TRACK_TAGSET) {
// setup the "VCF" TagSet
this.vcfTagSet = SWQEFactory.getQueryInterface().getLatestAtomByRowKey(VCF, TagSet.class);
if (vcfTagSet == null) {
vcfTagSet = modelManager.buildTagSet().setName(VCF).setFriendlyRowKey(VCF).build();
this.potentialTagSets.add(vcfTagSet);
}
// process potential tag sets
if (this.getTagSetIDs() != null) {
for (SGID tagSetID : this.getTagSetIDs()) {
this.potentialTagSets.add(SWQEFactory.getQueryInterface().getLatestAtomBySGID(tagSetID, TagSet.class));
}
}
this.adHocSet = SWQEFactory.getQueryInterface().getLatestAtomBySGID(this.getAdhoctagset(), TagSet.class);
modelManager.persist(adHocSet);
}
// open the file
BufferedReader inputStream;
try {
// first ask for a token from semaphore
//pmi.getLock();
// Attempting to guess the file format
if (compressed) {
inputStream = handleCompressedInput(input);
} else {
inputStream = new BufferedReader(new FileReader(input));
}
String l;
//Variant m = new Variant();
Feature.Builder fBuilder = modelManager.buildFeature();
// Coverage c = null;
// int currBin = 0;
int count = 0;
// String previousPos = null;
// Pattern p = Pattern.compile("-([ATGCNatgcn]+)");
while ((l = inputStream.readLine()) != null) {
// try to tag our dataset with feature set wide tags
if (l.contains(SOFeatureImporter.PRAGMA_QE_TAG_FORMAT)){
String[] parts = l.split(SOFeatureImporter.PRAGMA_QE_TAG_FORMAT);
String tag = parts[parts.length-1];
String[] tagParts = tag.split("=");
assert(tagParts.length == 2);
Tag featureTag = Tag.newBuilder().setKey(tagParts[0]).setValue(tagParts[1]).build();
fSet.associateTag(featureTag);
}
// display progress
count++;
// we need to flush and clear the manager in order to release the memory consumed by the Features themselves
// the featureSet has to be reattached
if (count % this.getBatch_size() == 0) {
modelManager.flush();
modelManager.clear();
if (Constants.TRACK_TAGSET){
modelManager.persist(adHocSet);
}
modelManager.persist(fSet);
}
// ignore commented lines
if (!l.startsWith("#")) {
if (Constants.OUTPUT_METRICS){
Logger.getLogger(HBaseStorage.class.getName()).info("Line " + count + " is " + l.getBytes().length + " bytes long");
}
// pileup string
String[] t = l.split("\t+");
// load the variant object
//m.setContig(t[0]);
fBuilder.setSeqid(t[0]);
// should not rename this actually
// if (!".".equals(t[0]) && !t[0].startsWith("chr")) {
// //m.setContig("chr" + t[0]);
// fBuilder.setSeqid("chr" + t[0]);
// }
// cache our tags till our message is built
Set<Tag> setOfTags = new HashSet<Tag>();
HashMap<String, String> strTags = new HashMap<String, String>();
//TODO: link this up with proper TagSets, these are ad hoc tags
//tagSet.add(Tag.newBuilder().setKey(t[0]).build());
//setOfTags.add(getTagSpec(t[0]));
//m.addTag(t[0], null);
// referenceBase, consensusBase, and calledBase can be ad hoc tags for now
//setOfTags.add(processVCFTagSpec(ImportConstants.VCF_REFERENCE_BASE, t[3].toUpperCase()));
strTags.put(ImportConstants.VCF_REFERENCE_BASE, t[3].toUpperCase());
//setOfTags.add(processVCFTagSpec(ImportConstants.VCF_CONSENSUS_BASE, t[4].toUpperCase()));
//Tag calledTag = processVCFTagSpec(ImportConstants.VCF_CALLED_BASE,t[4].toUpperCase());
//setOfTags.add(calledTag);
strTags.put(ImportConstants.VCF_CALLED_BASE,t[4].toUpperCase());
//m.setReferenceBase(t[3].toUpperCase());
//m.setConsensusBase(t[4].toUpperCase());
//m.setCalledBase(t[4].toUpperCase());
// figure out the consensusCallQuality
if (!".".equals(t[5])) {
fBuilder.setScore(Double.parseDouble(t[5]));
}
//m.setConsensusCallQuality(Float.parseFloat(t[5]));
// parse ID
if (!".".equals(t[2])) {
//setOfTags.add(processVCFTagSpec(ImportConstants.VCF_SECOND_ID,t[2]));
strTags.put(ImportConstants.VCF_SECOND_ID,t[2]);
//m.addTag("ID", t[2]);
}
// This had to be removed when adding tag support, adding every ID field as a tag would effectviely blow out our ad hoc tag sets to the size of a FeatureSet which
// is not currently feasible
// if (!".".equals(t[2])) {
// setOfTags.add(getTagSpec(t[2]).toBuilder().build());
// //m.addTag(t[2], null);
// }
// FIXME: only supports two alleles for now, see http://users.ox.ac.uk/~linc1775/blueprint.htm
// if there are multiple alleles then both the consensus and called bases should be
String calledBase = t[4].toUpperCase() /**
* m.getCalledBase()
*/
;
if (t[4].toUpperCase().length() > 1 && t[4].toUpperCase().contains(",")) {
//setOfTags.remove(calledTag);
if ("C,A".equals(calledBase) || "A,C".equals(calledBase)) {
calledBase = "M";
} else if ("A,G".equals(calledBase) || "G,A".equals(calledBase)) {
calledBase = "R";
} else if ("A,T".equals(calledBase) || "T,A".equals(calledBase)) {
calledBase = "W";
} else if ("C,G".equals(calledBase) || "G,C".equals(calledBase)) {
calledBase = "S";
} else if ("C,T".equals(calledBase) || "T,C".equals(calledBase)) {
calledBase = "Y";
} else if ("G,T".equals(calledBase) || "T,G".equals(calledBase)) {
calledBase = "K";
} else {
// this doesn't work when consensus base comes back like:
// TGCACGTCA,TAA
//throw new Exception("Don't know what "+m.getReferenceBase()+"->"+m.getConsensusBase()+" is!!!");
}
//calledTag = processVCFTagSpec(ImportConstants.VCF_CALLED_BASE, calledBase);
//setOfTags.add(calledTag);
strTags.put(ImportConstants.VCF_CALLED_BASE, calledBase);
//m.setCalledBase(calledBase);
// leave the consensus base as the original call syntax from the VCF file
}
/*
* I've seen another alternative way of representing alleles
* where the FQ and AF1 can be used to caall homozygous From
* http://seqanswers.com/forums/showthread.php?t=11651 In
* English, the first line means "check the FQ"; the FQ is
* negative when the SNP is homozygous, and positive when
* it's mixed, and the bigger the absolute value, the more
* confident the SNP.
*
* So if it's < 0, it does the first part of code (it checks
* against the AF1, and if the AF1 is > 0.5, which it should
* be for a homozygous SNP, it sets $b as the alternate
* letter, if for some reason the AF1 is < .5, it sets $b as
* the old reference letter.)
*
* If the FQ is positive, then the SNP should be mixed, and
* it concatenates the two letters, and checks the hash
* above to know what single letter to set $b to. Then it
* adds $b to the growing sequence.
*
* $q, which is derived from the FQ, ends up being the
* quality score, though it gets tweaked a little; it adds
* 33.449 to the figure, then converts it to a letter,
* capping it at a quality of 126.
*
* $q = int($q + 33 + .499); $q = chr($q <= 126? $q : 126);
*
* Gaps are handled as they were in the old program, where
* they are NOT added in, there is just a window of
* lowercase letters around them. Personally, I made a
* little perl script, and I feed it the genome, and a
* conservatively filtered list of SNPs, and I put the
* changes in that way.
*/
// FIXME: hard-coded for now
fBuilder.setType(ImportConstants.VCF_SNV);
//m.setType(Variant.SNV);
// always save a tag
//setOfTags.add(processVCFTagSpec(ImportConstants.VCF_SNV));
//m.addTag("SNV", null);
if (!".".equals(t[1])) {
Integer pos = Integer.parseInt(t[1]);
fBuilder.setStart(pos - 1);
fBuilder.setStop(pos);
}
//m.setStartPosition(pos - 1);
//m.setStopPosition(pos);
// now parse field 6
//setOfTags.add(processVCFTagSpec(ImportConstants.VCF_FILTER,t[6]));
strTags.put(ImportConstants.VCF_FILTER,t[6]);
//m.addTag(t[6], null);
// added to prototype, record the info field
// don't record the field as a whole, this is useless and big
//setOfTags.add(processVCFTagSpec(ImportConstants.VCF_INFO).toBuilder().setValue(t[7]).build());
// if FQ is < 0 and AF1 < 0.5 then the algorithm is calling homozygous reference so skip
boolean af1LtHalf = false;
boolean fqLt0 = false;
String[] tags = t[7].split(";");
for (String tag : tags) {
if (tag.contains("=")) {
String[] kv = tag.split("=");
strTags.put(kv[0],kv[1]);
//setOfTags.add(getTagSpec(kv[0],kv[1]));
//m.addTag(kv[0], kv[1]);
if ("DP".equals(kv[0])) {
//setOfTags.add(processVCFTagSpec(ImportConstants.VCF_READ_COUNTS,kv[1]));
strTags.put(ImportConstants.VCF_READ_COUNTS,kv[1]);
//m.setReadCount(Integer.parseInt(kv[1]));
}
// see above
if ("FQ".equals(kv[0])) {
float fq = Float.parseFloat(kv[1]);
if (fq < 0) {
//setOfTags.add(processVCFTagSpec(ImportConstants.VCF_HOMOZYGOUS));
strTags.put(ImportConstants.VCF_HOMOZYGOUS, null);
//m.setZygosity(m.VCF_HOMOZYGOUS);
//m.getTags().put("homozygous", null);
fqLt0 = true;
} else {
//setOfTags.add(processVCFTagSpec(ImportConstants.VCF_HETEROZYGOUS));
strTags.put(ImportConstants.VCF_HETEROZYGOUS, null);
//m.setZygosity(m.VCF_HETEROZYGOUS);
//m.getTags().put("heterozygous", null);
}
}
if ("AF1".equals(kv[0])) {
float af1 = Float.parseFloat(kv[1]);
if (af1 < 0.5) {
af1LtHalf = true;
}
}
} else {
// in a file provided, the ID is added as a tag, blowing up our ad hoc tag sets and crashing the region server
// if it is not allocated much memory
if (tag.equals(t[2])) {
if (!this.warnedAboutIDs){
Log.warn("Detected that the ID column is duplicated in the INFO column, skipping: " + tag);
this.warnedAboutIDs = true;
}
} else {
// this is dangerous because it could add an arbitrary number of additional Tags,
// but we need it for testing dbSNP
//setOfTags.add(getTagSpec(tag));
strTags.put(tag, null);
//m.addTag(tag, null);
}
}
}
// yet another way to encode hom/het
// FIXME: this doesn't conform to the standard
if (t.length > 9 && t[8].contains("GT") && t[9].contains("het")) {
///////////////setOfTags.add(processVCFTagSpec(ImportConstants.VCF_HETEROZYGOUS));
//m.setZygosity(m.VCF_HETEROZYGOUS);
//m.getTags().put("heterozygous", null);
} else if (t.length > 9 && t[8].contains("GT") && t[9].contains("hom")) {
/////////////////setOfTags.add(processVCFTagSpec(ImportConstants.VCF_HOMOZYGOUS));
//m.setZygosity(m.VCF_HOMOZYGOUS);
//m.getTags().put("homozygous", null);
}
// if this is true then it's just being called homozygous reference so don't even store
if (af1LtHalf && fqLt0) {
System.out.println("Dropping variant because FQ < 0 and AF1 < 0.5!");
} else {
// our equivalent of store is just making the model manager aware of this by building it
Feature build = fBuilder.build();
/*for (Tag tag : setOfTags) {
build.associateTag(tag);
}*/
for (String key : strTags.keySet()) {
build.fastAssociateTag(key, strTags.get(key));
}
//store.putMismatch(m);
// this is new, add it to a featureSet
fSet.add(build);
// if we use this, we will need to specify a tagset as well
// // hack to spit out secondary index
// if (SOFeatureImporter.SECONDARY_INDEX_HACK){
// if (build.getTagByKey(keyIndex) != null){
// FSGID fsgid = (FSGID) build.getSGID();
// FSGIDPB m2pb = FSGIDIO.m2pb(fsgid);
// String message = TextFormat.printToString(m2pb);
// out.print(message);
// out.println("!");
// }
// }
if (count % this.getBatch_size() == 0) {
System.out.println(new Date().toString() + workerName + " adding mismatch to db: " + build.getSeqid() + ":" + build.getStart() + "-" + build.getStop() + " total records added: " + build.getSeqid() + " total lines so far: " + count);
}
}
// if (count % 10000 == 0) {
// System.out.println(workerName + ": adding mismatch to db: " + m.getContig() + ":" + m.getStartPosition() + "-" + m.getStopPosition()
// + " total records added: " + m.getSeqid() + " total lines so far: " + count);
// }
// now prepare for next mismatch
fBuilder = modelManager.buildFeature();
//m = new Variant();
}
}
if (SOFeatureImporter.SECONDARY_INDEX_HACK) {
out.close();
}
// close file
inputStream.close();
} catch (Exception e) {
| public void run() {
// grab FeatureSet reference
// FeatureSets are totally new, hope this doesn't slow things too much
FeatureSet fSet = SWQEFactory.getQueryInterface().getAtomBySGID(FeatureSet.class, this.featureSetID);
this.modelManager = SWQEFactory.getModelManager();
modelManager.persist(fSet);
if (Constants.TRACK_TAGSET) {
// setup the "VCF" TagSet
this.vcfTagSet = SWQEFactory.getQueryInterface().getLatestAtomByRowKey(VCF, TagSet.class);
if (vcfTagSet == null) {
vcfTagSet = modelManager.buildTagSet().setName(VCF).setFriendlyRowKey(VCF).build();
this.potentialTagSets.add(vcfTagSet);
}
// process potential tag sets
if (this.getTagSetIDs() != null) {
for (SGID tagSetID : this.getTagSetIDs()) {
this.potentialTagSets.add(SWQEFactory.getQueryInterface().getLatestAtomBySGID(tagSetID, TagSet.class));
}
}
this.adHocSet = SWQEFactory.getQueryInterface().getLatestAtomBySGID(this.getAdhoctagset(), TagSet.class);
modelManager.persist(adHocSet);
}
// open the file
BufferedReader inputStream;
try {
// first ask for a token from semaphore
//pmi.getLock();
// Attempting to guess the file format
if (compressed) {
inputStream = handleCompressedInput(input);
} else {
inputStream = new BufferedReader(new FileReader(input));
}
String l;
//Variant m = new Variant();
Feature.Builder fBuilder = modelManager.buildFeature();
// Coverage c = null;
// int currBin = 0;
int count = 0;
// String previousPos = null;
// Pattern p = Pattern.compile("-([ATGCNatgcn]+)");
while ((l = inputStream.readLine()) != null) {
// try to tag our dataset with feature set wide tags
if (l.contains(SOFeatureImporter.PRAGMA_QE_TAG_FORMAT)){
String[] parts = l.split(SOFeatureImporter.PRAGMA_QE_TAG_FORMAT+"=");
String tag = parts[parts.length-1];
String[] tagParts = tag.split("=");
assert(tagParts.length == 2);
Tag featureTag = Tag.newBuilder().setKey(tagParts[0]).setValue(tagParts[1]).build();
fSet.associateTag(featureTag);
}
// display progress
count++;
// we need to flush and clear the manager in order to release the memory consumed by the Features themselves
// the featureSet has to be reattached
if (count % this.getBatch_size() == 0) {
modelManager.flush();
modelManager.clear();
if (Constants.TRACK_TAGSET){
modelManager.persist(adHocSet);
}
modelManager.persist(fSet);
}
// ignore commented lines
if (!l.startsWith("#")) {
if (Constants.OUTPUT_METRICS){
Logger.getLogger(HBaseStorage.class.getName()).info("Line " + count + " is " + l.getBytes().length + " bytes long");
}
// pileup string
String[] t = l.split("\t+");
// load the variant object
//m.setContig(t[0]);
fBuilder.setSeqid(t[0]);
// should not rename this actually
// if (!".".equals(t[0]) && !t[0].startsWith("chr")) {
// //m.setContig("chr" + t[0]);
// fBuilder.setSeqid("chr" + t[0]);
// }
// cache our tags till our message is built
Set<Tag> setOfTags = new HashSet<Tag>();
HashMap<String, String> strTags = new HashMap<String, String>();
//TODO: link this up with proper TagSets, these are ad hoc tags
//tagSet.add(Tag.newBuilder().setKey(t[0]).build());
//setOfTags.add(getTagSpec(t[0]));
//m.addTag(t[0], null);
// referenceBase, consensusBase, and calledBase can be ad hoc tags for now
//setOfTags.add(processVCFTagSpec(ImportConstants.VCF_REFERENCE_BASE, t[3].toUpperCase()));
strTags.put(ImportConstants.VCF_REFERENCE_BASE, t[3].toUpperCase());
//setOfTags.add(processVCFTagSpec(ImportConstants.VCF_CONSENSUS_BASE, t[4].toUpperCase()));
//Tag calledTag = processVCFTagSpec(ImportConstants.VCF_CALLED_BASE,t[4].toUpperCase());
//setOfTags.add(calledTag);
strTags.put(ImportConstants.VCF_CALLED_BASE,t[4].toUpperCase());
//m.setReferenceBase(t[3].toUpperCase());
//m.setConsensusBase(t[4].toUpperCase());
//m.setCalledBase(t[4].toUpperCase());
// figure out the consensusCallQuality
if (!".".equals(t[5])) {
fBuilder.setScore(Double.parseDouble(t[5]));
}
//m.setConsensusCallQuality(Float.parseFloat(t[5]));
// parse ID
if (!".".equals(t[2])) {
//setOfTags.add(processVCFTagSpec(ImportConstants.VCF_SECOND_ID,t[2]));
strTags.put(ImportConstants.VCF_SECOND_ID,t[2]);
//m.addTag("ID", t[2]);
}
// This had to be removed when adding tag support, adding every ID field as a tag would effectviely blow out our ad hoc tag sets to the size of a FeatureSet which
// is not currently feasible
// if (!".".equals(t[2])) {
// setOfTags.add(getTagSpec(t[2]).toBuilder().build());
// //m.addTag(t[2], null);
// }
// FIXME: only supports two alleles for now, see http://users.ox.ac.uk/~linc1775/blueprint.htm
// if there are multiple alleles then both the consensus and called bases should be
String calledBase = t[4].toUpperCase() /**
* m.getCalledBase()
*/
;
if (t[4].toUpperCase().length() > 1 && t[4].toUpperCase().contains(",")) {
//setOfTags.remove(calledTag);
if ("C,A".equals(calledBase) || "A,C".equals(calledBase)) {
calledBase = "M";
} else if ("A,G".equals(calledBase) || "G,A".equals(calledBase)) {
calledBase = "R";
} else if ("A,T".equals(calledBase) || "T,A".equals(calledBase)) {
calledBase = "W";
} else if ("C,G".equals(calledBase) || "G,C".equals(calledBase)) {
calledBase = "S";
} else if ("C,T".equals(calledBase) || "T,C".equals(calledBase)) {
calledBase = "Y";
} else if ("G,T".equals(calledBase) || "T,G".equals(calledBase)) {
calledBase = "K";
} else {
// this doesn't work when consensus base comes back like:
// TGCACGTCA,TAA
//throw new Exception("Don't know what "+m.getReferenceBase()+"->"+m.getConsensusBase()+" is!!!");
}
//calledTag = processVCFTagSpec(ImportConstants.VCF_CALLED_BASE, calledBase);
//setOfTags.add(calledTag);
strTags.put(ImportConstants.VCF_CALLED_BASE, calledBase);
//m.setCalledBase(calledBase);
// leave the consensus base as the original call syntax from the VCF file
}
/*
* I've seen another alternative way of representing alleles
* where the FQ and AF1 can be used to caall homozygous From
* http://seqanswers.com/forums/showthread.php?t=11651 In
* English, the first line means "check the FQ"; the FQ is
* negative when the SNP is homozygous, and positive when
* it's mixed, and the bigger the absolute value, the more
* confident the SNP.
*
* So if it's < 0, it does the first part of code (it checks
* against the AF1, and if the AF1 is > 0.5, which it should
* be for a homozygous SNP, it sets $b as the alternate
* letter, if for some reason the AF1 is < .5, it sets $b as
* the old reference letter.)
*
* If the FQ is positive, then the SNP should be mixed, and
* it concatenates the two letters, and checks the hash
* above to know what single letter to set $b to. Then it
* adds $b to the growing sequence.
*
* $q, which is derived from the FQ, ends up being the
* quality score, though it gets tweaked a little; it adds
* 33.449 to the figure, then converts it to a letter,
* capping it at a quality of 126.
*
* $q = int($q + 33 + .499); $q = chr($q <= 126? $q : 126);
*
* Gaps are handled as they were in the old program, where
* they are NOT added in, there is just a window of
* lowercase letters around them. Personally, I made a
* little perl script, and I feed it the genome, and a
* conservatively filtered list of SNPs, and I put the
* changes in that way.
*/
// FIXME: hard-coded for now
fBuilder.setType(ImportConstants.VCF_SNV);
//m.setType(Variant.SNV);
// always save a tag
//setOfTags.add(processVCFTagSpec(ImportConstants.VCF_SNV));
//m.addTag("SNV", null);
if (!".".equals(t[1])) {
Integer pos = Integer.parseInt(t[1]);
fBuilder.setStart(pos - 1);
fBuilder.setStop(pos);
}
//m.setStartPosition(pos - 1);
//m.setStopPosition(pos);
// now parse field 6
//setOfTags.add(processVCFTagSpec(ImportConstants.VCF_FILTER,t[6]));
strTags.put(ImportConstants.VCF_FILTER,t[6]);
//m.addTag(t[6], null);
// added to prototype, record the info field
// don't record the field as a whole, this is useless and big
//setOfTags.add(processVCFTagSpec(ImportConstants.VCF_INFO).toBuilder().setValue(t[7]).build());
// if FQ is < 0 and AF1 < 0.5 then the algorithm is calling homozygous reference so skip
boolean af1LtHalf = false;
boolean fqLt0 = false;
String[] tags = t[7].split(";");
for (String tag : tags) {
if (tag.contains("=")) {
String[] kv = tag.split("=");
strTags.put(kv[0],kv[1]);
//setOfTags.add(getTagSpec(kv[0],kv[1]));
//m.addTag(kv[0], kv[1]);
if ("DP".equals(kv[0])) {
//setOfTags.add(processVCFTagSpec(ImportConstants.VCF_READ_COUNTS,kv[1]));
strTags.put(ImportConstants.VCF_READ_COUNTS,kv[1]);
//m.setReadCount(Integer.parseInt(kv[1]));
}
// see above
if ("FQ".equals(kv[0])) {
float fq = Float.parseFloat(kv[1]);
if (fq < 0) {
//setOfTags.add(processVCFTagSpec(ImportConstants.VCF_HOMOZYGOUS));
strTags.put(ImportConstants.VCF_HOMOZYGOUS, null);
//m.setZygosity(m.VCF_HOMOZYGOUS);
//m.getTags().put("homozygous", null);
fqLt0 = true;
} else {
//setOfTags.add(processVCFTagSpec(ImportConstants.VCF_HETEROZYGOUS));
strTags.put(ImportConstants.VCF_HETEROZYGOUS, null);
//m.setZygosity(m.VCF_HETEROZYGOUS);
//m.getTags().put("heterozygous", null);
}
}
if ("AF1".equals(kv[0])) {
float af1 = Float.parseFloat(kv[1]);
if (af1 < 0.5) {
af1LtHalf = true;
}
}
} else {
// in a file provided, the ID is added as a tag, blowing up our ad hoc tag sets and crashing the region server
// if it is not allocated much memory
if (tag.equals(t[2])) {
if (!this.warnedAboutIDs){
Log.warn("Detected that the ID column is duplicated in the INFO column, skipping: " + tag);
this.warnedAboutIDs = true;
}
} else {
// this is dangerous because it could add an arbitrary number of additional Tags,
// but we need it for testing dbSNP
//setOfTags.add(getTagSpec(tag));
strTags.put(tag, null);
//m.addTag(tag, null);
}
}
}
// yet another way to encode hom/het
// FIXME: this doesn't conform to the standard
if (t.length > 9 && t[8].contains("GT") && t[9].contains("het")) {
///////////////setOfTags.add(processVCFTagSpec(ImportConstants.VCF_HETEROZYGOUS));
//m.setZygosity(m.VCF_HETEROZYGOUS);
//m.getTags().put("heterozygous", null);
} else if (t.length > 9 && t[8].contains("GT") && t[9].contains("hom")) {
/////////////////setOfTags.add(processVCFTagSpec(ImportConstants.VCF_HOMOZYGOUS));
//m.setZygosity(m.VCF_HOMOZYGOUS);
//m.getTags().put("homozygous", null);
}
// if this is true then it's just being called homozygous reference so don't even store
if (af1LtHalf && fqLt0) {
System.out.println("Dropping variant because FQ < 0 and AF1 < 0.5!");
} else {
// our equivalent of store is just making the model manager aware of this by building it
Feature build = fBuilder.build();
/*for (Tag tag : setOfTags) {
build.associateTag(tag);
}*/
for (String key : strTags.keySet()) {
build.fastAssociateTag(key, strTags.get(key));
}
//store.putMismatch(m);
// this is new, add it to a featureSet
fSet.add(build);
// if we use this, we will need to specify a tagset as well
// // hack to spit out secondary index
// if (SOFeatureImporter.SECONDARY_INDEX_HACK){
// if (build.getTagByKey(keyIndex) != null){
// FSGID fsgid = (FSGID) build.getSGID();
// FSGIDPB m2pb = FSGIDIO.m2pb(fsgid);
// String message = TextFormat.printToString(m2pb);
// out.print(message);
// out.println("!");
// }
// }
if (count % this.getBatch_size() == 0) {
System.out.println(new Date().toString() + workerName + " adding mismatch to db: " + build.getSeqid() + ":" + build.getStart() + "-" + build.getStop() + " total records added: " + build.getSeqid() + " total lines so far: " + count);
}
}
// if (count % 10000 == 0) {
// System.out.println(workerName + ": adding mismatch to db: " + m.getContig() + ":" + m.getStartPosition() + "-" + m.getStopPosition()
// + " total records added: " + m.getSeqid() + " total lines so far: " + count);
// }
// now prepare for next mismatch
fBuilder = modelManager.buildFeature();
//m = new Variant();
}
}
if (SOFeatureImporter.SECONDARY_INDEX_HACK) {
out.close();
}
// close file
inputStream.close();
} catch (Exception e) {
|
diff --git a/xwiki-commons-core/xwiki-commons-extension/xwiki-platform-extension-api/src/main/java/org/xwiki/extension/AbstractExtension.java b/xwiki-commons-core/xwiki-commons-extension/xwiki-platform-extension-api/src/main/java/org/xwiki/extension/AbstractExtension.java
index b968fcaaa..7b1c2c863 100644
--- a/xwiki-commons-core/xwiki-commons-extension/xwiki-platform-extension-api/src/main/java/org/xwiki/extension/AbstractExtension.java
+++ b/xwiki-commons-core/xwiki-commons-extension/xwiki-platform-extension-api/src/main/java/org/xwiki/extension/AbstractExtension.java
@@ -1,396 +1,401 @@
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This 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.1 of
* the License, or (at your option) any later version.
*
* This software 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 software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.extension;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.xwiki.extension.repository.ExtensionRepository;
/**
* Base class for {@link Extension} implementations.
*
* @version $Id$
*/
public abstract class AbstractExtension implements Extension
{
/**
* @see #getId()
*/
protected ExtensionId id;
/**
* @see #getFeatures()
*/
protected Set<String> features = new HashSet<String>();
/**
* @see #getType()
*/
protected String type;
/**
* @see #getName()
*/
protected String name;
/**
* @see #getLicenses()
*/
protected List<ExtensionLicense> licenses = new ArrayList<ExtensionLicense>();
/**
* @see #getSummary()
*/
protected String summary;
/**
* @see #getDescription()
*/
protected String description;
/**
* @see #getAuthors()
*/
protected List<String> authors = new ArrayList<String>();
/**
* @see #getWebSite()
*/
protected String website;
/**
* @see #getRepository()
*/
protected ExtensionRepository repository;
/**
* @see #getProperties()
*/
protected Map<String, Object> properties = new HashMap<String, Object>();
/**
* @see #getDependencies()
*/
protected List<ExtensionDependency> dependencies;
/**
* @param repository the repository where this extension comes from
* @param id the extension identifier
* @param type the extension type
*/
public AbstractExtension(ExtensionRepository repository, ExtensionId id, String type)
{
this.repository = repository;
this.id = id;
this.type = type;
}
/**
* Create new extension descriptor by copying provided one.
*
* @param repository the repository where this extension comes from
* @param extension the extension to copy
*/
public AbstractExtension(ExtensionRepository repository, Extension extension)
{
this(repository, extension.getId(), extension.getType());
setFeatures(extension.getFeatures());
+ setName(extension.getName());
setDescription(extension.getDescription());
setAuthors(extension.getAuthors());
setWebsite(extension.getWebSite());
+ if (extension.getLicenses() != null && !extension.getLicenses().isEmpty()) {
+ setLicense(extension.getLicenses());
+ }
+ setSummary(extension.getSummary());
List< ? extends ExtensionDependency> newDependencies = extension.getDependencies();
if (!newDependencies.isEmpty()) {
this.dependencies = new ArrayList<ExtensionDependency>(extension.getDependencies());
}
}
@Override
public ExtensionId getId()
{
return this.id;
}
/**
* @param id the extension id
* @see #getId()
*/
protected void setId(ExtensionId id)
{
this.id = id;
}
@Override
public Collection<String> getFeatures()
{
return this.features;
}
/**
* @param features the extension ids also provided by this extension
*/
public void setFeatures(Collection<String> features)
{
this.features = new LinkedHashSet<String>(features);
}
/**
* Add a new feature to the extension.
*
* @param feature a feature name
*/
public void addFeature(String feature)
{
this.features.add(feature);
}
@Override
public String getType()
{
return this.type;
}
/**
* @param type the type of the extension
* @see #getType()
*/
protected void setType(String type)
{
this.type = type;
}
@Override
public String getName()
{
return this.name;
}
/**
* @param name the display name of the extension
*/
public void setName(String name)
{
this.name = name;
}
@Override
public Collection<ExtensionLicense> getLicenses()
{
return this.licenses;
}
/**
* @param licenses the licenses of the extension
*/
public void setLicense(Collection<ExtensionLicense> licenses)
{
this.licenses = new ArrayList<ExtensionLicense>(licenses);
}
/**
* Add a new license to the extension.
*
* @param license a license
*/
public void addLicense(ExtensionLicense license)
{
this.licenses.add(license);
}
@Override
public String getSummary()
{
return this.summary;
}
/**
* @param summary a short description of the extension
*/
public void setSummary(String summary)
{
this.summary = summary;
}
@Override
public String getDescription()
{
return this.description;
}
/**
* @param description a description of the extension
*/
public void setDescription(String description)
{
this.description = description;
}
@Override
public List<String> getAuthors()
{
return this.authors;
}
/**
* @param authors the authors of the extension
*/
public void setAuthors(Collection<String> authors)
{
this.authors = new ArrayList<String>(authors);
}
/**
* Add a new author to the extension.
*
* @param author an author name
*/
public void addAuthor(String author)
{
this.authors.add(author);
}
@Override
public String getWebSite()
{
return this.website;
}
/**
* @param website an URL for the extension website
*/
public void setWebsite(String website)
{
this.website = website;
}
/**
* Add a new dependency to the extension.
*
* @param dependency a dependency
*/
public void addDependency(ExtensionDependency dependency)
{
if (this.dependencies == null) {
this.dependencies = new ArrayList<ExtensionDependency>();
}
this.dependencies.add(dependency);
}
@Override
public List< ? extends ExtensionDependency> getDependencies()
{
return this.dependencies != null ? Collections.unmodifiableList(this.dependencies) : Collections
.<ExtensionDependency> emptyList();
}
/**
* @param dependencies the dependencies of the extension
* @see #getDependencies()
*/
public void setDependencies(Collection< ? extends ExtensionDependency> dependencies)
{
this.dependencies = new ArrayList<ExtensionDependency>(dependencies);
}
@Override
public ExtensionRepository getRepository()
{
return this.repository;
}
/**
* @param repository the repository of the extension
* @see #getRepository()
*/
protected void setRepository(ExtensionRepository repository)
{
this.repository = repository;
}
@Override
public Map<String, Object> getProperties()
{
return Collections.unmodifiableMap(this.properties);
}
@Override
public Object getProperty(String key)
{
return this.properties.get(key);
}
/**
* Set a property.
*
* @param key the property key
* @param value the property value
* @see #getProperty(String)
*/
public void putProperty(String key, Object value)
{
this.properties.put(key, value);
}
/**
* Get a property.
*
* @param <T> type of the property value
* @param key the property key
* @param def the value to return if no property is associated to the provided key
* @return the property value or <code>default</code> of the property is not found
* @see #getProperty(String)
*/
public <T> T getProperty(String key, T def)
{
return this.properties.containsKey(key) ? (T) this.properties.get(key) : def;
}
// Object
@Override
public String toString()
{
return getId().toString();
}
@Override
public boolean equals(Object obj)
{
return this == obj || (obj instanceof Extension && getId().equals(((Extension) obj).getId()));
}
@Override
public int hashCode()
{
return getId().hashCode();
}
}
| false | true | public AbstractExtension(ExtensionRepository repository, Extension extension)
{
this(repository, extension.getId(), extension.getType());
setFeatures(extension.getFeatures());
setDescription(extension.getDescription());
setAuthors(extension.getAuthors());
setWebsite(extension.getWebSite());
List< ? extends ExtensionDependency> newDependencies = extension.getDependencies();
if (!newDependencies.isEmpty()) {
this.dependencies = new ArrayList<ExtensionDependency>(extension.getDependencies());
}
}
| public AbstractExtension(ExtensionRepository repository, Extension extension)
{
this(repository, extension.getId(), extension.getType());
setFeatures(extension.getFeatures());
setName(extension.getName());
setDescription(extension.getDescription());
setAuthors(extension.getAuthors());
setWebsite(extension.getWebSite());
if (extension.getLicenses() != null && !extension.getLicenses().isEmpty()) {
setLicense(extension.getLicenses());
}
setSummary(extension.getSummary());
List< ? extends ExtensionDependency> newDependencies = extension.getDependencies();
if (!newDependencies.isEmpty()) {
this.dependencies = new ArrayList<ExtensionDependency>(extension.getDependencies());
}
}
|
diff --git a/src/main/java/name/richardson/james/bukkit/timedmessages/Message.java b/src/main/java/name/richardson/james/bukkit/timedmessages/Message.java
index 29a4278..2326451 100644
--- a/src/main/java/name/richardson/james/bukkit/timedmessages/Message.java
+++ b/src/main/java/name/richardson/james/bukkit/timedmessages/Message.java
@@ -1,120 +1,121 @@
/*******************************************************************************
* Copyright (c) 2011 James Richardson.
*
* Message.java is part of TimedMessages.
*
* TimedMessages 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.
*
* TimedMessages 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
* TimedMessages. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package name.richardson.james.bukkit.timedmessages;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import name.richardson.james.bukkit.utilities.formatters.ColourFormatter;
import name.richardson.james.bukkit.utilities.permissions.PermissionManager;
import org.bukkit.Server;
import org.bukkit.entity.Player;
import com.sk89q.worldguard.protection.managers.RegionManager;
public abstract class Message implements Runnable {
protected final List<String> messages;
private final Long ticks;
private final String permission;
private final Server server;
private final PermissionManager permissionManager;
private final List<String> worlds = new LinkedList<String>();
private final Set<String> regions = new HashSet<String>();
private final TimedMessages plugin;
public Message(final TimedMessages plugin, final Server server, final Long milliseconds, final List<String> messages, final String permission, final List<String> worlds, List<String> regions) {
final long seconds = milliseconds / 1000;
this.ticks = seconds * 20;
this.messages = messages;
this.permission = permission;
this.permissionManager = plugin.getPermissionManager();
this.server = server;
this.worlds.addAll(worlds);
this.regions.addAll(regions);
this.plugin = plugin;
this.plugin.getCustomLogger().debug(this, String.format("Creating %s which broadcasts every %s seconds", this.getClass().getSimpleName(), seconds));
}
public List<String> getMessages() {
return this.messages;
}
public String getPermission() {
return this.permission;
}
public Long getTicks() {
return this.ticks;
}
public void run() {
+ this.plugin.getCustomLogger().debug(this, String.format("Running %s.", this.getClass().getSimpleName()));
String message = this.getNextMessage();
message = ColourFormatter.replace("&", message);
final String[] parts = message.split("/n");
final List<Player> players = new LinkedList<Player>();
for (final Player player : this.server.getOnlinePlayers()) {
// ignore the player if they are not in the world required
- if (!worlds.isEmpty() || !worlds.contains(player.getWorld().getName())) continue;
+ if (!worlds.isEmpty() && !worlds.contains(player.getWorld().getName())) continue;
// if the player is not in the correct region ignore them
if (!this.isPlayerInRegion(player)) continue;
// ignore the player if they do not have the correct permission
if (this.permission != null && !this.permissionManager.hasPlayerPermission(player, this.permission)) continue;
players.add(player);
}
if (players.isEmpty()) return;
this.plugin.getCustomLogger().debug(this, String.format("Sending message to following players: %s", players.toString()));
for (final String part : parts) {
for (final Player player : players) {
player.sendMessage(part);
}
}
}
public boolean isPlayerInRegion(Player player) {
if (this.worlds.isEmpty()) return true;
if (this.plugin.getGlobalRegionManager() == null) return true;
if (this.regions.isEmpty()) return true;
for (String worldName : this.worlds) {
if (!player.getWorld().getName().equals(worldName)) continue;
RegionManager manager = this.plugin.getRegionManager(worldName);
final int x = (int) player.getLocation().getX();
final int y = (int) player.getLocation().getY();
final int z = (int) player.getLocation().getZ();
for (String regionName : this.regions) {
if (manager.getRegion(regionName).contains(x, y, z)) return true;
}
}
return false;
}
protected abstract String getNextMessage();
}
| false | true | public void run() {
String message = this.getNextMessage();
message = ColourFormatter.replace("&", message);
final String[] parts = message.split("/n");
final List<Player> players = new LinkedList<Player>();
for (final Player player : this.server.getOnlinePlayers()) {
// ignore the player if they are not in the world required
if (!worlds.isEmpty() || !worlds.contains(player.getWorld().getName())) continue;
// if the player is not in the correct region ignore them
if (!this.isPlayerInRegion(player)) continue;
// ignore the player if they do not have the correct permission
if (this.permission != null && !this.permissionManager.hasPlayerPermission(player, this.permission)) continue;
players.add(player);
}
if (players.isEmpty()) return;
this.plugin.getCustomLogger().debug(this, String.format("Sending message to following players: %s", players.toString()));
for (final String part : parts) {
for (final Player player : players) {
player.sendMessage(part);
}
}
}
| public void run() {
this.plugin.getCustomLogger().debug(this, String.format("Running %s.", this.getClass().getSimpleName()));
String message = this.getNextMessage();
message = ColourFormatter.replace("&", message);
final String[] parts = message.split("/n");
final List<Player> players = new LinkedList<Player>();
for (final Player player : this.server.getOnlinePlayers()) {
// ignore the player if they are not in the world required
if (!worlds.isEmpty() && !worlds.contains(player.getWorld().getName())) continue;
// if the player is not in the correct region ignore them
if (!this.isPlayerInRegion(player)) continue;
// ignore the player if they do not have the correct permission
if (this.permission != null && !this.permissionManager.hasPlayerPermission(player, this.permission)) continue;
players.add(player);
}
if (players.isEmpty()) return;
this.plugin.getCustomLogger().debug(this, String.format("Sending message to following players: %s", players.toString()));
for (final String part : parts) {
for (final Player player : players) {
player.sendMessage(part);
}
}
}
|
diff --git a/src/com/android/bluetooth/btservice/AdapterState.java b/src/com/android/bluetooth/btservice/AdapterState.java
index fbc32a5..108c055 100755
--- a/src/com/android/bluetooth/btservice/AdapterState.java
+++ b/src/com/android/bluetooth/btservice/AdapterState.java
@@ -1,351 +1,360 @@
/*
* Copyright (C) 2012 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.bluetooth.btservice;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.os.Message;
import android.util.Log;
import com.android.internal.util.State;
import com.android.internal.util.StateMachine;
/**
* This state machine handles Bluetooth Adapter State.
* States:
* {@link OnState} : Bluetooth is on at this state
* {@link OffState}: Bluetooth is off at this state. This is the initial
* state.
* {@link PendingCommandState} : An enable / disable operation is pending.
* TODO(BT): Add per process on state.
*/
final class AdapterState extends StateMachine {
private static final boolean DBG = true;
private static final boolean VDBG = false;
private static final String TAG = "BluetoothAdapterState";
static final int USER_TURN_ON = 1;
static final int STARTED=2;
static final int ENABLED_READY = 3;
static final int USER_TURN_OFF = 20;
static final int BEGIN_DISABLE = 21;
static final int ALL_DEVICES_DISCONNECTED = 22;
static final int DISABLED = 24;
static final int STOPPED=25;
static final int START_TIMEOUT = 100;
static final int ENABLE_TIMEOUT = 101;
static final int DISABLE_TIMEOUT = 103;
static final int STOP_TIMEOUT = 104;
static final int SET_SCAN_MODE_TIMEOUT = 105;
static final int USER_TURN_OFF_DELAY_MS=500;
//TODO: tune me
private static final int ENABLE_TIMEOUT_DELAY = 8000;
private static final int DISABLE_TIMEOUT_DELAY = 8000;
private static final int START_TIMEOUT_DELAY = 5000;
private static final int STOP_TIMEOUT_DELAY = 5000;
private static final int PROPERTY_OP_DELAY =2000;
private AdapterService mAdapterService;
private AdapterProperties mAdapterProperties;
private PendingCommandState mPendingCommandState = new PendingCommandState();
private OnState mOnState = new OnState();
private OffState mOffState = new OffState();
public boolean isTurningOn() {
boolean isTurningOn= mPendingCommandState.isTurningOn();
if (VDBG) Log.d(TAG,"isTurningOn()=" + isTurningOn);
return isTurningOn;
}
public boolean isTurningOff() {
boolean isTurningOff= mPendingCommandState.isTurningOff();
if (VDBG) Log.d(TAG,"isTurningOff()=" + isTurningOff);
return isTurningOff;
}
private AdapterState(AdapterService service, AdapterProperties adapterProperties) {
super("BluetoothAdapterState:");
addState(mOnState);
addState(mOffState);
addState(mPendingCommandState);
mAdapterService = service;
mAdapterProperties = adapterProperties;
setInitialState(mOffState);
}
public static AdapterState make(AdapterService service, AdapterProperties adapterProperties) {
Log.d(TAG, "make");
AdapterState as = new AdapterState(service, adapterProperties);
as.start();
return as;
}
public void doQuit() {
quitNow();
}
public void cleanup() {
if(mAdapterProperties != null)
mAdapterProperties = null;
if(mAdapterService != null)
mAdapterService = null;
}
private class OffState extends State {
@Override
public void enter() {
infoLog("Entering OffState");
}
@Override
public boolean processMessage(Message msg) {
switch(msg.what) {
case USER_TURN_ON:
if (DBG) Log.d(TAG,"CURRENT_STATE=OFF, MESSAGE = USER_TURN_ON");
notifyAdapterStateChange(BluetoothAdapter.STATE_TURNING_ON);
mPendingCommandState.setTurningOn(true);
transitionTo(mPendingCommandState);
sendMessageDelayed(START_TIMEOUT, START_TIMEOUT_DELAY);
mAdapterService.processStart();
break;
case USER_TURN_OFF:
if (DBG) Log.d(TAG,"CURRENT_STATE=OFF, MESSAGE = USER_TURN_OFF");
//TODO: Handle case of service started and stopped without enable
break;
default:
if (DBG) Log.d(TAG,"ERROR: UNEXPECTED MESSAGE: CURRENT_STATE=OFF, MESSAGE = " + msg.what );
return false;
}
return true;
}
}
private class OnState extends State {
@Override
public void enter() {
infoLog("Entering On State");
mAdapterService.autoConnect();
}
@Override
public boolean processMessage(Message msg) {
switch(msg.what) {
case USER_TURN_OFF:
if (DBG) Log.d(TAG,"CURRENT_STATE=ON, MESSAGE = USER_TURN_OFF");
notifyAdapterStateChange(BluetoothAdapter.STATE_TURNING_OFF);
mPendingCommandState.setTurningOff(true);
transitionTo(mPendingCommandState);
// Invoke onBluetoothDisable which shall trigger a
// setScanMode to SCAN_MODE_NONE
Message m = obtainMessage(SET_SCAN_MODE_TIMEOUT);
sendMessageDelayed(m, PROPERTY_OP_DELAY);
mAdapterProperties.onBluetoothDisable();
break;
case USER_TURN_ON:
if (DBG) Log.d(TAG,"CURRENT_STATE=ON, MESSAGE = USER_TURN_ON");
Log.i(TAG,"Bluetooth already ON, ignoring USER_TURN_ON");
break;
default:
if (DBG) Log.d(TAG,"ERROR: UNEXPECTED MESSAGE: CURRENT_STATE=ON, MESSAGE = " + msg.what );
return false;
}
return true;
}
}
private class PendingCommandState extends State {
private boolean mIsTurningOn;
private boolean mIsTurningOff;
public void enter() {
infoLog("Entering PendingCommandState State: isTurningOn()=" + isTurningOn() + ", isTurningOff()=" + isTurningOff());
}
public void setTurningOn(boolean isTurningOn) {
mIsTurningOn = isTurningOn;
}
public boolean isTurningOn() {
return mIsTurningOn;
}
public void setTurningOff(boolean isTurningOff) {
mIsTurningOff = isTurningOff;
}
public boolean isTurningOff() {
return mIsTurningOff;
}
@Override
public boolean processMessage(Message msg) {
boolean isTurningOn= isTurningOn();
boolean isTurningOff = isTurningOff();
switch (msg.what) {
case USER_TURN_ON:
if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = USER_TURN_ON"
+ ", isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff);
if (isTurningOn) {
Log.i(TAG,"CURRENT_STATE=PENDING: Alreadying turning on bluetooth... Ignoring USER_TURN_ON...");
} else {
Log.i(TAG,"CURRENT_STATE=PENDING: Deferring request USER_TURN_ON");
deferMessage(msg);
}
break;
case USER_TURN_OFF:
if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = USER_TURN_ON"
+ ", isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff);
if (isTurningOff) {
Log.i(TAG,"CURRENT_STATE=PENDING: Alreadying turning off bluetooth... Ignoring USER_TURN_OFF...");
} else {
Log.i(TAG,"CURRENT_STATE=PENDING: Deferring request USER_TURN_OFF");
deferMessage(msg);
}
break;
case STARTED: {
if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = STARTED, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff);
//Remove start timeout
removeMessages(START_TIMEOUT);
//Enable
boolean ret = mAdapterService.enableNative();
if (!ret) {
Log.e(TAG, "Error while turning Bluetooth On");
notifyAdapterStateChange(BluetoothAdapter.STATE_OFF);
transitionTo(mOffState);
} else {
sendMessageDelayed(ENABLE_TIMEOUT, ENABLE_TIMEOUT_DELAY);
}
}
break;
case ENABLED_READY:
if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = ENABLE_READY, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff);
removeMessages(ENABLE_TIMEOUT);
mAdapterProperties.onBluetoothReady();
mPendingCommandState.setTurningOn(false);
transitionTo(mOnState);
notifyAdapterStateChange(BluetoothAdapter.STATE_ON);
break;
case SET_SCAN_MODE_TIMEOUT:
Log.w(TAG,"Timeout will setting scan mode..Continuing with disable...");
//Fall through
case BEGIN_DISABLE: {
- if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = BEGIN_DISABLE" + isTurningOn + ", isTurningOff=" + isTurningOff);
+ if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = BEGIN_DISABLE, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff);
removeMessages(SET_SCAN_MODE_TIMEOUT);
sendMessageDelayed(DISABLE_TIMEOUT, DISABLE_TIMEOUT_DELAY);
boolean ret = mAdapterService.disableNative();
if (!ret) {
removeMessages(DISABLE_TIMEOUT);
Log.e(TAG, "Error while turning Bluetooth Off");
//FIXME: what about post enable services
mPendingCommandState.setTurningOff(false);
notifyAdapterStateChange(BluetoothAdapter.STATE_ON);
}
}
break;
case DISABLED:
if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = DISABLED, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff);
+ if (isTurningOn) {
+ removeMessages(ENABLE_TIMEOUT);
+ errorLog("Error enabling Bluetooth - hardware init failed");
+ mPendingCommandState.setTurningOn(false);
+ transitionTo(mOffState);
+ mAdapterService.stopProfileServices();
+ notifyAdapterStateChange(BluetoothAdapter.STATE_OFF);
+ break;
+ }
removeMessages(DISABLE_TIMEOUT);
sendMessageDelayed(STOP_TIMEOUT, STOP_TIMEOUT_DELAY);
if (mAdapterService.stopProfileServices()) {
Log.d(TAG,"Stopping profile services that were post enabled");
break;
}
//Fall through if no services or services already stopped
case STOPPED:
if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = STOPPED, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff);
removeMessages(STOP_TIMEOUT);
setTurningOff(false);
transitionTo(mOffState);
notifyAdapterStateChange(BluetoothAdapter.STATE_OFF);
break;
case START_TIMEOUT:
if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = START_TIMEOUT, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff);
errorLog("Error enabling Bluetooth");
mPendingCommandState.setTurningOn(false);
transitionTo(mOffState);
notifyAdapterStateChange(BluetoothAdapter.STATE_OFF);
break;
case ENABLE_TIMEOUT:
if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = ENABLE_TIMEOUT, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff);
errorLog("Error enabling Bluetooth");
mPendingCommandState.setTurningOn(false);
transitionTo(mOffState);
notifyAdapterStateChange(BluetoothAdapter.STATE_OFF);
break;
case STOP_TIMEOUT:
if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = STOP_TIMEOUT, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff);
errorLog("Error stopping Bluetooth profiles");
mPendingCommandState.setTurningOff(false);
transitionTo(mOffState);
break;
case DISABLE_TIMEOUT:
if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = DISABLE_TIMEOUT, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff);
errorLog("Error disabling Bluetooth");
mPendingCommandState.setTurningOff(false);
transitionTo(mOnState);
break;
default:
if (DBG) Log.d(TAG,"ERROR: UNEXPECTED MESSAGE: CURRENT_STATE=PENDING, MESSAGE = " + msg.what );
return false;
}
return true;
}
}
private void notifyAdapterStateChange(int newState) {
int oldState = mAdapterProperties.getState();
mAdapterProperties.setState(newState);
infoLog("Bluetooth adapter state changed: " + oldState + "-> " + newState);
mAdapterService.updateAdapterState(oldState, newState);
}
void stateChangeCallback(int status) {
if (status == AbstractionLayer.BT_STATE_OFF) {
sendMessage(DISABLED);
} else if (status == AbstractionLayer.BT_STATE_ON) {
// We should have got the property change for adapter and remote devices.
sendMessage(ENABLED_READY);
} else {
errorLog("Incorrect status in stateChangeCallback");
}
}
private void infoLog(String msg) {
if (DBG) Log.i(TAG, msg);
}
private void errorLog(String msg) {
Log.e(TAG, msg);
}
}
| false | true | public boolean processMessage(Message msg) {
boolean isTurningOn= isTurningOn();
boolean isTurningOff = isTurningOff();
switch (msg.what) {
case USER_TURN_ON:
if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = USER_TURN_ON"
+ ", isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff);
if (isTurningOn) {
Log.i(TAG,"CURRENT_STATE=PENDING: Alreadying turning on bluetooth... Ignoring USER_TURN_ON...");
} else {
Log.i(TAG,"CURRENT_STATE=PENDING: Deferring request USER_TURN_ON");
deferMessage(msg);
}
break;
case USER_TURN_OFF:
if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = USER_TURN_ON"
+ ", isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff);
if (isTurningOff) {
Log.i(TAG,"CURRENT_STATE=PENDING: Alreadying turning off bluetooth... Ignoring USER_TURN_OFF...");
} else {
Log.i(TAG,"CURRENT_STATE=PENDING: Deferring request USER_TURN_OFF");
deferMessage(msg);
}
break;
case STARTED: {
if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = STARTED, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff);
//Remove start timeout
removeMessages(START_TIMEOUT);
//Enable
boolean ret = mAdapterService.enableNative();
if (!ret) {
Log.e(TAG, "Error while turning Bluetooth On");
notifyAdapterStateChange(BluetoothAdapter.STATE_OFF);
transitionTo(mOffState);
} else {
sendMessageDelayed(ENABLE_TIMEOUT, ENABLE_TIMEOUT_DELAY);
}
}
break;
case ENABLED_READY:
if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = ENABLE_READY, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff);
removeMessages(ENABLE_TIMEOUT);
mAdapterProperties.onBluetoothReady();
mPendingCommandState.setTurningOn(false);
transitionTo(mOnState);
notifyAdapterStateChange(BluetoothAdapter.STATE_ON);
break;
case SET_SCAN_MODE_TIMEOUT:
Log.w(TAG,"Timeout will setting scan mode..Continuing with disable...");
//Fall through
case BEGIN_DISABLE: {
if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = BEGIN_DISABLE" + isTurningOn + ", isTurningOff=" + isTurningOff);
removeMessages(SET_SCAN_MODE_TIMEOUT);
sendMessageDelayed(DISABLE_TIMEOUT, DISABLE_TIMEOUT_DELAY);
boolean ret = mAdapterService.disableNative();
if (!ret) {
removeMessages(DISABLE_TIMEOUT);
Log.e(TAG, "Error while turning Bluetooth Off");
//FIXME: what about post enable services
mPendingCommandState.setTurningOff(false);
notifyAdapterStateChange(BluetoothAdapter.STATE_ON);
}
}
break;
case DISABLED:
if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = DISABLED, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff);
removeMessages(DISABLE_TIMEOUT);
sendMessageDelayed(STOP_TIMEOUT, STOP_TIMEOUT_DELAY);
if (mAdapterService.stopProfileServices()) {
Log.d(TAG,"Stopping profile services that were post enabled");
break;
}
//Fall through if no services or services already stopped
case STOPPED:
if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = STOPPED, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff);
removeMessages(STOP_TIMEOUT);
setTurningOff(false);
transitionTo(mOffState);
notifyAdapterStateChange(BluetoothAdapter.STATE_OFF);
break;
case START_TIMEOUT:
if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = START_TIMEOUT, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff);
errorLog("Error enabling Bluetooth");
mPendingCommandState.setTurningOn(false);
transitionTo(mOffState);
notifyAdapterStateChange(BluetoothAdapter.STATE_OFF);
break;
case ENABLE_TIMEOUT:
if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = ENABLE_TIMEOUT, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff);
errorLog("Error enabling Bluetooth");
mPendingCommandState.setTurningOn(false);
transitionTo(mOffState);
notifyAdapterStateChange(BluetoothAdapter.STATE_OFF);
break;
case STOP_TIMEOUT:
if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = STOP_TIMEOUT, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff);
errorLog("Error stopping Bluetooth profiles");
mPendingCommandState.setTurningOff(false);
transitionTo(mOffState);
break;
case DISABLE_TIMEOUT:
if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = DISABLE_TIMEOUT, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff);
errorLog("Error disabling Bluetooth");
mPendingCommandState.setTurningOff(false);
transitionTo(mOnState);
break;
default:
if (DBG) Log.d(TAG,"ERROR: UNEXPECTED MESSAGE: CURRENT_STATE=PENDING, MESSAGE = " + msg.what );
return false;
}
return true;
}
| public boolean processMessage(Message msg) {
boolean isTurningOn= isTurningOn();
boolean isTurningOff = isTurningOff();
switch (msg.what) {
case USER_TURN_ON:
if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = USER_TURN_ON"
+ ", isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff);
if (isTurningOn) {
Log.i(TAG,"CURRENT_STATE=PENDING: Alreadying turning on bluetooth... Ignoring USER_TURN_ON...");
} else {
Log.i(TAG,"CURRENT_STATE=PENDING: Deferring request USER_TURN_ON");
deferMessage(msg);
}
break;
case USER_TURN_OFF:
if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = USER_TURN_ON"
+ ", isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff);
if (isTurningOff) {
Log.i(TAG,"CURRENT_STATE=PENDING: Alreadying turning off bluetooth... Ignoring USER_TURN_OFF...");
} else {
Log.i(TAG,"CURRENT_STATE=PENDING: Deferring request USER_TURN_OFF");
deferMessage(msg);
}
break;
case STARTED: {
if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = STARTED, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff);
//Remove start timeout
removeMessages(START_TIMEOUT);
//Enable
boolean ret = mAdapterService.enableNative();
if (!ret) {
Log.e(TAG, "Error while turning Bluetooth On");
notifyAdapterStateChange(BluetoothAdapter.STATE_OFF);
transitionTo(mOffState);
} else {
sendMessageDelayed(ENABLE_TIMEOUT, ENABLE_TIMEOUT_DELAY);
}
}
break;
case ENABLED_READY:
if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = ENABLE_READY, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff);
removeMessages(ENABLE_TIMEOUT);
mAdapterProperties.onBluetoothReady();
mPendingCommandState.setTurningOn(false);
transitionTo(mOnState);
notifyAdapterStateChange(BluetoothAdapter.STATE_ON);
break;
case SET_SCAN_MODE_TIMEOUT:
Log.w(TAG,"Timeout will setting scan mode..Continuing with disable...");
//Fall through
case BEGIN_DISABLE: {
if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = BEGIN_DISABLE, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff);
removeMessages(SET_SCAN_MODE_TIMEOUT);
sendMessageDelayed(DISABLE_TIMEOUT, DISABLE_TIMEOUT_DELAY);
boolean ret = mAdapterService.disableNative();
if (!ret) {
removeMessages(DISABLE_TIMEOUT);
Log.e(TAG, "Error while turning Bluetooth Off");
//FIXME: what about post enable services
mPendingCommandState.setTurningOff(false);
notifyAdapterStateChange(BluetoothAdapter.STATE_ON);
}
}
break;
case DISABLED:
if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = DISABLED, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff);
if (isTurningOn) {
removeMessages(ENABLE_TIMEOUT);
errorLog("Error enabling Bluetooth - hardware init failed");
mPendingCommandState.setTurningOn(false);
transitionTo(mOffState);
mAdapterService.stopProfileServices();
notifyAdapterStateChange(BluetoothAdapter.STATE_OFF);
break;
}
removeMessages(DISABLE_TIMEOUT);
sendMessageDelayed(STOP_TIMEOUT, STOP_TIMEOUT_DELAY);
if (mAdapterService.stopProfileServices()) {
Log.d(TAG,"Stopping profile services that were post enabled");
break;
}
//Fall through if no services or services already stopped
case STOPPED:
if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = STOPPED, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff);
removeMessages(STOP_TIMEOUT);
setTurningOff(false);
transitionTo(mOffState);
notifyAdapterStateChange(BluetoothAdapter.STATE_OFF);
break;
case START_TIMEOUT:
if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = START_TIMEOUT, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff);
errorLog("Error enabling Bluetooth");
mPendingCommandState.setTurningOn(false);
transitionTo(mOffState);
notifyAdapterStateChange(BluetoothAdapter.STATE_OFF);
break;
case ENABLE_TIMEOUT:
if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = ENABLE_TIMEOUT, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff);
errorLog("Error enabling Bluetooth");
mPendingCommandState.setTurningOn(false);
transitionTo(mOffState);
notifyAdapterStateChange(BluetoothAdapter.STATE_OFF);
break;
case STOP_TIMEOUT:
if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = STOP_TIMEOUT, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff);
errorLog("Error stopping Bluetooth profiles");
mPendingCommandState.setTurningOff(false);
transitionTo(mOffState);
break;
case DISABLE_TIMEOUT:
if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = DISABLE_TIMEOUT, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff);
errorLog("Error disabling Bluetooth");
mPendingCommandState.setTurningOff(false);
transitionTo(mOnState);
break;
default:
if (DBG) Log.d(TAG,"ERROR: UNEXPECTED MESSAGE: CURRENT_STATE=PENDING, MESSAGE = " + msg.what );
return false;
}
return true;
}
|
diff --git a/eol-globi-data-tool/src/main/java/org/eol/globi/data/StudyImporterForINaturalist.java b/eol-globi-data-tool/src/main/java/org/eol/globi/data/StudyImporterForINaturalist.java
index 455c299b..4b0a7467 100644
--- a/eol-globi-data-tool/src/main/java/org/eol/globi/data/StudyImporterForINaturalist.java
+++ b/eol-globi-data-tool/src/main/java/org/eol/globi/data/StudyImporterForINaturalist.java
@@ -1,166 +1,166 @@
package org.eol.globi.data;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.eol.globi.domain.InteractType;
import org.eol.globi.domain.Specimen;
import org.eol.globi.domain.Study;
import org.eol.globi.domain.TaxonomyProvider;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.ISODateTimeFormat;
import org.neo4j.graphdb.Relationship;
import java.io.IOException;
import java.io.InputStream;
public class StudyImporterForINaturalist extends BaseStudyImporter {
private static final Log LOG = LogFactory.getLog(StudyImporterForINaturalist.class);
public StudyImporterForINaturalist(ParserFactory parserFactory, NodeFactory nodeFactory) {
super(parserFactory, nodeFactory);
}
@Override
public Study importStudy() throws StudyImporterException {
Study study = nodeFactory.getOrCreateStudy("iNaturalist", "Ken-ichi Kueda", "http://inaturalist.org", "", "iNaturalist is a place where you can record what you see in nature, meet other nature lovers, and learn about the natural world. ", "");
retrieveDataParseResults(study);
return study;
}
private int retrieveDataParseResults(Study study) throws StudyImporterException {
int totalInteractions = 0;
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
try {
int previousResultCount;
int pageNumber = 1;
do {
String uri = "http://www.inaturalist.org/observation_field_values.json?type=taxon&page=" + pageNumber + "&per_page=100&license=any";
HttpGet get = new HttpGet(uri);
get.addHeader("accept", "application/json");
try {
HttpResponse response = defaultHttpClient.execute(get);
if (response.getStatusLine().getStatusCode() != 200) {
throw new StudyImporterException("failed to execute query to [ " + uri + "]: status code [" + response.getStatusLine().getStatusCode() + "]");
}
previousResultCount = parseJSON(response.getEntity().getContent(), study);
pageNumber++;
totalInteractions += previousResultCount;
LOG.info("importing [" + pageNumber + "] total [" + totalInteractions + "]");
} catch (IOException e) {
throw new StudyImporterException("failed to execute query to [ " + uri + "]", e);
}
} while (previousResultCount > 0);
} finally {
defaultHttpClient.getConnectionManager().shutdown();
}
return totalInteractions;
}
protected int parseJSON(InputStream retargetAsStream, Study study) throws StudyImporterException {
ObjectMapper mapper = new ObjectMapper();
JsonNode array = null;
try {
array = mapper.readTree(retargetAsStream);
} catch (IOException e) {
throw new StudyImporterException("error parsing inaturalist json", e);
}
if (!array.isArray()) {
throw new StudyImporterException("expected json array, but found object");
}
for (int i = 0; i < array.size(); i++) {
try {
parseSingleInteractions(study, array.get(i));
} catch (NodeFactoryException e) {
throw new StudyImporterException("failed to parse inaturalist interactions", e);
}
}
return array.size();
}
@Override
public void setImportFilter(ImportFilter importFilter) {
}
private void parseSingleInteractions(Study study, JsonNode jsonNode) throws NodeFactoryException, StudyImporterException {
JsonNode targetTaxon = jsonNode.get("taxon");
JsonNode targetTaxonNode = targetTaxon.get("name");
long observationId = jsonNode.get("observation_id").getLongValue();
if (targetTaxonNode == null) {
LOG.warn("skipping interaction with missing target taxon name for observation [" + observationId + "]");
} else {
String targetTaxonName = targetTaxonNode.getTextValue();
Specimen targetSpecimen = nodeFactory.createSpecimen(targetTaxonName);
JsonNode observationField = jsonNode.get("observation_field");
String interactionDataType = observationField.get("datatype").getTextValue();
String interactionType = observationField.get("name").getTextValue();
JsonNode observation = jsonNode.get("observation");
String latitudeString = observation.get("latitude").getTextValue();
String longitudeString = observation.get("longitude").getTextValue();
if (latitudeString != null && longitudeString != null) {
double latitude = Double.parseDouble(latitudeString);
double longitude = Double.parseDouble(longitudeString);
targetSpecimen.caughtIn(nodeFactory.getOrCreateLocation(latitude, longitude, null));
}
JsonNode sourceTaxon = observation.get("taxon");
if (sourceTaxon == null) {
LOG.warn("cannot create interaction with missing source taxon name for observation with id [" + observation.get("id") + "]");
} else {
JsonNode sourceTaxonNameNode = sourceTaxon.get("name");
String sourceTaxonName = sourceTaxonNameNode.getTextValue();
if (!"taxon".equals(interactionDataType)) {
throw new StudyImporterException("expected [taxon] as observation_type datatype, but found [" + interactionDataType + "]");
}
Specimen sourceSpecimen = nodeFactory.createSpecimen(sourceTaxonName);
sourceSpecimen.setExternalId(TaxonomyProvider.ID_PREFIX_INATURALIST + observationId);
Relationship collectedRel = study.collected(sourceSpecimen);
String timeObservedAtUtc = observation.get("time_observed_at_utc").getTextValue();
timeObservedAtUtc = timeObservedAtUtc == null ? observation.get("observed_on").getTextValue() : timeObservedAtUtc;
if (timeObservedAtUtc == null) {
LOG.warn("failed to retrieve observation time for [" + targetTaxonName + "]");
} else {
DateTime dateTime = parseUTCDateTime(timeObservedAtUtc);
nodeFactory.setUnixEpochProperty(collectedRel, dateTime.toDate());
}
InteractType type = null;
if ("Eating".equals(interactionType)) {
type = InteractType.ATE;
} else if ("Host".equals(interactionType)) {
- type = InteractType.HOST_OF;
+ type = InteractType.HAS_HOST;
} else if ("Flower species".equals(interactionType)) {
type = InteractType.POLLINATES;
} else if ("Perching on".equals(interactionType)) {
type = InteractType.PERCHING_ON;
} else if ("Pollinating".equals(interactionType)) {
type = InteractType.POLLINATES;
} else if ("Other Species in Group".equals(interactionType)) {
LOG.warn("interactionType [" + interactionDataType + "] not supported");
} else {
throw new StudyImporterException("found unsupported interactionType [" + interactionType + "]");
}
if (type != null) {
sourceSpecimen.interactsWith(targetSpecimen, type);
}
}
}
}
private DateTime parseUTCDateTime(String timeObservedAtUtc) {
return ISODateTimeFormat.dateTimeParser().parseDateTime(timeObservedAtUtc).withZone(DateTimeZone.UTC);
}
}
| true | true | private void parseSingleInteractions(Study study, JsonNode jsonNode) throws NodeFactoryException, StudyImporterException {
JsonNode targetTaxon = jsonNode.get("taxon");
JsonNode targetTaxonNode = targetTaxon.get("name");
long observationId = jsonNode.get("observation_id").getLongValue();
if (targetTaxonNode == null) {
LOG.warn("skipping interaction with missing target taxon name for observation [" + observationId + "]");
} else {
String targetTaxonName = targetTaxonNode.getTextValue();
Specimen targetSpecimen = nodeFactory.createSpecimen(targetTaxonName);
JsonNode observationField = jsonNode.get("observation_field");
String interactionDataType = observationField.get("datatype").getTextValue();
String interactionType = observationField.get("name").getTextValue();
JsonNode observation = jsonNode.get("observation");
String latitudeString = observation.get("latitude").getTextValue();
String longitudeString = observation.get("longitude").getTextValue();
if (latitudeString != null && longitudeString != null) {
double latitude = Double.parseDouble(latitudeString);
double longitude = Double.parseDouble(longitudeString);
targetSpecimen.caughtIn(nodeFactory.getOrCreateLocation(latitude, longitude, null));
}
JsonNode sourceTaxon = observation.get("taxon");
if (sourceTaxon == null) {
LOG.warn("cannot create interaction with missing source taxon name for observation with id [" + observation.get("id") + "]");
} else {
JsonNode sourceTaxonNameNode = sourceTaxon.get("name");
String sourceTaxonName = sourceTaxonNameNode.getTextValue();
if (!"taxon".equals(interactionDataType)) {
throw new StudyImporterException("expected [taxon] as observation_type datatype, but found [" + interactionDataType + "]");
}
Specimen sourceSpecimen = nodeFactory.createSpecimen(sourceTaxonName);
sourceSpecimen.setExternalId(TaxonomyProvider.ID_PREFIX_INATURALIST + observationId);
Relationship collectedRel = study.collected(sourceSpecimen);
String timeObservedAtUtc = observation.get("time_observed_at_utc").getTextValue();
timeObservedAtUtc = timeObservedAtUtc == null ? observation.get("observed_on").getTextValue() : timeObservedAtUtc;
if (timeObservedAtUtc == null) {
LOG.warn("failed to retrieve observation time for [" + targetTaxonName + "]");
} else {
DateTime dateTime = parseUTCDateTime(timeObservedAtUtc);
nodeFactory.setUnixEpochProperty(collectedRel, dateTime.toDate());
}
InteractType type = null;
if ("Eating".equals(interactionType)) {
type = InteractType.ATE;
} else if ("Host".equals(interactionType)) {
type = InteractType.HOST_OF;
} else if ("Flower species".equals(interactionType)) {
type = InteractType.POLLINATES;
} else if ("Perching on".equals(interactionType)) {
type = InteractType.PERCHING_ON;
} else if ("Pollinating".equals(interactionType)) {
type = InteractType.POLLINATES;
} else if ("Other Species in Group".equals(interactionType)) {
LOG.warn("interactionType [" + interactionDataType + "] not supported");
} else {
throw new StudyImporterException("found unsupported interactionType [" + interactionType + "]");
}
if (type != null) {
sourceSpecimen.interactsWith(targetSpecimen, type);
}
}
}
}
| private void parseSingleInteractions(Study study, JsonNode jsonNode) throws NodeFactoryException, StudyImporterException {
JsonNode targetTaxon = jsonNode.get("taxon");
JsonNode targetTaxonNode = targetTaxon.get("name");
long observationId = jsonNode.get("observation_id").getLongValue();
if (targetTaxonNode == null) {
LOG.warn("skipping interaction with missing target taxon name for observation [" + observationId + "]");
} else {
String targetTaxonName = targetTaxonNode.getTextValue();
Specimen targetSpecimen = nodeFactory.createSpecimen(targetTaxonName);
JsonNode observationField = jsonNode.get("observation_field");
String interactionDataType = observationField.get("datatype").getTextValue();
String interactionType = observationField.get("name").getTextValue();
JsonNode observation = jsonNode.get("observation");
String latitudeString = observation.get("latitude").getTextValue();
String longitudeString = observation.get("longitude").getTextValue();
if (latitudeString != null && longitudeString != null) {
double latitude = Double.parseDouble(latitudeString);
double longitude = Double.parseDouble(longitudeString);
targetSpecimen.caughtIn(nodeFactory.getOrCreateLocation(latitude, longitude, null));
}
JsonNode sourceTaxon = observation.get("taxon");
if (sourceTaxon == null) {
LOG.warn("cannot create interaction with missing source taxon name for observation with id [" + observation.get("id") + "]");
} else {
JsonNode sourceTaxonNameNode = sourceTaxon.get("name");
String sourceTaxonName = sourceTaxonNameNode.getTextValue();
if (!"taxon".equals(interactionDataType)) {
throw new StudyImporterException("expected [taxon] as observation_type datatype, but found [" + interactionDataType + "]");
}
Specimen sourceSpecimen = nodeFactory.createSpecimen(sourceTaxonName);
sourceSpecimen.setExternalId(TaxonomyProvider.ID_PREFIX_INATURALIST + observationId);
Relationship collectedRel = study.collected(sourceSpecimen);
String timeObservedAtUtc = observation.get("time_observed_at_utc").getTextValue();
timeObservedAtUtc = timeObservedAtUtc == null ? observation.get("observed_on").getTextValue() : timeObservedAtUtc;
if (timeObservedAtUtc == null) {
LOG.warn("failed to retrieve observation time for [" + targetTaxonName + "]");
} else {
DateTime dateTime = parseUTCDateTime(timeObservedAtUtc);
nodeFactory.setUnixEpochProperty(collectedRel, dateTime.toDate());
}
InteractType type = null;
if ("Eating".equals(interactionType)) {
type = InteractType.ATE;
} else if ("Host".equals(interactionType)) {
type = InteractType.HAS_HOST;
} else if ("Flower species".equals(interactionType)) {
type = InteractType.POLLINATES;
} else if ("Perching on".equals(interactionType)) {
type = InteractType.PERCHING_ON;
} else if ("Pollinating".equals(interactionType)) {
type = InteractType.POLLINATES;
} else if ("Other Species in Group".equals(interactionType)) {
LOG.warn("interactionType [" + interactionDataType + "] not supported");
} else {
throw new StudyImporterException("found unsupported interactionType [" + interactionType + "]");
}
if (type != null) {
sourceSpecimen.interactsWith(targetSpecimen, type);
}
}
}
}
|
diff --git a/core/plugins/org.eclipse.dltk.launching/src/org/eclipse/dltk/internal/launching/InterpreterContainer.java b/core/plugins/org.eclipse.dltk.launching/src/org/eclipse/dltk/internal/launching/InterpreterContainer.java
index c2f59e80e..925c56053 100644
--- a/core/plugins/org.eclipse.dltk.launching/src/org/eclipse/dltk/internal/launching/InterpreterContainer.java
+++ b/core/plugins/org.eclipse.dltk.launching/src/org/eclipse/dltk/internal/launching/InterpreterContainer.java
@@ -1,214 +1,214 @@
/*******************************************************************************
* Copyright (c) 2000, 2007 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
*
*******************************************************************************/
package org.eclipse.dltk.internal.launching;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.dltk.core.DLTKCore;
import org.eclipse.dltk.core.IAccessRule;
import org.eclipse.dltk.core.IBuildpathAttribute;
import org.eclipse.dltk.core.IBuildpathContainer;
import org.eclipse.dltk.core.IBuildpathEntry;
import org.eclipse.dltk.core.IBuiltinModuleProvider;
import org.eclipse.dltk.internal.core.BuildpathEntry;
import org.eclipse.dltk.launching.IInterpreterInstall;
import org.eclipse.dltk.launching.IInterpreterInstallChangedListener;
import org.eclipse.dltk.launching.LaunchingMessages;
import org.eclipse.dltk.launching.LibraryLocation;
import org.eclipse.dltk.launching.PropertyChangeEvent;
import org.eclipse.dltk.launching.ScriptRuntime;
import com.ibm.icu.text.MessageFormat;
/**
* Interpreter Container - resolves a buildpath container tp interpreter
*/
public class InterpreterContainer implements IBuildpathContainer {
/**
* Corresponding interpreter
*/
private IInterpreterInstall fInterpreterInstall = null;
/**
* Container path used to resolve to this interpreter
*/
private IPath fPath = null;
/**
* Cache of buildpath entries per Interpreter install. Cleared when a
* Interpreter changes.
*/
private static Map fgBuildpathEntries = null;
private static IAccessRule[] EMPTY_RULES = new IAccessRule[0];
/**
* Returns the buildpath entries associated with the given interpreter.
*
* @param interpreter
* @return buildpath entries
*/
private static IBuildpathEntry[] getBuildpathEntries(IInterpreterInstall interpreter) {
if (fgBuildpathEntries == null) {
fgBuildpathEntries = new HashMap(10);
// add a listener to clear cached value when a Interpreter changes or is
// removed
IInterpreterInstallChangedListener listener = new IInterpreterInstallChangedListener() {
public void defaultInterpreterInstallChanged(IInterpreterInstall previous, IInterpreterInstall current) {}
public void interpreterChanged(PropertyChangeEvent event) {
if (event.getSource() != null) {
fgBuildpathEntries.remove(event.getSource());
}
}
public void interpreterAdded(IInterpreterInstall newInterpreter) {
}
public void interpreterRemoved(IInterpreterInstall removedInterpreter) {
fgBuildpathEntries.remove(removedInterpreter);
}
};
ScriptRuntime.addInterpreterInstallChangedListener(listener);
}
IBuildpathEntry[] entries = (IBuildpathEntry[]) fgBuildpathEntries.get(interpreter);
if (entries == null) {
entries = computeBuildpathEntries(interpreter);
fgBuildpathEntries.put(interpreter, entries);
}
return entries;
}
/**
* Computes the buildpath entries associated with a interpreter - one entry
* per library.
*
* @param interpreter
* @return buildpath entries
*/
private static IBuildpathEntry[] computeBuildpathEntries(IInterpreterInstall interpreter) {
LibraryLocation[] libs = interpreter.getLibraryLocations();
if (libs == null) {
libs = ScriptRuntime.getLibraryLocations(interpreter);
}
List entries = new ArrayList(libs.length);
List rawEntries = new ArrayList (libs.length);
for (int i = 0; i < libs.length; i++) {
IPath entryPath = libs[i].getSystemLibraryPath();
if (!entryPath.isEmpty()) {
// resolve symlink
try {
File f = entryPath.toFile();
if (f == null)
continue;
entryPath = new Path(f.getCanonicalPath());
} catch (IOException e) {
continue;
}
if (rawEntries.contains(entryPath))
continue;
/*if (!entryPath.isAbsolute())
Assert.isTrue(false, "Path for IBuildpathEntry must be absolute"); //$NON-NLS-1$*/
IBuildpathAttribute[] attributes = new IBuildpathAttribute[0];
ArrayList excluded = new ArrayList(); // paths to exclude
for (int j = 0; j < libs.length; j++) {
IPath otherPath = libs[j].getSystemLibraryPath();
if (otherPath.isEmpty())
continue;
//resolve symlink
try {
File f = entryPath.toFile();
if (f == null)
continue;
entryPath = new Path(f.getCanonicalPath());
} catch (IOException e) {
continue;
}
// compare, if it contains some another
if (entryPath.isPrefixOf(otherPath) && !otherPath.equals(entryPath) ) {
IPath pattern = otherPath.removeFirstSegments(entryPath.segmentCount()).append("*");
if( !excluded.contains(pattern ) ) {
excluded.add(pattern);
}
}
}
entries.add(DLTKCore.newLibraryEntry(entryPath, EMPTY_RULES, attributes,
BuildpathEntry.INCLUDE_ALL, (IPath[]) excluded.toArray(new IPath[excluded.size()]), false, true));
rawEntries.add (entryPath);
}
}
// Add builtin entry.
{
IBuildpathAttribute[] attributes = new IBuildpathAttribute[0];
- entries.add(DLTKCore.newBuiltinEntry(IBuildpathEntry.BUILTIN_EXTERNAL_ENTRY, EMPTY_RULES, attributes, BuildpathEntry.INCLUDE_ALL, new IPath[0], false, true ));
+ entries.add(DLTKCore.newBuiltinEntry(IBuildpathEntry.BUILTIN_EXTERNAL_ENTRY.append(interpreter.getInstallLocation().getAbsolutePath()), EMPTY_RULES, attributes, BuildpathEntry.INCLUDE_ALL, new IPath[0], false, true ));
}
return (IBuildpathEntry[]) entries.toArray(new IBuildpathEntry[entries.size()]);
}
/**
* Constructs a interpreter buildpath container on the given interpreter
* install
*
* @param interpreter
* Interpreter install - cannot be <code>null</code>
* @param path
* container path used to resolve this interpreter
*/
public InterpreterContainer(IInterpreterInstall interpreter, IPath path) {
fInterpreterInstall = interpreter;
fPath = path;
}
/**
* @see IBuildpathContainer#getBuildpathEntries()
*/
public IBuildpathEntry[] getBuildpathEntries() {
return getBuildpathEntries(fInterpreterInstall);
}
/**
* @see IBuildpathContainer#getDescription()
*/
public String getDescription() {
String tag = fInterpreterInstall.getName();
return MessageFormat.format(LaunchingMessages.InterpreterEnvironmentContainer_InterpreterEnvironment_System_Library_1, new String[] {
tag
});
}
/**
* @see IBuildpathContainer#getKind()
*/
public int getKind() {
return IBuildpathContainer.K_DEFAULT_SYSTEM;
}
/**
* @see IBuildpathContainer#getPath()
*/
public IPath getPath() {
return fPath;
}
public IBuiltinModuleProvider getBuiltinProvider() {
return fInterpreterInstall;
}
}
| true | true | private static IBuildpathEntry[] computeBuildpathEntries(IInterpreterInstall interpreter) {
LibraryLocation[] libs = interpreter.getLibraryLocations();
if (libs == null) {
libs = ScriptRuntime.getLibraryLocations(interpreter);
}
List entries = new ArrayList(libs.length);
List rawEntries = new ArrayList (libs.length);
for (int i = 0; i < libs.length; i++) {
IPath entryPath = libs[i].getSystemLibraryPath();
if (!entryPath.isEmpty()) {
// resolve symlink
try {
File f = entryPath.toFile();
if (f == null)
continue;
entryPath = new Path(f.getCanonicalPath());
} catch (IOException e) {
continue;
}
if (rawEntries.contains(entryPath))
continue;
/*if (!entryPath.isAbsolute())
Assert.isTrue(false, "Path for IBuildpathEntry must be absolute"); //$NON-NLS-1$*/
IBuildpathAttribute[] attributes = new IBuildpathAttribute[0];
ArrayList excluded = new ArrayList(); // paths to exclude
for (int j = 0; j < libs.length; j++) {
IPath otherPath = libs[j].getSystemLibraryPath();
if (otherPath.isEmpty())
continue;
//resolve symlink
try {
File f = entryPath.toFile();
if (f == null)
continue;
entryPath = new Path(f.getCanonicalPath());
} catch (IOException e) {
continue;
}
// compare, if it contains some another
if (entryPath.isPrefixOf(otherPath) && !otherPath.equals(entryPath) ) {
IPath pattern = otherPath.removeFirstSegments(entryPath.segmentCount()).append("*");
if( !excluded.contains(pattern ) ) {
excluded.add(pattern);
}
}
}
entries.add(DLTKCore.newLibraryEntry(entryPath, EMPTY_RULES, attributes,
BuildpathEntry.INCLUDE_ALL, (IPath[]) excluded.toArray(new IPath[excluded.size()]), false, true));
rawEntries.add (entryPath);
}
}
// Add builtin entry.
{
IBuildpathAttribute[] attributes = new IBuildpathAttribute[0];
entries.add(DLTKCore.newBuiltinEntry(IBuildpathEntry.BUILTIN_EXTERNAL_ENTRY, EMPTY_RULES, attributes, BuildpathEntry.INCLUDE_ALL, new IPath[0], false, true ));
}
return (IBuildpathEntry[]) entries.toArray(new IBuildpathEntry[entries.size()]);
}
| private static IBuildpathEntry[] computeBuildpathEntries(IInterpreterInstall interpreter) {
LibraryLocation[] libs = interpreter.getLibraryLocations();
if (libs == null) {
libs = ScriptRuntime.getLibraryLocations(interpreter);
}
List entries = new ArrayList(libs.length);
List rawEntries = new ArrayList (libs.length);
for (int i = 0; i < libs.length; i++) {
IPath entryPath = libs[i].getSystemLibraryPath();
if (!entryPath.isEmpty()) {
// resolve symlink
try {
File f = entryPath.toFile();
if (f == null)
continue;
entryPath = new Path(f.getCanonicalPath());
} catch (IOException e) {
continue;
}
if (rawEntries.contains(entryPath))
continue;
/*if (!entryPath.isAbsolute())
Assert.isTrue(false, "Path for IBuildpathEntry must be absolute"); //$NON-NLS-1$*/
IBuildpathAttribute[] attributes = new IBuildpathAttribute[0];
ArrayList excluded = new ArrayList(); // paths to exclude
for (int j = 0; j < libs.length; j++) {
IPath otherPath = libs[j].getSystemLibraryPath();
if (otherPath.isEmpty())
continue;
//resolve symlink
try {
File f = entryPath.toFile();
if (f == null)
continue;
entryPath = new Path(f.getCanonicalPath());
} catch (IOException e) {
continue;
}
// compare, if it contains some another
if (entryPath.isPrefixOf(otherPath) && !otherPath.equals(entryPath) ) {
IPath pattern = otherPath.removeFirstSegments(entryPath.segmentCount()).append("*");
if( !excluded.contains(pattern ) ) {
excluded.add(pattern);
}
}
}
entries.add(DLTKCore.newLibraryEntry(entryPath, EMPTY_RULES, attributes,
BuildpathEntry.INCLUDE_ALL, (IPath[]) excluded.toArray(new IPath[excluded.size()]), false, true));
rawEntries.add (entryPath);
}
}
// Add builtin entry.
{
IBuildpathAttribute[] attributes = new IBuildpathAttribute[0];
entries.add(DLTKCore.newBuiltinEntry(IBuildpathEntry.BUILTIN_EXTERNAL_ENTRY.append(interpreter.getInstallLocation().getAbsolutePath()), EMPTY_RULES, attributes, BuildpathEntry.INCLUDE_ALL, new IPath[0], false, true ));
}
return (IBuildpathEntry[]) entries.toArray(new IBuildpathEntry[entries.size()]);
}
|
diff --git a/vol1/java-examples/src/main/java/com/heatonresearch/aifh/regression/TrainReweightLeastSquares.java b/vol1/java-examples/src/main/java/com/heatonresearch/aifh/regression/TrainReweightLeastSquares.java
index b48fc66..de1961f 100644
--- a/vol1/java-examples/src/main/java/com/heatonresearch/aifh/regression/TrainReweightLeastSquares.java
+++ b/vol1/java-examples/src/main/java/com/heatonresearch/aifh/regression/TrainReweightLeastSquares.java
@@ -1,159 +1,159 @@
/*
* Artificial Intelligence for Humans
* Volume 1: Fundamental Algorithms
* Java Version
* http://www.aifh.org
* http://www.jeffheaton.com
*
* Code repository:
* https://github.com/jeffheaton/aifh
* Copyright 2013 by Jeff Heaton
*
* 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.
*
* For more information on Heaton Research copyrights, licenses
* and trademarks visit:
* http://www.heatonresearch.com/copyright
*/
package com.heatonresearch.aifh.regression;
import Jama.LUDecomposition;
import Jama.Matrix;
import com.heatonresearch.aifh.AIFHError;
import com.heatonresearch.aifh.general.data.BasicData;
import java.util.List;
/**
* Train a GLM using iteratively reweighted least squares.
* <p/>
* http://en.wikipedia.org/wiki/Iteratively_reweighted_least_squares
*/
public class TrainReweightLeastSquares {
/**
* The GLM to train.
*/
private final MultipleLinearRegression algorithm;
/**
* The training data.
*/
private final List<BasicData> trainingData;
/**
* The last error.
*/
private double error;
/**
* The Hessian matrix.
*/
private final double[][] hessian;
/**
* The gradient matrix.
*/
private final Matrix gradient;
/**
* Construct the trainer.
*
* @param theAlgorithm The GLM to train.
* @param theTrainingData The training data.
*/
public TrainReweightLeastSquares(final MultipleLinearRegression theAlgorithm, final List<BasicData> theTrainingData) {
this.algorithm = theAlgorithm;
this.trainingData = theTrainingData;
this.gradient = new Matrix(theAlgorithm.getLongTermMemory().length, 1);
this.hessian = new double[theAlgorithm.getLongTermMemory().length][theAlgorithm.getLongTermMemory().length];
}
/**
* Perform one iteration of training.
*/
public void iteration() {
final int rowCount = this.trainingData.size();
final int coeffCount = this.algorithm.getLongTermMemory().length;
final double[][] working = new double[rowCount][coeffCount];
final double[] errors = new double[rowCount];
final double[] weights = new double[rowCount];
final Matrix deltas;
for (int i = 0; i < rowCount; i++) {
final BasicData element = this.trainingData.get(i);
working[i][0] = 1;
for (int j = 0; j < element.getInput().length; j++)
working[i][j + 1] = element.getInput()[j];
}
for (int i = 0; i < rowCount; i++) {
final BasicData element = this.trainingData.get(i);
final double y = this.algorithm.computeRegression(element.getInput())[0];
errors[i] = y - element.getIdeal()[0];
weights[i] = y * (1.0 - y);
}
for (int i = 0; i < gradient.getColumnDimension(); i++) {
gradient.set(0, i, 0);
for (int j = 0; j < gradient.getColumnDimension(); j++)
hessian[i][j] = 0;
}
for (int j = 0; j < working.length; j++) {
- for (int i = 0; i < gradient.getColumnDimension(); i++) {
+ for (int i = 0; i < gradient.getRowDimension(); i++) {
gradient.set(i, 0, gradient.get(i, 0) + working[j][i] * errors[j]);
}
}
for (int k = 0; k < weights.length; k++) {
final double[] r = working[k];
for (int j = 0; j < r.length; j++) {
for (int i = 0; i < r.length; i++) {
hessian[j][i] += r[i] * r[j] * weights[k];
}
}
}
final LUDecomposition lu = new LUDecomposition(new Matrix(hessian));
if (lu.isNonsingular()) {
deltas = lu.solve(gradient);
} else {
throw new AIFHError("Matrix Non singular");
}
final double[] prev = this.algorithm.getLongTermMemory().clone();
for (int i = 0; i < this.algorithm.getLongTermMemory().length; i++)
this.algorithm.getLongTermMemory()[i] -= deltas.get(i, 0);
double max = 0;
for (int i = 0; i < deltas.getColumnDimension(); i++)
max = Math.max(Math.abs(deltas.get(i, 0)) / Math.abs(prev[i]), max);
this.error = max;
}
/**
* @return The last error.
*/
public double getError() {
return this.error;
}
}
| true | true | public void iteration() {
final int rowCount = this.trainingData.size();
final int coeffCount = this.algorithm.getLongTermMemory().length;
final double[][] working = new double[rowCount][coeffCount];
final double[] errors = new double[rowCount];
final double[] weights = new double[rowCount];
final Matrix deltas;
for (int i = 0; i < rowCount; i++) {
final BasicData element = this.trainingData.get(i);
working[i][0] = 1;
for (int j = 0; j < element.getInput().length; j++)
working[i][j + 1] = element.getInput()[j];
}
for (int i = 0; i < rowCount; i++) {
final BasicData element = this.trainingData.get(i);
final double y = this.algorithm.computeRegression(element.getInput())[0];
errors[i] = y - element.getIdeal()[0];
weights[i] = y * (1.0 - y);
}
for (int i = 0; i < gradient.getColumnDimension(); i++) {
gradient.set(0, i, 0);
for (int j = 0; j < gradient.getColumnDimension(); j++)
hessian[i][j] = 0;
}
for (int j = 0; j < working.length; j++) {
for (int i = 0; i < gradient.getColumnDimension(); i++) {
gradient.set(i, 0, gradient.get(i, 0) + working[j][i] * errors[j]);
}
}
for (int k = 0; k < weights.length; k++) {
final double[] r = working[k];
for (int j = 0; j < r.length; j++) {
for (int i = 0; i < r.length; i++) {
hessian[j][i] += r[i] * r[j] * weights[k];
}
}
}
final LUDecomposition lu = new LUDecomposition(new Matrix(hessian));
if (lu.isNonsingular()) {
deltas = lu.solve(gradient);
} else {
throw new AIFHError("Matrix Non singular");
}
final double[] prev = this.algorithm.getLongTermMemory().clone();
for (int i = 0; i < this.algorithm.getLongTermMemory().length; i++)
this.algorithm.getLongTermMemory()[i] -= deltas.get(i, 0);
double max = 0;
for (int i = 0; i < deltas.getColumnDimension(); i++)
max = Math.max(Math.abs(deltas.get(i, 0)) / Math.abs(prev[i]), max);
this.error = max;
}
| public void iteration() {
final int rowCount = this.trainingData.size();
final int coeffCount = this.algorithm.getLongTermMemory().length;
final double[][] working = new double[rowCount][coeffCount];
final double[] errors = new double[rowCount];
final double[] weights = new double[rowCount];
final Matrix deltas;
for (int i = 0; i < rowCount; i++) {
final BasicData element = this.trainingData.get(i);
working[i][0] = 1;
for (int j = 0; j < element.getInput().length; j++)
working[i][j + 1] = element.getInput()[j];
}
for (int i = 0; i < rowCount; i++) {
final BasicData element = this.trainingData.get(i);
final double y = this.algorithm.computeRegression(element.getInput())[0];
errors[i] = y - element.getIdeal()[0];
weights[i] = y * (1.0 - y);
}
for (int i = 0; i < gradient.getColumnDimension(); i++) {
gradient.set(0, i, 0);
for (int j = 0; j < gradient.getColumnDimension(); j++)
hessian[i][j] = 0;
}
for (int j = 0; j < working.length; j++) {
for (int i = 0; i < gradient.getRowDimension(); i++) {
gradient.set(i, 0, gradient.get(i, 0) + working[j][i] * errors[j]);
}
}
for (int k = 0; k < weights.length; k++) {
final double[] r = working[k];
for (int j = 0; j < r.length; j++) {
for (int i = 0; i < r.length; i++) {
hessian[j][i] += r[i] * r[j] * weights[k];
}
}
}
final LUDecomposition lu = new LUDecomposition(new Matrix(hessian));
if (lu.isNonsingular()) {
deltas = lu.solve(gradient);
} else {
throw new AIFHError("Matrix Non singular");
}
final double[] prev = this.algorithm.getLongTermMemory().clone();
for (int i = 0; i < this.algorithm.getLongTermMemory().length; i++)
this.algorithm.getLongTermMemory()[i] -= deltas.get(i, 0);
double max = 0;
for (int i = 0; i < deltas.getColumnDimension(); i++)
max = Math.max(Math.abs(deltas.get(i, 0)) / Math.abs(prev[i]), max);
this.error = max;
}
|
diff --git a/jsf/tests/org.jboss.tools.jsf.text.ext.test/src/org/jboss/tools/jsf/text/ext/tests/ELExprPartitionerTest.java b/jsf/tests/org.jboss.tools.jsf.text.ext.test/src/org/jboss/tools/jsf/text/ext/tests/ELExprPartitionerTest.java
index ab0abaf7d..fd5abef0f 100644
--- a/jsf/tests/org.jboss.tools.jsf.text.ext.test/src/org/jboss/tools/jsf/text/ext/tests/ELExprPartitionerTest.java
+++ b/jsf/tests/org.jboss.tools.jsf.text.ext.test/src/org/jboss/tools/jsf/text/ext/tests/ELExprPartitionerTest.java
@@ -1,283 +1,287 @@
/*******************************************************************************
* 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.jsf.text.ext.tests;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentExtension3;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.Region;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.texteditor.DocumentProviderRegistry;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.wst.sse.core.StructuredModelManager;
import org.eclipse.wst.sse.core.internal.provisional.IModelManager;
import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
import org.eclipse.wst.sse.ui.internal.editor.EditorModelUtil;
import org.jboss.tools.common.model.XJob;
import org.jboss.tools.common.test.util.TestProjectProvider;
import org.jboss.tools.common.text.ext.hyperlink.IHyperlinkRegion;
import org.jboss.tools.common.text.ext.util.AxisUtil;
import org.jboss.tools.jsf.text.ext.hyperlink.JSPExprHyperlinkPartitioner;
public class ELExprPartitionerTest extends TestCase {
TestProjectProvider provider = null;
IProject project = null;
boolean makeCopy = false;
private static final String PROJECT_NAME = "numberguess";
private static final String PAGE_NAME = "/web/giveup.jspx";
public static Test suite() {
return new TestSuite(ELExprPartitionerTest.class);
}
public void setUp() throws Exception {
provider = new TestProjectProvider("org.jboss.tools.jsf.text.ext.test", null, PROJECT_NAME, makeCopy);
project = provider.getProject();
Throwable exception = null;
try {
project.refreshLocal(IResource.DEPTH_INFINITE, null);
} catch (Exception x) {
exception = x;
x.printStackTrace();
}
assertNull("An exception caught: " + (exception != null? exception.getMessage() : ""), exception);
}
protected void tearDown() throws Exception {
if(provider != null) {
provider.dispose();
}
}
public void testELExprPartitioner() {
try {
XJob.waitForJob();
} catch (InterruptedException e) {
e.printStackTrace();
}
assertTrue("Test project \"" + PROJECT_NAME + "\" is not loaded", (project != null));
IFile jspFile = project.getFile(PAGE_NAME);
assertTrue("The file \"" + PAGE_NAME + "\" is not found", (jspFile != null));
assertTrue("The file \"" + PAGE_NAME + "\" is not found", (jspFile.exists()));
FileEditorInput editorInput = new FileEditorInput(jspFile);
IDocumentProvider documentProvider = null;
Throwable exception = null;
try {
documentProvider = DocumentProviderRegistry.getDefault().getDocumentProvider(editorInput);
} catch (Exception x) {
exception = x;
x.printStackTrace();
}
assertNull("An exception caught: " + (exception != null? exception.getMessage() : ""), exception);
assertTrue("The document provider for the file \"" + PAGE_NAME + "\" is not loaded", (documentProvider != null));
try {
documentProvider.connect(editorInput);
} catch (Exception x) {
exception = x;
x.printStackTrace();
assertTrue("The document provider is not able to be initialized with the editor input", false);
}
assertNull("An exception caught: " + (exception != null? exception.getMessage() : ""), exception);
IDocument document = documentProvider.getDocument(editorInput);
assertTrue("The document for the file \"" + PAGE_NAME + "\" is not loaded", (document != null));
IStructuredModel model = null;
if (document instanceof IStructuredDocument) {
// corresponding releaseFromEdit occurs in
// dispose()
model = StructuredModelManager.getModelManager().getModelForEdit((IStructuredDocument) document);
EditorModelUtil.addFactoriesTo(model);
}
assertTrue("The document model for the file \"" + PAGE_NAME + "\" is not loaded", (model != null));
JSPExprHyperlinkPartitioner elPartitioner = new JSPExprHyperlinkPartitioner();
HashMap<Object, ArrayList> recognitionTest = new HashMap<Object, ArrayList>();
ArrayList<Region> regionList = new ArrayList<Region>();
regionList.add(new Region(623, 16));
regionList.add(new Region(706, 16));
regionList.add(new Region(813, 18));
regionList.add(new Region(914, 19));
regionList.add(new Region(972, 18));
regionList.add(new Region(1041, 17));
recognitionTest.put("org.jboss.tools.common.text.ext.jsp.JSP_BUNDLE", regionList);
regionList = new ArrayList<Region>();
regionList.add(new Region(859, 11));
regionList.add(new Region(871, 16));
recognitionTest.put("org.jboss.tools.common.text.ext.jsp.JSP_BEAN", regionList);
regionList = new ArrayList<Region>();
+ regionList.add(new Region(859, 11));
+ regionList.add(new Region(871, 16));
+ recognitionTest.put("org.jboss.tools.seam.text.ext.SEAM_BEAN", regionList);
+ regionList = new ArrayList<Region>();
regionList.add(new Region(639, 1));
regionList.add(new Region(722, 1));
regionList.add(new Region(831, 1));
regionList.add(new Region(887, 1));
regionList.add(new Region(933, 1));
regionList.add(new Region(990, 1));
regionList.add(new Region(1058, 1));
recognitionTest.put("org.jboss.tools.common.text.ext.jsp.JSP_EXPRESSION", regionList);
int counter = 0;
for (int i = 0; i < document.getLength(); i++) {
TestData testData = new TestData(document, i);
boolean recognized = elPartitioner.recognize(testData.document, testData.getHyperlinkRegion());
if (recognized) {
String childPartitionType = elPartitioner.getChildPartitionType(testData.document, testData.getHyperlinkRegion());
if (childPartitionType != null) {
ArrayList test = (ArrayList)recognitionTest.get(childPartitionType);
boolean testResult = false;
Iterator regions = test.iterator();
Region r = null;
while (!testResult && regions.hasNext()) {
r = (Region)regions.next();
if (r.getOffset() <= testData.offset && testData.offset < (r.getOffset() + r.getLength()))
testResult = true;
}
assertTrue("Wrong recognition for the region: " + testData.getHyperlinkRegion().toString()
+ " doesn't matches the region [" + r.getOffset() + "-" + (r.getOffset() + r.getLength()) + "]" , testResult);
counter++;
} else {
recognized = false;
}
}
if (!recognized) {
boolean testResult = false;
Iterator keys = recognitionTest.keySet().iterator();
Region r = null;
while (keys != null && keys.hasNext()) {
Object key = keys.next();
ArrayList test = (ArrayList)recognitionTest.get(key);
Iterator regions = test.iterator();
while (!testResult && regions.hasNext()) {
r = (Region)regions.next();
if (r.getOffset() <= testData.offset && testData.offset < (r.getOffset() + r.getLength()))
testResult = true;
}
}
assertTrue("Wrong recognition for the region: " + testData.getHyperlinkRegion().toString()
+ " matches the wrong region [" + r.getOffset() + "-" + (r.getOffset() + r.getLength()) + "]" , (testResult == false));
}
}
assertTrue("Wrong recognized region count: " + counter
+ " (must be 138)" , (counter == 138));
model.releaseFromEdit();
documentProvider.disconnect(editorInput);
}
class TestData {
IDocument document;
int offset;
ITypedRegion region;
String contentType;
private IHyperlinkRegion hyperlinkRegion = null;
TestData (IDocument document, int offset) {
this.document = document;
this.offset = offset;
init();
}
private void init() {
this.region = getDocumentRegion();
this.contentType = getContentType();
this.hyperlinkRegion = getHyperlinkRegion();
}
private ITypedRegion getDocumentRegion() {
ITypedRegion region = null;
try {
region = (document instanceof IDocumentExtension3 ?
((IDocumentExtension3)document).getDocumentPartitioner("org.eclipse.wst.sse.core.default_structured_text_partitioning").getPartition(offset) :
document.getDocumentPartitioner().getPartition(offset));
} catch (Exception x) {}
return region;
}
public IHyperlinkRegion getHyperlinkRegion() {
if (hyperlinkRegion != null)
return hyperlinkRegion;
return new IHyperlinkRegion() {
public String getAxis() {
return AxisUtil.getAxis(document, region.getOffset());
}
public String getContentType() {
return contentType;
}
public String getType() {
return region.getType();
}
public int getLength() {
return region.getLength();
}
public int getOffset() {
return region.getOffset();
}
public String toString() {
return "[" + getOffset() + "-" + (getOffset() + getLength() - 1) + ":" + getType() + ":" + getContentType() + "]";
}
};
}
/**
* Returns the content type of document
*
* @param document -
* assumes document is not null
* @return String content type of given document
*/
private String getContentType() {
String type = null;
IModelManager mgr = StructuredModelManager.getModelManager();
IStructuredModel model = null;
try {
model = mgr.getExistingModelForRead(document);
if (model != null) {
type = model.getContentTypeIdentifier();
}
} finally {
if (model != null) {
model.releaseFromRead();
}
}
return type;
}
}
}
| true | true | public void testELExprPartitioner() {
try {
XJob.waitForJob();
} catch (InterruptedException e) {
e.printStackTrace();
}
assertTrue("Test project \"" + PROJECT_NAME + "\" is not loaded", (project != null));
IFile jspFile = project.getFile(PAGE_NAME);
assertTrue("The file \"" + PAGE_NAME + "\" is not found", (jspFile != null));
assertTrue("The file \"" + PAGE_NAME + "\" is not found", (jspFile.exists()));
FileEditorInput editorInput = new FileEditorInput(jspFile);
IDocumentProvider documentProvider = null;
Throwable exception = null;
try {
documentProvider = DocumentProviderRegistry.getDefault().getDocumentProvider(editorInput);
} catch (Exception x) {
exception = x;
x.printStackTrace();
}
assertNull("An exception caught: " + (exception != null? exception.getMessage() : ""), exception);
assertTrue("The document provider for the file \"" + PAGE_NAME + "\" is not loaded", (documentProvider != null));
try {
documentProvider.connect(editorInput);
} catch (Exception x) {
exception = x;
x.printStackTrace();
assertTrue("The document provider is not able to be initialized with the editor input", false);
}
assertNull("An exception caught: " + (exception != null? exception.getMessage() : ""), exception);
IDocument document = documentProvider.getDocument(editorInput);
assertTrue("The document for the file \"" + PAGE_NAME + "\" is not loaded", (document != null));
IStructuredModel model = null;
if (document instanceof IStructuredDocument) {
// corresponding releaseFromEdit occurs in
// dispose()
model = StructuredModelManager.getModelManager().getModelForEdit((IStructuredDocument) document);
EditorModelUtil.addFactoriesTo(model);
}
assertTrue("The document model for the file \"" + PAGE_NAME + "\" is not loaded", (model != null));
JSPExprHyperlinkPartitioner elPartitioner = new JSPExprHyperlinkPartitioner();
HashMap<Object, ArrayList> recognitionTest = new HashMap<Object, ArrayList>();
ArrayList<Region> regionList = new ArrayList<Region>();
regionList.add(new Region(623, 16));
regionList.add(new Region(706, 16));
regionList.add(new Region(813, 18));
regionList.add(new Region(914, 19));
regionList.add(new Region(972, 18));
regionList.add(new Region(1041, 17));
recognitionTest.put("org.jboss.tools.common.text.ext.jsp.JSP_BUNDLE", regionList);
regionList = new ArrayList<Region>();
regionList.add(new Region(859, 11));
regionList.add(new Region(871, 16));
recognitionTest.put("org.jboss.tools.common.text.ext.jsp.JSP_BEAN", regionList);
regionList = new ArrayList<Region>();
regionList.add(new Region(639, 1));
regionList.add(new Region(722, 1));
regionList.add(new Region(831, 1));
regionList.add(new Region(887, 1));
regionList.add(new Region(933, 1));
regionList.add(new Region(990, 1));
regionList.add(new Region(1058, 1));
recognitionTest.put("org.jboss.tools.common.text.ext.jsp.JSP_EXPRESSION", regionList);
int counter = 0;
for (int i = 0; i < document.getLength(); i++) {
TestData testData = new TestData(document, i);
boolean recognized = elPartitioner.recognize(testData.document, testData.getHyperlinkRegion());
if (recognized) {
String childPartitionType = elPartitioner.getChildPartitionType(testData.document, testData.getHyperlinkRegion());
if (childPartitionType != null) {
ArrayList test = (ArrayList)recognitionTest.get(childPartitionType);
boolean testResult = false;
Iterator regions = test.iterator();
Region r = null;
while (!testResult && regions.hasNext()) {
r = (Region)regions.next();
if (r.getOffset() <= testData.offset && testData.offset < (r.getOffset() + r.getLength()))
testResult = true;
}
assertTrue("Wrong recognition for the region: " + testData.getHyperlinkRegion().toString()
+ " doesn't matches the region [" + r.getOffset() + "-" + (r.getOffset() + r.getLength()) + "]" , testResult);
counter++;
} else {
recognized = false;
}
}
if (!recognized) {
boolean testResult = false;
Iterator keys = recognitionTest.keySet().iterator();
Region r = null;
while (keys != null && keys.hasNext()) {
Object key = keys.next();
ArrayList test = (ArrayList)recognitionTest.get(key);
Iterator regions = test.iterator();
while (!testResult && regions.hasNext()) {
r = (Region)regions.next();
if (r.getOffset() <= testData.offset && testData.offset < (r.getOffset() + r.getLength()))
testResult = true;
}
}
assertTrue("Wrong recognition for the region: " + testData.getHyperlinkRegion().toString()
+ " matches the wrong region [" + r.getOffset() + "-" + (r.getOffset() + r.getLength()) + "]" , (testResult == false));
}
}
assertTrue("Wrong recognized region count: " + counter
+ " (must be 138)" , (counter == 138));
model.releaseFromEdit();
documentProvider.disconnect(editorInput);
}
| public void testELExprPartitioner() {
try {
XJob.waitForJob();
} catch (InterruptedException e) {
e.printStackTrace();
}
assertTrue("Test project \"" + PROJECT_NAME + "\" is not loaded", (project != null));
IFile jspFile = project.getFile(PAGE_NAME);
assertTrue("The file \"" + PAGE_NAME + "\" is not found", (jspFile != null));
assertTrue("The file \"" + PAGE_NAME + "\" is not found", (jspFile.exists()));
FileEditorInput editorInput = new FileEditorInput(jspFile);
IDocumentProvider documentProvider = null;
Throwable exception = null;
try {
documentProvider = DocumentProviderRegistry.getDefault().getDocumentProvider(editorInput);
} catch (Exception x) {
exception = x;
x.printStackTrace();
}
assertNull("An exception caught: " + (exception != null? exception.getMessage() : ""), exception);
assertTrue("The document provider for the file \"" + PAGE_NAME + "\" is not loaded", (documentProvider != null));
try {
documentProvider.connect(editorInput);
} catch (Exception x) {
exception = x;
x.printStackTrace();
assertTrue("The document provider is not able to be initialized with the editor input", false);
}
assertNull("An exception caught: " + (exception != null? exception.getMessage() : ""), exception);
IDocument document = documentProvider.getDocument(editorInput);
assertTrue("The document for the file \"" + PAGE_NAME + "\" is not loaded", (document != null));
IStructuredModel model = null;
if (document instanceof IStructuredDocument) {
// corresponding releaseFromEdit occurs in
// dispose()
model = StructuredModelManager.getModelManager().getModelForEdit((IStructuredDocument) document);
EditorModelUtil.addFactoriesTo(model);
}
assertTrue("The document model for the file \"" + PAGE_NAME + "\" is not loaded", (model != null));
JSPExprHyperlinkPartitioner elPartitioner = new JSPExprHyperlinkPartitioner();
HashMap<Object, ArrayList> recognitionTest = new HashMap<Object, ArrayList>();
ArrayList<Region> regionList = new ArrayList<Region>();
regionList.add(new Region(623, 16));
regionList.add(new Region(706, 16));
regionList.add(new Region(813, 18));
regionList.add(new Region(914, 19));
regionList.add(new Region(972, 18));
regionList.add(new Region(1041, 17));
recognitionTest.put("org.jboss.tools.common.text.ext.jsp.JSP_BUNDLE", regionList);
regionList = new ArrayList<Region>();
regionList.add(new Region(859, 11));
regionList.add(new Region(871, 16));
recognitionTest.put("org.jboss.tools.common.text.ext.jsp.JSP_BEAN", regionList);
regionList = new ArrayList<Region>();
regionList.add(new Region(859, 11));
regionList.add(new Region(871, 16));
recognitionTest.put("org.jboss.tools.seam.text.ext.SEAM_BEAN", regionList);
regionList = new ArrayList<Region>();
regionList.add(new Region(639, 1));
regionList.add(new Region(722, 1));
regionList.add(new Region(831, 1));
regionList.add(new Region(887, 1));
regionList.add(new Region(933, 1));
regionList.add(new Region(990, 1));
regionList.add(new Region(1058, 1));
recognitionTest.put("org.jboss.tools.common.text.ext.jsp.JSP_EXPRESSION", regionList);
int counter = 0;
for (int i = 0; i < document.getLength(); i++) {
TestData testData = new TestData(document, i);
boolean recognized = elPartitioner.recognize(testData.document, testData.getHyperlinkRegion());
if (recognized) {
String childPartitionType = elPartitioner.getChildPartitionType(testData.document, testData.getHyperlinkRegion());
if (childPartitionType != null) {
ArrayList test = (ArrayList)recognitionTest.get(childPartitionType);
boolean testResult = false;
Iterator regions = test.iterator();
Region r = null;
while (!testResult && regions.hasNext()) {
r = (Region)regions.next();
if (r.getOffset() <= testData.offset && testData.offset < (r.getOffset() + r.getLength()))
testResult = true;
}
assertTrue("Wrong recognition for the region: " + testData.getHyperlinkRegion().toString()
+ " doesn't matches the region [" + r.getOffset() + "-" + (r.getOffset() + r.getLength()) + "]" , testResult);
counter++;
} else {
recognized = false;
}
}
if (!recognized) {
boolean testResult = false;
Iterator keys = recognitionTest.keySet().iterator();
Region r = null;
while (keys != null && keys.hasNext()) {
Object key = keys.next();
ArrayList test = (ArrayList)recognitionTest.get(key);
Iterator regions = test.iterator();
while (!testResult && regions.hasNext()) {
r = (Region)regions.next();
if (r.getOffset() <= testData.offset && testData.offset < (r.getOffset() + r.getLength()))
testResult = true;
}
}
assertTrue("Wrong recognition for the region: " + testData.getHyperlinkRegion().toString()
+ " matches the wrong region [" + r.getOffset() + "-" + (r.getOffset() + r.getLength()) + "]" , (testResult == false));
}
}
assertTrue("Wrong recognized region count: " + counter
+ " (must be 138)" , (counter == 138));
model.releaseFromEdit();
documentProvider.disconnect(editorInput);
}
|
diff --git a/src/niagara/client/QueryFactory.java b/src/niagara/client/QueryFactory.java
index 454d3be..b237ebf 100755
--- a/src/niagara/client/QueryFactory.java
+++ b/src/niagara/client/QueryFactory.java
@@ -1,14 +1,12 @@
package niagara.client;
public class QueryFactory {
public static Query makeQuery(String text) throws ClientException {
if (text.startsWith("<?xml"))
return new QPQuery(text);
- else if (text.toUpperCase().indexOf("WHERE") != -1)
- return new XMLQLQuery(text);
- else {
- throw new ClientException("Invalid query: " + text);
- }
+ else
+ throw new ClientException("Invalid Query: " + text);
+ // return new XMLQLQuery(text);
}
}
| true | true | public static Query makeQuery(String text) throws ClientException {
if (text.startsWith("<?xml"))
return new QPQuery(text);
else if (text.toUpperCase().indexOf("WHERE") != -1)
return new XMLQLQuery(text);
else {
throw new ClientException("Invalid query: " + text);
}
}
| public static Query makeQuery(String text) throws ClientException {
if (text.startsWith("<?xml"))
return new QPQuery(text);
else
throw new ClientException("Invalid Query: " + text);
// return new XMLQLQuery(text);
}
|
diff --git a/java/src/memoplayer/FontStyle.java b/java/src/memoplayer/FontStyle.java
index 5e5969b..ae1202b 100644
--- a/java/src/memoplayer/FontStyle.java
+++ b/java/src/memoplayer/FontStyle.java
@@ -1,202 +1,202 @@
/*
* Copyright (C) 2010 France Telecom
*
* 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 memoplayer;
//#ifndef BlackBerry
import javax.microedition.lcdui.Font;
//#endif
public class FontStyle extends Node {
final static int LEFT = 0;
final static int MIDDLE = 1;
final static int RIGHT = 2;
final static int TOP = 3;
final static int BASELINE = 4;
final static int BOTTOM = 5;
ExternFont m_externFont;
int size = Font.SIZE_MEDIUM;
int style = Font.STYLE_BOLD;
int family = Font.FACE_SYSTEM;
int justifyH = MIDDLE;
int justifyV = TOP;
// initialize default font sizes
static int s_fontLarge = Font.SIZE_LARGE;
static int s_fontMedium = Font.SIZE_MEDIUM;
static int s_fontSmall = Font.SIZE_SMALL;
// check font size modifier from jad
static {
String p;
if ((p = MiniPlayer.getJadProperty("MEMO-FONT_LARGE")) != null && p.length() > 0) {
s_fontLarge = getFontToken(p);
}
if ((p = MiniPlayer.getJadProperty("MEMO-FONT_MEDIUM")) != null && p.length() > 0) {
s_fontMedium = getFontToken(p);
}
if ((p = MiniPlayer.getJadProperty("MEMO-FONT_SMALL")) != null && p.length() > 0) {
s_fontSmall = getFontToken(p);
}
}
static private int getFontToken (String s) {
if (s.equals ("LARGE")) return Font.SIZE_LARGE;
if (s.equals ("SMALL")) return Font.SIZE_SMALL;
return Font.SIZE_MEDIUM;
}
// Constructor
FontStyle () {
super (5);
//System.out.println ("Text created");
m_field[0] = new SFFloat (12, this); // size
m_field[1] = new SFString ("plain", this); // style
m_field[2] = new MFString (this); // justify
m_field[3] = new MFString (this); // family
m_field[4] = new SFBool (false, null); // family
}
boolean getFilterMode () {
return ((SFBool)m_field[4]).getValue ();
}
void start (Context c) {
fieldChanged (m_field[0]); // any field triggers the whole parsing
}
void stop (Context c) {
if (m_externFont != null) {
m_externFont.release ();
m_externFont = null;
}
}
public void fieldChanged (Field f) {
if (f == m_field [0]) {
int tmpSize = FixFloat.fix2int (((SFFloat)m_field[0]).getValue ());
m_isUpdated = m_externFont == null || size != tmpSize;
} else {
m_isUpdated = true;
}
}
final boolean compose (Context c, Region clip, boolean forceUpdate) {
if (m_isUpdated) {
openFont (c);
}
return isUpdated (forceUpdate);
}
static public int getNativeFontSize (int size) {
if (size < 10) {
return s_fontSmall;
} else if (size > 14) {
return s_fontLarge;
} else {
return s_fontMedium;
}
}
public ExternFont getExternFont (Context c) {
if (m_externFont == null || m_isUpdated) {
openFont (c);
m_isUpdated = false;
}
return m_externFont;
}
public void openFont (Context c) {
stop (c);
// size
int tmpSize = FixFloat.fix2int (((SFFloat)m_field[0]).getValue ());
size = getNativeFontSize (tmpSize);
// style
String str = ((SFString)m_field[1]).getValue();
if (str == null) {
style = Font.STYLE_PLAIN;
} else if (str.equals ("bold")) {
style = Font.STYLE_BOLD;
} else if (str.equals ("italic")) {
style = Font.STYLE_ITALIC;
} else if (str.equals ("bolditalic")) {
style = Font.STYLE_ITALIC | Font.STYLE_BOLD;
} else {
style = Font.STYLE_PLAIN;
}
// justify horizontally
str = ((MFString)m_field[2]).getValue(0);
if (str == null) {
//System.err.println ("no style justif. using left");
justifyH = LEFT;
} else if (str.equalsIgnoreCase ("MIDDLE")) {
justifyH = MIDDLE;
} else if (str.equalsIgnoreCase ("RIGHT")) {
justifyH = RIGHT;
} else { // LEFT
justifyH = LEFT;
}
// jutify vertically
str = ((MFString)m_field[2]).getValue(1);
if (str == null) {
justifyV = TOP;
} else if (str.equalsIgnoreCase ("BOTTOM")) {
justifyV = BOTTOM;
} else if (str.equalsIgnoreCase ("BASELINE")) {
justifyV = BASELINE;
} else if (str.equalsIgnoreCase ("MIDDLE")) {
justifyV = MIDDLE;
} else { // TOP
justifyV = TOP;
}
// family
int nbFamilies = ((MFString)m_field[3]).m_size;
for (int i = 0; i < nbFamilies; i++) {
str = ((MFString)m_field[3]).getValue(0);
if (str == null) {
//System.err.println ("no style justif. using System");
family = Font.FACE_SYSTEM; break;
} else if (str.equalsIgnoreCase ("SERIF")) {
family = Font.FACE_MONOSPACE; break;
} else if (str.equalsIgnoreCase ("SANS")) {
family = Font.FACE_PROPORTIONAL; break;
} else if (str.equalsIgnoreCase ("TYPEWRITER")) {
family = Font.FACE_SYSTEM; break;
} else { // try to load extern font
family = -1;
// remove the part after the # like in times/ABCDE
int index = str.indexOf ('/');
if (index > 0) {
str = str.substring (0, index);
}
//Logger.println ("FontStyle.openFont: trying: "+str+"_"+tmpSize);
if ( (m_externFont = ExternFont.open (c.decoder, str, tmpSize)) != null) {
break;
} else {
- family = Font.FACE_MONOSPACE;
+ family = Font.FACE_SYSTEM;
}
}
}
if (m_externFont == null) { // no external font, then open a system one
m_externFont = ExternFont.open (family, style, size);
}
}
}
| true | true | public void openFont (Context c) {
stop (c);
// size
int tmpSize = FixFloat.fix2int (((SFFloat)m_field[0]).getValue ());
size = getNativeFontSize (tmpSize);
// style
String str = ((SFString)m_field[1]).getValue();
if (str == null) {
style = Font.STYLE_PLAIN;
} else if (str.equals ("bold")) {
style = Font.STYLE_BOLD;
} else if (str.equals ("italic")) {
style = Font.STYLE_ITALIC;
} else if (str.equals ("bolditalic")) {
style = Font.STYLE_ITALIC | Font.STYLE_BOLD;
} else {
style = Font.STYLE_PLAIN;
}
// justify horizontally
str = ((MFString)m_field[2]).getValue(0);
if (str == null) {
//System.err.println ("no style justif. using left");
justifyH = LEFT;
} else if (str.equalsIgnoreCase ("MIDDLE")) {
justifyH = MIDDLE;
} else if (str.equalsIgnoreCase ("RIGHT")) {
justifyH = RIGHT;
} else { // LEFT
justifyH = LEFT;
}
// jutify vertically
str = ((MFString)m_field[2]).getValue(1);
if (str == null) {
justifyV = TOP;
} else if (str.equalsIgnoreCase ("BOTTOM")) {
justifyV = BOTTOM;
} else if (str.equalsIgnoreCase ("BASELINE")) {
justifyV = BASELINE;
} else if (str.equalsIgnoreCase ("MIDDLE")) {
justifyV = MIDDLE;
} else { // TOP
justifyV = TOP;
}
// family
int nbFamilies = ((MFString)m_field[3]).m_size;
for (int i = 0; i < nbFamilies; i++) {
str = ((MFString)m_field[3]).getValue(0);
if (str == null) {
//System.err.println ("no style justif. using System");
family = Font.FACE_SYSTEM; break;
} else if (str.equalsIgnoreCase ("SERIF")) {
family = Font.FACE_MONOSPACE; break;
} else if (str.equalsIgnoreCase ("SANS")) {
family = Font.FACE_PROPORTIONAL; break;
} else if (str.equalsIgnoreCase ("TYPEWRITER")) {
family = Font.FACE_SYSTEM; break;
} else { // try to load extern font
family = -1;
// remove the part after the # like in times/ABCDE
int index = str.indexOf ('/');
if (index > 0) {
str = str.substring (0, index);
}
//Logger.println ("FontStyle.openFont: trying: "+str+"_"+tmpSize);
if ( (m_externFont = ExternFont.open (c.decoder, str, tmpSize)) != null) {
break;
} else {
family = Font.FACE_MONOSPACE;
}
}
}
if (m_externFont == null) { // no external font, then open a system one
m_externFont = ExternFont.open (family, style, size);
}
}
| public void openFont (Context c) {
stop (c);
// size
int tmpSize = FixFloat.fix2int (((SFFloat)m_field[0]).getValue ());
size = getNativeFontSize (tmpSize);
// style
String str = ((SFString)m_field[1]).getValue();
if (str == null) {
style = Font.STYLE_PLAIN;
} else if (str.equals ("bold")) {
style = Font.STYLE_BOLD;
} else if (str.equals ("italic")) {
style = Font.STYLE_ITALIC;
} else if (str.equals ("bolditalic")) {
style = Font.STYLE_ITALIC | Font.STYLE_BOLD;
} else {
style = Font.STYLE_PLAIN;
}
// justify horizontally
str = ((MFString)m_field[2]).getValue(0);
if (str == null) {
//System.err.println ("no style justif. using left");
justifyH = LEFT;
} else if (str.equalsIgnoreCase ("MIDDLE")) {
justifyH = MIDDLE;
} else if (str.equalsIgnoreCase ("RIGHT")) {
justifyH = RIGHT;
} else { // LEFT
justifyH = LEFT;
}
// jutify vertically
str = ((MFString)m_field[2]).getValue(1);
if (str == null) {
justifyV = TOP;
} else if (str.equalsIgnoreCase ("BOTTOM")) {
justifyV = BOTTOM;
} else if (str.equalsIgnoreCase ("BASELINE")) {
justifyV = BASELINE;
} else if (str.equalsIgnoreCase ("MIDDLE")) {
justifyV = MIDDLE;
} else { // TOP
justifyV = TOP;
}
// family
int nbFamilies = ((MFString)m_field[3]).m_size;
for (int i = 0; i < nbFamilies; i++) {
str = ((MFString)m_field[3]).getValue(0);
if (str == null) {
//System.err.println ("no style justif. using System");
family = Font.FACE_SYSTEM; break;
} else if (str.equalsIgnoreCase ("SERIF")) {
family = Font.FACE_MONOSPACE; break;
} else if (str.equalsIgnoreCase ("SANS")) {
family = Font.FACE_PROPORTIONAL; break;
} else if (str.equalsIgnoreCase ("TYPEWRITER")) {
family = Font.FACE_SYSTEM; break;
} else { // try to load extern font
family = -1;
// remove the part after the # like in times/ABCDE
int index = str.indexOf ('/');
if (index > 0) {
str = str.substring (0, index);
}
//Logger.println ("FontStyle.openFont: trying: "+str+"_"+tmpSize);
if ( (m_externFont = ExternFont.open (c.decoder, str, tmpSize)) != null) {
break;
} else {
family = Font.FACE_SYSTEM;
}
}
}
if (m_externFont == null) { // no external font, then open a system one
m_externFont = ExternFont.open (family, style, size);
}
}
|
diff --git a/apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImage.java b/apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImage.java
index d0a4f0acb0..125584360a 100644
--- a/apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImage.java
+++ b/apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImage.java
@@ -1,56 +1,56 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds 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.jclouds.openstack.nova.compute.functions;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.ImageBuilder;
import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.domain.Credentials;
import com.google.common.base.Function;
/**
*
* @author Adrian Cole
*/
@Singleton
public class NovaImageToImage implements Function<org.jclouds.openstack.nova.domain.Image, Image> {
private final Function<org.jclouds.openstack.nova.domain.Image, OperatingSystem> imageToOs;
@Inject
NovaImageToImage(Function<org.jclouds.openstack.nova.domain.Image, OperatingSystem> imageToOs) {
this.imageToOs = imageToOs;
}
public Image apply(org.jclouds.openstack.nova.domain.Image from) {
ImageBuilder builder = new ImageBuilder();
builder.ids(from.getId() + "");
builder.name(from.getName() != null ? from.getName() : "unspecified");
builder.description(from.getName() != null ? from.getName() : "unspecified");
- builder.version(from.getUpdated().getTime() + "");
+ builder.version(from.getUpdated() != null ? from.getUpdated().getTime() + "" : "-1");
builder.operatingSystem(imageToOs.apply(from)); //image name may not represent the OS type
builder.defaultCredentials(new Credentials("root", null));
builder.uri(from.getURI());
Image image = builder.build();
return image;
}
}
| true | true | public Image apply(org.jclouds.openstack.nova.domain.Image from) {
ImageBuilder builder = new ImageBuilder();
builder.ids(from.getId() + "");
builder.name(from.getName() != null ? from.getName() : "unspecified");
builder.description(from.getName() != null ? from.getName() : "unspecified");
builder.version(from.getUpdated().getTime() + "");
builder.operatingSystem(imageToOs.apply(from)); //image name may not represent the OS type
builder.defaultCredentials(new Credentials("root", null));
builder.uri(from.getURI());
Image image = builder.build();
return image;
}
| public Image apply(org.jclouds.openstack.nova.domain.Image from) {
ImageBuilder builder = new ImageBuilder();
builder.ids(from.getId() + "");
builder.name(from.getName() != null ? from.getName() : "unspecified");
builder.description(from.getName() != null ? from.getName() : "unspecified");
builder.version(from.getUpdated() != null ? from.getUpdated().getTime() + "" : "-1");
builder.operatingSystem(imageToOs.apply(from)); //image name may not represent the OS type
builder.defaultCredentials(new Credentials("root", null));
builder.uri(from.getURI());
Image image = builder.build();
return image;
}
|
diff --git a/src/main/java/com/fapiko/faceworm/server/FacewormServer.java b/src/main/java/com/fapiko/faceworm/server/FacewormServer.java
index 6cd6793..4d88da3 100644
--- a/src/main/java/com/fapiko/faceworm/server/FacewormServer.java
+++ b/src/main/java/com/fapiko/faceworm/server/FacewormServer.java
@@ -1,180 +1,180 @@
package com.fapiko.faceworm.server;
import com.fapiko.faceworm.server.win32.User32;
import com.sun.jna.platform.win32.WinDef;
import com.sun.jna.platform.win32.WinDef.HWND;
import com.sun.jna.platform.win32.WinUser;
import com.sun.jna.platform.unix.X11;
import org.apache.log4j.Logger;
import org.zeromq.ZMQ;
import java.awt.event.KeyEvent;
public class FacewormServer {
private static final int VK_WIN_PLUS = 0x6B;
private static final int VK_WIN_MINUS = 0xBD;
private static final int APPLICATION_LOOP_DELAY = 50;
private static final int HEALTHCHECK_DELAY = 30000;
private HWND pandoraHandle;
private boolean isWindows = false;
private static Logger logger = Logger.getLogger(FacewormServer.class);
public void applicationLoop() {
isWindows = System.getProperty("os.name").toLowerCase().indexOf("win") >= 0;
ZMQ.Context context = ZMQ.context(1);
ZMQ.Socket socket = context.socket(ZMQ.SUB);
ZMQ.Socket socketHealthcheck = context.socket(ZMQ.PUB);
socket.subscribe("ACTION".getBytes());
socket.bind("tcp://*:5555");
socketHealthcheck.bind("tcp://*:5556");
if (isWindows) {
pandoraHandle = User32.INSTANCE.FindWindow(null, "Pandora");
logger.info(pandoraHandle);
}
while(true) {
int healthcheckTime = 0;
byte[] reply = socket.recv(ZMQ.NOBLOCK);
if (reply != null) {
String message = new String(reply);
String[] pieces = message.split("\\|");
logger.debug(message);
if (pieces.length > 1 && pieces[0].equals("ACTION")) {
if (pieces[1].equals("NEXT_TRACK")) {
skipSong();
} else if (pieces[1].equals("PLAY_PAUSE")) {
togglePlayPause();
} else if (pieces[1].equals("THUMBS_UP")) {
thumbsUpSong();
} else if (pieces[1].equals("THUMBS_DOWN")) {
thumbsDownSong();
}
} else {
logger.warn("Message failed to split properly");
logger.warn("Message received: " + message);
}
}
healthcheckTime += APPLICATION_LOOP_DELAY;
if (healthcheckTime >= HEALTHCHECK_DELAY) {
- socketHealthcheck.send("APPLICATION|HEALTHCHECK".getBytes(), 0);
+ socketHealthcheck.send("ACTION|HEALTHCHECK".getBytes(), 0);
}
try {
Thread.sleep(APPLICATION_LOOP_DELAY);
} catch (InterruptedException e) {
- e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
+ e.printStackTrace();
}
}
}
public void togglePlayPause() {
sendKeystroke(KeyEvent.VK_SPACE);
}
public void skipSong() {
sendKeystroke(KeyEvent.VK_RIGHT);
}
public void thumbsUpSong() {
sendKeystroke(VK_WIN_PLUS);
}
public void thumbsDownSong() {
sendKeystroke(VK_WIN_MINUS);
}
public void increaseVolume() {
sendKeystroke(KeyEvent.VK_UP);
}
public void decreaseVolume() {
sendKeystroke(KeyEvent.VK_DOWN);
}
public void maxVolume() {
sendKeyCombination(KeyEvent.VK_SHIFT, KeyEvent.VK_UP);
}
public void muteVolume() {
sendKeyCombination(0x10, 0x28);
}
public void sendKeystroke(int keystroke) {
logger.debug("Sending keystroke " + keystroke);
if (isWindows) {
User32.INSTANCE.PostMessage(pandoraHandle, WinUser.WM_KEYDOWN, new WinDef.WPARAM(keystroke), new WinDef.LPARAM(0));
User32.INSTANCE.PostMessage(pandoraHandle, WinUser.WM_KEYUP, new WinDef.WPARAM(keystroke), new WinDef.LPARAM(0));
} else {
logger.warn("Operating system unsupported");
}
}
public void sendKeyCombination(int ... keystrokes) {
/*
Watching the messages fly across the wire with Spy++ indicates the following combination should work
but isn't. I'm guessing the keyboard state may be a little whacky and we might have to make a call to
GetKeyState to check it.
For reference, this is the Spy++ output of a human hitting Shift+Down on the application window:
<03284> 001F0170 P WM_KEYDOWN nVirtKey:VK_SHIFT cRepeat:1 ScanCode:2A fExtended:0 fAltDown:0 fRepeat:0 fUp:0
<03285> 001F0170 P WM_KEYDOWN nVirtKey:VK_DOWN cRepeat:1 ScanCode:50 fExtended:1 fAltDown:0 fRepeat:0 fUp:0
<03286> 001F0170 P WM_KEYUP nVirtKey:VK_DOWN cRepeat:1 ScanCode:50 fExtended:1 fAltDown:0 fRepeat:1 fUp:1
<03287> 001F0170 P WM_KEYUP nVirtKey:VK_SHIFT cRepeat:1 ScanCode:2A fExtended:0 fAltDown:0 fRepeat:1 fUp:1
And when it is done programmatically:
<03298> 001F0170 P WM_KEYDOWN nVirtKey:VK_SHIFT cRepeat:1 ScanCode:2A fExtended:0 fAltDown:0 fRepeat:0 fUp:0
<03299> 001F0170 P WM_KEYDOWN nVirtKey:VK_DOWN cRepeat:1 ScanCode:50 fExtended:1 fAltDown:0 fRepeat:0 fUp:0
<03300> 001F0170 P WM_KEYUP nVirtKey:VK_DOWN cRepeat:1 ScanCode:50 fExtended:1 fAltDown:0 fRepeat:1 fUp:1
<03301> 001F0170 P WM_KEYUP nVirtKey:VK_SHIFT cRepeat:0 ScanCode:2A fExtended:0 fAltDown:0 fRepeat:1 fUp:1
*/
// User32.INSTANCE.PostMessage(pandoraHandle, WinUser.WM_KEYDOWN, new WinDef.WPARAM(0x10), new WinDef.LPARAM(0x002A0001));
// User32.INSTANCE.PostMessage(pandoraHandle, WinUser.WM_KEYDOWN, new WinDef.WPARAM(0x28), new WinDef.LPARAM(0x01500001));
// User32.INSTANCE.PostMessage(pandoraHandle, WinUser.WM_KEYUP, new WinDef.WPARAM(0x28), new WinDef.LPARAM(0xC1500001));
// User32.INSTANCE.PostMessage(pandoraHandle, WinUser.WM_KEYUP, new WinDef.WPARAM(0x10), new WinDef.LPARAM(0xC02A0000));
for(int keystroke : keystrokes) {
User32.INSTANCE.SendMessage(pandoraHandle, WinUser.WM_KEYDOWN, new WinDef.WPARAM(keystroke), new WinDef.LPARAM(0x80000000));
}
for(int keystroke : keystrokes) {
User32.INSTANCE.SendMessage(pandoraHandle, WinUser.WM_KEYUP, new WinDef.WPARAM(keystroke), new WinDef.LPARAM());
}
}
}
| false | true | public void applicationLoop() {
isWindows = System.getProperty("os.name").toLowerCase().indexOf("win") >= 0;
ZMQ.Context context = ZMQ.context(1);
ZMQ.Socket socket = context.socket(ZMQ.SUB);
ZMQ.Socket socketHealthcheck = context.socket(ZMQ.PUB);
socket.subscribe("ACTION".getBytes());
socket.bind("tcp://*:5555");
socketHealthcheck.bind("tcp://*:5556");
if (isWindows) {
pandoraHandle = User32.INSTANCE.FindWindow(null, "Pandora");
logger.info(pandoraHandle);
}
while(true) {
int healthcheckTime = 0;
byte[] reply = socket.recv(ZMQ.NOBLOCK);
if (reply != null) {
String message = new String(reply);
String[] pieces = message.split("\\|");
logger.debug(message);
if (pieces.length > 1 && pieces[0].equals("ACTION")) {
if (pieces[1].equals("NEXT_TRACK")) {
skipSong();
} else if (pieces[1].equals("PLAY_PAUSE")) {
togglePlayPause();
} else if (pieces[1].equals("THUMBS_UP")) {
thumbsUpSong();
} else if (pieces[1].equals("THUMBS_DOWN")) {
thumbsDownSong();
}
} else {
logger.warn("Message failed to split properly");
logger.warn("Message received: " + message);
}
}
healthcheckTime += APPLICATION_LOOP_DELAY;
if (healthcheckTime >= HEALTHCHECK_DELAY) {
socketHealthcheck.send("APPLICATION|HEALTHCHECK".getBytes(), 0);
}
try {
Thread.sleep(APPLICATION_LOOP_DELAY);
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
| public void applicationLoop() {
isWindows = System.getProperty("os.name").toLowerCase().indexOf("win") >= 0;
ZMQ.Context context = ZMQ.context(1);
ZMQ.Socket socket = context.socket(ZMQ.SUB);
ZMQ.Socket socketHealthcheck = context.socket(ZMQ.PUB);
socket.subscribe("ACTION".getBytes());
socket.bind("tcp://*:5555");
socketHealthcheck.bind("tcp://*:5556");
if (isWindows) {
pandoraHandle = User32.INSTANCE.FindWindow(null, "Pandora");
logger.info(pandoraHandle);
}
while(true) {
int healthcheckTime = 0;
byte[] reply = socket.recv(ZMQ.NOBLOCK);
if (reply != null) {
String message = new String(reply);
String[] pieces = message.split("\\|");
logger.debug(message);
if (pieces.length > 1 && pieces[0].equals("ACTION")) {
if (pieces[1].equals("NEXT_TRACK")) {
skipSong();
} else if (pieces[1].equals("PLAY_PAUSE")) {
togglePlayPause();
} else if (pieces[1].equals("THUMBS_UP")) {
thumbsUpSong();
} else if (pieces[1].equals("THUMBS_DOWN")) {
thumbsDownSong();
}
} else {
logger.warn("Message failed to split properly");
logger.warn("Message received: " + message);
}
}
healthcheckTime += APPLICATION_LOOP_DELAY;
if (healthcheckTime >= HEALTHCHECK_DELAY) {
socketHealthcheck.send("ACTION|HEALTHCHECK".getBytes(), 0);
}
try {
Thread.sleep(APPLICATION_LOOP_DELAY);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
|
diff --git a/APITestingCG/src/cz/cvut/fit/hybljan2/apitestingcg/scanner/SourceTreeScanner.java b/APITestingCG/src/cz/cvut/fit/hybljan2/apitestingcg/scanner/SourceTreeScanner.java
index 18ff955..8010ae9 100644
--- a/APITestingCG/src/cz/cvut/fit/hybljan2/apitestingcg/scanner/SourceTreeScanner.java
+++ b/APITestingCG/src/cz/cvut/fit/hybljan2/apitestingcg/scanner/SourceTreeScanner.java
@@ -1,95 +1,95 @@
package cz.cvut.fit.hybljan2.apitestingcg.scanner;
import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import com.sun.tools.javac.tree.JCTree.JCClassDecl;
import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
import com.sun.tools.javac.tree.JCTree.JCImport;
import com.sun.tools.javac.tree.JCTree.JCMethodDecl;
import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
import com.sun.tools.javac.tree.TreeScanner;
import cz.cvut.fit.hybljan2.apitestingcg.apimodel.API;
import cz.cvut.fit.hybljan2.apitestingcg.apimodel.APIClass;
import cz.cvut.fit.hybljan2.apitestingcg.apimodel.APIField;
import cz.cvut.fit.hybljan2.apitestingcg.apimodel.APIMethod;
import cz.cvut.fit.hybljan2.apitestingcg.apimodel.APIPackage;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
/**
*
* @author Jan Hýbl
*/
public class SourceTreeScanner extends TreeScanner{
private Map<String,String> currentClassImports = new HashMap<String, String>();
private API api;
private APIPackage currentPackage;
private APIClass currentClass;
private Stack<APIClass> classes = new Stack<APIClass>();
private Map<String, APIPackage> pkgs = new HashMap<String, APIPackage>();
public API getAPI() {
api = new API("");
// Add all packages to API. We don't want default package in API, we can't import it!
for(APIPackage p : pkgs.values()) if(!p.getName().equals("")) api.addPackage(p);
return api;
}
@Override
public void visitTopLevel(JCCompilationUnit jccu) {
String n = jccu.packge.fullname.toString();
currentPackage = pkgs.get(n);
if (currentPackage == null) {
currentPackage = new APIPackage(n);
pkgs.put(n, currentPackage);
}
super.visitTopLevel(jccu);
currentPackage = null;
}
@Override
public void visitClassDef(JCClassDecl jccd) {
ClassSymbol cs = jccd.sym;
if ((cs.flags() & (Flags.PUBLIC | Flags.PROTECTED)) != 0) {
classes.push(currentClass);
- currentClass = new APIClass(jccd);
+ currentClass = new APIClass(jccd, currentPackage.getName(), currentClassImports);
super.visitClassDef(jccd);
currentPackage.addClass(currentClass);
currentClass = classes.pop();
currentClassImports = new HashMap<String, String>();
}
}
@Override
public void visitMethodDef(JCMethodDecl jcmd) {
MethodSymbol ms = jcmd.sym;
if ((ms.flags() & (Flags.PUBLIC | Flags.PROTECTED)) != 0) {
if ((ms.flags() & Flags.GENERATEDCONSTR) == 0) {
currentClass.addMethod(new APIMethod(jcmd, currentClassImports));
super.visitMethodDef(jcmd);
}
}
}
@Override
public void visitVarDef(JCVariableDecl jcvd) {
VarSymbol vs = jcvd.sym;
if ((vs.flags() & (Flags.PUBLIC | Flags.PROTECTED)) != 0) {
currentClass.addField(new APIField(jcvd, currentClassImports));
super.visitVarDef(jcvd);
}
}
@Override
public void visitImport(JCImport jci) {
String importClassName = jci.getQualifiedIdentifier().toString();
String simpleClassName = importClassName.substring(importClassName.lastIndexOf('.')+1);
currentClassImports.put(simpleClassName, importClassName);
super.visitImport(jci);
}
}
| true | true | public void visitClassDef(JCClassDecl jccd) {
ClassSymbol cs = jccd.sym;
if ((cs.flags() & (Flags.PUBLIC | Flags.PROTECTED)) != 0) {
classes.push(currentClass);
currentClass = new APIClass(jccd);
super.visitClassDef(jccd);
currentPackage.addClass(currentClass);
currentClass = classes.pop();
currentClassImports = new HashMap<String, String>();
}
}
| public void visitClassDef(JCClassDecl jccd) {
ClassSymbol cs = jccd.sym;
if ((cs.flags() & (Flags.PUBLIC | Flags.PROTECTED)) != 0) {
classes.push(currentClass);
currentClass = new APIClass(jccd, currentPackage.getName(), currentClassImports);
super.visitClassDef(jccd);
currentPackage.addClass(currentClass);
currentClass = classes.pop();
currentClassImports = new HashMap<String, String>();
}
}
|
diff --git a/astrid/src/com/todoroo/astrid/service/TaskService.java b/astrid/src/com/todoroo/astrid/service/TaskService.java
index f217e93e6..d7650f38c 100644
--- a/astrid/src/com/todoroo/astrid/service/TaskService.java
+++ b/astrid/src/com/todoroo/astrid/service/TaskService.java
@@ -1,600 +1,600 @@
/**
* Copyright (c) 2012 Todoroo Inc
*
* See the file "LICENSE" for the full license governing this code.
*/
package com.todoroo.astrid.service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import android.content.ContentValues;
import android.text.TextUtils;
import com.todoroo.andlib.data.Property;
import com.todoroo.andlib.data.TodorooCursor;
import com.todoroo.andlib.service.Autowired;
import com.todoroo.andlib.service.DependencyInjectionService;
import com.todoroo.andlib.sql.Criterion;
import com.todoroo.andlib.sql.Field;
import com.todoroo.andlib.sql.Functions;
import com.todoroo.andlib.sql.Join;
import com.todoroo.andlib.sql.Order;
import com.todoroo.andlib.sql.Query;
import com.todoroo.andlib.utility.AndroidUtilities;
import com.todoroo.andlib.utility.DateUtilities;
import com.todoroo.andlib.utility.Preferences;
import com.todoroo.astrid.actfm.sync.ActFmPreferenceService;
import com.todoroo.astrid.actfm.sync.messages.NameMaps;
import com.todoroo.astrid.adapter.UpdateAdapter;
import com.todoroo.astrid.api.Filter;
import com.todoroo.astrid.api.PermaSql;
import com.todoroo.astrid.core.PluginServices;
import com.todoroo.astrid.dao.MetadataDao;
import com.todoroo.astrid.dao.MetadataDao.MetadataCriteria;
import com.todoroo.astrid.dao.TaskDao;
import com.todoroo.astrid.dao.TaskDao.TaskCriteria;
import com.todoroo.astrid.dao.TaskOutstandingDao;
import com.todoroo.astrid.dao.UserActivityDao;
import com.todoroo.astrid.data.History;
import com.todoroo.astrid.data.Metadata;
import com.todoroo.astrid.data.RemoteModel;
import com.todoroo.astrid.data.SyncFlags;
import com.todoroo.astrid.data.Task;
import com.todoroo.astrid.data.TaskOutstanding;
import com.todoroo.astrid.data.User;
import com.todoroo.astrid.data.UserActivity;
import com.todoroo.astrid.gcal.GCalHelper;
import com.todoroo.astrid.gtasks.GtasksMetadata;
import com.todoroo.astrid.opencrx.OpencrxCoreUtils;
import com.todoroo.astrid.tags.TagService;
import com.todoroo.astrid.tags.TaskToTagMetadata;
import com.todoroo.astrid.utility.TitleParser;
/**
* Service layer for {@link Task}-centered activities.
*
* @author Tim Su <[email protected]>
*
*/
public class TaskService {
public static final String TRANS_QUICK_ADD_MARKUP = "markup"; //$NON-NLS-1$
public static final String TRANS_REPEAT_CHANGED = "repeat_changed"; //$NON-NLS-1$
public static final String TRANS_TAGS = "tags"; //$NON-NLS-1$
public static final String TRANS_ASSIGNED = "task-assigned"; //$NON-NLS-1$
public static final String TRANS_EDIT_SAVE = "task-edit-save"; //$NON-NLS-1$
public static final String TRANS_REPEAT_COMPLETE = "repeat-complete"; //$NON-NLS-1$
private static final int TOTAL_TASKS_FOR_ACTIVATION = 3;
private static final int COMPLETED_TASKS_FOR_ACTIVATION = 1;
private static final String PREF_USER_ACTVATED = "user-activated"; //$NON-NLS-1$
@Autowired
private TaskDao taskDao;
@Autowired
private TaskOutstandingDao taskOutstandingDao;
@Autowired
private MetadataDao metadataDao;
@Autowired
private UserActivityDao userActivityDao;
public TaskService() {
DependencyInjectionService.getInstance().inject(this);
}
// --- service layer
/**
* Query underlying database
* @param query
* @return
*/
public TodorooCursor<Task> query(Query query) {
return taskDao.query(query);
}
/**
*
* @param properties
* @param id id
* @return item, or null if it doesn't exist
*/
public Task fetchById(long id, Property<?>... properties) {
return taskDao.fetch(id, properties);
}
/**
*
* @param uuid
* @param properties
* @return item, or null if it doesn't exist
*/
public Task fetchByUUID(String uuid, Property<?>... properties) {
TodorooCursor<Task> task = query(Query.select(properties).where(Task.UUID.eq(uuid)));
try {
if (task.getCount() > 0) {
task.moveToFirst();
return new Task(task);
}
return null;
} finally {
task.close();
}
}
/**
* Mark the given task as completed and save it.
*
* @param item
*/
public void setComplete(Task item, boolean completed) {
if(completed) {
item.setValue(Task.COMPLETION_DATE, DateUtilities.now());
long reminderLast = item.getValue(Task.REMINDER_LAST);
String socialReminder = item.getValue(Task.SOCIAL_REMINDER);
if (reminderLast > 0) {
long diff = DateUtilities.now() - reminderLast;
if (diff > 0 && diff < DateUtilities.ONE_DAY) {
// within one day of last reminder
StatisticsService.reportEvent(StatisticsConstants.TASK_COMPLETED_ONE_DAY, "social", socialReminder); //$NON-NLS-1$
}
if (diff > 0 && diff < DateUtilities.ONE_WEEK) {
// within one week of last reminder
StatisticsService.reportEvent(StatisticsConstants.TASK_COMPLETED_ONE_WEEK, "social", socialReminder); //$NON-NLS-1$
}
}
StatisticsService.reportEvent(StatisticsConstants.TASK_COMPLETED_V2);
} else {
item.setValue(Task.COMPLETION_DATE, 0L);
}
taskDao.save(item);
}
/**
* Create or save the given action item
*
* @param item
* @param skipHooks
* Whether pre and post hooks should run. This should be set
* to true if tasks are created as part of synchronization
*/
public boolean save(Task item) {
return taskDao.save(item);
}
/**
* Clone the given task and all its metadata
*
* @param the old task
* @return the new task
*/
public Task clone(Task task) {
Task newTask = fetchById(task.getId(), Task.PROPERTIES);
if(newTask == null)
return new Task();
newTask.clearValue(Task.ID);
newTask.clearValue(Task.UUID);
TodorooCursor<Metadata> cursor = metadataDao.query(
Query.select(Metadata.PROPERTIES).where(MetadataCriteria.byTask(task.getId())));
try {
if(cursor.getCount() > 0) {
Metadata metadata = new Metadata();
newTask.putTransitory(SyncFlags.GTASKS_SUPPRESS_SYNC, true);
taskDao.save(newTask);
long newId = newTask.getId();
for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
metadata.readFromCursor(cursor);
if(!metadata.containsNonNullValue(Metadata.KEY))
continue;
if(GtasksMetadata.METADATA_KEY.equals(metadata.getValue(Metadata.KEY)))
metadata.setValue(GtasksMetadata.ID, ""); //$NON-NLS-1$
if(OpencrxCoreUtils.OPENCRX_ACTIVITY_METADATA_KEY.equals(metadata.getValue(Metadata.KEY)))
metadata.setValue(OpencrxCoreUtils.ACTIVITY_ID, 0L);
metadata.setValue(Metadata.TASK, newId);
metadata.clearValue(Metadata.ID);
metadataDao.createNew(metadata);
}
}
} finally {
cursor.close();
}
return newTask;
}
public Task cloneReusableTask(Task task, String tagName, String tagUuid) {
Task newTask = fetchById(task.getId(), Task.PROPERTIES);
if (newTask == null)
return new Task();
newTask.clearValue(Task.ID);
newTask.clearValue(Task.UUID);
newTask.clearValue(Task.USER);
newTask.clearValue(Task.USER_ID);
newTask.clearValue(Task.IS_READONLY);
newTask.clearValue(Task.IS_PUBLIC);
taskDao.save(newTask);
if (!RemoteModel.isUuidEmpty(tagUuid)) {
TagService.getInstance().createLink(newTask, tagName, tagUuid);
}
return newTask;
}
/**
* Delete the given task. Instead of deleting from the database, we set
* the deleted flag.
*
* @param model
*/
public void delete(Task item) {
if(!item.isSaved())
return;
else if(item.containsValue(Task.TITLE) && item.getValue(Task.TITLE).length() == 0) {
taskDao.delete(item.getId());
taskOutstandingDao.deleteWhere(TaskOutstanding.ENTITY_ID_PROPERTY.eq(item.getId()));
item.setId(Task.NO_ID);
} else {
long id = item.getId();
item.clear();
item.setId(id);
GCalHelper.deleteTaskEvent(item);
item.setValue(Task.DELETION_DATE, DateUtilities.now());
taskDao.save(item);
}
}
/**
* Permanently delete the given task.
*
* @param model
*/
public void purge(long taskId) {
taskDao.delete(taskId);
}
/**
* Clean up tasks. Typically called on startup
*/
public void cleanup() {
TodorooCursor<Task> cursor = taskDao.query(
Query.select(Task.ID).where(TaskCriteria.hasNoTitle()));
try {
if(cursor.getCount() == 0)
return;
for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
long id = cursor.getLong(0);
taskDao.delete(id);
}
} finally {
cursor.close();
}
}
/**
* Fetch tasks for the given filter
* @param properties
* @param constraint text constraint, or null
* @param filter
* @return
*/
@SuppressWarnings("nls")
public TodorooCursor<Task> fetchFiltered(String queryTemplate, CharSequence constraint,
Property<?>... properties) {
Criterion whereConstraint = null;
if(constraint != null)
whereConstraint = Functions.upper(Task.TITLE).like("%" +
constraint.toString().toUpperCase() + "%");
if(queryTemplate == null) {
if(whereConstraint == null)
return taskDao.query(Query.selectDistinct(properties));
else
return taskDao.query(Query.selectDistinct(properties).where(whereConstraint));
}
String sql;
if(whereConstraint != null) {
if(!queryTemplate.toUpperCase().contains("WHERE"))
sql = queryTemplate + " WHERE " + whereConstraint;
else
sql = queryTemplate.replace("WHERE ", "WHERE " + whereConstraint + " AND ");
} else
sql = queryTemplate;
sql = PermaSql.replacePlaceholders(sql);
return taskDao.query(Query.select(properties).withQueryTemplate(sql));
}
public boolean getUserActivationStatus() {
if (Preferences.getBoolean(PREF_USER_ACTVATED, false))
return true;
TodorooCursor<Task> all = query(Query.select(Task.ID));
try {
if (all.getCount() < TOTAL_TASKS_FOR_ACTIVATION)
return false;
TodorooCursor<Task> completed = query(Query.select(Task.ID).where(TaskCriteria.completed()));
try {
if (completed.getCount() < COMPLETED_TASKS_FOR_ACTIVATION)
return false;
} finally {
completed.close();
}
} finally {
all.close();
}
Preferences.setBoolean(PREF_USER_ACTVATED, true);
return true;
}
/**
* @param query
* @return how many tasks are matched by this query
*/
public int count(Query query) {
TodorooCursor<Task> cursor = taskDao.query(query);
try {
return cursor.getCount();
} finally {
cursor.close();
}
}
/**
* Clear details cache. Useful if user performs some operation that
* affects details
* @param criterion
*
* @return # of affected rows
*/
public int clearDetails(Criterion criterion) {
Task template = new Task();
template.setValue(Task.DETAILS_DATE, 0L);
return taskDao.update(criterion, template);
}
/**
* Update database based on selection and values
* @param selection
* @param selectionArgs
* @param setValues
* @return
*/
public int updateBySelection(String selection, String[] selectionArgs,
Task taskValues) {
TodorooCursor<Task> cursor = taskDao.rawQuery(selection, selectionArgs, Task.ID);
try {
for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
taskValues.setValue(Task.ID, cursor.get(Task.ID));
taskDao.save(taskValues);
}
return cursor.getCount();
} finally {
cursor.close();
}
}
/**
* Update all matching a clause to have the values set on template object.
* <p>
* Example (updates "joe" => "bob" in metadata value1):
* {code}
* Metadata item = new Metadata();
* item.setValue(Metadata.VALUE1, "bob");
* update(item, Metadata.VALUE1.eq("joe"));
* {code}
* @param where sql criteria
* @param template set fields on this object in order to set them in the db.
* @return # of updated items
*/
public int update(Criterion where, Task template) {
return taskDao.update(where, template);
}
/**
* Count tasks overall
* @param filter
* @return
*/
public int countTasks() {
TodorooCursor<Task> cursor = query(Query.select(Task.ID));
try {
return cursor.getCount();
} finally {
cursor.close();
}
}
/** count tasks in a given filter */
public int countTasks(Filter filter) {
String queryTemplate = PermaSql.replacePlaceholders(filter.getSqlQuery());
TodorooCursor<Task> cursor = query(Query.select(Task.ID).withQueryTemplate(
queryTemplate));
try {
return cursor.getCount();
} finally {
cursor.close();
}
}
/**
* Delete all tasks matching a given criterion
* @param all
*/
public int deleteWhere(Criterion criteria) {
return taskDao.deleteWhere(criteria);
}
/**
* Save task, parsing quick-add mark-up:
* <ul>
* <li>#tag - add the tag "tag"
* <li>@context - add the tag "@context"
* <li>!4 - set priority to !!!!
*/
private void quickAdd(Task task, List<String> tags) {
save(task);
for(String tag : tags) {
TagService.getInstance().createLink(task, tag);
}
}
/**
* Parse quick add markup for the given task
* @param task
* @param tags an empty array to apply tags to
* @return
*/
public static boolean parseQuickAddMarkup(Task task, ArrayList<String> tags) {
return TitleParser.parse(task, tags);
}
/**
* Create an uncompleted copy of this task and edit it
* @param itemId
* @return cloned item id
*/
public long duplicateTask(long itemId) {
Task original = new Task();
original.setId(itemId);
Task clone = clone(original);
String userId = clone.getValue(Task.USER_ID);
if (!Task.USER_ID_SELF.equals(userId) && !ActFmPreferenceService.userId().equals(userId))
clone.putTransitory(TRANS_ASSIGNED, true);
clone.setValue(Task.CREATION_DATE, DateUtilities.now());
clone.setValue(Task.COMPLETION_DATE, 0L);
clone.setValue(Task.DELETION_DATE, 0L);
clone.setValue(Task.CALENDAR_URI, ""); //$NON-NLS-1$
GCalHelper.createTaskEventIfEnabled(clone);
save(clone);
return clone.getId();
}
/**
* Create task from the given content values, saving it. This version
* doesn't need to start with a base task model.
*
* @param values
* @param title
* @param taskService
* @param metadataService
* @return
*/
public static Task createWithValues(ContentValues values, String title) {
Task task = new Task();
return createWithValues(task, values, title);
}
/**
* Create task from the given content values, saving it.
*
* @param task base task to start with
* @param values
* @param title
* @param taskService
* @param metadataService
* @return
*/
public static Task createWithValues(Task task, ContentValues values, String title) {
if (title != null)
task.setValue(Task.TITLE, title);
ArrayList<String> tags = new ArrayList<String>();
boolean quickAddMarkup = false;
try {
quickAddMarkup = parseQuickAddMarkup(task, tags);
} catch (Throwable e) {
PluginServices.getExceptionService().reportError("parse-quick-add", e); //$NON-NLS-1$
}
ContentValues forMetadata = null;
if (values != null && values.size() > 0) {
ContentValues forTask = new ContentValues();
forMetadata = new ContentValues();
outer: for (Entry<String, Object> item : values.valueSet()) {
String key = item.getKey();
Object value = item.getValue();
if (value instanceof String)
value = PermaSql.replacePlaceholders((String) value);
for (Property<?> property : Metadata.PROPERTIES)
if (property.name.equals(key)) {
AndroidUtilities.putInto(forMetadata, key, value, true);
continue outer;
}
AndroidUtilities.putInto(forTask, key, value, true);
}
task.mergeWithoutReplacement(forTask);
}
- if (task.getValue(Task.USER_ID) != Task.USER_ID_SELF)
+ if (!Task.USER_ID_SELF.equals(task.getValue(Task.USER_ID)))
task.putTransitory(TRANS_ASSIGNED, true);
PluginServices.getTaskService().quickAdd(task, tags);
if (quickAddMarkup)
task.putTransitory(TRANS_QUICK_ADD_MARKUP, true);
if (forMetadata != null && forMetadata.size() > 0) {
Metadata metadata = new Metadata();
metadata.setValue(Metadata.TASK, task.getId());
metadata.mergeWith(forMetadata);
if (TaskToTagMetadata.KEY.equals(metadata.getValue(Metadata.KEY))) {
if (metadata.containsNonNullValue(TaskToTagMetadata.TAG_UUID) && !RemoteModel.NO_UUID.equals(metadata.getValue(TaskToTagMetadata.TAG_UUID))) {
// This is more efficient
TagService.getInstance().createLink(task, metadata.getValue(TaskToTagMetadata.TAG_NAME), metadata.getValue(TaskToTagMetadata.TAG_UUID));
} else {
// This is necessary for backwards compatibility
TagService.getInstance().createLink(task, metadata.getValue(TaskToTagMetadata.TAG_NAME));
}
} else {
PluginServices.getMetadataService().save(metadata);
}
}
return task;
}
public TodorooCursor<UserActivity> getActivityAndHistoryForTask(Task task) {
Query taskQuery = queryForTask(task, UpdateAdapter.USER_TABLE_ALIAS, UpdateAdapter.USER_ACTIVITY_PROPERTIES, UpdateAdapter.USER_PROPERTIES);
Query historyQuery = Query.select(AndroidUtilities.addToArray(UpdateAdapter.HISTORY_PROPERTIES, UpdateAdapter.USER_PROPERTIES)).from(History.TABLE)
.where(Criterion.and(History.TABLE_ID.eq(NameMaps.TABLE_ID_TASKS), History.TARGET_ID.eq(task.getUuid())))
.from(History.TABLE)
.join(Join.left(User.TABLE.as(UpdateAdapter.USER_TABLE_ALIAS), History.USER_UUID.eq(Field.field(UpdateAdapter.USER_TABLE_ALIAS + "." + User.UUID.name)))); //$NON-NLS-1$;
Query resultQuery = taskQuery.union(historyQuery).orderBy(Order.desc("1")); //$NON-NLS-1$
return userActivityDao.query(resultQuery);
}
private static Query queryForTask(Task task, String userTableAlias, Property<?>[] activityProperties, Property<?>[] userProperties) {
Query result = Query.select(AndroidUtilities.addToArray(activityProperties, userProperties))
.where(Criterion.and(UserActivity.ACTION.eq(UserActivity.ACTION_TASK_COMMENT), UserActivity.TARGET_ID.eq(task.getUuid())));
if (!TextUtils.isEmpty(userTableAlias))
result = result.join(Join.left(User.TABLE.as(userTableAlias), UserActivity.USER_UUID.eq(Field.field(userTableAlias + "." + User.UUID.name)))); //$NON-NLS-1$
return result;
}
}
| true | true | public static Task createWithValues(Task task, ContentValues values, String title) {
if (title != null)
task.setValue(Task.TITLE, title);
ArrayList<String> tags = new ArrayList<String>();
boolean quickAddMarkup = false;
try {
quickAddMarkup = parseQuickAddMarkup(task, tags);
} catch (Throwable e) {
PluginServices.getExceptionService().reportError("parse-quick-add", e); //$NON-NLS-1$
}
ContentValues forMetadata = null;
if (values != null && values.size() > 0) {
ContentValues forTask = new ContentValues();
forMetadata = new ContentValues();
outer: for (Entry<String, Object> item : values.valueSet()) {
String key = item.getKey();
Object value = item.getValue();
if (value instanceof String)
value = PermaSql.replacePlaceholders((String) value);
for (Property<?> property : Metadata.PROPERTIES)
if (property.name.equals(key)) {
AndroidUtilities.putInto(forMetadata, key, value, true);
continue outer;
}
AndroidUtilities.putInto(forTask, key, value, true);
}
task.mergeWithoutReplacement(forTask);
}
if (task.getValue(Task.USER_ID) != Task.USER_ID_SELF)
task.putTransitory(TRANS_ASSIGNED, true);
PluginServices.getTaskService().quickAdd(task, tags);
if (quickAddMarkup)
task.putTransitory(TRANS_QUICK_ADD_MARKUP, true);
if (forMetadata != null && forMetadata.size() > 0) {
Metadata metadata = new Metadata();
metadata.setValue(Metadata.TASK, task.getId());
metadata.mergeWith(forMetadata);
if (TaskToTagMetadata.KEY.equals(metadata.getValue(Metadata.KEY))) {
if (metadata.containsNonNullValue(TaskToTagMetadata.TAG_UUID) && !RemoteModel.NO_UUID.equals(metadata.getValue(TaskToTagMetadata.TAG_UUID))) {
// This is more efficient
TagService.getInstance().createLink(task, metadata.getValue(TaskToTagMetadata.TAG_NAME), metadata.getValue(TaskToTagMetadata.TAG_UUID));
} else {
// This is necessary for backwards compatibility
TagService.getInstance().createLink(task, metadata.getValue(TaskToTagMetadata.TAG_NAME));
}
} else {
PluginServices.getMetadataService().save(metadata);
}
}
return task;
}
| public static Task createWithValues(Task task, ContentValues values, String title) {
if (title != null)
task.setValue(Task.TITLE, title);
ArrayList<String> tags = new ArrayList<String>();
boolean quickAddMarkup = false;
try {
quickAddMarkup = parseQuickAddMarkup(task, tags);
} catch (Throwable e) {
PluginServices.getExceptionService().reportError("parse-quick-add", e); //$NON-NLS-1$
}
ContentValues forMetadata = null;
if (values != null && values.size() > 0) {
ContentValues forTask = new ContentValues();
forMetadata = new ContentValues();
outer: for (Entry<String, Object> item : values.valueSet()) {
String key = item.getKey();
Object value = item.getValue();
if (value instanceof String)
value = PermaSql.replacePlaceholders((String) value);
for (Property<?> property : Metadata.PROPERTIES)
if (property.name.equals(key)) {
AndroidUtilities.putInto(forMetadata, key, value, true);
continue outer;
}
AndroidUtilities.putInto(forTask, key, value, true);
}
task.mergeWithoutReplacement(forTask);
}
if (!Task.USER_ID_SELF.equals(task.getValue(Task.USER_ID)))
task.putTransitory(TRANS_ASSIGNED, true);
PluginServices.getTaskService().quickAdd(task, tags);
if (quickAddMarkup)
task.putTransitory(TRANS_QUICK_ADD_MARKUP, true);
if (forMetadata != null && forMetadata.size() > 0) {
Metadata metadata = new Metadata();
metadata.setValue(Metadata.TASK, task.getId());
metadata.mergeWith(forMetadata);
if (TaskToTagMetadata.KEY.equals(metadata.getValue(Metadata.KEY))) {
if (metadata.containsNonNullValue(TaskToTagMetadata.TAG_UUID) && !RemoteModel.NO_UUID.equals(metadata.getValue(TaskToTagMetadata.TAG_UUID))) {
// This is more efficient
TagService.getInstance().createLink(task, metadata.getValue(TaskToTagMetadata.TAG_NAME), metadata.getValue(TaskToTagMetadata.TAG_UUID));
} else {
// This is necessary for backwards compatibility
TagService.getInstance().createLink(task, metadata.getValue(TaskToTagMetadata.TAG_NAME));
}
} else {
PluginServices.getMetadataService().save(metadata);
}
}
return task;
}
|
diff --git a/Dreamworld/src/de/blablubbabc/dreamworld/managers/ConfigManager.java b/Dreamworld/src/de/blablubbabc/dreamworld/managers/ConfigManager.java
index 66a0e99..9a3ef91 100644
--- a/Dreamworld/src/de/blablubbabc/dreamworld/managers/ConfigManager.java
+++ b/Dreamworld/src/de/blablubbabc/dreamworld/managers/ConfigManager.java
@@ -1,177 +1,177 @@
package de.blablubbabc.dreamworld.managers;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.plugin.Plugin;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import de.blablubbabc.dreamworld.objects.SoftLocation;
public class ConfigManager {
private Plugin plugin;
private boolean wasConfigValid = false;
// world settings:
public String dreamWorldName;
public boolean noAnimalSpawning;
public boolean noMonsterSpawning;
public int dreamChance;
public int minDurationSeconds;
public int maxDurationSeconds;
// spawning:
public boolean spawnRandomly;
public List<SoftLocation> dreamSpawns;
public boolean applyInitialGamemode;
public boolean applyInitialHealth;
public boolean applyInitialHunger;
public boolean applyInitialPotionEffects;
public GameMode initialGamemode;
public double initialHealth;
public int initialHunger;
public List<PotionEffect> initialPotionEffects;
public boolean clearAndRestorePlayer;
public int purgeAfterMinutes;
public int ignoreIfRemainingTimeIsLowerThan;
// fake time
public boolean fakeTimeEnabled;
public int fakeTime;
public int fakeTimeRandomBounds;
public boolean fakeTimeFixed;
// fake weather
public boolean fakeRain;
// disabled:
public boolean hungerDisabled;
public boolean fallDamageDisabled;
public boolean entityDamageDisabled;
public boolean allDamageDisabled;
public boolean weatherDisabled;
public boolean itemDroppingDisabled;
public boolean itemPickupDisabled;
// allowed commands:
public List<String> allowedCommands;
public ConfigManager(Plugin plugin) {
this.plugin = plugin;
// default config:
FileConfiguration config = plugin.getConfig();
config.options().copyDefaults(true);
plugin.saveDefaultConfig();
// load values:
try {
ConfigurationSection dreamSection = config.getConfigurationSection("dream");
// world settings:
dreamWorldName = dreamSection.getString("world name");
noAnimalSpawning = dreamSection.getBoolean("no animal spawning");
noMonsterSpawning = dreamSection.getBoolean("no monster spawning");
dreamChance = dreamSection.getInt("chance");
minDurationSeconds = dreamSection.getInt("min duration in seconds");
maxDurationSeconds = dreamSection.getInt("max duration in seconds");
// spawning:
spawnRandomly = dreamSection.getBoolean("spawn randomly each time");
dreamSpawns = SoftLocation.getFromStringList(dreamSection.getStringList("random spawns"));
// some initial values:
applyInitialGamemode = dreamSection.getBoolean("gamemode.apply");
initialGamemode = GameMode.getByValue(dreamSection.getInt("gamemode.initial gamemode"));
applyInitialHealth = dreamSection.getBoolean("health.apply");
initialHealth = dreamSection.getInt("health.initial health");
applyInitialHunger = dreamSection.getBoolean("hunger.apply");
initialHunger = dreamSection.getInt("hunger.initial hunger");
applyInitialPotionEffects = dreamSection.getBoolean("potion effects.apply");
initialPotionEffects = new ArrayList<PotionEffect>();
ConfigurationSection potionsSection = dreamSection.getConfigurationSection("potion effects.initial potion effects");
if (potionsSection != null) {
for (String type : potionsSection.getKeys(false)) {
ConfigurationSection potionSection = potionsSection.getConfigurationSection(type);
if (potionSection == null) continue;
PotionEffectType potionType = PotionEffectType.getByName(type);
if (potionType == null) {
- plugin.getLogger().warning("Invalid potion effect type '" + type + "'. Skipping this effect now.");
+ plugin.getLogger().warning("Invalid potion effect type '" + type + "'. Skipping this effect now. You can find a list of all possible PotionEffectTypes by googling 'bukkit PotionEffectType'.");
continue;
}
initialPotionEffects.add(new PotionEffect(potionType, potionSection.getInt("duration"), potionSection.getInt("level", 1)));
}
}
clearAndRestorePlayer = dreamSection.getBoolean("clear and restore player");
purgeAfterMinutes = dreamSection.getInt("purge saved dream data after x minutes");
ignoreIfRemainingTimeIsLowerThan = dreamSection.getInt("ignore if remaining seconds is lower than");
// fake time
ConfigurationSection fakeTimeSection = dreamSection.getConfigurationSection("fake client time");
fakeTimeEnabled = fakeTimeSection.getBoolean("enabled") ;
fakeTime = fakeTimeSection.getInt("time (in ticks)");
fakeTimeRandomBounds = fakeTimeSection.getInt("random bounds");
fakeTimeFixed = fakeTimeSection.getBoolean("fixed time");
// fake weather
fakeRain = dreamSection.getBoolean("fake client weather.raining");
// disabled:
ConfigurationSection disabledSection = dreamSection.getConfigurationSection("disabled");
hungerDisabled = disabledSection.getBoolean("hunger");
fallDamageDisabled = disabledSection.getBoolean("fall damage");
entityDamageDisabled = disabledSection.getBoolean("entity damage");
allDamageDisabled = disabledSection.getBoolean("all damage");
weatherDisabled = disabledSection.getBoolean("weather");
itemDroppingDisabled = disabledSection.getBoolean("item dropping");
itemPickupDisabled = disabledSection.getBoolean("item pickup");
// allowed commands:
allowedCommands = dreamSection.getStringList("allowed commands");
wasConfigValid = true;
} catch (Exception e) {
e.printStackTrace();
wasConfigValid = false;
}
}
public boolean wasConfigValid() {
return wasConfigValid;
}
public void addSpawnLocation(Location location) {
dreamSpawns.add(new SoftLocation(location));
saveSpawns();
}
public void removeAllSpawnLocations() {
dreamSpawns.clear();
saveSpawns();
}
private void saveSpawns() {
plugin.getConfig().set("random spawns", SoftLocation.toStringList(dreamSpawns));
plugin.saveConfig();
}
}
| true | true | public ConfigManager(Plugin plugin) {
this.plugin = plugin;
// default config:
FileConfiguration config = plugin.getConfig();
config.options().copyDefaults(true);
plugin.saveDefaultConfig();
// load values:
try {
ConfigurationSection dreamSection = config.getConfigurationSection("dream");
// world settings:
dreamWorldName = dreamSection.getString("world name");
noAnimalSpawning = dreamSection.getBoolean("no animal spawning");
noMonsterSpawning = dreamSection.getBoolean("no monster spawning");
dreamChance = dreamSection.getInt("chance");
minDurationSeconds = dreamSection.getInt("min duration in seconds");
maxDurationSeconds = dreamSection.getInt("max duration in seconds");
// spawning:
spawnRandomly = dreamSection.getBoolean("spawn randomly each time");
dreamSpawns = SoftLocation.getFromStringList(dreamSection.getStringList("random spawns"));
// some initial values:
applyInitialGamemode = dreamSection.getBoolean("gamemode.apply");
initialGamemode = GameMode.getByValue(dreamSection.getInt("gamemode.initial gamemode"));
applyInitialHealth = dreamSection.getBoolean("health.apply");
initialHealth = dreamSection.getInt("health.initial health");
applyInitialHunger = dreamSection.getBoolean("hunger.apply");
initialHunger = dreamSection.getInt("hunger.initial hunger");
applyInitialPotionEffects = dreamSection.getBoolean("potion effects.apply");
initialPotionEffects = new ArrayList<PotionEffect>();
ConfigurationSection potionsSection = dreamSection.getConfigurationSection("potion effects.initial potion effects");
if (potionsSection != null) {
for (String type : potionsSection.getKeys(false)) {
ConfigurationSection potionSection = potionsSection.getConfigurationSection(type);
if (potionSection == null) continue;
PotionEffectType potionType = PotionEffectType.getByName(type);
if (potionType == null) {
plugin.getLogger().warning("Invalid potion effect type '" + type + "'. Skipping this effect now.");
continue;
}
initialPotionEffects.add(new PotionEffect(potionType, potionSection.getInt("duration"), potionSection.getInt("level", 1)));
}
}
clearAndRestorePlayer = dreamSection.getBoolean("clear and restore player");
purgeAfterMinutes = dreamSection.getInt("purge saved dream data after x minutes");
ignoreIfRemainingTimeIsLowerThan = dreamSection.getInt("ignore if remaining seconds is lower than");
// fake time
ConfigurationSection fakeTimeSection = dreamSection.getConfigurationSection("fake client time");
fakeTimeEnabled = fakeTimeSection.getBoolean("enabled") ;
fakeTime = fakeTimeSection.getInt("time (in ticks)");
fakeTimeRandomBounds = fakeTimeSection.getInt("random bounds");
fakeTimeFixed = fakeTimeSection.getBoolean("fixed time");
// fake weather
fakeRain = dreamSection.getBoolean("fake client weather.raining");
// disabled:
ConfigurationSection disabledSection = dreamSection.getConfigurationSection("disabled");
hungerDisabled = disabledSection.getBoolean("hunger");
fallDamageDisabled = disabledSection.getBoolean("fall damage");
entityDamageDisabled = disabledSection.getBoolean("entity damage");
allDamageDisabled = disabledSection.getBoolean("all damage");
weatherDisabled = disabledSection.getBoolean("weather");
itemDroppingDisabled = disabledSection.getBoolean("item dropping");
itemPickupDisabled = disabledSection.getBoolean("item pickup");
// allowed commands:
allowedCommands = dreamSection.getStringList("allowed commands");
wasConfigValid = true;
} catch (Exception e) {
e.printStackTrace();
wasConfigValid = false;
}
}
| public ConfigManager(Plugin plugin) {
this.plugin = plugin;
// default config:
FileConfiguration config = plugin.getConfig();
config.options().copyDefaults(true);
plugin.saveDefaultConfig();
// load values:
try {
ConfigurationSection dreamSection = config.getConfigurationSection("dream");
// world settings:
dreamWorldName = dreamSection.getString("world name");
noAnimalSpawning = dreamSection.getBoolean("no animal spawning");
noMonsterSpawning = dreamSection.getBoolean("no monster spawning");
dreamChance = dreamSection.getInt("chance");
minDurationSeconds = dreamSection.getInt("min duration in seconds");
maxDurationSeconds = dreamSection.getInt("max duration in seconds");
// spawning:
spawnRandomly = dreamSection.getBoolean("spawn randomly each time");
dreamSpawns = SoftLocation.getFromStringList(dreamSection.getStringList("random spawns"));
// some initial values:
applyInitialGamemode = dreamSection.getBoolean("gamemode.apply");
initialGamemode = GameMode.getByValue(dreamSection.getInt("gamemode.initial gamemode"));
applyInitialHealth = dreamSection.getBoolean("health.apply");
initialHealth = dreamSection.getInt("health.initial health");
applyInitialHunger = dreamSection.getBoolean("hunger.apply");
initialHunger = dreamSection.getInt("hunger.initial hunger");
applyInitialPotionEffects = dreamSection.getBoolean("potion effects.apply");
initialPotionEffects = new ArrayList<PotionEffect>();
ConfigurationSection potionsSection = dreamSection.getConfigurationSection("potion effects.initial potion effects");
if (potionsSection != null) {
for (String type : potionsSection.getKeys(false)) {
ConfigurationSection potionSection = potionsSection.getConfigurationSection(type);
if (potionSection == null) continue;
PotionEffectType potionType = PotionEffectType.getByName(type);
if (potionType == null) {
plugin.getLogger().warning("Invalid potion effect type '" + type + "'. Skipping this effect now. You can find a list of all possible PotionEffectTypes by googling 'bukkit PotionEffectType'.");
continue;
}
initialPotionEffects.add(new PotionEffect(potionType, potionSection.getInt("duration"), potionSection.getInt("level", 1)));
}
}
clearAndRestorePlayer = dreamSection.getBoolean("clear and restore player");
purgeAfterMinutes = dreamSection.getInt("purge saved dream data after x minutes");
ignoreIfRemainingTimeIsLowerThan = dreamSection.getInt("ignore if remaining seconds is lower than");
// fake time
ConfigurationSection fakeTimeSection = dreamSection.getConfigurationSection("fake client time");
fakeTimeEnabled = fakeTimeSection.getBoolean("enabled") ;
fakeTime = fakeTimeSection.getInt("time (in ticks)");
fakeTimeRandomBounds = fakeTimeSection.getInt("random bounds");
fakeTimeFixed = fakeTimeSection.getBoolean("fixed time");
// fake weather
fakeRain = dreamSection.getBoolean("fake client weather.raining");
// disabled:
ConfigurationSection disabledSection = dreamSection.getConfigurationSection("disabled");
hungerDisabled = disabledSection.getBoolean("hunger");
fallDamageDisabled = disabledSection.getBoolean("fall damage");
entityDamageDisabled = disabledSection.getBoolean("entity damage");
allDamageDisabled = disabledSection.getBoolean("all damage");
weatherDisabled = disabledSection.getBoolean("weather");
itemDroppingDisabled = disabledSection.getBoolean("item dropping");
itemPickupDisabled = disabledSection.getBoolean("item pickup");
// allowed commands:
allowedCommands = dreamSection.getStringList("allowed commands");
wasConfigValid = true;
} catch (Exception e) {
e.printStackTrace();
wasConfigValid = false;
}
}
|
diff --git a/dspace-api/src/main/java/org/dspace/submit/step/StartSubmissionLookupStep.java b/dspace-api/src/main/java/org/dspace/submit/step/StartSubmissionLookupStep.java
index cfb488493..c7dd7375a 100644
--- a/dspace-api/src/main/java/org/dspace/submit/step/StartSubmissionLookupStep.java
+++ b/dspace-api/src/main/java/org/dspace/submit/step/StartSubmissionLookupStep.java
@@ -1,310 +1,310 @@
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.submit.step;
import gr.ekt.bte.core.Record;
import gr.ekt.bte.core.TransformationEngine;
import gr.ekt.bte.core.TransformationSpec;
import gr.ekt.bte.exceptions.BadTransformationSpec;
import gr.ekt.bte.exceptions.MalformedSourceException;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.dspace.app.util.DCInputSet;
import org.dspace.app.util.DCInputsReader;
import org.dspace.app.util.SubmissionInfo;
import org.dspace.app.util.Util;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Collection;
import org.dspace.content.WorkspaceItem;
import org.dspace.core.Context;
import org.dspace.submit.AbstractProcessingStep;
import org.dspace.submit.lookup.DSpaceWorkspaceItemOutputGenerator;
import org.dspace.submit.lookup.SubmissionItemDataLoader;
import org.dspace.submit.lookup.SubmissionLookupService;
import org.dspace.submit.util.ItemSubmissionLookupDTO;
import org.dspace.submit.util.SubmissionLookupDTO;
import org.dspace.submit.util.SubmissionLookupPublication;
import org.dspace.utils.DSpace;
/**
* StartSubmissionLookupStep is used when you want enabled the user to auto fill
* the item in submission with metadata retrieved from external bibliographic
* services (like pubmed, arxiv, and so on...)
*
* <p>
* At the moment this step is only available for JSPUI
* </p>
*
* @see org.dspace.app.util.SubmissionConfig
* @see org.dspace.app.util.SubmissionStepConfig
* @see org.dspace.submit.AbstractProcessingStep
*
* @author Andrea Bollini
* @author Kostas Stamatis
* @author Luigi Andrea Pascarelli
* @author Panagiotis Koutsourakis
* @version $Revision$
*/
public class StartSubmissionLookupStep extends AbstractProcessingStep
{
/***************************************************************************
* STATUS / ERROR FLAGS (returned by doProcessing() if an error occurs or
* additional user interaction may be required)
*
* (Do NOT use status of 0, since it corresponds to STATUS_COMPLETE flag
* defined in the JSPStepManager class)
**************************************************************************/
// no collection was selected
public static final int STATUS_NO_COLLECTION = 1;
// invalid collection or error finding collection
public static final int STATUS_INVALID_COLLECTION = 2;
public static final int STATUS_NO_SUUID = 3;
public static final int STATUS_SUBMISSION_EXPIRED = 4;
private SubmissionLookupService slService = new DSpace()
.getServiceManager().getServiceByName(
SubmissionLookupService.class.getCanonicalName(),
SubmissionLookupService.class);
/** log4j logger */
private static Logger log = Logger
.getLogger(StartSubmissionLookupStep.class);
/**
* Do any processing of the information input by the user, and/or perform
* step processing (if no user interaction required)
* <P>
* It is this method's job to save any data to the underlying database, as
* necessary, and return error messages (if any) which can then be processed
* by the appropriate user interface (JSP-UI or XML-UI)
* <P>
* NOTE: If this step is a non-interactive step (i.e. requires no UI), then
* it should perform *all* of its processing in this method!
*
* @param context
* current DSpace context
* @param request
* current servlet request object
* @param response
* current servlet response object
* @param subInfo
* submission info object
* @return Status or error flag which will be processed by
* doPostProcessing() below! (if STATUS_COMPLETE or 0 is returned,
* no errors occurred!)
*/
public int doProcessing(Context context, HttpServletRequest request,
HttpServletResponse response, SubmissionInfo subInfo)
throws ServletException, IOException, SQLException,
AuthorizeException
{
// First we find the collection which was selected
int id = Util.getIntParameter(request, "collectionid");
String titolo = request.getParameter("search_title");
String date = request.getParameter("search_year");
String autori = request.getParameter("search_authors");
String uuidSubmission = request.getParameter("suuid");
String uuidLookup = request.getParameter("iuuid");
String fuuidLookup = request.getParameter("fuuid");
if (StringUtils.isBlank(uuidSubmission))
{
return STATUS_NO_SUUID;
}
SubmissionLookupDTO submissionDTO = slService.getSubmissionLookupDTO(
request, uuidSubmission);
if (submissionDTO == null)
{
return STATUS_SUBMISSION_EXPIRED;
}
ItemSubmissionLookupDTO itemLookup = null;
if (fuuidLookup == null || fuuidLookup.isEmpty())
{
if (StringUtils.isNotBlank(uuidLookup))
{
itemLookup = submissionDTO.getLookupItem(uuidLookup);
if (itemLookup == null)
{
return STATUS_SUBMISSION_EXPIRED;
}
}
}
// if the user didn't select a collection,
// send him/her back to "select a collection" page
if (id < 0)
{
return STATUS_NO_COLLECTION;
}
// try to load the collection
Collection col = Collection.find(context, id);
// Show an error if the collection is invalid
if (col == null)
{
return STATUS_INVALID_COLLECTION;
}
else
{
// create our new Workspace Item
DCInputSet inputSet = null;
try
{
inputSet = new DCInputsReader().getInputs(col.getHandle());
}
catch (Exception e)
{
e.printStackTrace();
}
List<ItemSubmissionLookupDTO> dto = new ArrayList<ItemSubmissionLookupDTO>();
if (itemLookup != null)
{
dto.add(itemLookup);
}
- else if (fuuidLookup != null)
+ else if (fuuidLookup != null && !fuuidLookup.isEmpty())
{
String[] ss = fuuidLookup.split(",");
for (String s : ss)
{
itemLookup = submissionDTO.getLookupItem(s);
if (itemLookup == null)
{
return STATUS_SUBMISSION_EXPIRED;
}
dto.add(itemLookup);
}
}
else
{
SubmissionLookupPublication manualPub = new SubmissionLookupPublication(
SubmissionLookupService.MANUAL_USER_INPUT);
manualPub.add("title", titolo);
manualPub.add("year", date);
manualPub.add("allauthors", autori);
Enumeration e = request.getParameterNames();
while (e.hasMoreElements())
{
String parameterName = (String) e.nextElement();
String parameterValue = request.getParameter(parameterName);
if (parameterName.startsWith("identifier_")
&& StringUtils.isNotBlank(parameterValue))
{
manualPub
.add(parameterName.substring("identifier_"
.length()), parameterValue);
}
}
List<Record> publications = new ArrayList<Record>();
publications.add(manualPub);
dto.add(new ItemSubmissionLookupDTO(publications));
}
List<WorkspaceItem> result = null;
TransformationEngine transformationEngine = slService
.getPhase2TransformationEngine();
if (transformationEngine != null)
{
SubmissionItemDataLoader dataLoader = (SubmissionItemDataLoader) transformationEngine
.getDataLoader();
dataLoader.setDtoList(dto);
// dataLoader.setProviders()
DSpaceWorkspaceItemOutputGenerator outputGenerator = (DSpaceWorkspaceItemOutputGenerator) transformationEngine
.getOutputGenerator();
outputGenerator.setCollection(col);
outputGenerator.setContext(context);
outputGenerator.setFormName(inputSet.getFormName());
outputGenerator.setDto(dto.get(0));
try
{
transformationEngine.transform(new TransformationSpec());
result = outputGenerator.getWitems();
}
catch (BadTransformationSpec e1)
{
e1.printStackTrace();
}
catch (MalformedSourceException e1)
{
e1.printStackTrace();
}
}
if (result != null && result.size() > 0)
{
// update Submission Information with this Workspace Item
subInfo.setSubmissionItem(result.iterator().next());
}
// commit changes to database
context.commit();
// need to reload current submission process config,
// since it is based on the Collection selected
subInfo.reloadSubmissionConfig(request);
}
slService.invalidateDTOs(request, uuidSubmission);
// no errors occurred
return STATUS_COMPLETE;
}
/**
* Retrieves the number of pages that this "step" extends over. This method
* is used to build the progress bar.
* <P>
* This method may just return 1 for most steps (since most steps consist of
* a single page). But, it should return a number greater than 1 for any
* "step" which spans across a number of HTML pages. For example, the
* configurable "Describe" step (configured using input-forms.xml) overrides
* this method to return the number of pages that are defined by its
* configuration file.
* <P>
* Steps which are non-interactive (i.e. they do not display an interface to
* the user) should return a value of 1, so that they are only processed
* once!
*
* @param request
* The HTTP Request
* @param subInfo
* The current submission information object
*
* @return the number of pages in this step
*/
public int getNumberOfPages(HttpServletRequest request,
SubmissionInfo subInfo) throws ServletException
{
// there is always just one page in the "select a collection" step!
return 1;
}
}
| true | true | public int doProcessing(Context context, HttpServletRequest request,
HttpServletResponse response, SubmissionInfo subInfo)
throws ServletException, IOException, SQLException,
AuthorizeException
{
// First we find the collection which was selected
int id = Util.getIntParameter(request, "collectionid");
String titolo = request.getParameter("search_title");
String date = request.getParameter("search_year");
String autori = request.getParameter("search_authors");
String uuidSubmission = request.getParameter("suuid");
String uuidLookup = request.getParameter("iuuid");
String fuuidLookup = request.getParameter("fuuid");
if (StringUtils.isBlank(uuidSubmission))
{
return STATUS_NO_SUUID;
}
SubmissionLookupDTO submissionDTO = slService.getSubmissionLookupDTO(
request, uuidSubmission);
if (submissionDTO == null)
{
return STATUS_SUBMISSION_EXPIRED;
}
ItemSubmissionLookupDTO itemLookup = null;
if (fuuidLookup == null || fuuidLookup.isEmpty())
{
if (StringUtils.isNotBlank(uuidLookup))
{
itemLookup = submissionDTO.getLookupItem(uuidLookup);
if (itemLookup == null)
{
return STATUS_SUBMISSION_EXPIRED;
}
}
}
// if the user didn't select a collection,
// send him/her back to "select a collection" page
if (id < 0)
{
return STATUS_NO_COLLECTION;
}
// try to load the collection
Collection col = Collection.find(context, id);
// Show an error if the collection is invalid
if (col == null)
{
return STATUS_INVALID_COLLECTION;
}
else
{
// create our new Workspace Item
DCInputSet inputSet = null;
try
{
inputSet = new DCInputsReader().getInputs(col.getHandle());
}
catch (Exception e)
{
e.printStackTrace();
}
List<ItemSubmissionLookupDTO> dto = new ArrayList<ItemSubmissionLookupDTO>();
if (itemLookup != null)
{
dto.add(itemLookup);
}
else if (fuuidLookup != null)
{
String[] ss = fuuidLookup.split(",");
for (String s : ss)
{
itemLookup = submissionDTO.getLookupItem(s);
if (itemLookup == null)
{
return STATUS_SUBMISSION_EXPIRED;
}
dto.add(itemLookup);
}
}
else
{
SubmissionLookupPublication manualPub = new SubmissionLookupPublication(
SubmissionLookupService.MANUAL_USER_INPUT);
manualPub.add("title", titolo);
manualPub.add("year", date);
manualPub.add("allauthors", autori);
Enumeration e = request.getParameterNames();
while (e.hasMoreElements())
{
String parameterName = (String) e.nextElement();
String parameterValue = request.getParameter(parameterName);
if (parameterName.startsWith("identifier_")
&& StringUtils.isNotBlank(parameterValue))
{
manualPub
.add(parameterName.substring("identifier_"
.length()), parameterValue);
}
}
List<Record> publications = new ArrayList<Record>();
publications.add(manualPub);
dto.add(new ItemSubmissionLookupDTO(publications));
}
List<WorkspaceItem> result = null;
TransformationEngine transformationEngine = slService
.getPhase2TransformationEngine();
if (transformationEngine != null)
{
SubmissionItemDataLoader dataLoader = (SubmissionItemDataLoader) transformationEngine
.getDataLoader();
dataLoader.setDtoList(dto);
// dataLoader.setProviders()
DSpaceWorkspaceItemOutputGenerator outputGenerator = (DSpaceWorkspaceItemOutputGenerator) transformationEngine
.getOutputGenerator();
outputGenerator.setCollection(col);
outputGenerator.setContext(context);
outputGenerator.setFormName(inputSet.getFormName());
outputGenerator.setDto(dto.get(0));
try
{
transformationEngine.transform(new TransformationSpec());
result = outputGenerator.getWitems();
}
catch (BadTransformationSpec e1)
{
e1.printStackTrace();
}
catch (MalformedSourceException e1)
{
e1.printStackTrace();
}
}
if (result != null && result.size() > 0)
{
// update Submission Information with this Workspace Item
subInfo.setSubmissionItem(result.iterator().next());
}
// commit changes to database
context.commit();
// need to reload current submission process config,
// since it is based on the Collection selected
subInfo.reloadSubmissionConfig(request);
}
slService.invalidateDTOs(request, uuidSubmission);
// no errors occurred
return STATUS_COMPLETE;
}
| public int doProcessing(Context context, HttpServletRequest request,
HttpServletResponse response, SubmissionInfo subInfo)
throws ServletException, IOException, SQLException,
AuthorizeException
{
// First we find the collection which was selected
int id = Util.getIntParameter(request, "collectionid");
String titolo = request.getParameter("search_title");
String date = request.getParameter("search_year");
String autori = request.getParameter("search_authors");
String uuidSubmission = request.getParameter("suuid");
String uuidLookup = request.getParameter("iuuid");
String fuuidLookup = request.getParameter("fuuid");
if (StringUtils.isBlank(uuidSubmission))
{
return STATUS_NO_SUUID;
}
SubmissionLookupDTO submissionDTO = slService.getSubmissionLookupDTO(
request, uuidSubmission);
if (submissionDTO == null)
{
return STATUS_SUBMISSION_EXPIRED;
}
ItemSubmissionLookupDTO itemLookup = null;
if (fuuidLookup == null || fuuidLookup.isEmpty())
{
if (StringUtils.isNotBlank(uuidLookup))
{
itemLookup = submissionDTO.getLookupItem(uuidLookup);
if (itemLookup == null)
{
return STATUS_SUBMISSION_EXPIRED;
}
}
}
// if the user didn't select a collection,
// send him/her back to "select a collection" page
if (id < 0)
{
return STATUS_NO_COLLECTION;
}
// try to load the collection
Collection col = Collection.find(context, id);
// Show an error if the collection is invalid
if (col == null)
{
return STATUS_INVALID_COLLECTION;
}
else
{
// create our new Workspace Item
DCInputSet inputSet = null;
try
{
inputSet = new DCInputsReader().getInputs(col.getHandle());
}
catch (Exception e)
{
e.printStackTrace();
}
List<ItemSubmissionLookupDTO> dto = new ArrayList<ItemSubmissionLookupDTO>();
if (itemLookup != null)
{
dto.add(itemLookup);
}
else if (fuuidLookup != null && !fuuidLookup.isEmpty())
{
String[] ss = fuuidLookup.split(",");
for (String s : ss)
{
itemLookup = submissionDTO.getLookupItem(s);
if (itemLookup == null)
{
return STATUS_SUBMISSION_EXPIRED;
}
dto.add(itemLookup);
}
}
else
{
SubmissionLookupPublication manualPub = new SubmissionLookupPublication(
SubmissionLookupService.MANUAL_USER_INPUT);
manualPub.add("title", titolo);
manualPub.add("year", date);
manualPub.add("allauthors", autori);
Enumeration e = request.getParameterNames();
while (e.hasMoreElements())
{
String parameterName = (String) e.nextElement();
String parameterValue = request.getParameter(parameterName);
if (parameterName.startsWith("identifier_")
&& StringUtils.isNotBlank(parameterValue))
{
manualPub
.add(parameterName.substring("identifier_"
.length()), parameterValue);
}
}
List<Record> publications = new ArrayList<Record>();
publications.add(manualPub);
dto.add(new ItemSubmissionLookupDTO(publications));
}
List<WorkspaceItem> result = null;
TransformationEngine transformationEngine = slService
.getPhase2TransformationEngine();
if (transformationEngine != null)
{
SubmissionItemDataLoader dataLoader = (SubmissionItemDataLoader) transformationEngine
.getDataLoader();
dataLoader.setDtoList(dto);
// dataLoader.setProviders()
DSpaceWorkspaceItemOutputGenerator outputGenerator = (DSpaceWorkspaceItemOutputGenerator) transformationEngine
.getOutputGenerator();
outputGenerator.setCollection(col);
outputGenerator.setContext(context);
outputGenerator.setFormName(inputSet.getFormName());
outputGenerator.setDto(dto.get(0));
try
{
transformationEngine.transform(new TransformationSpec());
result = outputGenerator.getWitems();
}
catch (BadTransformationSpec e1)
{
e1.printStackTrace();
}
catch (MalformedSourceException e1)
{
e1.printStackTrace();
}
}
if (result != null && result.size() > 0)
{
// update Submission Information with this Workspace Item
subInfo.setSubmissionItem(result.iterator().next());
}
// commit changes to database
context.commit();
// need to reload current submission process config,
// since it is based on the Collection selected
subInfo.reloadSubmissionConfig(request);
}
slService.invalidateDTOs(request, uuidSubmission);
// no errors occurred
return STATUS_COMPLETE;
}
|
diff --git a/src/main/java/TomcatMain.java b/src/main/java/TomcatMain.java
index a67766c..4fccb68 100644
--- a/src/main/java/TomcatMain.java
+++ b/src/main/java/TomcatMain.java
@@ -1,39 +1,39 @@
import de.javakaffee.web.msm.MemcachedBackupSessionManager;
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;
import javax.servlet.ServletException;
import java.io.File;
public class TomcatMain {
public static void main(String[] args) throws ServletException, LifecycleException {
String webappDirLocation = "src/main/webapp/";
Tomcat tomcat = new Tomcat();
//The port that we should run on can be set into an environment variable
//Look for that variable and default to 8080 if it isn't there.
String webPort = System.getenv("PORT");
if (webPort == null || webPort.isEmpty()) {
webPort = "8080";
}
MemcachedBackupSessionManager manager = new MemcachedBackupSessionManager();
- manager.setMemcachedNodes(System.getenv("MEMCACHED_SERVERS"));
+ manager.setMemcachedNodes(System.getenv("MEMCACHE_SERVERS"));
manager.setMemcachedProtocol("binary");
- manager.setUsername(System.getenv("MEMCACHED_USERNAME"));
- manager.setPassword(System.getenv("MEMCACHED_PASSWORD"));
+ manager.setUsername(System.getenv("MEMCACHE_USERNAME"));
+ manager.setPassword(System.getenv("MEMCACHE_PASSWORD"));
manager.setLockingMode("auto");
tomcat.setPort(Integer.valueOf(webPort));
Context context = tomcat.addWebapp("/", new File(webappDirLocation).getAbsolutePath());
context.setManager(manager);
System.out.println("configuring app with basedir: " + new File("./" + webappDirLocation).getAbsolutePath());
tomcat.start();
tomcat.getServer().await();
}
}
| false | true | public static void main(String[] args) throws ServletException, LifecycleException {
String webappDirLocation = "src/main/webapp/";
Tomcat tomcat = new Tomcat();
//The port that we should run on can be set into an environment variable
//Look for that variable and default to 8080 if it isn't there.
String webPort = System.getenv("PORT");
if (webPort == null || webPort.isEmpty()) {
webPort = "8080";
}
MemcachedBackupSessionManager manager = new MemcachedBackupSessionManager();
manager.setMemcachedNodes(System.getenv("MEMCACHED_SERVERS"));
manager.setMemcachedProtocol("binary");
manager.setUsername(System.getenv("MEMCACHED_USERNAME"));
manager.setPassword(System.getenv("MEMCACHED_PASSWORD"));
manager.setLockingMode("auto");
tomcat.setPort(Integer.valueOf(webPort));
Context context = tomcat.addWebapp("/", new File(webappDirLocation).getAbsolutePath());
context.setManager(manager);
System.out.println("configuring app with basedir: " + new File("./" + webappDirLocation).getAbsolutePath());
tomcat.start();
tomcat.getServer().await();
}
| public static void main(String[] args) throws ServletException, LifecycleException {
String webappDirLocation = "src/main/webapp/";
Tomcat tomcat = new Tomcat();
//The port that we should run on can be set into an environment variable
//Look for that variable and default to 8080 if it isn't there.
String webPort = System.getenv("PORT");
if (webPort == null || webPort.isEmpty()) {
webPort = "8080";
}
MemcachedBackupSessionManager manager = new MemcachedBackupSessionManager();
manager.setMemcachedNodes(System.getenv("MEMCACHE_SERVERS"));
manager.setMemcachedProtocol("binary");
manager.setUsername(System.getenv("MEMCACHE_USERNAME"));
manager.setPassword(System.getenv("MEMCACHE_PASSWORD"));
manager.setLockingMode("auto");
tomcat.setPort(Integer.valueOf(webPort));
Context context = tomcat.addWebapp("/", new File(webappDirLocation).getAbsolutePath());
context.setManager(manager);
System.out.println("configuring app with basedir: " + new File("./" + webappDirLocation).getAbsolutePath());
tomcat.start();
tomcat.getServer().await();
}
|
diff --git a/src/java/net/sf/jabref/external/DownloadExternalFile.java b/src/java/net/sf/jabref/external/DownloadExternalFile.java
index 157053768..fec73b7d9 100644
--- a/src/java/net/sf/jabref/external/DownloadExternalFile.java
+++ b/src/java/net/sf/jabref/external/DownloadExternalFile.java
@@ -1,334 +1,334 @@
package net.sf.jabref.external;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import net.sf.jabref.*;
import net.sf.jabref.gui.FileListEntry;
import net.sf.jabref.gui.FileListEntryEditor;
import net.sf.jabref.net.URLDownload;
/**
* This class handles the download of an external file. Typically called when the user clicks
* the "Download" button in a FileListEditor shown in an EntryEditor.
* <p/>
* The FileListEditor constructs the DownloadExternalFile instance, then calls the download()
* method passing a reference to itself as a callback. The download() method asks for the URL,
* then starts the download. When the download is completed, it calls the downloadCompleted()
* method on the callback FileListEditor, which then needs to take care of linking to the file.
* The local filename is passed as an argument to the downloadCompleted() method.
* <p/>
* If the download is cancelled, or failed, the user is informed. The callback is never called.
*/
public class DownloadExternalFile {
private JabRefFrame frame;
private MetaData metaData;
private String bibtexKey;
private FileListEntryEditor editor;
private boolean downloadFinished = false;
private boolean dontShowDialog = false;
public DownloadExternalFile(JabRefFrame frame, MetaData metaData, String bibtexKey) {
this.frame = frame;
this.metaData = metaData;
this.bibtexKey = bibtexKey;
}
/**
* Start a download.
*
* @param callback The object to which the filename should be reported when download
* is complete.
*/
public void download(final DownloadCallback callback) throws IOException {
dontShowDialog = false;
final String res = JOptionPane.showInputDialog(frame,
Globals.lang("Enter URL to download"));
if (res == null || res.trim().length() == 0)
return;
URL url = null;
try {
url = new URL(res);
} catch (MalformedURLException ex1) {
JOptionPane.showMessageDialog(frame, Globals.lang("Invalid URL"), Globals
.lang("Download file"), JOptionPane.ERROR_MESSAGE);
return;
}
download(url, callback);
}
/**
* Start a download.
*
* @param callback The object to which the filename should be reported when download
* is complete.
*/
public void download(URL url, final DownloadCallback callback) throws IOException {
String res = url.toString();
URLDownload udl = null;
// First of all, start the download itself in the background to a temporary file:
final File tmp = File.createTempFile("jabref_download", "tmp");
tmp.deleteOnExit();
//long time = System.currentTimeMillis();
try {
udl = new URLDownload(frame, url, tmp);
// TODO: what if this takes long time?
// TODO: stop editor dialog if this results in an error:
udl.openConnectionOnly(); // Read MIME type
} catch (IOException ex) {
JOptionPane.showMessageDialog(frame, Globals.lang("Invalid URL")+": "
+ ex.getMessage(), Globals.lang("Download file"),
JOptionPane.ERROR_MESSAGE);
Globals.logger("Error while downloading " + "'" + res + "'");
return;
}
final URL urlF = url;
final URLDownload udlF = udl;
//System.out.println("Time: "+(System.currentTimeMillis()-time));
(new Thread() {
public void run() {
try {
udlF.download();
} catch (IOException e2) {
dontShowDialog = true;
if ((editor != null) && (editor.isVisible()))
editor.setVisible(false);
JOptionPane.showMessageDialog(frame, Globals.lang("Invalid URL")+": "
+ e2.getMessage(), Globals.lang("Download file"),
JOptionPane.ERROR_MESSAGE);
Globals.logger("Error while downloading " + "'" + urlF.toString()+ "'");
return;
}
// Download finished: call the method that stops the progress bar etc.:
SwingUtilities.invokeLater(new Runnable() {
public void run() {
downloadFinished();
}
});
}
}).start();
ExternalFileType suggestedType = null;
if (udl.getMimeType() != null) {
System.out.println("mimetype:"+udl.getMimeType());
suggestedType = Globals.prefs.getExternalFileTypeByMimeType(udl.getMimeType());
/*if (suggestedType != null)
System.out.println("Found type '"+suggestedType.getName()+"' by MIME type '"+udl.getMimeType()+"'");*/
}
// Then, while the download is proceeding, let the user choose the details of the file:
String suffix;
if (suggestedType != null) {
suffix = suggestedType.getExtension();
}
else {
// If we didn't find a file type from the MIME type, try based on extension:
suffix = getSuffix(res);
suggestedType = Globals.prefs.getExternalFileTypeByExt(suffix);
}
String suggestedName = bibtexKey != null ? getSuggestedFileName(suffix) : "";
String fDirectory = getFileDirectory(res);
- if (fDirectory.trim().equals(""))
+ if ((fDirectory != null) && fDirectory.trim().equals(""))
fDirectory = null;
final String directory = fDirectory;
final String suggestDir = directory != null ? directory : System.getProperty("user.home");
File file = new File(new File(suggestDir), suggestedName);
FileListEntry entry = new FileListEntry("", bibtexKey != null ? file.getCanonicalPath() : "",
suggestedType);
editor = new FileListEntryEditor(frame, entry, true, false, metaData);
editor.getProgressBar().setIndeterminate(true);
editor.setOkEnabled(false);
editor.setExternalConfirm(new ConfirmCloseFileListEntryEditor() {
public boolean confirmClose(FileListEntry entry) {
File f = directory != null ? expandFilename(directory, entry.getLink())
: new File(entry.getLink());
if (f.isDirectory()) {
JOptionPane.showMessageDialog(frame,
Globals.lang("Target file cannot be a directory."), Globals.lang("Download file"),
JOptionPane.ERROR_MESSAGE);
return false;
}
if (f.exists()) {
return JOptionPane.showConfirmDialog
(frame, "'"+f.getName()+"' "+Globals.lang("exists. Overwrite file?"),
Globals.lang("Download file"), JOptionPane.OK_CANCEL_OPTION)
== JOptionPane.OK_OPTION;
} else
return true;
}
});
if (!dontShowDialog) // If an error occured with the URL, this flag may have been set
editor.setVisible(true);
else
return;
// Editor closed. Go on:
if (editor.okPressed()) {
File toFile = directory != null ? expandFilename(directory, entry.getLink())
: new File(entry.getLink());
String dirPrefix;
if (directory != null) {
if (!directory.endsWith(System.getProperty("file.separator")))
dirPrefix = directory+System.getProperty("file.separator");
else
dirPrefix = directory;
} else
dirPrefix = null;
try {
boolean success = Util.copyFile(tmp, toFile, true);
if (!success) {
// OOps, the file exists!
System.out.println("File already exists! DownloadExternalFile.download()");
}
// If the local file is in or below the main file directory, change the
// path to relative:
if ((directory != null) && entry.getLink().startsWith(directory) &&
(entry.getLink().length() > dirPrefix.length())) {
entry.setLink(entry.getLink().substring(dirPrefix.length()));
}
callback.downloadComplete(entry);
} catch (IOException ex) {
ex.printStackTrace();
}
tmp.delete();
}
else {
// Cancelled. Just delete the temp file:
if (downloadFinished)
tmp.delete();
}
}
/**
* Construct a File object pointing to the file linked, whether the link is
* absolute or relative to the main directory.
* @param directory The main directory.
* @param link The absolute or relative link.
* @return The expanded File.
*/
private File expandFilename(String directory, String link) {
File toFile = new File(link);
// If this is a relative link, we should perhaps append the directory:
String dirPrefix = directory+System.getProperty("file.separator");
if (!toFile.isAbsolute()) {
toFile = new File(dirPrefix+link);
}
return toFile;
}
/**
* This is called by the download thread when download is completed.
*/
public void downloadFinished() {
downloadFinished = true;
editor.getProgressBar().setVisible(false);
editor.getProgressBarLabel().setVisible(false);
editor.setOkEnabled(true);
editor.getProgressBar().setValue(editor.getProgressBar().getMaximum());
}
public String getSuggestedFileName(String suffix) {
String plannedName = bibtexKey;
if (suffix.length() > 0)
plannedName += "." + suffix;
/*
* [ 1548875 ] download pdf produces unsupported filename
*
* http://sourceforge.net/tracker/index.php?func=detail&aid=1548875&group_id=92314&atid=600306
*
*/
if (Globals.ON_WIN) {
plannedName = plannedName.replaceAll(
"\\?|\\*|\\<|\\>|\\||\\\"|\\:|\\.$|\\[|\\]", "");
} else if (Globals.ON_MAC) {
plannedName = plannedName.replaceAll(":", "");
}
return plannedName;
}
/**
* Look for the last '.' in the link, and returnthe following characters.
* This gives the extension for most reasonably named links.
*
* @param link The link
* @return The suffix, excluding the dot (e.g. "pdf")
*/
public String getSuffix(final String link) {
String strippedLink = link;
try {
// Try to strip the query string, if any, to get the correct suffix:
URL url = new URL(link);
if ((url.getQuery() != null) && (url.getQuery().length() < link.length()-1)) {
strippedLink = link.substring(0, link.length()-url.getQuery().length()-1);
}
} catch (MalformedURLException e) {
// Don't report this error, since this getting the suffix is a non-critical
// operation, and this error will be triggered and reported elsewhere.
}
// First see if the stripped link gives a reasonable suffix:
String suffix;
int index = strippedLink.lastIndexOf('.');
if ((index <= 0) || (index == strippedLink.length() - 1)) // No occurence, or at the end
suffix = null;
else suffix = strippedLink.substring(index + 1);
if (Globals.prefs.getExternalFileTypeByExt(suffix) != null) {
return suffix;
}
else {
// If the suffix doesn't seem to give any reasonable file type, try
// with the non-stripped link:
index = link.lastIndexOf('.');
if ((index <= 0) || (index == strippedLink.length() - 1)) {
// No occurence, or at the end
// Check if there are path separators in the suffix - if so, it is definitely
// not a proper suffix, so we should give up:
if (suffix.indexOf('/') > 0)
return "";
else
return suffix; // return the first one we found, anyway.
}
else {
// Check if there are path separators in the suffix - if so, it is definitely
// not a proper suffix, so we should give up:
if (link.substring(index + 1).indexOf('/') > 0)
return "";
else
return link.substring(index + 1);
}
}
}
public String getFileDirectory(String link) {
return metaData.getFileDirectory(GUIGlobals.FILE_FIELD);
}
/**
* Callback interface that users of this class must implement in order to receive
* notification when download is complete.
*/
public interface DownloadCallback {
public void downloadComplete(FileListEntry file);
}
}
| true | true | public void download(URL url, final DownloadCallback callback) throws IOException {
String res = url.toString();
URLDownload udl = null;
// First of all, start the download itself in the background to a temporary file:
final File tmp = File.createTempFile("jabref_download", "tmp");
tmp.deleteOnExit();
//long time = System.currentTimeMillis();
try {
udl = new URLDownload(frame, url, tmp);
// TODO: what if this takes long time?
// TODO: stop editor dialog if this results in an error:
udl.openConnectionOnly(); // Read MIME type
} catch (IOException ex) {
JOptionPane.showMessageDialog(frame, Globals.lang("Invalid URL")+": "
+ ex.getMessage(), Globals.lang("Download file"),
JOptionPane.ERROR_MESSAGE);
Globals.logger("Error while downloading " + "'" + res + "'");
return;
}
final URL urlF = url;
final URLDownload udlF = udl;
//System.out.println("Time: "+(System.currentTimeMillis()-time));
(new Thread() {
public void run() {
try {
udlF.download();
} catch (IOException e2) {
dontShowDialog = true;
if ((editor != null) && (editor.isVisible()))
editor.setVisible(false);
JOptionPane.showMessageDialog(frame, Globals.lang("Invalid URL")+": "
+ e2.getMessage(), Globals.lang("Download file"),
JOptionPane.ERROR_MESSAGE);
Globals.logger("Error while downloading " + "'" + urlF.toString()+ "'");
return;
}
// Download finished: call the method that stops the progress bar etc.:
SwingUtilities.invokeLater(new Runnable() {
public void run() {
downloadFinished();
}
});
}
}).start();
ExternalFileType suggestedType = null;
if (udl.getMimeType() != null) {
System.out.println("mimetype:"+udl.getMimeType());
suggestedType = Globals.prefs.getExternalFileTypeByMimeType(udl.getMimeType());
/*if (suggestedType != null)
System.out.println("Found type '"+suggestedType.getName()+"' by MIME type '"+udl.getMimeType()+"'");*/
}
// Then, while the download is proceeding, let the user choose the details of the file:
String suffix;
if (suggestedType != null) {
suffix = suggestedType.getExtension();
}
else {
// If we didn't find a file type from the MIME type, try based on extension:
suffix = getSuffix(res);
suggestedType = Globals.prefs.getExternalFileTypeByExt(suffix);
}
String suggestedName = bibtexKey != null ? getSuggestedFileName(suffix) : "";
String fDirectory = getFileDirectory(res);
if (fDirectory.trim().equals(""))
fDirectory = null;
final String directory = fDirectory;
final String suggestDir = directory != null ? directory : System.getProperty("user.home");
File file = new File(new File(suggestDir), suggestedName);
FileListEntry entry = new FileListEntry("", bibtexKey != null ? file.getCanonicalPath() : "",
suggestedType);
editor = new FileListEntryEditor(frame, entry, true, false, metaData);
editor.getProgressBar().setIndeterminate(true);
editor.setOkEnabled(false);
editor.setExternalConfirm(new ConfirmCloseFileListEntryEditor() {
public boolean confirmClose(FileListEntry entry) {
File f = directory != null ? expandFilename(directory, entry.getLink())
: new File(entry.getLink());
if (f.isDirectory()) {
JOptionPane.showMessageDialog(frame,
Globals.lang("Target file cannot be a directory."), Globals.lang("Download file"),
JOptionPane.ERROR_MESSAGE);
return false;
}
if (f.exists()) {
return JOptionPane.showConfirmDialog
(frame, "'"+f.getName()+"' "+Globals.lang("exists. Overwrite file?"),
Globals.lang("Download file"), JOptionPane.OK_CANCEL_OPTION)
== JOptionPane.OK_OPTION;
} else
return true;
}
});
if (!dontShowDialog) // If an error occured with the URL, this flag may have been set
editor.setVisible(true);
else
return;
// Editor closed. Go on:
if (editor.okPressed()) {
File toFile = directory != null ? expandFilename(directory, entry.getLink())
: new File(entry.getLink());
String dirPrefix;
if (directory != null) {
if (!directory.endsWith(System.getProperty("file.separator")))
dirPrefix = directory+System.getProperty("file.separator");
else
dirPrefix = directory;
} else
dirPrefix = null;
try {
boolean success = Util.copyFile(tmp, toFile, true);
if (!success) {
// OOps, the file exists!
System.out.println("File already exists! DownloadExternalFile.download()");
}
// If the local file is in or below the main file directory, change the
// path to relative:
if ((directory != null) && entry.getLink().startsWith(directory) &&
(entry.getLink().length() > dirPrefix.length())) {
entry.setLink(entry.getLink().substring(dirPrefix.length()));
}
callback.downloadComplete(entry);
} catch (IOException ex) {
ex.printStackTrace();
}
tmp.delete();
}
else {
// Cancelled. Just delete the temp file:
if (downloadFinished)
tmp.delete();
}
}
| public void download(URL url, final DownloadCallback callback) throws IOException {
String res = url.toString();
URLDownload udl = null;
// First of all, start the download itself in the background to a temporary file:
final File tmp = File.createTempFile("jabref_download", "tmp");
tmp.deleteOnExit();
//long time = System.currentTimeMillis();
try {
udl = new URLDownload(frame, url, tmp);
// TODO: what if this takes long time?
// TODO: stop editor dialog if this results in an error:
udl.openConnectionOnly(); // Read MIME type
} catch (IOException ex) {
JOptionPane.showMessageDialog(frame, Globals.lang("Invalid URL")+": "
+ ex.getMessage(), Globals.lang("Download file"),
JOptionPane.ERROR_MESSAGE);
Globals.logger("Error while downloading " + "'" + res + "'");
return;
}
final URL urlF = url;
final URLDownload udlF = udl;
//System.out.println("Time: "+(System.currentTimeMillis()-time));
(new Thread() {
public void run() {
try {
udlF.download();
} catch (IOException e2) {
dontShowDialog = true;
if ((editor != null) && (editor.isVisible()))
editor.setVisible(false);
JOptionPane.showMessageDialog(frame, Globals.lang("Invalid URL")+": "
+ e2.getMessage(), Globals.lang("Download file"),
JOptionPane.ERROR_MESSAGE);
Globals.logger("Error while downloading " + "'" + urlF.toString()+ "'");
return;
}
// Download finished: call the method that stops the progress bar etc.:
SwingUtilities.invokeLater(new Runnable() {
public void run() {
downloadFinished();
}
});
}
}).start();
ExternalFileType suggestedType = null;
if (udl.getMimeType() != null) {
System.out.println("mimetype:"+udl.getMimeType());
suggestedType = Globals.prefs.getExternalFileTypeByMimeType(udl.getMimeType());
/*if (suggestedType != null)
System.out.println("Found type '"+suggestedType.getName()+"' by MIME type '"+udl.getMimeType()+"'");*/
}
// Then, while the download is proceeding, let the user choose the details of the file:
String suffix;
if (suggestedType != null) {
suffix = suggestedType.getExtension();
}
else {
// If we didn't find a file type from the MIME type, try based on extension:
suffix = getSuffix(res);
suggestedType = Globals.prefs.getExternalFileTypeByExt(suffix);
}
String suggestedName = bibtexKey != null ? getSuggestedFileName(suffix) : "";
String fDirectory = getFileDirectory(res);
if ((fDirectory != null) && fDirectory.trim().equals(""))
fDirectory = null;
final String directory = fDirectory;
final String suggestDir = directory != null ? directory : System.getProperty("user.home");
File file = new File(new File(suggestDir), suggestedName);
FileListEntry entry = new FileListEntry("", bibtexKey != null ? file.getCanonicalPath() : "",
suggestedType);
editor = new FileListEntryEditor(frame, entry, true, false, metaData);
editor.getProgressBar().setIndeterminate(true);
editor.setOkEnabled(false);
editor.setExternalConfirm(new ConfirmCloseFileListEntryEditor() {
public boolean confirmClose(FileListEntry entry) {
File f = directory != null ? expandFilename(directory, entry.getLink())
: new File(entry.getLink());
if (f.isDirectory()) {
JOptionPane.showMessageDialog(frame,
Globals.lang("Target file cannot be a directory."), Globals.lang("Download file"),
JOptionPane.ERROR_MESSAGE);
return false;
}
if (f.exists()) {
return JOptionPane.showConfirmDialog
(frame, "'"+f.getName()+"' "+Globals.lang("exists. Overwrite file?"),
Globals.lang("Download file"), JOptionPane.OK_CANCEL_OPTION)
== JOptionPane.OK_OPTION;
} else
return true;
}
});
if (!dontShowDialog) // If an error occured with the URL, this flag may have been set
editor.setVisible(true);
else
return;
// Editor closed. Go on:
if (editor.okPressed()) {
File toFile = directory != null ? expandFilename(directory, entry.getLink())
: new File(entry.getLink());
String dirPrefix;
if (directory != null) {
if (!directory.endsWith(System.getProperty("file.separator")))
dirPrefix = directory+System.getProperty("file.separator");
else
dirPrefix = directory;
} else
dirPrefix = null;
try {
boolean success = Util.copyFile(tmp, toFile, true);
if (!success) {
// OOps, the file exists!
System.out.println("File already exists! DownloadExternalFile.download()");
}
// If the local file is in or below the main file directory, change the
// path to relative:
if ((directory != null) && entry.getLink().startsWith(directory) &&
(entry.getLink().length() > dirPrefix.length())) {
entry.setLink(entry.getLink().substring(dirPrefix.length()));
}
callback.downloadComplete(entry);
} catch (IOException ex) {
ex.printStackTrace();
}
tmp.delete();
}
else {
// Cancelled. Just delete the temp file:
if (downloadFinished)
tmp.delete();
}
}
|
diff --git a/benchmarks/src/ibis/ipl/benchmarks/registry/Main.java b/benchmarks/src/ibis/ipl/benchmarks/registry/Main.java
index 39364cd2..a2ac57c3 100644
--- a/benchmarks/src/ibis/ipl/benchmarks/registry/Main.java
+++ b/benchmarks/src/ibis/ipl/benchmarks/registry/Main.java
@@ -1,93 +1,93 @@
package ibis.ipl.benchmarks.registry;
import java.text.DateFormat;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class Main {
private static final Logger logger = LoggerFactory.getLogger(Main.class);
private final IbisApplication[] apps;
Main(int threads, boolean generateEvents, boolean fail) throws Exception {
apps = new IbisApplication[threads];
for (int i = 0; i < threads; i++) {
logger.debug("starting thread " + i + " of " + threads);
apps[i] = new IbisApplication(generateEvents, fail);
}
}
void end() {
for (IbisApplication app : apps) {
app.end();
}
}
void printStats() {
int totalSeen = 0;
for (int i = 0; i < apps.length; i++) {
totalSeen += apps[i].nrOfIbisses();
}
double average = (double) totalSeen / (double) apps.length;
String date =
DateFormat.getTimeInstance().format(
new Date(System.currentTimeMillis()));
System.out.printf(date + " average seen members = %.2f\n", average,
apps.length);
}
public static void main(String[] args) throws Exception {
int threads = 1;
boolean generateEvents = false;
long start = System.currentTimeMillis();
long runtime = Long.MAX_VALUE;
long delay = 0;
boolean fail = false;
- int rank = new Integer(System.getProperty("rank", "0"));
+ // int rank = new Integer(System.getProperty("rank", "0"));
for (int i = 0; i < args.length; i++) {
if (args[i].equalsIgnoreCase("--threads")) {
i++;
threads = new Integer(args[i]);
} else if (args[i].equalsIgnoreCase("--events")) {
generateEvents = true;
} else if (args[i].equalsIgnoreCase("--fail")) {
fail = true;
} else if (args[i].equalsIgnoreCase("--runtime")) {
i++;
runtime = new Integer(args[i]) * 1000;
} else if (args[i].equalsIgnoreCase("--delay")) {
i++;
delay = new Integer(args[i]) * 1000;
} else {
System.err.println("unknown option: " + args[i]);
System.exit(1);
}
}
//delay specified time
if (delay > 0) {
Thread.sleep(delay);
}
//create ibisses
new Main(threads, generateEvents, fail);
//sleep for specified runtime
long sleep = runtime - (System.currentTimeMillis() - start);
System.err.println("Benchmark app sleeping : " + sleep);
if (sleep > 0) {
Thread.sleep(sleep);
}
//app stopped automatically
}
}
| true | true | public static void main(String[] args) throws Exception {
int threads = 1;
boolean generateEvents = false;
long start = System.currentTimeMillis();
long runtime = Long.MAX_VALUE;
long delay = 0;
boolean fail = false;
int rank = new Integer(System.getProperty("rank", "0"));
for (int i = 0; i < args.length; i++) {
if (args[i].equalsIgnoreCase("--threads")) {
i++;
threads = new Integer(args[i]);
} else if (args[i].equalsIgnoreCase("--events")) {
generateEvents = true;
} else if (args[i].equalsIgnoreCase("--fail")) {
fail = true;
} else if (args[i].equalsIgnoreCase("--runtime")) {
i++;
runtime = new Integer(args[i]) * 1000;
} else if (args[i].equalsIgnoreCase("--delay")) {
i++;
delay = new Integer(args[i]) * 1000;
} else {
System.err.println("unknown option: " + args[i]);
System.exit(1);
}
}
//delay specified time
if (delay > 0) {
Thread.sleep(delay);
}
//create ibisses
new Main(threads, generateEvents, fail);
//sleep for specified runtime
long sleep = runtime - (System.currentTimeMillis() - start);
System.err.println("Benchmark app sleeping : " + sleep);
if (sleep > 0) {
Thread.sleep(sleep);
}
//app stopped automatically
}
| public static void main(String[] args) throws Exception {
int threads = 1;
boolean generateEvents = false;
long start = System.currentTimeMillis();
long runtime = Long.MAX_VALUE;
long delay = 0;
boolean fail = false;
// int rank = new Integer(System.getProperty("rank", "0"));
for (int i = 0; i < args.length; i++) {
if (args[i].equalsIgnoreCase("--threads")) {
i++;
threads = new Integer(args[i]);
} else if (args[i].equalsIgnoreCase("--events")) {
generateEvents = true;
} else if (args[i].equalsIgnoreCase("--fail")) {
fail = true;
} else if (args[i].equalsIgnoreCase("--runtime")) {
i++;
runtime = new Integer(args[i]) * 1000;
} else if (args[i].equalsIgnoreCase("--delay")) {
i++;
delay = new Integer(args[i]) * 1000;
} else {
System.err.println("unknown option: " + args[i]);
System.exit(1);
}
}
//delay specified time
if (delay > 0) {
Thread.sleep(delay);
}
//create ibisses
new Main(threads, generateEvents, fail);
//sleep for specified runtime
long sleep = runtime - (System.currentTimeMillis() - start);
System.err.println("Benchmark app sleeping : " + sleep);
if (sleep > 0) {
Thread.sleep(sleep);
}
//app stopped automatically
}
|
diff --git a/src/main/java/org/ebayopensource/turmeric/tools/annoparser/WSDLDocument.java b/src/main/java/org/ebayopensource/turmeric/tools/annoparser/WSDLDocument.java
index 2dee579..bda4b10 100644
--- a/src/main/java/org/ebayopensource/turmeric/tools/annoparser/WSDLDocument.java
+++ b/src/main/java/org/ebayopensource/turmeric/tools/annoparser/WSDLDocument.java
@@ -1,313 +1,313 @@
/*******************************************************************************
* Copyright (c) 2006-2010 eBay 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
*******************************************************************************/
package org.ebayopensource.turmeric.tools.annoparser;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.ebayopensource.turmeric.tools.annoparser.dataobjects.ComplexType;
import org.ebayopensource.turmeric.tools.annoparser.dataobjects.Element;
import org.ebayopensource.turmeric.tools.annoparser.dataobjects.EnumElement;
import org.ebayopensource.turmeric.tools.annoparser.dataobjects.OperationHolder;
import org.ebayopensource.turmeric.tools.annoparser.dataobjects.ParsedAnnotationInfo;
import org.ebayopensource.turmeric.tools.annoparser.dataobjects.PortType;
import org.ebayopensource.turmeric.tools.annoparser.dataobjects.SimpleType;
/**
* The implementation of WSDLDocInterface.
*
* @author srengarajan
*/
public class WSDLDocument implements WSDLDocInterface {
/** The xsd document defined in the WSDL. */
private XSDDocInterface xsdDocument = null;
/** The service name. */
private String serviceName = null;
/** List of all operations defined in the WSDl */
private List<OperationHolder> operations = new ArrayList<OperationHolder>();
/** List of all port types defined in the WSDL. */
private List<PortType> portTypes;
/** The package name. */
private String packageName;
/** The annotations. */
private ParsedAnnotationInfo annotations;
/** The complete remote path. */
private String completeRemotePath;
/** Actual URL of the WSDL document.*/
private URL documentURL;
/* (non-Javadoc)
* @see org.ebayopensource.turmeric.tools.annoparser.XSDDocInterface#getDocumentURL()
*/
public URL getDocumentURL() {
return documentURL;
}
/**
* Sets the document url.
*
* @param documentURL the new document url
*/
public void setDocumentURL(URL documentURL) {
this.documentURL = documentURL;
}
/**
* Gets the operations.
*
* @return the operations
*/
public List<OperationHolder> getOperations() {
return operations;
}
/**
* Gets the xsd document.
*
* @return the xsd document
*/
public XSDDocInterface getXsdDocument() {
return xsdDocument;
}
/**
* Sets the xsd document.
*
* @param xsdDocument the new xsd document
*/
public void setXsdDocument(XSDDocInterface xsdDocument) {
this.xsdDocument = xsdDocument;
}
/**
* Instantiates a new wSDL document.
*/
public WSDLDocument() {
super();
}
/* (non-Javadoc)
* @see org.ebayopensource.turmeric.tools.annoparser.WSDLDocInterface#getAllOperations()
*/
public List<OperationHolder> getAllOperations() {
return operations;
}
/**
* Sets the operations.
*
* @param operations the new operations
*/
public void setOperations(List<OperationHolder> operations) {
this.operations = operations;
}
/**
* Adds the operation.
*
* @param operation the operation
*/
public void addOperation(OperationHolder operation) {
operations.add(operation);
}
/* (non-Javadoc)
* @see org.ebayopensource.turmeric.tools.annoparser.WSDLDocInterface#getServiceName()
*/
public String getServiceName() {
return serviceName;
}
/**
* Sets the service name.
*
* @param serviceName the new service name
*/
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
/* (non-Javadoc)
* @see org.ebayopensource.turmeric.tools.annoparser.XSDDocInterface#getAllComplexTypes()
*/
public List<ComplexType> getAllComplexTypes() {
// TODO Auto-generated method stub
return xsdDocument.getAllComplexTypes();
}
/* (non-Javadoc)
* @see org.ebayopensource.turmeric.tools.annoparser.XSDDocInterface#getAllIndependentElements()
*/
public List<Element> getAllIndependentElements() {
return xsdDocument.getAllIndependentElements();
}
/* (non-Javadoc)
* @see org.ebayopensource.turmeric.tools.annoparser.XSDDocInterface#getAllEnums()
*/
public List<EnumElement> getAllEnums() {
return xsdDocument.getAllEnums();
}
/* (non-Javadoc)
* @see org.ebayopensource.turmeric.tools.annoparser.XSDDocInterface#getAllSimpleTypes()
*/
public List<SimpleType> getAllSimpleTypes() {
return xsdDocument.getAllSimpleTypes();
}
/* (non-Javadoc)
* @see org.ebayopensource.turmeric.tools.annoparser.XSDDocInterface#searchCType(java.lang.String)
*/
public ComplexType searchCType(String name) {
if(xsdDocument!=null){
return this.xsdDocument.searchCType(name);
}
- return xsdDocument.searchCType(name);
+ return null;
}
/* (non-Javadoc)
* @see org.ebayopensource.turmeric.tools.annoparser.XSDDocInterface#searchIndependentElement(java.lang.String)
*/
public Element searchIndependentElement(String elementName) {
return xsdDocument.searchIndependentElement(elementName);
}
/* (non-Javadoc)
* @see org.ebayopensource.turmeric.tools.annoparser.XSDDocInterface#getElementComplexTypeMap()
*/
public Map<String, List<ComplexType>> getElementComplexTypeMap() {
// TODO Auto-generated method stub
return xsdDocument.getElementComplexTypeMap();
}
/* (non-Javadoc)
* @see org.ebayopensource.turmeric.tools.annoparser.WSDLDocInterface#getPortTypes()
*/
public List<PortType> getPortTypes() {
return portTypes;
}
/**
* Sets the port types.
*
* @param portTypes the new port types
*/
public void setPortTypes(List<PortType> portTypes) {
this.portTypes = portTypes;
}
/**
* Adds the port type.
*
* @param portType the port type
*/
public void addPortType(PortType portType){
if(portTypes==null){
portTypes=new ArrayList<PortType>();
}
this.getPortTypes().add(portType);
}
/* (non-Javadoc)
* @see org.ebayopensource.turmeric.tools.annoparser.XSDDocInterface#searchSimpleType(java.lang.String)
*/
public SimpleType searchSimpleType(String name) {
if(xsdDocument!=null){
return this.xsdDocument.searchSimpleType(name);
}
return null;
}
/**
* Sets the package name.
*
* @param packageName the new package name
*/
public void setPackageName(String packageName){
this.packageName=packageName;
}
/* (non-Javadoc)
* @see org.ebayopensource.turmeric.tools.annoparser.WSDLDocInterface#getPackageName()
*/
public String getPackageName() {
return packageName;
}
/* (non-Javadoc)
* @see org.ebayopensource.turmeric.tools.annoparser.WSDLDocInterface#getCompleteRemotePath()
*/
public String getCompleteRemotePath() {
return completeRemotePath;
}
/**
* Sets the complete remote path.
*
* @param completeRemotePath the new complete remote path
*/
public void setCompleteRemotePath(String completeRemotePath) {
this.completeRemotePath = completeRemotePath;
}
public ParsedAnnotationInfo getAnnotations() {
return annotations;
}
public void setAnnotations(ParsedAnnotationInfo annotations) {
this.annotations = annotations;
}
@Override
public Map<String, Set<String>> getParentToComplexTypeMap() {
return xsdDocument.getParentToComplexTypeMap();
}
}
| true | true | public ComplexType searchCType(String name) {
if(xsdDocument!=null){
return this.xsdDocument.searchCType(name);
}
return xsdDocument.searchCType(name);
}
| public ComplexType searchCType(String name) {
if(xsdDocument!=null){
return this.xsdDocument.searchCType(name);
}
return null;
}
|
diff --git a/PaintroidTest/src/org/catrobat/paintroid/test/integration/tools/FillToolIntegrationTest.java b/PaintroidTest/src/org/catrobat/paintroid/test/integration/tools/FillToolIntegrationTest.java
index f77d7dce..b2fc3cc6 100644
--- a/PaintroidTest/src/org/catrobat/paintroid/test/integration/tools/FillToolIntegrationTest.java
+++ b/PaintroidTest/src/org/catrobat/paintroid/test/integration/tools/FillToolIntegrationTest.java
@@ -1,131 +1,131 @@
package org.catrobat.paintroid.test.integration.tools;
import org.catrobat.paintroid.MainActivity;
import org.catrobat.paintroid.PaintroidApplication;
import org.catrobat.paintroid.R;
import org.catrobat.paintroid.test.integration.BaseIntegrationTestClass;
import org.catrobat.paintroid.test.utils.PrivateAccess;
import org.catrobat.paintroid.tools.Tool;
import org.catrobat.paintroid.tools.ToolType;
import org.catrobat.paintroid.ui.DrawingSurface;
import org.catrobat.paintroid.ui.Statusbar;
import org.catrobat.paintroid.ui.implementation.DrawingSurfaceImplementation;
import org.junit.Before;
import android.graphics.PointF;
import android.widget.Button;
import android.widget.TableRow;
public class FillToolIntegrationTest extends BaseIntegrationTestClass {
private static final String PRIVATE_ACCESS_STATUSBAR_NAME = "mStatusbar";
protected Statusbar mStatusbar;
public FillToolIntegrationTest() throws Exception {
super();
}
@Override
@Before
protected void setUp() {
super.setUp();
resetBrush();
try {
mStatusbar = (Statusbar) PrivateAccess.getMemberValue(MainActivity.class, getActivity(),
PRIVATE_ACCESS_STATUSBAR_NAME);
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
public void testBitmapIsFilled() throws InterruptedException {
assertTrue("Waiting for DrawingSurface", mSolo.waitForView(DrawingSurfaceImplementation.class, 1, TIMEOUT));
selectTool(ToolType.FILL);
Tool mFillTool = mStatusbar.getCurrentTool();
int colorToFill = mStatusbar.getCurrentTool().getDrawPaint().getColor();
DrawingSurface drawingSurface = (DrawingSurfaceImplementation) getActivity().findViewById(
R.id.drawingSurfaceView);
int xCoord = 100;
int yCoord = 200;
PointF pointOnBitmap = new PointF(xCoord, yCoord);
int colorBeforeFill = drawingSurface.getBitmapColor(pointOnBitmap);
PointF pointOnScreen = new PointF(pointOnBitmap.x, pointOnBitmap.y);
PaintroidApplication.CURRENT_PERSPECTIVE.convertFromScreenToCanvas(pointOnScreen);
mSolo.clickOnScreen(pointOnScreen.x, pointOnScreen.y); // to fill the bitmap
mSolo.sleep(5000);
int colorAfterFill = drawingSurface.getBitmapColor(pointOnBitmap);
assertEquals("Pixel color should be the same", colorToFill, colorAfterFill);
}
public void testOnlyFillInnerArea() {
assertTrue("Waiting for DrawingSurface", mSolo.waitForView(DrawingSurfaceImplementation.class, 1, TIMEOUT));
DrawingSurface drawingSurface = (DrawingSurfaceImplementation) getActivity().findViewById(
R.id.drawingSurfaceView);
assertEquals("BrushTool should be selected", ToolType.BRUSH, mStatusbar.getCurrentTool().getToolType());
int colorToDrawBorder = mStatusbar.getCurrentTool().getDrawPaint().getColor();
int checkPointXCoord = 300;
int checkPointYCoord = 500;
PointF pointOnBitmap = new PointF(checkPointXCoord, checkPointYCoord);
int checkPointStartColor = drawingSurface.getBitmapColor(pointOnBitmap);
assertFalse(colorToDrawBorder == checkPointStartColor);
PointF pointOnScreen = new PointF(pointOnBitmap.x, pointOnBitmap.y);
PaintroidApplication.CURRENT_PERSPECTIVE.convertFromScreenToCanvas(pointOnScreen);
PointF leftPointOnBitmap = new PointF(checkPointXCoord - 150, checkPointYCoord);
PointF leftPointOnScreen = new PointF(leftPointOnBitmap.x, leftPointOnBitmap.y);
PointF upperPointOnScreen = new PointF(checkPointXCoord, checkPointYCoord - 150);
PointF rightPointOnScreen = new PointF(checkPointXCoord + 150, checkPointYCoord);
PointF bottomPointOnScreen = new PointF(checkPointXCoord, checkPointYCoord + 150);
PaintroidApplication.CURRENT_PERSPECTIVE.convertFromScreenToCanvas(leftPointOnScreen);
PaintroidApplication.CURRENT_PERSPECTIVE.convertFromScreenToCanvas(upperPointOnScreen);
PaintroidApplication.CURRENT_PERSPECTIVE.convertFromScreenToCanvas(rightPointOnScreen);
PaintroidApplication.CURRENT_PERSPECTIVE.convertFromScreenToCanvas(bottomPointOnScreen);
mSolo.drag(leftPointOnScreen.x, upperPointOnScreen.x, leftPointOnScreen.y, upperPointOnScreen.y, 1);
mSolo.drag(upperPointOnScreen.x, rightPointOnScreen.x, upperPointOnScreen.y, rightPointOnScreen.y, 1);
mSolo.drag(rightPointOnScreen.x, bottomPointOnScreen.x, rightPointOnScreen.y, bottomPointOnScreen.y, 1);
mSolo.drag(bottomPointOnScreen.x, leftPointOnScreen.x, bottomPointOnScreen.y, leftPointOnScreen.y, 1);
selectTool(ToolType.FILL);
// change color
mSolo.clickOnView(mMenuBottomParameter2);
- assertTrue("Waiting for DrawingSurface", mSolo.waitForText(mSolo.getString(R.string.ok), 1, TIMEOUT * 2));
+ assertTrue("Waiting for DrawingSurface", mSolo.waitForText(mSolo.getString(R.string.done), 1, TIMEOUT * 2));
Button colorButton = mSolo.getButton(5);
assertTrue(colorButton.getParent() instanceof TableRow);
mSolo.clickOnButton(5);
mSolo.sleep(50);
- mSolo.clickOnButton(getActivity().getResources().getString(R.string.ok));
+ mSolo.clickOnButton(getActivity().getResources().getString(R.string.done));
int colorToFill = mStatusbar.getCurrentTool().getDrawPaint().getColor();
assertFalse(colorToDrawBorder == colorToFill);
assertFalse(checkPointStartColor == colorToFill);
// to fill the bitmap
mSolo.clickOnScreen(pointOnScreen.x, pointOnScreen.y);
mSolo.sleep(5000);
int colorAfterFill = drawingSurface.getBitmapColor(pointOnBitmap);
assertEquals("Pixel color should be the same", colorToFill, colorAfterFill);
int outsideColorAfterFill = drawingSurface.getBitmapColor(new PointF(leftPointOnBitmap.x - 30,
leftPointOnBitmap.y));
assertFalse("Pixel color should be different", colorToFill == outsideColorAfterFill);
}
}
| false | true | public void testOnlyFillInnerArea() {
assertTrue("Waiting for DrawingSurface", mSolo.waitForView(DrawingSurfaceImplementation.class, 1, TIMEOUT));
DrawingSurface drawingSurface = (DrawingSurfaceImplementation) getActivity().findViewById(
R.id.drawingSurfaceView);
assertEquals("BrushTool should be selected", ToolType.BRUSH, mStatusbar.getCurrentTool().getToolType());
int colorToDrawBorder = mStatusbar.getCurrentTool().getDrawPaint().getColor();
int checkPointXCoord = 300;
int checkPointYCoord = 500;
PointF pointOnBitmap = new PointF(checkPointXCoord, checkPointYCoord);
int checkPointStartColor = drawingSurface.getBitmapColor(pointOnBitmap);
assertFalse(colorToDrawBorder == checkPointStartColor);
PointF pointOnScreen = new PointF(pointOnBitmap.x, pointOnBitmap.y);
PaintroidApplication.CURRENT_PERSPECTIVE.convertFromScreenToCanvas(pointOnScreen);
PointF leftPointOnBitmap = new PointF(checkPointXCoord - 150, checkPointYCoord);
PointF leftPointOnScreen = new PointF(leftPointOnBitmap.x, leftPointOnBitmap.y);
PointF upperPointOnScreen = new PointF(checkPointXCoord, checkPointYCoord - 150);
PointF rightPointOnScreen = new PointF(checkPointXCoord + 150, checkPointYCoord);
PointF bottomPointOnScreen = new PointF(checkPointXCoord, checkPointYCoord + 150);
PaintroidApplication.CURRENT_PERSPECTIVE.convertFromScreenToCanvas(leftPointOnScreen);
PaintroidApplication.CURRENT_PERSPECTIVE.convertFromScreenToCanvas(upperPointOnScreen);
PaintroidApplication.CURRENT_PERSPECTIVE.convertFromScreenToCanvas(rightPointOnScreen);
PaintroidApplication.CURRENT_PERSPECTIVE.convertFromScreenToCanvas(bottomPointOnScreen);
mSolo.drag(leftPointOnScreen.x, upperPointOnScreen.x, leftPointOnScreen.y, upperPointOnScreen.y, 1);
mSolo.drag(upperPointOnScreen.x, rightPointOnScreen.x, upperPointOnScreen.y, rightPointOnScreen.y, 1);
mSolo.drag(rightPointOnScreen.x, bottomPointOnScreen.x, rightPointOnScreen.y, bottomPointOnScreen.y, 1);
mSolo.drag(bottomPointOnScreen.x, leftPointOnScreen.x, bottomPointOnScreen.y, leftPointOnScreen.y, 1);
selectTool(ToolType.FILL);
// change color
mSolo.clickOnView(mMenuBottomParameter2);
assertTrue("Waiting for DrawingSurface", mSolo.waitForText(mSolo.getString(R.string.ok), 1, TIMEOUT * 2));
Button colorButton = mSolo.getButton(5);
assertTrue(colorButton.getParent() instanceof TableRow);
mSolo.clickOnButton(5);
mSolo.sleep(50);
mSolo.clickOnButton(getActivity().getResources().getString(R.string.ok));
int colorToFill = mStatusbar.getCurrentTool().getDrawPaint().getColor();
assertFalse(colorToDrawBorder == colorToFill);
assertFalse(checkPointStartColor == colorToFill);
// to fill the bitmap
mSolo.clickOnScreen(pointOnScreen.x, pointOnScreen.y);
mSolo.sleep(5000);
int colorAfterFill = drawingSurface.getBitmapColor(pointOnBitmap);
assertEquals("Pixel color should be the same", colorToFill, colorAfterFill);
int outsideColorAfterFill = drawingSurface.getBitmapColor(new PointF(leftPointOnBitmap.x - 30,
leftPointOnBitmap.y));
assertFalse("Pixel color should be different", colorToFill == outsideColorAfterFill);
}
| public void testOnlyFillInnerArea() {
assertTrue("Waiting for DrawingSurface", mSolo.waitForView(DrawingSurfaceImplementation.class, 1, TIMEOUT));
DrawingSurface drawingSurface = (DrawingSurfaceImplementation) getActivity().findViewById(
R.id.drawingSurfaceView);
assertEquals("BrushTool should be selected", ToolType.BRUSH, mStatusbar.getCurrentTool().getToolType());
int colorToDrawBorder = mStatusbar.getCurrentTool().getDrawPaint().getColor();
int checkPointXCoord = 300;
int checkPointYCoord = 500;
PointF pointOnBitmap = new PointF(checkPointXCoord, checkPointYCoord);
int checkPointStartColor = drawingSurface.getBitmapColor(pointOnBitmap);
assertFalse(colorToDrawBorder == checkPointStartColor);
PointF pointOnScreen = new PointF(pointOnBitmap.x, pointOnBitmap.y);
PaintroidApplication.CURRENT_PERSPECTIVE.convertFromScreenToCanvas(pointOnScreen);
PointF leftPointOnBitmap = new PointF(checkPointXCoord - 150, checkPointYCoord);
PointF leftPointOnScreen = new PointF(leftPointOnBitmap.x, leftPointOnBitmap.y);
PointF upperPointOnScreen = new PointF(checkPointXCoord, checkPointYCoord - 150);
PointF rightPointOnScreen = new PointF(checkPointXCoord + 150, checkPointYCoord);
PointF bottomPointOnScreen = new PointF(checkPointXCoord, checkPointYCoord + 150);
PaintroidApplication.CURRENT_PERSPECTIVE.convertFromScreenToCanvas(leftPointOnScreen);
PaintroidApplication.CURRENT_PERSPECTIVE.convertFromScreenToCanvas(upperPointOnScreen);
PaintroidApplication.CURRENT_PERSPECTIVE.convertFromScreenToCanvas(rightPointOnScreen);
PaintroidApplication.CURRENT_PERSPECTIVE.convertFromScreenToCanvas(bottomPointOnScreen);
mSolo.drag(leftPointOnScreen.x, upperPointOnScreen.x, leftPointOnScreen.y, upperPointOnScreen.y, 1);
mSolo.drag(upperPointOnScreen.x, rightPointOnScreen.x, upperPointOnScreen.y, rightPointOnScreen.y, 1);
mSolo.drag(rightPointOnScreen.x, bottomPointOnScreen.x, rightPointOnScreen.y, bottomPointOnScreen.y, 1);
mSolo.drag(bottomPointOnScreen.x, leftPointOnScreen.x, bottomPointOnScreen.y, leftPointOnScreen.y, 1);
selectTool(ToolType.FILL);
// change color
mSolo.clickOnView(mMenuBottomParameter2);
assertTrue("Waiting for DrawingSurface", mSolo.waitForText(mSolo.getString(R.string.done), 1, TIMEOUT * 2));
Button colorButton = mSolo.getButton(5);
assertTrue(colorButton.getParent() instanceof TableRow);
mSolo.clickOnButton(5);
mSolo.sleep(50);
mSolo.clickOnButton(getActivity().getResources().getString(R.string.done));
int colorToFill = mStatusbar.getCurrentTool().getDrawPaint().getColor();
assertFalse(colorToDrawBorder == colorToFill);
assertFalse(checkPointStartColor == colorToFill);
// to fill the bitmap
mSolo.clickOnScreen(pointOnScreen.x, pointOnScreen.y);
mSolo.sleep(5000);
int colorAfterFill = drawingSurface.getBitmapColor(pointOnBitmap);
assertEquals("Pixel color should be the same", colorToFill, colorAfterFill);
int outsideColorAfterFill = drawingSurface.getBitmapColor(new PointF(leftPointOnBitmap.x - 30,
leftPointOnBitmap.y));
assertFalse("Pixel color should be different", colorToFill == outsideColorAfterFill);
}
|
diff --git a/BlueFinderRS/src/pia/BipartiteGraphPathGenerator.java b/BlueFinderRS/src/pia/BipartiteGraphPathGenerator.java
index 6533cf5..8100b89 100644
--- a/BlueFinderRS/src/pia/BipartiteGraphPathGenerator.java
+++ b/BlueFinderRS/src/pia/BipartiteGraphPathGenerator.java
@@ -1,84 +1,84 @@
package pia;
import db.WikipediaConnector;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
*
* @author dtorres
* Main class to execute the Pia Index Algorithm. This class receives from console the basic params to initialize the indexing.
* The PIA Index is represented by means of three Mysql tables: U_Page: pairs of Wikipedia pages, V_Normalized: path queries and
* UxV: the edges set. This main class invokes the BipartiteGraphGenerator class.
*/
public class BipartiteGraphPathGenerator {
private static final String DBPEDIA_PREFIX = "http://dbpedia.org/resource/";
public static void main(String[] args) throws ClassNotFoundException, SQLException, FileNotFoundException, IOException {
Connection conReserarch = WikipediaConnector.getResultsConnection();
Statement st = conReserarch.createStatement();
int counter = 0;
if (args.length < 4 || args[0].equalsIgnoreCase("help")) {
System.out.println("Usage: <inf_limit> <max_limit> <iterations_limit> <from_to_table> [<dbpedia prefix>] [clean]");
System.out.println("Where:");
System.out.println("\t\t<inf_limit> is a number which represents the min row in from_to_table\n\t\t<max_limit> is a number\n\t\t <iterations_limit> is a number\n\t\t<from_to_table> name of the sources table.");
System.out.println("dbpedia prefix is the prefix to delete");
System.out.println("write clean as 6 parameter to clean the index results");
return;
}
- int inf_limit = Integer.parseInt(args[0]);
- int max_limjt = Integer.parseInt(args[1]);
+ long inf_limit = Long.parseLong(args[0]);
+ long max_limjt = Long.parseLong(args[1]);
int iterations = Integer.parseInt(args[2]);
String from_to_table = args[3];
String dbpediaPrefix = DBPEDIA_PREFIX;
if (args.length >= 4) {
dbpediaPrefix = args[4];
}
String clean = "tidy";
if(args.length == 6){
clean = args[5];
System.out.println("Clean = "+ clean);
}
long start = System.nanoTime();
BipartiteGraphGenerator bgg = new BipartiteGraphGenerator(iterations);
if(clean.equalsIgnoreCase("clean")){
WikipediaConnector.restoreResultIndex();
}
ResultSet resultSet = st.executeQuery("SELECT * FROM " + from_to_table + " limit " + inf_limit + " ," + max_limjt);
while (resultSet.next()) {
String to = resultSet.getString("to");
to = URLDecoder.decode(to, "UTF-8");
String from = resultSet.getString("from");
from = URLDecoder.decode(from, "UTF-8");
from = from.replace(dbpediaPrefix, "");
to = to.replace(dbpediaPrefix, "");
System.out.println("Processing paths from " + from + " to " + to + "CASE: " + counter++);
bgg.generateBiGraph(from, to);
}
long elapsedTimeMillis = System.nanoTime() - start;
System.out.println("Regular generated paths = " + bgg.getRegularGeneratedPaths());
System.out.println("Elapsed time in nanoseconds" + elapsedTimeMillis);
System.out.println("Finalized !!!!");
st.close();
conReserarch.close();
}
}
| true | true | public static void main(String[] args) throws ClassNotFoundException, SQLException, FileNotFoundException, IOException {
Connection conReserarch = WikipediaConnector.getResultsConnection();
Statement st = conReserarch.createStatement();
int counter = 0;
if (args.length < 4 || args[0].equalsIgnoreCase("help")) {
System.out.println("Usage: <inf_limit> <max_limit> <iterations_limit> <from_to_table> [<dbpedia prefix>] [clean]");
System.out.println("Where:");
System.out.println("\t\t<inf_limit> is a number which represents the min row in from_to_table\n\t\t<max_limit> is a number\n\t\t <iterations_limit> is a number\n\t\t<from_to_table> name of the sources table.");
System.out.println("dbpedia prefix is the prefix to delete");
System.out.println("write clean as 6 parameter to clean the index results");
return;
}
int inf_limit = Integer.parseInt(args[0]);
int max_limjt = Integer.parseInt(args[1]);
int iterations = Integer.parseInt(args[2]);
String from_to_table = args[3];
String dbpediaPrefix = DBPEDIA_PREFIX;
if (args.length >= 4) {
dbpediaPrefix = args[4];
}
String clean = "tidy";
if(args.length == 6){
clean = args[5];
System.out.println("Clean = "+ clean);
}
long start = System.nanoTime();
BipartiteGraphGenerator bgg = new BipartiteGraphGenerator(iterations);
if(clean.equalsIgnoreCase("clean")){
WikipediaConnector.restoreResultIndex();
}
ResultSet resultSet = st.executeQuery("SELECT * FROM " + from_to_table + " limit " + inf_limit + " ," + max_limjt);
while (resultSet.next()) {
String to = resultSet.getString("to");
to = URLDecoder.decode(to, "UTF-8");
String from = resultSet.getString("from");
from = URLDecoder.decode(from, "UTF-8");
from = from.replace(dbpediaPrefix, "");
to = to.replace(dbpediaPrefix, "");
System.out.println("Processing paths from " + from + " to " + to + "CASE: " + counter++);
bgg.generateBiGraph(from, to);
}
long elapsedTimeMillis = System.nanoTime() - start;
System.out.println("Regular generated paths = " + bgg.getRegularGeneratedPaths());
System.out.println("Elapsed time in nanoseconds" + elapsedTimeMillis);
System.out.println("Finalized !!!!");
st.close();
conReserarch.close();
}
| public static void main(String[] args) throws ClassNotFoundException, SQLException, FileNotFoundException, IOException {
Connection conReserarch = WikipediaConnector.getResultsConnection();
Statement st = conReserarch.createStatement();
int counter = 0;
if (args.length < 4 || args[0].equalsIgnoreCase("help")) {
System.out.println("Usage: <inf_limit> <max_limit> <iterations_limit> <from_to_table> [<dbpedia prefix>] [clean]");
System.out.println("Where:");
System.out.println("\t\t<inf_limit> is a number which represents the min row in from_to_table\n\t\t<max_limit> is a number\n\t\t <iterations_limit> is a number\n\t\t<from_to_table> name of the sources table.");
System.out.println("dbpedia prefix is the prefix to delete");
System.out.println("write clean as 6 parameter to clean the index results");
return;
}
long inf_limit = Long.parseLong(args[0]);
long max_limjt = Long.parseLong(args[1]);
int iterations = Integer.parseInt(args[2]);
String from_to_table = args[3];
String dbpediaPrefix = DBPEDIA_PREFIX;
if (args.length >= 4) {
dbpediaPrefix = args[4];
}
String clean = "tidy";
if(args.length == 6){
clean = args[5];
System.out.println("Clean = "+ clean);
}
long start = System.nanoTime();
BipartiteGraphGenerator bgg = new BipartiteGraphGenerator(iterations);
if(clean.equalsIgnoreCase("clean")){
WikipediaConnector.restoreResultIndex();
}
ResultSet resultSet = st.executeQuery("SELECT * FROM " + from_to_table + " limit " + inf_limit + " ," + max_limjt);
while (resultSet.next()) {
String to = resultSet.getString("to");
to = URLDecoder.decode(to, "UTF-8");
String from = resultSet.getString("from");
from = URLDecoder.decode(from, "UTF-8");
from = from.replace(dbpediaPrefix, "");
to = to.replace(dbpediaPrefix, "");
System.out.println("Processing paths from " + from + " to " + to + "CASE: " + counter++);
bgg.generateBiGraph(from, to);
}
long elapsedTimeMillis = System.nanoTime() - start;
System.out.println("Regular generated paths = " + bgg.getRegularGeneratedPaths());
System.out.println("Elapsed time in nanoseconds" + elapsedTimeMillis);
System.out.println("Finalized !!!!");
st.close();
conReserarch.close();
}
|
diff --git a/src/main/java/org/jrecruiter/persistent/dao/JobsDAOHibernate.java b/src/main/java/org/jrecruiter/persistent/dao/JobsDAOHibernate.java
index 344eeaf..5ae680f 100644
--- a/src/main/java/org/jrecruiter/persistent/dao/JobsDAOHibernate.java
+++ b/src/main/java/org/jrecruiter/persistent/dao/JobsDAOHibernate.java
@@ -1,295 +1,295 @@
/*
* http://www.jrecruiter.org
*
* Disclaimer of Warranty.
*
* Unless required by applicable law or agreed to in writing, Licensor provides
* the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
* including, without limitation, any warranties or conditions of TITLE,
* NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
* solely responsible for determining the appropriateness of using or
* redistributing the Work and assume any risks associated with Your exercise of
* permissions under this License.
*
*/
package org.jrecruiter.persistent.dao;
import java.util.Iterator;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.jrecruiter.Constants.StatsMode;
import org.jrecruiter.model.Job;
import org.jrecruiter.model.User;
import org.jrecruiter.model.UserRole;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
/**
* This DAO provides job-related database methods.
*
* @author Jerzy Puchala, Gunnar Hillert
* @version @version $Id$
*/
public class JobsDAOHibernate extends HibernateDaoSupport implements JobsDAO {
private static JobsDAOHibernate daoHibernate = null;
/**
* User Dao.
*/
private UserDAO userDao;
/**
* @param userDao The userDao to set.
*/
public void setUserDao(UserDAO userDao) {
this.userDao = userDao;
}
/**
* Constructor.
*
*/
private JobsDAOHibernate() {
super();
}
/**
* Returns a new instance of the JobsDAO.
* @return JobsDAO
*/
public static JobsDAO getInstance() {
if (daoHibernate == null) {
daoHibernate = new JobsDAOHibernate();
}
return daoHibernate;
}
/**
* Method for returning list of all jobs.
*
* @return List of Jobs
*
* @throws DAOException
*
*/
public List<Job> getAllJobs() throws DAOException {
List<Job> jobs = (List<Job>) getHibernateTemplate().find(
"select job from Job job " +
"left outer join fetch job.statistics order by job.updateDate DESC");
return jobs;
}
/**
* Update a job posting in the persistence store.
*/
public void update(Job job) {
getHibernateTemplate().saveOrUpdate(job);
}
/**
* Get a gob from the persistence store.
*
* @param jobId Id of the job posting.
* @return A single job posting
*
* @see org.jrecruiter.persistent.dao.JobReqDAO#get(java.lang.Integer)
*/
public Job get(Long jobId) throws DAOException {
Job job = (Job) getHibernateTemplate().get(Job.class, jobId);
return job;
}
/**
* @see org.jrecruiter.persistent.dao.JobReqDAO#delete(java.lang.Integer)
*/
public void delete(final Long jobId) throws DAOException {
Job job = (Job) getHibernateTemplate().load(Job.class, jobId);
getHibernateTemplate().delete(job);
}
/* (non-Javadoc)
* @see org.jrecruiter.persistent.dao.
* JobReqDAO#getAllUserJobs(java.lang.String)
*/
public List<Job> getAllUserJobs(String username) {
List<Job> jobs;
User user = userDao.getUser(username);
boolean administrator = false;
Iterator it = user.getRoles().iterator();
while (it.hasNext()) {
UserRole userRole = (UserRole) it.next();
if ("admin".equals(userRole.getName())) {
administrator = true;
}
}
if (administrator) {
jobs = this.getAllJobs();
} else {
jobs = getHibernateTemplate().find(
"from Job j where j.owner.username=?", username);
}
return jobs;
}
/* (non-Javadoc)
* @see org.jrecruiter.persistent.dao.
* JobReqDAO#getAllUserJobs(java.lang.String)
*/
public List<Job> getAllUserJobsForStatistics(String username) {
List < Job > jobs;
User user = userDao.getUser(username);
boolean administrator = false;
Iterator it = user.getRoles().iterator();
while (it.hasNext()) {
UserRole userRole = (UserRole) it.next();
if ("admin".equals(userRole.getName())) {
administrator = true;
}
}
if (administrator) {
jobs = this.getAllJobs();
} else {
jobs = getHibernateTemplate().find(
"from Job j left outer join fetch j.statistics where j.owner.username=?", username);
}
return jobs;
}
/* (non-Javadoc)
* @see org.jrecruiter.persistent.dao.JobsDAO#getUsersJobsForStatistics(java.lang.String, java.lang.Integer, org.jrecruiter.Constants.StatsMode)
*/
public List<Job> getUsersJobsForStatistics(String username, Integer maxResult, StatsMode statsMode) {
List < Job > jobs;
User user = userDao.getUser(username);
boolean administrator = false;
Iterator it = user.getRoles().iterator();
while (it.hasNext()) {
UserRole userRole = (UserRole) it.next();
if ("admin".equals(userRole.getName())) {
administrator = true;
}
}
final Session session = getSession(false);
try {
Query query = null;
if (statsMode == StatsMode.PAGE_HITS) {
if (administrator) {
query = session.createQuery("select j from Job j left outer join fetch j.statistics as stats "
- + "order by stats.counter asc");
+ + "where stats is not null order by stats.counter desc");
} else {
query = session
.createQuery("select j from Job j left outer join fetch j.statistics as stats "
- + "where j.owner.username=:username "
- + "order by stats.counter asc");
+ + "where j.owner.username=:username and stats is not null "
+ + "order by stats.counter desc");
query.setString("username", username);
}
} else {
if (administrator) {
query = session
.createQuery("select j from Job j left outer join fetch j.statistics as stats "
- + "order by stats.uniqueVisits asc");
+ + "where stats is not null order by stats.uniqueVisits desc");
} else {
query = session
.createQuery("select j from Job j left outer join fetch j.statistics as stats "
- + "where j.owner.username=:username "
- + "order by stats.uniqueVisits asc");
+ + "where j.owner.username=:username and stats is not null "
+ + "order by stats.uniqueVisits desc");
query.setString("username", username);
}
}
query.setMaxResults(maxResult);
jobs = query.list();
} catch (HibernateException ex) {
throw convertHibernateAccessException(ex);
}
return jobs;
}
/**
* Perform a simple search within the persistence store.
*
* @param keyword
* The search keyword
* @return List of job postings representing the search results.
*/
public List searchByKeyword(final String keyword) throws DAOException {
List list = (List) getHibernateTemplate().execute(
new HibernateCallback() {
public Object doInHibernate(final Session session)
throws HibernateException {
Query q = session.createQuery("from Job j where "
+ "lower(j.jobTitle) like :keyword or "
+ "lower(j.description) like :keyword or "
+ "lower(j.jobRestrictions) like :keyword or "
+ "lower(j.businessLocation) like :keyword");
q.setString("keyword", "%" + keyword + "%");
return q.list();
}
});
return list;
}
}
| false | true | public List<Job> getUsersJobsForStatistics(String username, Integer maxResult, StatsMode statsMode) {
List < Job > jobs;
User user = userDao.getUser(username);
boolean administrator = false;
Iterator it = user.getRoles().iterator();
while (it.hasNext()) {
UserRole userRole = (UserRole) it.next();
if ("admin".equals(userRole.getName())) {
administrator = true;
}
}
final Session session = getSession(false);
try {
Query query = null;
if (statsMode == StatsMode.PAGE_HITS) {
if (administrator) {
query = session.createQuery("select j from Job j left outer join fetch j.statistics as stats "
+ "order by stats.counter asc");
} else {
query = session
.createQuery("select j from Job j left outer join fetch j.statistics as stats "
+ "where j.owner.username=:username "
+ "order by stats.counter asc");
query.setString("username", username);
}
} else {
if (administrator) {
query = session
.createQuery("select j from Job j left outer join fetch j.statistics as stats "
+ "order by stats.uniqueVisits asc");
} else {
query = session
.createQuery("select j from Job j left outer join fetch j.statistics as stats "
+ "where j.owner.username=:username "
+ "order by stats.uniqueVisits asc");
query.setString("username", username);
}
}
query.setMaxResults(maxResult);
jobs = query.list();
} catch (HibernateException ex) {
throw convertHibernateAccessException(ex);
}
return jobs;
}
| public List<Job> getUsersJobsForStatistics(String username, Integer maxResult, StatsMode statsMode) {
List < Job > jobs;
User user = userDao.getUser(username);
boolean administrator = false;
Iterator it = user.getRoles().iterator();
while (it.hasNext()) {
UserRole userRole = (UserRole) it.next();
if ("admin".equals(userRole.getName())) {
administrator = true;
}
}
final Session session = getSession(false);
try {
Query query = null;
if (statsMode == StatsMode.PAGE_HITS) {
if (administrator) {
query = session.createQuery("select j from Job j left outer join fetch j.statistics as stats "
+ "where stats is not null order by stats.counter desc");
} else {
query = session
.createQuery("select j from Job j left outer join fetch j.statistics as stats "
+ "where j.owner.username=:username and stats is not null "
+ "order by stats.counter desc");
query.setString("username", username);
}
} else {
if (administrator) {
query = session
.createQuery("select j from Job j left outer join fetch j.statistics as stats "
+ "where stats is not null order by stats.uniqueVisits desc");
} else {
query = session
.createQuery("select j from Job j left outer join fetch j.statistics as stats "
+ "where j.owner.username=:username and stats is not null "
+ "order by stats.uniqueVisits desc");
query.setString("username", username);
}
}
query.setMaxResults(maxResult);
jobs = query.list();
} catch (HibernateException ex) {
throw convertHibernateAccessException(ex);
}
return jobs;
}
|
diff --git a/mideaas-codeeditor/src/main/java/org/vaadin/mideaas/editor/MultiUserDoc.java b/mideaas-codeeditor/src/main/java/org/vaadin/mideaas/editor/MultiUserDoc.java
index 2d6d94b..b87c492 100644
--- a/mideaas-codeeditor/src/main/java/org/vaadin/mideaas/editor/MultiUserDoc.java
+++ b/mideaas-codeeditor/src/main/java/org/vaadin/mideaas/editor/MultiUserDoc.java
@@ -1,134 +1,136 @@
package org.vaadin.mideaas.editor;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.CopyOnWriteArrayList;
import org.apache.commons.io.FileUtils;
import org.vaadin.aceeditor.client.AceDoc;
import org.vaadin.mideaas.editor.DocDiffMediator.Guard;
public class MultiUserDoc implements SharedDoc.Listener {
public interface DifferingChangedListener {
public void differingChanged(Map<EditorUser, DocDifference> diffs);
}
private final Guard guard;
private final File saveBaseTo;
private final SharedDoc base;
private final HashMap<EditorUser, UserDoc> userDocs
= new HashMap<EditorUser, UserDoc>();
private final CopyOnWriteArrayList<DifferingChangedListener> dcListeners =
new CopyOnWriteArrayList<DifferingChangedListener>();
// ...
private final Timer baseChangeTimer = new Timer();
private boolean fireScheduled = false;
public MultiUserDoc(AceDoc initial, File saveBaseTo, Guard guard) {
this.saveBaseTo = saveBaseTo;
this.guard = guard;
base = new SharedDoc(initial);
base.addListener(this);
}
public SharedDoc getBase() {
return base;
}
public synchronized UserDoc getUserDoc(EditorUser user) {
UserDoc ud = userDocs.get(user);
if (ud==null) {
ud = createUserDoc(user);
userDocs.put(user, ud);
}
return ud;
}
public synchronized void removeUserDoc(EditorUser user) {
UserDoc ud = userDocs.remove(user);
if (ud!=null) {
ud.getDoc().removeListener(this);
ud.getMed().detach();
}
}
public synchronized Map<EditorUser, DocDifference> getDifferences() {
HashMap<EditorUser, DocDifference> diffs = new HashMap<EditorUser, DocDifference>();
for (UserDoc ud : userDocs.values()) {
DocDifference dd = ud.getDiff();
if (dd.isChanged()) {
diffs.put(ud.getUser(), dd);
}
}
return diffs;
}
private UserDoc createUserDoc(EditorUser user) {
SharedDoc doc = new SharedDoc(getBase().getDoc());
DocDiffMediator med = new DocDiffMediator(base, doc);
med.setUpwardsGuard(guard);
UserDoc ud = new UserDoc(user, doc, med, base);
doc.addListener(this);
return ud;
}
@Override
public void changed() {
// Delaying a bit. Not acting on each change, only after a while.
// This is a bit so so...
synchronized (baseChangeTimer) {
if (fireScheduled) {
return;
}
baseChangeTimer.schedule(new TimerTask() {
@Override
public void run() {
synchronized (baseChangeTimer) {
- saveBaseToDisk();
+ if (saveBaseTo!=null) {
+ saveBaseToDisk();
+ }
fireDifferingChanged(getDifferences());
fireScheduled = false;
}
}
}, 400);
fireScheduled = true;
}
}
protected void saveBaseToDisk() {
try {
FileUtils.write(saveBaseTo, getBaseText());
} catch (IOException e) {
System.err.println("WARNING: could not save to "+saveBaseTo);
}
}
public synchronized void addDifferingChangedListener(DifferingChangedListener li) {
dcListeners.add(li);
}
public synchronized void removeDifferingChangedListener(DifferingChangedListener li) {
dcListeners.remove(li);
}
private void fireDifferingChanged(Map<EditorUser, DocDifference> diffs) {
for (DifferingChangedListener li : dcListeners) {
li.differingChanged(diffs);
}
}
public String getBaseText() {
return base.getDoc().getText();
}
public void setBaseNoFire(String xml) {
base.setDoc(new AceDoc(xml));
}
}
| true | true | public void changed() {
// Delaying a bit. Not acting on each change, only after a while.
// This is a bit so so...
synchronized (baseChangeTimer) {
if (fireScheduled) {
return;
}
baseChangeTimer.schedule(new TimerTask() {
@Override
public void run() {
synchronized (baseChangeTimer) {
saveBaseToDisk();
fireDifferingChanged(getDifferences());
fireScheduled = false;
}
}
}, 400);
fireScheduled = true;
}
}
| public void changed() {
// Delaying a bit. Not acting on each change, only after a while.
// This is a bit so so...
synchronized (baseChangeTimer) {
if (fireScheduled) {
return;
}
baseChangeTimer.schedule(new TimerTask() {
@Override
public void run() {
synchronized (baseChangeTimer) {
if (saveBaseTo!=null) {
saveBaseToDisk();
}
fireDifferingChanged(getDifferences());
fireScheduled = false;
}
}
}, 400);
fireScheduled = true;
}
}
|
diff --git a/tests-src/net/grinder/console/swingui/TestGraph.java b/tests-src/net/grinder/console/swingui/TestGraph.java
index c016b8a2..caf16b97 100755
--- a/tests-src/net/grinder/console/swingui/TestGraph.java
+++ b/tests-src/net/grinder/console/swingui/TestGraph.java
@@ -1,132 +1,132 @@
// The Grinder
// Copyright (C) 2000, 2001 Paco Gomez
// Copyright (C) 2000, 2001 Philip Aston
// 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
package net.grinder.console.swingui;
import junit.framework.TestCase;
import junit.swingui.TestRunner;
//import junit.textui.TestRunner;
import java.awt.BorderLayout;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import javax.swing.JComponent;
import javax.swing.JFrame;
import net.grinder.statistics.Statistics;
/**
* @author Philip Aston
* @version $Revision$
*/
public class TestGraph extends TestCase
{
public static void main(String[] args)
{
TestRunner.run(TestGraph.class);
}
public TestGraph(String name)
{
super(name);
}
private int m_pauseTime = 1;
private Random s_random = new Random();
private JFrame m_frame;
protected void setUp() throws Exception
{
m_frame = new JFrame("Test Graph");
}
protected void tearDown() throws Exception
{
m_frame.dispose();
}
private void createUI(JComponent component) throws Exception
{
m_frame.getContentPane().add(component, BorderLayout.CENTER);
m_frame.pack();
m_frame.setVisible(true);
}
public void testRamp() throws Exception
{
final Graph graph = new Graph(25);
createUI(graph);
graph.setMaximum(150);
for (int i=0; i<150; i++) {
graph.add(i);
pause();
}
}
public void testRandom() throws Exception
{
final Graph graph = new Graph(100);
createUI(graph);
graph.setMaximum(1);
for (int i=0; i<500; i++) {
graph.add(s_random.nextDouble());
pause();
}
}
public void testLabelledGraph() throws Exception
{
final LabelledGraph labelledGraph = new LabelledGraph("Test");
createUI(labelledGraph);
double peak = 0d;
final Statistics statistics = new Statistics();
statistics.addAbortion();
statistics.addError();
statistics.addTransaction(1);
for (int i=0; i<500; i++) {
final double random = s_random.nextDouble();
if (random > peak) {
peak = random;
}
- labelledGraph.add(random, peak, statistics);
+ labelledGraph.add(random, peak, peak, statistics);
pause();
statistics.add(statistics);
}
}
private void pause() throws Exception
{
if (m_pauseTime > 0) {
Thread.sleep(m_pauseTime);
}
}
}
| true | true | public void testLabelledGraph() throws Exception
{
final LabelledGraph labelledGraph = new LabelledGraph("Test");
createUI(labelledGraph);
double peak = 0d;
final Statistics statistics = new Statistics();
statistics.addAbortion();
statistics.addError();
statistics.addTransaction(1);
for (int i=0; i<500; i++) {
final double random = s_random.nextDouble();
if (random > peak) {
peak = random;
}
labelledGraph.add(random, peak, statistics);
pause();
statistics.add(statistics);
}
}
| public void testLabelledGraph() throws Exception
{
final LabelledGraph labelledGraph = new LabelledGraph("Test");
createUI(labelledGraph);
double peak = 0d;
final Statistics statistics = new Statistics();
statistics.addAbortion();
statistics.addError();
statistics.addTransaction(1);
for (int i=0; i<500; i++) {
final double random = s_random.nextDouble();
if (random > peak) {
peak = random;
}
labelledGraph.add(random, peak, peak, statistics);
pause();
statistics.add(statistics);
}
}
|
diff --git a/Nof1/src/uk/co/jwlawson/nof1/fragments/AdHocEntryComplete.java b/Nof1/src/uk/co/jwlawson/nof1/fragments/AdHocEntryComplete.java
index 4e7d709..4406687 100644
--- a/Nof1/src/uk/co/jwlawson/nof1/fragments/AdHocEntryComplete.java
+++ b/Nof1/src/uk/co/jwlawson/nof1/fragments/AdHocEntryComplete.java
@@ -1,151 +1,151 @@
/*******************************************************************************
* Nof1 Trials helper, making life easier for clinicians and patients in N of 1 trials.
* Copyright (C) 2012 WMG, University of Warwick
*
* 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 may obtain a copy of the GNU General Public License at
* <http://www.gnu.org/licenses/>.
*
* Contributors:
* John Lawson - initial API and implementation
******************************************************************************/
package uk.co.jwlawson.nof1.fragments;
import java.util.Calendar;
import uk.co.jwlawson.nof1.Keys;
import uk.co.jwlawson.nof1.R;
import uk.co.jwlawson.nof1.Scheduler;
import uk.co.jwlawson.nof1.activities.GraphChooser;
import uk.co.jwlawson.nof1.activities.HomeScreen;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.TaskStackBuilder;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockDialogFragment;
/**
* Dialog fragment to show when the user fills in the questionnaire without prompting.
*
* @author John Lawson
*
*/
public class AdHocEntryComplete extends SherlockDialogFragment {
public static AdHocEntryComplete newInstance() {
AdHocEntryComplete frag = new AdHocEntryComplete();
return frag;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(STYLE_NO_TITLE, 0);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.ad_hoc_complete, container, false);
TextView thanks = (TextView) view.findViewById(R.id.ad_hoc_text_thanks);
RelativeLayout layout = (RelativeLayout) thanks.getParent();
SharedPreferences userPrefs = getActivity().getSharedPreferences(Keys.DEFAULT_PREFS, Context.MODE_PRIVATE);
SharedPreferences configPrefs = getActivity().getSharedPreferences(Keys.CONFIG_NAME, Context.MODE_PRIVATE);
SharedPreferences schedPrefs = getActivity().getSharedPreferences(Keys.SCHED_NAME, Context.MODE_PRIVATE);
Resources res = getActivity().getResources();
thanks.setText(res.getText(R.string.thanks) + " " + userPrefs.getString(Keys.DEFAULT_PATIENT_NAME, ""));
TextView progress = (TextView) view.findViewById(R.id.ad_hoc_text_you_are);
progress.setText("" + res.getText(R.string.you_are_now) + schedPrefs.getInt(Keys.SCHED_CUMULATIVE_DAY, 0) + res.getText(R.string.out_of)
+ (configPrefs.getInt(Keys.CONFIG_PERIOD_LENGTH, 0) * configPrefs.getInt(Keys.CONFIG_NUMBER_PERIODS, 0) * 2));
TextView cancelText = (TextView) view.findViewById(R.id.ad_hoc_text_cancel_today);
Button btnCancel = (Button) view.findViewById(R.id.ad_hoc_btn_cancel_today);
// Get next date for scheduler to run
SharedPreferences sp = getActivity().getSharedPreferences(Keys.SCHED_NAME, Context.MODE_PRIVATE);
String alarm = sp.getString(Keys.SCHED_LAST_DATE, "");
Calendar cal = Calendar.getInstance();
String now = cal.get(Calendar.DAY_OF_MONTH) + ":" + cal.get(Calendar.MONTH) + ":" + cal.get(Calendar.YEAR);
if (alarm.equalsIgnoreCase(now)) {
// Will have an alarm today
btnCancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Run scheduler to cancel todays alarm
Intent intent = new Intent(getActivity(), Scheduler.class);
intent.putExtra(Keys.INTENT_BOOT, false);
intent.putExtra(Keys.INTENT_ALARM, true);
getActivity().startService(intent);
}
});
} else {
// Was not scheduled to enter data today, hide buttons
cancelText.setVisibility(View.GONE);
btnCancel.setVisibility(View.GONE);
layout.requestLayout();
}
- Button btnGraph = (Button) view.findViewById(R.id.complete_btn_graphs);
+ Button btnGraph = (Button) view.findViewById(R.id.ad_hoc_btn_graphs);
btnGraph.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
TaskStackBuilder builder = TaskStackBuilder.create(getActivity());
builder.addNextIntent(new Intent(getActivity(), HomeScreen.class)).addNextIntent(new Intent(getActivity(), GraphChooser.class));
builder.startActivities();
getActivity().finish();
}
});
- Button btnHome = (Button) view.findViewById(R.id.complete_btn_home);
+ Button btnHome = (Button) view.findViewById(R.id.ad_hoc_btn_home);
btnHome.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
TaskStackBuilder builder = TaskStackBuilder.create(getActivity());
builder.addNextIntent(new Intent(getActivity(), HomeScreen.class));
builder.startActivities();
getActivity().finish();
}
});
- Button btnExit = (Button) view.findViewById(R.id.complete_btn_exit);
+ Button btnExit = (Button) view.findViewById(R.id.ad_hoc_btn_exit);
btnExit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent();
i.setAction(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_HOME);
startActivity(i);
getActivity().finish();
}
});
return view;
}
}
| false | true | public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.ad_hoc_complete, container, false);
TextView thanks = (TextView) view.findViewById(R.id.ad_hoc_text_thanks);
RelativeLayout layout = (RelativeLayout) thanks.getParent();
SharedPreferences userPrefs = getActivity().getSharedPreferences(Keys.DEFAULT_PREFS, Context.MODE_PRIVATE);
SharedPreferences configPrefs = getActivity().getSharedPreferences(Keys.CONFIG_NAME, Context.MODE_PRIVATE);
SharedPreferences schedPrefs = getActivity().getSharedPreferences(Keys.SCHED_NAME, Context.MODE_PRIVATE);
Resources res = getActivity().getResources();
thanks.setText(res.getText(R.string.thanks) + " " + userPrefs.getString(Keys.DEFAULT_PATIENT_NAME, ""));
TextView progress = (TextView) view.findViewById(R.id.ad_hoc_text_you_are);
progress.setText("" + res.getText(R.string.you_are_now) + schedPrefs.getInt(Keys.SCHED_CUMULATIVE_DAY, 0) + res.getText(R.string.out_of)
+ (configPrefs.getInt(Keys.CONFIG_PERIOD_LENGTH, 0) * configPrefs.getInt(Keys.CONFIG_NUMBER_PERIODS, 0) * 2));
TextView cancelText = (TextView) view.findViewById(R.id.ad_hoc_text_cancel_today);
Button btnCancel = (Button) view.findViewById(R.id.ad_hoc_btn_cancel_today);
// Get next date for scheduler to run
SharedPreferences sp = getActivity().getSharedPreferences(Keys.SCHED_NAME, Context.MODE_PRIVATE);
String alarm = sp.getString(Keys.SCHED_LAST_DATE, "");
Calendar cal = Calendar.getInstance();
String now = cal.get(Calendar.DAY_OF_MONTH) + ":" + cal.get(Calendar.MONTH) + ":" + cal.get(Calendar.YEAR);
if (alarm.equalsIgnoreCase(now)) {
// Will have an alarm today
btnCancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Run scheduler to cancel todays alarm
Intent intent = new Intent(getActivity(), Scheduler.class);
intent.putExtra(Keys.INTENT_BOOT, false);
intent.putExtra(Keys.INTENT_ALARM, true);
getActivity().startService(intent);
}
});
} else {
// Was not scheduled to enter data today, hide buttons
cancelText.setVisibility(View.GONE);
btnCancel.setVisibility(View.GONE);
layout.requestLayout();
}
Button btnGraph = (Button) view.findViewById(R.id.complete_btn_graphs);
btnGraph.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
TaskStackBuilder builder = TaskStackBuilder.create(getActivity());
builder.addNextIntent(new Intent(getActivity(), HomeScreen.class)).addNextIntent(new Intent(getActivity(), GraphChooser.class));
builder.startActivities();
getActivity().finish();
}
});
Button btnHome = (Button) view.findViewById(R.id.complete_btn_home);
btnHome.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
TaskStackBuilder builder = TaskStackBuilder.create(getActivity());
builder.addNextIntent(new Intent(getActivity(), HomeScreen.class));
builder.startActivities();
getActivity().finish();
}
});
Button btnExit = (Button) view.findViewById(R.id.complete_btn_exit);
btnExit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent();
i.setAction(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_HOME);
startActivity(i);
getActivity().finish();
}
});
return view;
}
| public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.ad_hoc_complete, container, false);
TextView thanks = (TextView) view.findViewById(R.id.ad_hoc_text_thanks);
RelativeLayout layout = (RelativeLayout) thanks.getParent();
SharedPreferences userPrefs = getActivity().getSharedPreferences(Keys.DEFAULT_PREFS, Context.MODE_PRIVATE);
SharedPreferences configPrefs = getActivity().getSharedPreferences(Keys.CONFIG_NAME, Context.MODE_PRIVATE);
SharedPreferences schedPrefs = getActivity().getSharedPreferences(Keys.SCHED_NAME, Context.MODE_PRIVATE);
Resources res = getActivity().getResources();
thanks.setText(res.getText(R.string.thanks) + " " + userPrefs.getString(Keys.DEFAULT_PATIENT_NAME, ""));
TextView progress = (TextView) view.findViewById(R.id.ad_hoc_text_you_are);
progress.setText("" + res.getText(R.string.you_are_now) + schedPrefs.getInt(Keys.SCHED_CUMULATIVE_DAY, 0) + res.getText(R.string.out_of)
+ (configPrefs.getInt(Keys.CONFIG_PERIOD_LENGTH, 0) * configPrefs.getInt(Keys.CONFIG_NUMBER_PERIODS, 0) * 2));
TextView cancelText = (TextView) view.findViewById(R.id.ad_hoc_text_cancel_today);
Button btnCancel = (Button) view.findViewById(R.id.ad_hoc_btn_cancel_today);
// Get next date for scheduler to run
SharedPreferences sp = getActivity().getSharedPreferences(Keys.SCHED_NAME, Context.MODE_PRIVATE);
String alarm = sp.getString(Keys.SCHED_LAST_DATE, "");
Calendar cal = Calendar.getInstance();
String now = cal.get(Calendar.DAY_OF_MONTH) + ":" + cal.get(Calendar.MONTH) + ":" + cal.get(Calendar.YEAR);
if (alarm.equalsIgnoreCase(now)) {
// Will have an alarm today
btnCancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Run scheduler to cancel todays alarm
Intent intent = new Intent(getActivity(), Scheduler.class);
intent.putExtra(Keys.INTENT_BOOT, false);
intent.putExtra(Keys.INTENT_ALARM, true);
getActivity().startService(intent);
}
});
} else {
// Was not scheduled to enter data today, hide buttons
cancelText.setVisibility(View.GONE);
btnCancel.setVisibility(View.GONE);
layout.requestLayout();
}
Button btnGraph = (Button) view.findViewById(R.id.ad_hoc_btn_graphs);
btnGraph.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
TaskStackBuilder builder = TaskStackBuilder.create(getActivity());
builder.addNextIntent(new Intent(getActivity(), HomeScreen.class)).addNextIntent(new Intent(getActivity(), GraphChooser.class));
builder.startActivities();
getActivity().finish();
}
});
Button btnHome = (Button) view.findViewById(R.id.ad_hoc_btn_home);
btnHome.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
TaskStackBuilder builder = TaskStackBuilder.create(getActivity());
builder.addNextIntent(new Intent(getActivity(), HomeScreen.class));
builder.startActivities();
getActivity().finish();
}
});
Button btnExit = (Button) view.findViewById(R.id.ad_hoc_btn_exit);
btnExit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent();
i.setAction(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_HOME);
startActivity(i);
getActivity().finish();
}
});
return view;
}
|
diff --git a/src/de/cdauth/osm/basic/ChangesetContent.java b/src/de/cdauth/osm/basic/ChangesetContent.java
index 7456704..64d7c1c 100644
--- a/src/de/cdauth/osm/basic/ChangesetContent.java
+++ b/src/de/cdauth/osm/basic/ChangesetContent.java
@@ -1,408 +1,408 @@
/*
This file is part of OSM Route Manager.
OSM Route Manager 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.
OSM Route Manager 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 OSM Route Manager. If not, see <http://www.gnu.org/licenses/>.
*/
package de.cdauth.osm.basic;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class ChangesetContent extends XMLObject
{
static private Hashtable<String,ChangesetContent> sm_cache = new Hashtable<String,ChangesetContent>();
private String m_id;
public enum ChangeType { create, modify, delete };
protected ChangesetContent(String a_id, Element a_dom)
{
super(a_dom);
m_id = a_id;
}
public static ChangesetContent fetch(String a_id) throws IOException, APIError, SAXException, ParserConfigurationException
{
if(isCached(a_id))
return sm_cache.get(a_id);
ChangesetContent root = new ChangesetContent(a_id, API.fetch("/changeset/"+a_id+"/download"));
sm_cache.put(a_id, root);
return root;
}
protected static boolean isCached(String a_id)
{
return sm_cache.containsKey(a_id);
}
/**
* Returns an array of all objects that are part of one ChangeType of this changeset.
* @param a_type
* @return For created and modified objects, their new version. For deleted objects, their old version.
*/
public Object[] getMemberObjects(ChangeType a_type)
{
ArrayList<Object> ret = new ArrayList<Object>();
NodeList nodes = getDOM().getElementsByTagName(a_type.toString());
for(int i=0; i<nodes.getLength(); i++)
ret.addAll(API.makeObjects((Element) nodes.item(i), false));
return ret.toArray(new Object[0]);
}
/**
* Returns all objects that are part of this changeset.
* @return For created and modified objects, their new version. For deleted objects, their old version.
*/
public Object[] getMemberObjects()
{
ArrayList<Object> ret = new ArrayList<Object>();
ret.addAll(Arrays.asList(getMemberObjects(ChangeType.create)));
ret.addAll(Arrays.asList(getMemberObjects(ChangeType.modify)));
ret.addAll(Arrays.asList(getMemberObjects(ChangeType.delete)));
return ret.toArray(new Object[0]);
}
/**
* Fetches the previous version of all objects that were modified in this changeset.
* @return A hashtable with the new version of an object in the key and the old version in the value
* @throws IOException
* @throws SAXException
* @throws ParserConfigurationException
* @throws APIError
*/
public Hashtable<Object,Object> getPreviousVersions() throws IOException, SAXException, ParserConfigurationException, APIError
{
Object[] newVersions = getMemberObjects(ChangeType.modify);
Hashtable<Object,Object> ret = new Hashtable<Object,Object>();
for(int i=0; i<newVersions.length; i++)
{
Object last = null;
String tagName = newVersions[i].getDOM().getTagName();
try
{
if(tagName.equals("node"))
last = Node.fetch(newVersions[i].getDOM().getAttribute("id"), ""+(Long.parseLong(newVersions[i].getDOM().getAttribute("version"))-1));
else if(tagName.equals("way"))
last = Way.fetch(newVersions[i].getDOM().getAttribute("id"), ""+(Long.parseLong(newVersions[i].getDOM().getAttribute("version"))-1));
else if(tagName.equals("relation"))
last = Relation.fetch(newVersions[i].getDOM().getAttribute("id"), ""+(Long.parseLong(newVersions[i].getDOM().getAttribute("version"))-1));
}
catch(APIError e)
{
}
ret.put(newVersions[i], last);
}
return ret;
}
/**
* Checks which nodes and ways were changed on a per-node basis. If a node is moved, this
* influences all the ways that it belongs to, but they don’t necessarily appear in the
* changeset. This method gets all ways that were changed by adding, removing of moving
* their nodes. Thus, created and removed ways are also returned. Nodes that are part of the
* changeset but that weren’t moved are ignored. Moved nodes are returned as well, represented
* by an array of one node (whereas ways are repesented by an array of multiple nodes). An
* empty array indicates that the way or node did not exist before or afterwards.
* @return An array of two ArrayLists of ArrayLists of Nodes. For each index, the value in the
* first ArrayList represents the nodes of the way before the changeset was commited, the
* value in the second one represents the nodes after the commit.
* @throws IOException
* @throws SAXException
* @throws ParserConfigurationException
* @throws APIError
* @throws ParseException
*/
public Node[][][] getNodeChanges() throws IOException, SAXException, ParserConfigurationException, APIError, ParseException
{
Hashtable<Object,Object> old = getPreviousVersions();
Hashtable<String,Node> nodesRemoved = new Hashtable<String,Node>(); // All removed nodes and the old versions of all moved nodes
Hashtable<String,Node> nodesAdded = new Hashtable<String,Node>(); // All created nodes and the new versions of all moved nodes
Hashtable<String,Node> nodesChanged = new Hashtable<String,Node>(); // Only the new versions of all moved nodes
Hashtable<String,Node> nodePosition = new Hashtable<String,Node>(); // Nodes that are part of the changeset but whose position isn’t changed
for(Object obj : getMemberObjects(ChangeType.delete))
{
if(obj.getDOM().getTagName().equals("node"))
{
nodesRemoved.put(obj.getDOM().getAttribute("id"), (Node) obj);
nodePosition.put(obj.getDOM().getAttribute("id"), (Node) obj);
}
}
for(Object obj : getMemberObjects(ChangeType.create))
{
if(obj.getDOM().getTagName().equals("node"))
{
nodesAdded.put(obj.getDOM().getAttribute("id"), (Node) obj);
nodePosition.put(obj.getDOM().getAttribute("id"), (Node) obj);
}
}
for(Object obj : getMemberObjects(ChangeType.modify))
{
if(!obj.getDOM().getTagName().equals("node"))
continue;
Node newVersion = (Node)obj;
nodePosition.put(newVersion.getDOM().getAttribute("id"), newVersion);
Node oldVersion = (Node)old.get(obj);
if(oldVersion == null)
continue;
if(oldVersion.getLonLat().equals(newVersion.getLonLat()))
continue;
nodesRemoved.put(oldVersion.getDOM().getAttribute("id"), oldVersion);
nodesAdded.put(newVersion.getDOM().getAttribute("id"), newVersion);
nodesChanged.put(newVersion.getDOM().getAttribute("id"), newVersion);
}
Hashtable<Way,List<String>> containedWays = new Hashtable<Way,List<String>>();
Hashtable<String,Way> previousWays = new Hashtable<String,Way>();
for(Object obj : getMemberObjects(ChangeType.modify))
{
if(!obj.getDOM().getTagName().equals("way"))
continue;
Way way = (Way) obj;
containedWays.put(way, Arrays.asList(way.getMembers()));
previousWays.put(way.getDOM().getAttribute("id"), (Way)old.get(way));
}
// If only one node is moved in a changeset, that node might be a member of one or more
// ways and thus change these. As there is no real way to find out the parent ways
// of a node at the time of the changeset, we have to guess them.
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
Date changesetDate = dateFormat.parse(Changeset.fetch(m_id).getDOM().getAttribute("created_at"));
Hashtable<String,Way> waysChanged = new Hashtable<String,Way>();
for(Node node : nodesChanged.values())
{
String nodeID = node.getDOM().getAttribute("id");
// First guess: Ways that have been changed in the changeset
for(Map.Entry<Way,List<String>> entry : containedWays.entrySet())
{
if(entry.getValue().contains(nodeID))
{
String id = entry.getKey().getDOM().getAttribute("id");
waysChanged.put(id, previousWays.get(id));
}
}
// Second guess: Current parent nodes of the node
for(Object obj : API.get("/node/"+node.getDOM().getAttribute("id")+"/ways"))
{
if(!obj.getDOM().getTagName().equals("way"))
continue;
if(waysChanged.containsKey(obj.getDOM().getAttribute("id")))
continue;
if(containedWays.containsKey(obj))
continue;
TreeMap<Long,Way> history = Way.getHistory(obj.getDOM().getAttribute("id"));
for(Way historyEntry : history.descendingMap().values())
{
Date historyDate = dateFormat.parse(historyEntry.getDOM().getAttribute("timestamp"));
if(historyDate.compareTo(changesetDate) < 0)
{
if(Arrays.asList(historyEntry.getMembers()).contains(nodeID))
waysChanged.put(historyEntry.getDOM().getAttribute("id"), historyEntry);
break;
}
}
}
}
// Now make an array of node arrays to represent the old and the new form of the changed ways
ArrayList<ArrayList<String>> wayNodes1 = new ArrayList<ArrayList<String>>();
ArrayList<ArrayList<String>> wayNodes2 = new ArrayList<ArrayList<String>>();
HashSet<String> fetchNodes = new HashSet<String>();
for(Object obj : getMemberObjects(ChangeType.create))
{
if(!obj.getDOM().getTagName().equals("way"))
continue;
ArrayList<String> oldVersion = new ArrayList<String>();
ArrayList<String> newVersion = new ArrayList<String>();
newVersion.addAll(Arrays.asList(((Way)obj).getMembers()));
for(String id : newVersion)
{
if(!nodePosition.containsKey(id))
fetchNodes.add(id);
}
wayNodes1.add(oldVersion);
wayNodes2.add(newVersion);
}
for(Object obj : getMemberObjects(ChangeType.delete))
{
if(!obj.getDOM().getTagName().equals("way"))
continue;
ArrayList<String> oldVersion = new ArrayList<String>();
ArrayList<String> newVersion = new ArrayList<String>();
oldVersion.addAll(Arrays.asList(((Way)obj).getMembers()));
for(String id : oldVersion)
{
if(!nodePosition.containsKey(id))
fetchNodes.add(id);
}
wayNodes1.add(oldVersion);
wayNodes2.add(newVersion);
}
for(Object obj : getMemberObjects(ChangeType.modify))
{
if(!obj.getDOM().getTagName().equals("way"))
continue;
ArrayList<String> oldVersion = new ArrayList<String>();
ArrayList<String> newVersion = new ArrayList<String>();
oldVersion.addAll(Arrays.asList(((Way)old.get(obj)).getMembers()));
newVersion.addAll(Arrays.asList(((Way)obj).getMembers()));
if(oldVersion.equals(newVersion))
{
boolean changed = false;
for(String id : newVersion)
{
if(nodesChanged.containsKey(id))
{
changed = true;
break;
}
}
if(!changed)
- break;
+ continue;
}
for(String id : newVersion)
{
if(!nodePosition.containsKey(id))
fetchNodes.add(id);
}
wayNodes1.add(oldVersion);
wayNodes2.add(newVersion);
}
for(Way way : waysChanged.values())
{
ArrayList<String> members = new ArrayList<String>();
members.addAll(Arrays.asList(way.getMembers()));
for(String id : members)
{
if(!nodePosition.containsKey(id))
fetchNodes.add(id);
}
wayNodes1.add(members);
wayNodes2.add(members);
}
// Download all needed nodes in the right version
for(String id : fetchNodes)
{
TreeMap<Long,Node> history = Node.getHistory(id);
for(Node historyEntry : history.descendingMap().values())
{
Date historyDate = dateFormat.parse(historyEntry.getDOM().getAttribute("timestamp"));
if(historyDate.compareTo(changesetDate) < 0)
{
nodePosition.put(id, historyEntry);
break;
}
}
}
// Make arrays of nodes
ArrayList<ArrayList<Node>> wayPoints1 = new ArrayList<ArrayList<Node>>();
ArrayList<ArrayList<Node>> wayPoints2 = new ArrayList<ArrayList<Node>>();
for(int i=0; i<wayNodes1.size(); i++)
{
ArrayList<Node> oldVersion = new ArrayList<Node>();
ArrayList<Node> newVersion = new ArrayList<Node>();
for(String id : wayNodes1.get(i))
{
if(nodesRemoved.containsKey(id))
oldVersion.add(nodesRemoved.get(id));
else
oldVersion.add(nodePosition.get(id));
}
for(String id : wayNodes2.get(i))
{
if(nodesAdded.containsKey(id))
newVersion.add(nodesAdded.get(id));
else
newVersion.add(nodePosition.get(id));
}
wayPoints1.add(oldVersion);
wayPoints2.add(newVersion);
}
// Create one-node entries for node changes
ArrayList<String> changedNodes = new ArrayList<String>();
changedNodes.addAll(nodesAdded.keySet());
changedNodes.addAll(nodesRemoved.keySet());
for(String id : changedNodes)
{
ArrayList<Node> oldVersion = new ArrayList<Node>();
ArrayList<Node> newVersion = new ArrayList<Node>();
if(nodesRemoved.containsKey(id))
oldVersion.add(nodesRemoved.get(id));
if(nodesAdded.containsKey(id))
newVersion.add(nodesAdded.get(id));
wayPoints1.add(oldVersion);
wayPoints2.add(newVersion);
}
Node[][][] ret = new Node[2][wayPoints1.size()][];
for(int i=0; i<wayPoints1.size(); i++)
{
ret[0][i] = wayPoints1.get(i).toArray(new Node[0]);
ret[1][i] = wayPoints2.get(i).toArray(new Node[0]);
}
return ret;
}
}
| true | true | public Node[][][] getNodeChanges() throws IOException, SAXException, ParserConfigurationException, APIError, ParseException
{
Hashtable<Object,Object> old = getPreviousVersions();
Hashtable<String,Node> nodesRemoved = new Hashtable<String,Node>(); // All removed nodes and the old versions of all moved nodes
Hashtable<String,Node> nodesAdded = new Hashtable<String,Node>(); // All created nodes and the new versions of all moved nodes
Hashtable<String,Node> nodesChanged = new Hashtable<String,Node>(); // Only the new versions of all moved nodes
Hashtable<String,Node> nodePosition = new Hashtable<String,Node>(); // Nodes that are part of the changeset but whose position isn’t changed
for(Object obj : getMemberObjects(ChangeType.delete))
{
if(obj.getDOM().getTagName().equals("node"))
{
nodesRemoved.put(obj.getDOM().getAttribute("id"), (Node) obj);
nodePosition.put(obj.getDOM().getAttribute("id"), (Node) obj);
}
}
for(Object obj : getMemberObjects(ChangeType.create))
{
if(obj.getDOM().getTagName().equals("node"))
{
nodesAdded.put(obj.getDOM().getAttribute("id"), (Node) obj);
nodePosition.put(obj.getDOM().getAttribute("id"), (Node) obj);
}
}
for(Object obj : getMemberObjects(ChangeType.modify))
{
if(!obj.getDOM().getTagName().equals("node"))
continue;
Node newVersion = (Node)obj;
nodePosition.put(newVersion.getDOM().getAttribute("id"), newVersion);
Node oldVersion = (Node)old.get(obj);
if(oldVersion == null)
continue;
if(oldVersion.getLonLat().equals(newVersion.getLonLat()))
continue;
nodesRemoved.put(oldVersion.getDOM().getAttribute("id"), oldVersion);
nodesAdded.put(newVersion.getDOM().getAttribute("id"), newVersion);
nodesChanged.put(newVersion.getDOM().getAttribute("id"), newVersion);
}
Hashtable<Way,List<String>> containedWays = new Hashtable<Way,List<String>>();
Hashtable<String,Way> previousWays = new Hashtable<String,Way>();
for(Object obj : getMemberObjects(ChangeType.modify))
{
if(!obj.getDOM().getTagName().equals("way"))
continue;
Way way = (Way) obj;
containedWays.put(way, Arrays.asList(way.getMembers()));
previousWays.put(way.getDOM().getAttribute("id"), (Way)old.get(way));
}
// If only one node is moved in a changeset, that node might be a member of one or more
// ways and thus change these. As there is no real way to find out the parent ways
// of a node at the time of the changeset, we have to guess them.
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
Date changesetDate = dateFormat.parse(Changeset.fetch(m_id).getDOM().getAttribute("created_at"));
Hashtable<String,Way> waysChanged = new Hashtable<String,Way>();
for(Node node : nodesChanged.values())
{
String nodeID = node.getDOM().getAttribute("id");
// First guess: Ways that have been changed in the changeset
for(Map.Entry<Way,List<String>> entry : containedWays.entrySet())
{
if(entry.getValue().contains(nodeID))
{
String id = entry.getKey().getDOM().getAttribute("id");
waysChanged.put(id, previousWays.get(id));
}
}
// Second guess: Current parent nodes of the node
for(Object obj : API.get("/node/"+node.getDOM().getAttribute("id")+"/ways"))
{
if(!obj.getDOM().getTagName().equals("way"))
continue;
if(waysChanged.containsKey(obj.getDOM().getAttribute("id")))
continue;
if(containedWays.containsKey(obj))
continue;
TreeMap<Long,Way> history = Way.getHistory(obj.getDOM().getAttribute("id"));
for(Way historyEntry : history.descendingMap().values())
{
Date historyDate = dateFormat.parse(historyEntry.getDOM().getAttribute("timestamp"));
if(historyDate.compareTo(changesetDate) < 0)
{
if(Arrays.asList(historyEntry.getMembers()).contains(nodeID))
waysChanged.put(historyEntry.getDOM().getAttribute("id"), historyEntry);
break;
}
}
}
}
// Now make an array of node arrays to represent the old and the new form of the changed ways
ArrayList<ArrayList<String>> wayNodes1 = new ArrayList<ArrayList<String>>();
ArrayList<ArrayList<String>> wayNodes2 = new ArrayList<ArrayList<String>>();
HashSet<String> fetchNodes = new HashSet<String>();
for(Object obj : getMemberObjects(ChangeType.create))
{
if(!obj.getDOM().getTagName().equals("way"))
continue;
ArrayList<String> oldVersion = new ArrayList<String>();
ArrayList<String> newVersion = new ArrayList<String>();
newVersion.addAll(Arrays.asList(((Way)obj).getMembers()));
for(String id : newVersion)
{
if(!nodePosition.containsKey(id))
fetchNodes.add(id);
}
wayNodes1.add(oldVersion);
wayNodes2.add(newVersion);
}
for(Object obj : getMemberObjects(ChangeType.delete))
{
if(!obj.getDOM().getTagName().equals("way"))
continue;
ArrayList<String> oldVersion = new ArrayList<String>();
ArrayList<String> newVersion = new ArrayList<String>();
oldVersion.addAll(Arrays.asList(((Way)obj).getMembers()));
for(String id : oldVersion)
{
if(!nodePosition.containsKey(id))
fetchNodes.add(id);
}
wayNodes1.add(oldVersion);
wayNodes2.add(newVersion);
}
for(Object obj : getMemberObjects(ChangeType.modify))
{
if(!obj.getDOM().getTagName().equals("way"))
continue;
ArrayList<String> oldVersion = new ArrayList<String>();
ArrayList<String> newVersion = new ArrayList<String>();
oldVersion.addAll(Arrays.asList(((Way)old.get(obj)).getMembers()));
newVersion.addAll(Arrays.asList(((Way)obj).getMembers()));
if(oldVersion.equals(newVersion))
{
boolean changed = false;
for(String id : newVersion)
{
if(nodesChanged.containsKey(id))
{
changed = true;
break;
}
}
if(!changed)
break;
}
for(String id : newVersion)
{
if(!nodePosition.containsKey(id))
fetchNodes.add(id);
}
wayNodes1.add(oldVersion);
wayNodes2.add(newVersion);
}
for(Way way : waysChanged.values())
{
ArrayList<String> members = new ArrayList<String>();
members.addAll(Arrays.asList(way.getMembers()));
for(String id : members)
{
if(!nodePosition.containsKey(id))
fetchNodes.add(id);
}
wayNodes1.add(members);
wayNodes2.add(members);
}
// Download all needed nodes in the right version
for(String id : fetchNodes)
{
TreeMap<Long,Node> history = Node.getHistory(id);
for(Node historyEntry : history.descendingMap().values())
{
Date historyDate = dateFormat.parse(historyEntry.getDOM().getAttribute("timestamp"));
if(historyDate.compareTo(changesetDate) < 0)
{
nodePosition.put(id, historyEntry);
break;
}
}
}
// Make arrays of nodes
ArrayList<ArrayList<Node>> wayPoints1 = new ArrayList<ArrayList<Node>>();
ArrayList<ArrayList<Node>> wayPoints2 = new ArrayList<ArrayList<Node>>();
for(int i=0; i<wayNodes1.size(); i++)
{
ArrayList<Node> oldVersion = new ArrayList<Node>();
ArrayList<Node> newVersion = new ArrayList<Node>();
for(String id : wayNodes1.get(i))
{
if(nodesRemoved.containsKey(id))
oldVersion.add(nodesRemoved.get(id));
else
oldVersion.add(nodePosition.get(id));
}
for(String id : wayNodes2.get(i))
{
if(nodesAdded.containsKey(id))
newVersion.add(nodesAdded.get(id));
else
newVersion.add(nodePosition.get(id));
}
wayPoints1.add(oldVersion);
wayPoints2.add(newVersion);
}
// Create one-node entries for node changes
ArrayList<String> changedNodes = new ArrayList<String>();
changedNodes.addAll(nodesAdded.keySet());
changedNodes.addAll(nodesRemoved.keySet());
for(String id : changedNodes)
{
ArrayList<Node> oldVersion = new ArrayList<Node>();
ArrayList<Node> newVersion = new ArrayList<Node>();
if(nodesRemoved.containsKey(id))
oldVersion.add(nodesRemoved.get(id));
if(nodesAdded.containsKey(id))
newVersion.add(nodesAdded.get(id));
wayPoints1.add(oldVersion);
wayPoints2.add(newVersion);
}
Node[][][] ret = new Node[2][wayPoints1.size()][];
for(int i=0; i<wayPoints1.size(); i++)
{
ret[0][i] = wayPoints1.get(i).toArray(new Node[0]);
ret[1][i] = wayPoints2.get(i).toArray(new Node[0]);
}
return ret;
}
| public Node[][][] getNodeChanges() throws IOException, SAXException, ParserConfigurationException, APIError, ParseException
{
Hashtable<Object,Object> old = getPreviousVersions();
Hashtable<String,Node> nodesRemoved = new Hashtable<String,Node>(); // All removed nodes and the old versions of all moved nodes
Hashtable<String,Node> nodesAdded = new Hashtable<String,Node>(); // All created nodes and the new versions of all moved nodes
Hashtable<String,Node> nodesChanged = new Hashtable<String,Node>(); // Only the new versions of all moved nodes
Hashtable<String,Node> nodePosition = new Hashtable<String,Node>(); // Nodes that are part of the changeset but whose position isn’t changed
for(Object obj : getMemberObjects(ChangeType.delete))
{
if(obj.getDOM().getTagName().equals("node"))
{
nodesRemoved.put(obj.getDOM().getAttribute("id"), (Node) obj);
nodePosition.put(obj.getDOM().getAttribute("id"), (Node) obj);
}
}
for(Object obj : getMemberObjects(ChangeType.create))
{
if(obj.getDOM().getTagName().equals("node"))
{
nodesAdded.put(obj.getDOM().getAttribute("id"), (Node) obj);
nodePosition.put(obj.getDOM().getAttribute("id"), (Node) obj);
}
}
for(Object obj : getMemberObjects(ChangeType.modify))
{
if(!obj.getDOM().getTagName().equals("node"))
continue;
Node newVersion = (Node)obj;
nodePosition.put(newVersion.getDOM().getAttribute("id"), newVersion);
Node oldVersion = (Node)old.get(obj);
if(oldVersion == null)
continue;
if(oldVersion.getLonLat().equals(newVersion.getLonLat()))
continue;
nodesRemoved.put(oldVersion.getDOM().getAttribute("id"), oldVersion);
nodesAdded.put(newVersion.getDOM().getAttribute("id"), newVersion);
nodesChanged.put(newVersion.getDOM().getAttribute("id"), newVersion);
}
Hashtable<Way,List<String>> containedWays = new Hashtable<Way,List<String>>();
Hashtable<String,Way> previousWays = new Hashtable<String,Way>();
for(Object obj : getMemberObjects(ChangeType.modify))
{
if(!obj.getDOM().getTagName().equals("way"))
continue;
Way way = (Way) obj;
containedWays.put(way, Arrays.asList(way.getMembers()));
previousWays.put(way.getDOM().getAttribute("id"), (Way)old.get(way));
}
// If only one node is moved in a changeset, that node might be a member of one or more
// ways and thus change these. As there is no real way to find out the parent ways
// of a node at the time of the changeset, we have to guess them.
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
Date changesetDate = dateFormat.parse(Changeset.fetch(m_id).getDOM().getAttribute("created_at"));
Hashtable<String,Way> waysChanged = new Hashtable<String,Way>();
for(Node node : nodesChanged.values())
{
String nodeID = node.getDOM().getAttribute("id");
// First guess: Ways that have been changed in the changeset
for(Map.Entry<Way,List<String>> entry : containedWays.entrySet())
{
if(entry.getValue().contains(nodeID))
{
String id = entry.getKey().getDOM().getAttribute("id");
waysChanged.put(id, previousWays.get(id));
}
}
// Second guess: Current parent nodes of the node
for(Object obj : API.get("/node/"+node.getDOM().getAttribute("id")+"/ways"))
{
if(!obj.getDOM().getTagName().equals("way"))
continue;
if(waysChanged.containsKey(obj.getDOM().getAttribute("id")))
continue;
if(containedWays.containsKey(obj))
continue;
TreeMap<Long,Way> history = Way.getHistory(obj.getDOM().getAttribute("id"));
for(Way historyEntry : history.descendingMap().values())
{
Date historyDate = dateFormat.parse(historyEntry.getDOM().getAttribute("timestamp"));
if(historyDate.compareTo(changesetDate) < 0)
{
if(Arrays.asList(historyEntry.getMembers()).contains(nodeID))
waysChanged.put(historyEntry.getDOM().getAttribute("id"), historyEntry);
break;
}
}
}
}
// Now make an array of node arrays to represent the old and the new form of the changed ways
ArrayList<ArrayList<String>> wayNodes1 = new ArrayList<ArrayList<String>>();
ArrayList<ArrayList<String>> wayNodes2 = new ArrayList<ArrayList<String>>();
HashSet<String> fetchNodes = new HashSet<String>();
for(Object obj : getMemberObjects(ChangeType.create))
{
if(!obj.getDOM().getTagName().equals("way"))
continue;
ArrayList<String> oldVersion = new ArrayList<String>();
ArrayList<String> newVersion = new ArrayList<String>();
newVersion.addAll(Arrays.asList(((Way)obj).getMembers()));
for(String id : newVersion)
{
if(!nodePosition.containsKey(id))
fetchNodes.add(id);
}
wayNodes1.add(oldVersion);
wayNodes2.add(newVersion);
}
for(Object obj : getMemberObjects(ChangeType.delete))
{
if(!obj.getDOM().getTagName().equals("way"))
continue;
ArrayList<String> oldVersion = new ArrayList<String>();
ArrayList<String> newVersion = new ArrayList<String>();
oldVersion.addAll(Arrays.asList(((Way)obj).getMembers()));
for(String id : oldVersion)
{
if(!nodePosition.containsKey(id))
fetchNodes.add(id);
}
wayNodes1.add(oldVersion);
wayNodes2.add(newVersion);
}
for(Object obj : getMemberObjects(ChangeType.modify))
{
if(!obj.getDOM().getTagName().equals("way"))
continue;
ArrayList<String> oldVersion = new ArrayList<String>();
ArrayList<String> newVersion = new ArrayList<String>();
oldVersion.addAll(Arrays.asList(((Way)old.get(obj)).getMembers()));
newVersion.addAll(Arrays.asList(((Way)obj).getMembers()));
if(oldVersion.equals(newVersion))
{
boolean changed = false;
for(String id : newVersion)
{
if(nodesChanged.containsKey(id))
{
changed = true;
break;
}
}
if(!changed)
continue;
}
for(String id : newVersion)
{
if(!nodePosition.containsKey(id))
fetchNodes.add(id);
}
wayNodes1.add(oldVersion);
wayNodes2.add(newVersion);
}
for(Way way : waysChanged.values())
{
ArrayList<String> members = new ArrayList<String>();
members.addAll(Arrays.asList(way.getMembers()));
for(String id : members)
{
if(!nodePosition.containsKey(id))
fetchNodes.add(id);
}
wayNodes1.add(members);
wayNodes2.add(members);
}
// Download all needed nodes in the right version
for(String id : fetchNodes)
{
TreeMap<Long,Node> history = Node.getHistory(id);
for(Node historyEntry : history.descendingMap().values())
{
Date historyDate = dateFormat.parse(historyEntry.getDOM().getAttribute("timestamp"));
if(historyDate.compareTo(changesetDate) < 0)
{
nodePosition.put(id, historyEntry);
break;
}
}
}
// Make arrays of nodes
ArrayList<ArrayList<Node>> wayPoints1 = new ArrayList<ArrayList<Node>>();
ArrayList<ArrayList<Node>> wayPoints2 = new ArrayList<ArrayList<Node>>();
for(int i=0; i<wayNodes1.size(); i++)
{
ArrayList<Node> oldVersion = new ArrayList<Node>();
ArrayList<Node> newVersion = new ArrayList<Node>();
for(String id : wayNodes1.get(i))
{
if(nodesRemoved.containsKey(id))
oldVersion.add(nodesRemoved.get(id));
else
oldVersion.add(nodePosition.get(id));
}
for(String id : wayNodes2.get(i))
{
if(nodesAdded.containsKey(id))
newVersion.add(nodesAdded.get(id));
else
newVersion.add(nodePosition.get(id));
}
wayPoints1.add(oldVersion);
wayPoints2.add(newVersion);
}
// Create one-node entries for node changes
ArrayList<String> changedNodes = new ArrayList<String>();
changedNodes.addAll(nodesAdded.keySet());
changedNodes.addAll(nodesRemoved.keySet());
for(String id : changedNodes)
{
ArrayList<Node> oldVersion = new ArrayList<Node>();
ArrayList<Node> newVersion = new ArrayList<Node>();
if(nodesRemoved.containsKey(id))
oldVersion.add(nodesRemoved.get(id));
if(nodesAdded.containsKey(id))
newVersion.add(nodesAdded.get(id));
wayPoints1.add(oldVersion);
wayPoints2.add(newVersion);
}
Node[][][] ret = new Node[2][wayPoints1.size()][];
for(int i=0; i<wayPoints1.size(); i++)
{
ret[0][i] = wayPoints1.get(i).toArray(new Node[0]);
ret[1][i] = wayPoints2.get(i).toArray(new Node[0]);
}
return ret;
}
|
diff --git a/core/impl/main/java/org/directwebremoting/convert/JDOMConverter.java b/core/impl/main/java/org/directwebremoting/convert/JDOMConverter.java
index 414d7862..baf5fd9c 100644
--- a/core/impl/main/java/org/directwebremoting/convert/JDOMConverter.java
+++ b/core/impl/main/java/org/directwebremoting/convert/JDOMConverter.java
@@ -1,129 +1,129 @@
/*
* Copyright 2005 Joe Walker
*
* 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.directwebremoting.convert;
import java.io.StringReader;
import java.io.StringWriter;
import org.directwebremoting.ConversionException;
import org.directwebremoting.extend.AbstractConverter;
import org.directwebremoting.extend.EnginePrivate;
import org.directwebremoting.extend.InboundVariable;
import org.directwebremoting.extend.NonNestedOutboundVariable;
import org.directwebremoting.extend.OutboundContext;
import org.directwebremoting.extend.OutboundVariable;
import org.directwebremoting.util.LocalUtil;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
/**
* An implementation of Converter for DOM objects.
* @author Joe Walker [joe at getahead dot ltd dot uk]
*/
public class JDOMConverter extends AbstractConverter
{
/* (non-Javadoc)
* @see org.directwebremoting.Converter#convertInbound(java.lang.Class, org.directwebremoting.InboundVariable, org.directwebremoting.InboundContext)
*/
public Object convertInbound(Class<?> paramType, InboundVariable data) throws ConversionException
{
if (data.isNull())
{
return null;
}
String value = LocalUtil.urlDecode(data.getValue());
try
{
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(new StringReader(value));
if (paramType == Document.class)
{
return doc;
}
else if (paramType == Element.class)
{
return doc.getRootElement();
}
throw new ConversionException(paramType);
}
catch (ConversionException ex)
{
throw ex;
}
catch (Exception ex)
{
throw new ConversionException(paramType, ex);
}
}
/* (non-Javadoc)
* @see org.directwebremoting.Converter#convertOutbound(java.lang.Object, org.directwebremoting.OutboundContext)
*/
public OutboundVariable convertOutbound(Object data, OutboundContext outctx) throws ConversionException
{
try
{
- Format outformat = Format.getCompactFormat();
+ Format outformat = Format.getRawFormat();
outformat.setEncoding("UTF-8");
// Setup the destination
String script;
// Using XSLT to convert to a stream. Setup the source
if (data instanceof Document)
{
StringWriter xml = new StringWriter();
XMLOutputter writer = new XMLOutputter(outformat);
writer.output((Document) data, xml);
xml.flush();
script = EnginePrivate.xmlStringToJavascriptDomDocument(xml.toString());
}
else if (data instanceof Element)
{
StringWriter xml = new StringWriter();
XMLOutputter writer = new XMLOutputter(outformat);
writer.output((Element) data, xml);
xml.flush();
script = EnginePrivate.xmlStringToJavascriptDomElement(xml.toString());
}
else
{
throw new ConversionException(data.getClass());
}
OutboundVariable ov = new NonNestedOutboundVariable(script);
outctx.put(data, ov);
return ov;
}
catch (ConversionException ex)
{
throw ex;
}
catch (Exception ex)
{
throw new ConversionException(data.getClass(), ex);
}
}
}
| true | true | public OutboundVariable convertOutbound(Object data, OutboundContext outctx) throws ConversionException
{
try
{
Format outformat = Format.getCompactFormat();
outformat.setEncoding("UTF-8");
// Setup the destination
String script;
// Using XSLT to convert to a stream. Setup the source
if (data instanceof Document)
{
StringWriter xml = new StringWriter();
XMLOutputter writer = new XMLOutputter(outformat);
writer.output((Document) data, xml);
xml.flush();
script = EnginePrivate.xmlStringToJavascriptDomDocument(xml.toString());
}
else if (data instanceof Element)
{
StringWriter xml = new StringWriter();
XMLOutputter writer = new XMLOutputter(outformat);
writer.output((Element) data, xml);
xml.flush();
script = EnginePrivate.xmlStringToJavascriptDomElement(xml.toString());
}
else
{
throw new ConversionException(data.getClass());
}
OutboundVariable ov = new NonNestedOutboundVariable(script);
outctx.put(data, ov);
return ov;
}
catch (ConversionException ex)
{
throw ex;
}
catch (Exception ex)
{
throw new ConversionException(data.getClass(), ex);
}
}
| public OutboundVariable convertOutbound(Object data, OutboundContext outctx) throws ConversionException
{
try
{
Format outformat = Format.getRawFormat();
outformat.setEncoding("UTF-8");
// Setup the destination
String script;
// Using XSLT to convert to a stream. Setup the source
if (data instanceof Document)
{
StringWriter xml = new StringWriter();
XMLOutputter writer = new XMLOutputter(outformat);
writer.output((Document) data, xml);
xml.flush();
script = EnginePrivate.xmlStringToJavascriptDomDocument(xml.toString());
}
else if (data instanceof Element)
{
StringWriter xml = new StringWriter();
XMLOutputter writer = new XMLOutputter(outformat);
writer.output((Element) data, xml);
xml.flush();
script = EnginePrivate.xmlStringToJavascriptDomElement(xml.toString());
}
else
{
throw new ConversionException(data.getClass());
}
OutboundVariable ov = new NonNestedOutboundVariable(script);
outctx.put(data, ov);
return ov;
}
catch (ConversionException ex)
{
throw ex;
}
catch (Exception ex)
{
throw new ConversionException(data.getClass(), ex);
}
}
|
diff --git a/RiverSim/src/riversim/RiverSim.java b/RiverSim/src/riversim/RiverSim.java
index 7207044..110bc84 100644
--- a/RiverSim/src/riversim/RiverSim.java
+++ b/RiverSim/src/riversim/RiverSim.java
@@ -1,94 +1,89 @@
package riversim;
import java.util.ArrayList;
import riversim.vehicles.Boat;
import riversim.vehicles.WaterVehicle;
/**
*
* @author gavin
*/
public class RiverSim {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
/*
* Kludge Test
*/
/*
Boat b = new Boat();
Boat c = new Boat();
System.out.println("b = = c = " + (b.equals(c)));
if(true) {
return;
}
*/
/*
* End Kludge
*/
River r = new River(18, 18);
ArrayList<WaterVehicle[]> pastStates = new ArrayList<WaterVehicle[]>();
WaterVehicle[] state;
int loopStart = 0;
int loopEnd = 0;
boolean equal = false;
while (!equal) {
for (int i = 0; i < pastStates.size(); i++) {
boolean currentEqual = true;
for (int j = 0; j < r.getStops().length; j++) {
if (pastStates.get(i)[j] == null && r.getStops()[j] != null) {
/*
* If the current state is occupied, and the past state is not.
*/
currentEqual = false;
break;
}
if (!pastStates.get(i)[j].equals(r.getStops()[j])) {
/*
* If only the past state is occupied, or both occupied by an different water vehicle
*/
//System.out.println((i) + " is unequal at stop " + (j + 1));
//System.out.print(((pastStates.get(i)[j] instanceof Boat) ? ("B ") : ("R ")) + pastStates.get(i)[j].getNightsRested());
- if (r.getStops()[j] == null) {
- System.out.println(":: ");
- } else {
- System.out.println("::" + ((r.getStops()[j] instanceof Boat) ? ("B ") : ("R ")) + r.getStops()[j].getNightsRested());
- }
currentEqual = false;
break;
}
}
if (currentEqual) {
//System.out.println("Equal");
loopStart = i;
loopEnd = pastStates.size();
equal = true;
break;
}
}
pastStates.add(r.getStops());
if (!equal) {
r.dayCycle();
}
r.printRiver();
}
System.out.println("First loop: ");
state = pastStates.get(loopStart);
for (int i = 0; i < state.length; i++) {
if (state[i] == null) {
System.out.println((i + 1) + ":");
} else {
System.out.println((i + 1) + ":\t" + ((state[i] instanceof Boat) ? ("B\t") : ("R\t")) + state[i].getNightsRested());
}
}
System.out.println("Second loop: ");
r.printRiver();
System.out.println("Loop Time is:" + (loopEnd - loopStart));
System.out.println("PastStates len: " + pastStates.size());
}
}
| true | true | public static void main(String[] args) {
/*
* Kludge Test
*/
/*
Boat b = new Boat();
Boat c = new Boat();
System.out.println("b = = c = " + (b.equals(c)));
if(true) {
return;
}
*/
/*
* End Kludge
*/
River r = new River(18, 18);
ArrayList<WaterVehicle[]> pastStates = new ArrayList<WaterVehicle[]>();
WaterVehicle[] state;
int loopStart = 0;
int loopEnd = 0;
boolean equal = false;
while (!equal) {
for (int i = 0; i < pastStates.size(); i++) {
boolean currentEqual = true;
for (int j = 0; j < r.getStops().length; j++) {
if (pastStates.get(i)[j] == null && r.getStops()[j] != null) {
/*
* If the current state is occupied, and the past state is not.
*/
currentEqual = false;
break;
}
if (!pastStates.get(i)[j].equals(r.getStops()[j])) {
/*
* If only the past state is occupied, or both occupied by an different water vehicle
*/
//System.out.println((i) + " is unequal at stop " + (j + 1));
//System.out.print(((pastStates.get(i)[j] instanceof Boat) ? ("B ") : ("R ")) + pastStates.get(i)[j].getNightsRested());
if (r.getStops()[j] == null) {
System.out.println(":: ");
} else {
System.out.println("::" + ((r.getStops()[j] instanceof Boat) ? ("B ") : ("R ")) + r.getStops()[j].getNightsRested());
}
currentEqual = false;
break;
}
}
if (currentEqual) {
//System.out.println("Equal");
loopStart = i;
loopEnd = pastStates.size();
equal = true;
break;
}
}
pastStates.add(r.getStops());
if (!equal) {
r.dayCycle();
}
r.printRiver();
}
System.out.println("First loop: ");
state = pastStates.get(loopStart);
for (int i = 0; i < state.length; i++) {
if (state[i] == null) {
System.out.println((i + 1) + ":");
} else {
System.out.println((i + 1) + ":\t" + ((state[i] instanceof Boat) ? ("B\t") : ("R\t")) + state[i].getNightsRested());
}
}
System.out.println("Second loop: ");
r.printRiver();
System.out.println("Loop Time is:" + (loopEnd - loopStart));
System.out.println("PastStates len: " + pastStates.size());
}
| public static void main(String[] args) {
/*
* Kludge Test
*/
/*
Boat b = new Boat();
Boat c = new Boat();
System.out.println("b = = c = " + (b.equals(c)));
if(true) {
return;
}
*/
/*
* End Kludge
*/
River r = new River(18, 18);
ArrayList<WaterVehicle[]> pastStates = new ArrayList<WaterVehicle[]>();
WaterVehicle[] state;
int loopStart = 0;
int loopEnd = 0;
boolean equal = false;
while (!equal) {
for (int i = 0; i < pastStates.size(); i++) {
boolean currentEqual = true;
for (int j = 0; j < r.getStops().length; j++) {
if (pastStates.get(i)[j] == null && r.getStops()[j] != null) {
/*
* If the current state is occupied, and the past state is not.
*/
currentEqual = false;
break;
}
if (!pastStates.get(i)[j].equals(r.getStops()[j])) {
/*
* If only the past state is occupied, or both occupied by an different water vehicle
*/
//System.out.println((i) + " is unequal at stop " + (j + 1));
//System.out.print(((pastStates.get(i)[j] instanceof Boat) ? ("B ") : ("R ")) + pastStates.get(i)[j].getNightsRested());
currentEqual = false;
break;
}
}
if (currentEqual) {
//System.out.println("Equal");
loopStart = i;
loopEnd = pastStates.size();
equal = true;
break;
}
}
pastStates.add(r.getStops());
if (!equal) {
r.dayCycle();
}
r.printRiver();
}
System.out.println("First loop: ");
state = pastStates.get(loopStart);
for (int i = 0; i < state.length; i++) {
if (state[i] == null) {
System.out.println((i + 1) + ":");
} else {
System.out.println((i + 1) + ":\t" + ((state[i] instanceof Boat) ? ("B\t") : ("R\t")) + state[i].getNightsRested());
}
}
System.out.println("Second loop: ");
r.printRiver();
System.out.println("Loop Time is:" + (loopEnd - loopStart));
System.out.println("PastStates len: " + pastStates.size());
}
|
diff --git a/src/main/org/codehaus/groovy/tools/javac/JavaStubGenerator.java b/src/main/org/codehaus/groovy/tools/javac/JavaStubGenerator.java
index ede1a7154..7a24ad70b 100644
--- a/src/main/org/codehaus/groovy/tools/javac/JavaStubGenerator.java
+++ b/src/main/org/codehaus/groovy/tools/javac/JavaStubGenerator.java
@@ -1,588 +1,588 @@
/*
* Copyright 2003-2007 the original author or authors.
*
* 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.codehaus.groovy.tools.javac;
import org.codehaus.groovy.ast.*;
import org.codehaus.groovy.ast.expr.ArgumentListExpression;
import org.codehaus.groovy.ast.expr.ConstantExpression;
import org.codehaus.groovy.ast.expr.ConstructorCallExpression;
import org.codehaus.groovy.ast.expr.Expression;
import org.codehaus.groovy.ast.expr.VariableExpression;
import org.codehaus.groovy.ast.stmt.BlockStatement;
import org.codehaus.groovy.ast.stmt.ExpressionStatement;
import org.codehaus.groovy.ast.stmt.Statement;
import org.codehaus.groovy.classgen.Verifier;
import org.codehaus.groovy.control.ResolveVisitor;
import org.codehaus.groovy.tools.Utilities;
import org.objectweb.asm.Opcodes;
import java.io.*;
import java.util.*;
public class JavaStubGenerator
{
private boolean java5 = false;
private boolean requireSuperResolved = false;
private File outputPath;
private List toCompile = new ArrayList();
private ArrayList propertyMethods = new ArrayList();
public JavaStubGenerator(final File outputPath, final boolean requireSuperResolved, final boolean java5) {
this.outputPath = outputPath;
this.requireSuperResolved = requireSuperResolved;
this.java5 = java5;
outputPath.mkdirs();
}
public JavaStubGenerator(final File outputPath) {
this(outputPath, false, false);
}
private void mkdirs(File parent, String relativeFile) {
int index = relativeFile.lastIndexOf('/');
if (index==-1) return;
File dir = new File(parent,relativeFile.substring(0,index));
dir.mkdirs();
}
public void generateClass(ClassNode classNode) throws FileNotFoundException {
// Only attempt to render our self if our super-class is resolved, else wait for it
if (requireSuperResolved && !classNode.getSuperClass().isResolved()) {
return;
}
// don't generate stubs for private classes, as they are only visible in the same file
if ((classNode.getModifiers() & Opcodes.ACC_PRIVATE) != 0) return;
String fileName = classNode.getName().replace('.', '/');
mkdirs(outputPath,fileName);
toCompile.add(fileName);
File file = new File(outputPath, fileName + ".java");
FileOutputStream fos = new FileOutputStream(file);
PrintWriter out = new PrintWriter(fos);
Verifier verifier = new Verifier() {
public void addCovariantMethods(ClassNode cn) {}
protected void addTimeStamp(ClassNode node) {}
protected void addInitialization(ClassNode node) {}
protected void addPropertyMethod(MethodNode method) {
- propertyMethods.add(method);
+ propertyMethods.add(method);
}
protected void addReturnIfNeeded(MethodNode node) {}
};
verifier.visitClass(classNode);
try {
String packageName = classNode.getPackageName();
if (packageName != null) {
out.println("package " + packageName + ";\n");
}
genImports(classNode, out);
boolean isInterface = classNode.isInterface();
boolean isEnum = (classNode.getModifiers() & Opcodes.ACC_ENUM) !=0;
printModifiers(out, classNode.getModifiers()
& ~(isInterface ? Opcodes.ACC_ABSTRACT : 0));
if (isInterface) {
out.print ("interface ");
} else if (isEnum) {
out.print ("enum ");
} else {
out.print ("class ");
}
out.println(classNode.getNameWithoutPackage());
writeGenericsBounds(out, classNode, true);
ClassNode superClass = classNode.getUnresolvedSuperClass(false);
if (!isInterface && !isEnum) {
out.print(" extends ");
printType(superClass,out);
}
ClassNode[] interfaces = classNode.getInterfaces();
if (interfaces != null && interfaces.length > 0) {
if (isInterface) {
out.println(" extends");
} else {
out.println(" implements");
}
for (int i = 0; i < interfaces.length - 1; ++i) {
out.print(" ");
printType(interfaces[i], out);
out.print(",");
}
out.print(" ");
printType(interfaces[interfaces.length - 1],out);
}
out.println(" {");
genFields(classNode, out, isEnum);
genMethods(classNode, out, isEnum);
out.println("}");
} finally {
- propertyMethods.clear();
+ propertyMethods.clear();
try {
out.close();
} catch (Exception e) {
// ignore
}
try {
fos.close();
} catch (IOException e) {
// ignore
}
}
}
private void genMethods(ClassNode classNode, PrintWriter out, boolean isEnum) {
if (!isEnum) getConstructors(classNode, out);
List methods = (List) propertyMethods.clone();
methods.addAll(classNode.getMethods());
if (methods != null)
for (Iterator it = methods.iterator(); it.hasNext();) {
MethodNode methodNode = (MethodNode) it.next();
if(isEnum && methodNode.isSynthetic()) {
// skip values() method and valueOf(String)
String name = methodNode.getName();
Parameter[] params = methodNode.getParameters();
if (name.equals("values") && params.length==0) continue;
if (name.equals("valueOf") &&
params.length==1 &&
params[0].getType().equals(ClassHelper.STRING_TYPE))
{
continue;
}
}
genMethod(classNode, methodNode, out);
}
}
private void getConstructors(ClassNode classNode, PrintWriter out) {
List constrs = classNode.getDeclaredConstructors();
if (constrs != null)
for (Iterator it = constrs.iterator(); it.hasNext();) {
ConstructorNode constrNode = (ConstructorNode) it.next();
genConstructor(classNode, constrNode, out);
}
}
private void genFields(ClassNode classNode, PrintWriter out, boolean isEnum) {
List fields = classNode.getFields();
if (fields == null) return;
ArrayList enumFields = new ArrayList(fields.size());
ArrayList normalFields = new ArrayList(fields.size());
for (Iterator it = fields.iterator(); it.hasNext();) {
FieldNode fieldNode = (FieldNode) it.next();
boolean isEnumField = (fieldNode.getModifiers() & Opcodes.ACC_ENUM) !=0;
boolean isSynthetic = (fieldNode.getModifiers() & Opcodes.ACC_SYNTHETIC) !=0;
if (isEnumField) {
enumFields.add(fieldNode);
} else if (!isSynthetic) {
normalFields.add(fieldNode);
}
}
genEnumFields(enumFields, out);
for (Iterator iterator = normalFields.iterator(); iterator.hasNext();) {
FieldNode fieldNode = (FieldNode) iterator.next();
genField(fieldNode, out);
}
}
private void genEnumFields(List fields, PrintWriter out) {
if (fields.size()==0) return;
boolean first = true;
for (Iterator iterator = fields.iterator(); iterator.hasNext();) {
FieldNode fieldNode = (FieldNode) iterator.next();
if (!first) {
out.print(", ");
} else {
first = false;
}
out.print(fieldNode.getName());
}
out.println(";");
}
private void genField(FieldNode fieldNode, PrintWriter out) {
if ((fieldNode.getModifiers()&Opcodes.ACC_PRIVATE)!=0) return;
printModifiers(out, fieldNode.getModifiers());
printType(fieldNode.getType(), out);
out.print(" ");
out.print(fieldNode.getName());
out.println(";");
}
private ConstructorCallExpression getConstructorCallExpression(
ConstructorNode constructorNode) {
Statement code = constructorNode.getCode();
if (!(code instanceof BlockStatement))
return null;
BlockStatement block = (BlockStatement) code;
List stats = block.getStatements();
if (stats == null || stats.size() == 0)
return null;
Statement stat = (Statement) stats.get(0);
if (!(stat instanceof ExpressionStatement))
return null;
Expression expr = ((ExpressionStatement) stat).getExpression();
if (!(expr instanceof ConstructorCallExpression))
return null;
return (ConstructorCallExpression) expr;
}
private void genConstructor(ClassNode clazz, ConstructorNode constructorNode, PrintWriter out) {
// printModifiers(out, constructorNode.getModifiers());
out.print("public "); // temporary hack
out.print(clazz.getNameWithoutPackage());
printParams(constructorNode, out);
ConstructorCallExpression constrCall = getConstructorCallExpression(constructorNode);
if (constrCall == null || !constrCall.isSpecialCall()) {
out.println(" {}");
} else {
out.println(" {");
genSpecialConstructorArgs(out, constructorNode, constrCall);
out.println("}");
}
}
private Parameter[] selectAccessibleConstructorFromSuper(ConstructorNode node) {
ClassNode type = node.getDeclaringClass();
ClassNode superType = type.getSuperClass();
boolean hadPrivateConstructor = false;
for (Iterator iter = superType.getDeclaredConstructors().iterator(); iter.hasNext();) {
ConstructorNode c = (ConstructorNode)iter.next();
// Only look at things we can actually call
if (c.isPublic() || c.isProtected()) {
return c.getParameters();
}
}
// fall back for parameterless constructor
if (superType.isPrimaryClassNode()) {
return Parameter.EMPTY_ARRAY;
}
return null;
}
private void genSpecialConstructorArgs(PrintWriter out, ConstructorNode node, ConstructorCallExpression constrCall) {
// Select a constructor from our class, or super-class which is legal to call,
// then write out an invoke w/nulls using casts to avoid abigous crapo
Parameter[] params = selectAccessibleConstructorFromSuper(node);
if (params != null) {
out.print("super (");
for (int i=0; i<params.length; i++) {
printDefaultValue(out, params[i].getType());
if (i + 1 < params.length) {
out.print(", ");
}
}
out.println(");");
return;
}
// Otherwise try the older method based on the constructor's call expression
Expression arguments = constrCall.getArguments();
if (constrCall.isSuperCall()) {
out.print("super(");
}
else {
out.print("this(");
}
// Else try to render some arguments
if (arguments instanceof ArgumentListExpression) {
ArgumentListExpression argumentListExpression = (ArgumentListExpression) arguments;
List args = argumentListExpression.getExpressions();
for (Iterator it = args.iterator(); it.hasNext();) {
Expression arg = (Expression) it.next();
if (arg instanceof ConstantExpression) {
ConstantExpression expression = (ConstantExpression) arg;
Object o = expression.getValue();
if (o instanceof String) {
out.print("(String)null");
} else {
out.print(expression.getText());
}
} else {
ClassNode type = getConstructorArgumentType(arg, node);
printDefaultValue(out, type);
}
if (arg != args.get(args.size() - 1)) {
out.print(", ");
}
}
}
out.println(");");
}
private ClassNode getConstructorArgumentType(Expression arg, ConstructorNode node) {
if (!(arg instanceof VariableExpression)) return arg.getType();
VariableExpression vexp = (VariableExpression) arg;
String name = vexp.getName();
Parameter[] params = node.getParameters();
for (int i=0; i<params.length; i++) {
if (params[i].getName().equals(name)) {
return params[i].getType();
}
}
return vexp.getType();
}
private void genMethod(ClassNode clazz, MethodNode methodNode, PrintWriter out) {
if (methodNode.getName().equals("<clinit>")) return;
if (methodNode.isPrivate() || !Utilities.isJavaIdentifier(methodNode.getName())) return;
if (!clazz.isInterface()) printModifiers(out, methodNode.getModifiers());
writeGenericsBounds(out, methodNode.getGenericsTypes());
out.print(" ");
printType(methodNode.getReturnType(), out);
out.print(" ");
out.print(methodNode.getName());
printParams(methodNode, out);
ClassNode[] exceptions = methodNode.getExceptions();
for (int i=0; i<exceptions.length; i++) {
ClassNode exception = exceptions[i];
if (i==0) {
out.print("throws ");
} else {
out.print(", ");
}
printType(exception,out);
}
if ((methodNode.getModifiers() & Opcodes.ACC_ABSTRACT) != 0) {
out.println(";");
} else {
out.print(" { ");
ClassNode retType = methodNode.getReturnType();
printReturn(out, retType);
out.println("}");
}
}
private void printReturn(PrintWriter out, ClassNode retType) {
String retName = retType.getName();
if (!retName.equals("void")) {
out.print("return ");
printDefaultValue(out, retType);
out.print(";");
}
}
private void printDefaultValue(PrintWriter out, ClassNode type) {
if (type.redirect()!=ClassHelper.OBJECT_TYPE) {
out.print("(");
printType(type,out);
out.print(")");
}
if (ClassHelper.isPrimitiveType(type)) {
if (type==ClassHelper.boolean_TYPE){
out.print("false");
} else {
out.print("0");
}
} else {
out.print("null");
}
}
private void printType(ClassNode type, PrintWriter out) {
if (type.isArray()) {
printType(type.getComponentType(),out);
out.print("[]");
} else if (java5 && type.isGenericsPlaceHolder()) {
out.print(type.getGenericsTypes()[0].getName());
} else {
writeGenericsBounds(out,type,false);
}
}
private void printTypeName(ClassNode type, PrintWriter out) {
if (ClassHelper.isPrimitiveType(type)) {
if (type==ClassHelper.boolean_TYPE) {
out.print("boolean");
} else if (type==ClassHelper.char_TYPE) {
out.print("char");
} else if (type==ClassHelper.int_TYPE) {
out.print("int");
} else if (type==ClassHelper.short_TYPE) {
out.print("short");
} else if (type==ClassHelper.long_TYPE) {
out.print("long");
} else if (type==ClassHelper.float_TYPE) {
out.print("float");
} else if (type==ClassHelper.double_TYPE) {
out.print("double");
} else if (type==ClassHelper.byte_TYPE) {
out.print("byte");
} else {
out.print("void");
}
} else {
out.print(type.redirect().getName().replace('$', '.'));
}
}
private void writeGenericsBounds(PrintWriter out, ClassNode type, boolean skipName) {
if (!skipName) printTypeName(type,out);
if (!java5) return;
if (!ClassHelper.isCachedType(type)) {
writeGenericsBounds(out,type.getGenericsTypes());
}
}
private void writeGenericsBounds(PrintWriter out, GenericsType[] genericsTypes) {
if (genericsTypes==null || genericsTypes.length==0) return;
out.print('<');
for (int i = 0; i < genericsTypes.length; i++) {
if (i!=0) out.print(", ");
writeGenericsBounds(out,genericsTypes[i]);
}
out.print('>');
}
private void writeGenericsBounds(PrintWriter out, GenericsType genericsType) {
if (genericsType.isPlaceholder()) {
out.print(genericsType.getName());
} else {
printType(genericsType.getType(),out);
}
ClassNode[] upperBounds = genericsType.getUpperBounds();
ClassNode lowerBound = genericsType.getLowerBound();
if (upperBounds != null) {
out.print(" extends ");
for (int i = 0; i < upperBounds.length; i++) {
printType(upperBounds[i], out);
if (i + 1 < upperBounds.length) out.print(" & ");
}
} else if (lowerBound != null) {
out.print(" super ");
printType(lowerBound, out);
}
}
private void printParams(MethodNode methodNode, PrintWriter out) {
out.print("(");
Parameter[] parameters = methodNode.getParameters();
if (parameters != null && parameters.length != 0) {
for (int i = 0; i != parameters.length; ++i) {
printType(parameters[i].getType(), out);
out.print(" ");
out.print(parameters[i].getName());
if (i + 1 < parameters.length) {
out.print(", ");
}
}
}
out.print(")");
}
private void printModifiers(PrintWriter out, int modifiers) {
if ((modifiers & Opcodes.ACC_PUBLIC) != 0)
out.print("public ");
if ((modifiers & Opcodes.ACC_PROTECTED) != 0)
out.print("protected ");
if ((modifiers & Opcodes.ACC_PRIVATE) != 0)
out.print("private ");
if ((modifiers & Opcodes.ACC_STATIC) != 0)
out.print("static ");
if ((modifiers & Opcodes.ACC_SYNCHRONIZED) != 0)
out.print("synchronized ");
if ((modifiers & Opcodes.ACC_ABSTRACT) != 0)
out.print("abstract ");
}
private void genImports(ClassNode classNode, PrintWriter out) {
Set<String> imports = new HashSet<String>();
//
// HACK: Add the default imports... since things like Closure and GroovyObject seem to parse out w/o fully qualified classnames.
//
imports.addAll(Arrays.asList(ResolveVisitor.DEFAULT_IMPORTS));
ModuleNode moduleNode = classNode.getModule();
for (ImportNode importNode : moduleNode.getStarImports()) {
imports.add(importNode.getPackageName());
}
for (ImportNode imp : moduleNode.getImports()) {
String name = imp.getType().getName();
int lastDot = name.lastIndexOf('.');
if (lastDot != -1)
imports.add(name.substring(0, lastDot + 1));
}
for (String imp : imports) {
out.print("import ");
out.print(imp);
out.println("*;");
}
out.println();
}
public void clean() {
for (Iterator it = toCompile.iterator(); it.hasNext();) {
String path = (String) it.next();
new File(outputPath, path + ".java").delete();
}
}
}
| false | true | public void generateClass(ClassNode classNode) throws FileNotFoundException {
// Only attempt to render our self if our super-class is resolved, else wait for it
if (requireSuperResolved && !classNode.getSuperClass().isResolved()) {
return;
}
// don't generate stubs for private classes, as they are only visible in the same file
if ((classNode.getModifiers() & Opcodes.ACC_PRIVATE) != 0) return;
String fileName = classNode.getName().replace('.', '/');
mkdirs(outputPath,fileName);
toCompile.add(fileName);
File file = new File(outputPath, fileName + ".java");
FileOutputStream fos = new FileOutputStream(file);
PrintWriter out = new PrintWriter(fos);
Verifier verifier = new Verifier() {
public void addCovariantMethods(ClassNode cn) {}
protected void addTimeStamp(ClassNode node) {}
protected void addInitialization(ClassNode node) {}
protected void addPropertyMethod(MethodNode method) {
propertyMethods.add(method);
}
protected void addReturnIfNeeded(MethodNode node) {}
};
verifier.visitClass(classNode);
try {
String packageName = classNode.getPackageName();
if (packageName != null) {
out.println("package " + packageName + ";\n");
}
genImports(classNode, out);
boolean isInterface = classNode.isInterface();
boolean isEnum = (classNode.getModifiers() & Opcodes.ACC_ENUM) !=0;
printModifiers(out, classNode.getModifiers()
& ~(isInterface ? Opcodes.ACC_ABSTRACT : 0));
if (isInterface) {
out.print ("interface ");
} else if (isEnum) {
out.print ("enum ");
} else {
out.print ("class ");
}
out.println(classNode.getNameWithoutPackage());
writeGenericsBounds(out, classNode, true);
ClassNode superClass = classNode.getUnresolvedSuperClass(false);
if (!isInterface && !isEnum) {
out.print(" extends ");
printType(superClass,out);
}
ClassNode[] interfaces = classNode.getInterfaces();
if (interfaces != null && interfaces.length > 0) {
if (isInterface) {
out.println(" extends");
} else {
out.println(" implements");
}
for (int i = 0; i < interfaces.length - 1; ++i) {
out.print(" ");
printType(interfaces[i], out);
out.print(",");
}
out.print(" ");
printType(interfaces[interfaces.length - 1],out);
}
out.println(" {");
genFields(classNode, out, isEnum);
genMethods(classNode, out, isEnum);
out.println("}");
} finally {
propertyMethods.clear();
try {
out.close();
} catch (Exception e) {
// ignore
}
try {
fos.close();
} catch (IOException e) {
// ignore
}
}
}
| public void generateClass(ClassNode classNode) throws FileNotFoundException {
// Only attempt to render our self if our super-class is resolved, else wait for it
if (requireSuperResolved && !classNode.getSuperClass().isResolved()) {
return;
}
// don't generate stubs for private classes, as they are only visible in the same file
if ((classNode.getModifiers() & Opcodes.ACC_PRIVATE) != 0) return;
String fileName = classNode.getName().replace('.', '/');
mkdirs(outputPath,fileName);
toCompile.add(fileName);
File file = new File(outputPath, fileName + ".java");
FileOutputStream fos = new FileOutputStream(file);
PrintWriter out = new PrintWriter(fos);
Verifier verifier = new Verifier() {
public void addCovariantMethods(ClassNode cn) {}
protected void addTimeStamp(ClassNode node) {}
protected void addInitialization(ClassNode node) {}
protected void addPropertyMethod(MethodNode method) {
propertyMethods.add(method);
}
protected void addReturnIfNeeded(MethodNode node) {}
};
verifier.visitClass(classNode);
try {
String packageName = classNode.getPackageName();
if (packageName != null) {
out.println("package " + packageName + ";\n");
}
genImports(classNode, out);
boolean isInterface = classNode.isInterface();
boolean isEnum = (classNode.getModifiers() & Opcodes.ACC_ENUM) !=0;
printModifiers(out, classNode.getModifiers()
& ~(isInterface ? Opcodes.ACC_ABSTRACT : 0));
if (isInterface) {
out.print ("interface ");
} else if (isEnum) {
out.print ("enum ");
} else {
out.print ("class ");
}
out.println(classNode.getNameWithoutPackage());
writeGenericsBounds(out, classNode, true);
ClassNode superClass = classNode.getUnresolvedSuperClass(false);
if (!isInterface && !isEnum) {
out.print(" extends ");
printType(superClass,out);
}
ClassNode[] interfaces = classNode.getInterfaces();
if (interfaces != null && interfaces.length > 0) {
if (isInterface) {
out.println(" extends");
} else {
out.println(" implements");
}
for (int i = 0; i < interfaces.length - 1; ++i) {
out.print(" ");
printType(interfaces[i], out);
out.print(",");
}
out.print(" ");
printType(interfaces[interfaces.length - 1],out);
}
out.println(" {");
genFields(classNode, out, isEnum);
genMethods(classNode, out, isEnum);
out.println("}");
} finally {
propertyMethods.clear();
try {
out.close();
} catch (Exception e) {
// ignore
}
try {
fos.close();
} catch (IOException e) {
// ignore
}
}
}
|
diff --git a/poj-countdowntimer/src/net/diogomarques/utils/CountDownTimer.java b/poj-countdowntimer/src/net/diogomarques/utils/CountDownTimer.java
index 041c1ea..c61bef5 100644
--- a/poj-countdowntimer/src/net/diogomarques/utils/CountDownTimer.java
+++ b/poj-countdowntimer/src/net/diogomarques/utils/CountDownTimer.java
@@ -1,56 +1,57 @@
package net.diogomarques.utils;
import java.util.Timer;
import java.util.TimerTask;
/**
* A plain old Java implementation of Android's <a href=
* "http://developer.android.com/reference/android/os/CountDownTimer.html"
* >CountDownTimer</a>.
*
* @author Diogo Marques <[email protected]>
*
*/
public abstract class CountDownTimer {
private final long mMillisInFuture;
private final long mCountdownInterval;
private Timer mTimer;
public CountDownTimer(long millisInFuture, long countDownInterval) {
mMillisInFuture = millisInFuture;
mCountdownInterval = countDownInterval;
}
public final void cancel() {
if (mTimer != null)
mTimer.cancel();
}
public synchronized final CountDownTimer start() {
mTimer = new Timer();
final long deadline = System.currentTimeMillis() + mMillisInFuture;
TimerTask tickerTask = new TimerTask() {
@Override
public void run() {
long now = System.currentTimeMillis();
if (now + mCountdownInterval > deadline) {
- cancel();
+ onFinish();
+ cancel();
} else {
onTick(deadline - now);
}
}
};
mTimer.scheduleAtFixedRate(tickerTask, mCountdownInterval,
mCountdownInterval);
return this;
}
public abstract void onTick(long millisUntilFinished);
public abstract void onFinish();
}
| true | true | public synchronized final CountDownTimer start() {
mTimer = new Timer();
final long deadline = System.currentTimeMillis() + mMillisInFuture;
TimerTask tickerTask = new TimerTask() {
@Override
public void run() {
long now = System.currentTimeMillis();
if (now + mCountdownInterval > deadline) {
cancel();
} else {
onTick(deadline - now);
}
}
};
mTimer.scheduleAtFixedRate(tickerTask, mCountdownInterval,
mCountdownInterval);
return this;
}
| public synchronized final CountDownTimer start() {
mTimer = new Timer();
final long deadline = System.currentTimeMillis() + mMillisInFuture;
TimerTask tickerTask = new TimerTask() {
@Override
public void run() {
long now = System.currentTimeMillis();
if (now + mCountdownInterval > deadline) {
onFinish();
cancel();
} else {
onTick(deadline - now);
}
}
};
mTimer.scheduleAtFixedRate(tickerTask, mCountdownInterval,
mCountdownInterval);
return this;
}
|
diff --git a/src/main/java/org/json/simple/parser/Yylex.java b/src/main/java/org/json/simple/parser/Yylex.java
index 42ce508..e58e27e 100644
--- a/src/main/java/org/json/simple/parser/Yylex.java
+++ b/src/main/java/org/json/simple/parser/Yylex.java
@@ -1,688 +1,688 @@
/* The following code was generated by JFlex 1.4.2 */
package org.json.simple.parser;
class Yylex {
/** This character denotes the end of file */
public static final int YYEOF = -1;
/** initial size of the lookahead buffer */
private static final int ZZ_BUFFERSIZE = 16384;
/** lexical states */
public static final int YYINITIAL = 0;
public static final int STRING_BEGIN = 2;
/**
* ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l
* ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l
* at the beginning of a line
* l is of the form l = 2*k, k a non negative integer
*/
private static final int ZZ_LEXSTATE[] = {
0, 0, 1, 1
};
/**
* Translates characters to character classes
*/
private static final String ZZ_CMAP_PACKED =
"\11\0\1\7\1\7\2\0\1\7\22\0\1\7\1\0\1\11\10\0"+
"\1\6\1\31\1\2\1\4\1\12\12\3\1\32\6\0\4\1\1\5"+
"\1\1\24\0\1\27\1\10\1\30\3\0\1\22\1\13\2\1\1\21"+
"\1\14\5\0\1\23\1\0\1\15\3\0\1\16\1\24\1\17\1\20"+
"\5\0\1\25\1\0\1\26\uff82\0";
/**
* Translates characters to character classes
*/
private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED);
/**
* Translates DFA states to action switch labels.
*/
private static final int [] ZZ_ACTION = zzUnpackAction();
private static final String ZZ_ACTION_PACKED_0 =
"\2\0\2\1\1\2\1\3\1\4\3\1\1\5\1\6"+
"\1\7\1\10\1\11\1\12\1\13\1\14\1\15\5\0"+
"\1\14\1\16\1\17\1\20\1\21\1\22\1\23\1\24"+
"\1\0\1\25\1\0\1\25\4\0\1\26\1\27\2\0"+
"\1\30";
private static int [] zzUnpackAction() {
int [] result = new int[45];
int offset = 0;
offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result);
return result;
}
private static int zzUnpackAction(String packed, int offset, int [] result) {
int i = 0; /* index in packed string */
int j = offset; /* index in unpacked array */
int l = packed.length();
while (i < l) {
int count = packed.charAt(i++);
int value = packed.charAt(i++);
do result[j++] = value; while (--count > 0);
}
return j;
}
/**
* Translates a state to a row index in the transition table
*/
private static final int [] ZZ_ROWMAP = zzUnpackRowMap();
private static final String ZZ_ROWMAP_PACKED_0 =
"\0\0\0\33\0\66\0\121\0\154\0\207\0\66\0\242"+
"\0\275\0\330\0\66\0\66\0\66\0\66\0\66\0\66"+
"\0\363\0\u010e\0\66\0\u0129\0\u0144\0\u015f\0\u017a\0\u0195"+
"\0\66\0\66\0\66\0\66\0\66\0\66\0\66\0\66"+
"\0\u01b0\0\u01cb\0\u01e6\0\u01e6\0\u0201\0\u021c\0\u0237\0\u0252"+
"\0\66\0\66\0\u026d\0\u0288\0\66";
private static int [] zzUnpackRowMap() {
int [] result = new int[45];
int offset = 0;
offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result);
return result;
}
private static int zzUnpackRowMap(String packed, int offset, int [] result) {
int i = 0; /* index in packed string */
int j = offset; /* index in unpacked array */
int l = packed.length();
while (i < l) {
int high = packed.charAt(i++) << 16;
result[j++] = high | packed.charAt(i++);
}
return j;
}
/**
* The transition table of the DFA
*/
private static final int ZZ_TRANS [] = {
2, 2, 3, 4, 2, 2, 2, 5, 2, 6,
2, 2, 7, 8, 2, 9, 2, 2, 2, 2,
2, 10, 11, 12, 13, 14, 15, 16, 16, 16,
16, 16, 16, 16, 16, 17, 18, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, 4, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, 4, 19, 20, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, 20, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, 5, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
21, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, 22, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
23, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, 16, 16, 16, 16, 16, 16, 16,
16, -1, -1, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
-1, -1, -1, -1, -1, -1, -1, -1, 24, 25,
26, 27, 28, 29, 30, 31, 32, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
33, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, 34, 35, -1, -1,
34, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
36, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, 37, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, 38, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, 39, -1, 39, -1, 39, -1, -1,
-1, -1, -1, 39, 39, -1, -1, -1, -1, 39,
39, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, 33, -1, 20, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, 20, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, 35,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, 38, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, 40,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, 41, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, 42, -1, 42, -1, 42,
-1, -1, -1, -1, -1, 42, 42, -1, -1, -1,
-1, 42, 42, -1, -1, -1, -1, -1, -1, -1,
-1, -1, 43, -1, 43, -1, 43, -1, -1, -1,
-1, -1, 43, 43, -1, -1, -1, -1, 43, 43,
-1, -1, -1, -1, -1, -1, -1, -1, -1, 44,
-1, 44, -1, 44, -1, -1, -1, -1, -1, 44,
44, -1, -1, -1, -1, 44, 44, -1, -1, -1,
-1, -1, -1, -1, -1,
};
/* error codes */
private static final int ZZ_UNKNOWN_ERROR = 0;
private static final int ZZ_NO_MATCH = 1;
private static final int ZZ_PUSHBACK_2BIG = 2;
/* error messages for the codes above */
private static final String ZZ_ERROR_MSG[] = {
"Unkown internal scanner error",
"Error: could not match input",
"Error: pushback value was too large"
};
/**
* ZZ_ATTRIBUTE[aState] contains the attributes of state <code>aState</code>
*/
private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute();
private static final String ZZ_ATTRIBUTE_PACKED_0 =
"\2\0\1\11\3\1\1\11\3\1\6\11\2\1\1\11"+
"\5\0\10\11\1\0\1\1\1\0\1\1\4\0\2\11"+
"\2\0\1\11";
private static int [] zzUnpackAttribute() {
int [] result = new int[45];
int offset = 0;
offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result);
return result;
}
private static int zzUnpackAttribute(String packed, int offset, int [] result) {
int i = 0; /* index in packed string */
int j = offset; /* index in unpacked array */
int l = packed.length();
while (i < l) {
int count = packed.charAt(i++);
int value = packed.charAt(i++);
do result[j++] = value; while (--count > 0);
}
return j;
}
/** the input device */
private java.io.Reader zzReader;
/** the current state of the DFA */
private int zzState;
/** the current lexical state */
private int zzLexicalState = YYINITIAL;
/** this buffer contains the current text to be matched and is
the source of the yytext() string */
private char zzBuffer[] = new char[ZZ_BUFFERSIZE];
/** the textposition at the last accepting state */
private int zzMarkedPos;
/** the current text position in the buffer */
private int zzCurrentPos;
/** startRead marks the beginning of the yytext() string in the buffer */
private int zzStartRead;
/** endRead marks the last character in the buffer, that has been read
from input */
private int zzEndRead;
/** number of newlines encountered up to the start of the matched text */
private int yyline;
/** the number of characters up to the start of the matched text */
private int yychar;
/**
* the number of characters from the last newline up to the start of the
* matched text
*/
private int yycolumn;
/**
* zzAtBOL == true <=> the scanner is currently at the beginning of a line
*/
private boolean zzAtBOL = true;
/** zzAtEOF == true <=> the scanner is at the EOF */
private boolean zzAtEOF;
/* user code: */
private StringBuffer sb=new StringBuffer();
int getPosition(){
return yychar;
}
/**
* Creates a new scanner
* There is also a java.io.InputStream version of this constructor.
*
* @param in the java.io.Reader to read input from.
*/
Yylex(java.io.Reader in) {
this.zzReader = in;
}
/**
* Creates a new scanner.
* There is also java.io.Reader version of this constructor.
*
* @param in the java.io.Inputstream to read input from.
*/
Yylex(java.io.InputStream in) {
this(new java.io.InputStreamReader(in));
}
/**
* Unpacks the compressed character translation table.
*
* @param packed the packed character translation table
* @return the unpacked character translation table
*/
private static char [] zzUnpackCMap(String packed) {
char [] map = new char[0x10000];
int i = 0; /* index in packed string */
int j = 0; /* index in unpacked array */
while (i < 90) {
int count = packed.charAt(i++);
char value = packed.charAt(i++);
do map[j++] = value; while (--count > 0);
}
return map;
}
/**
* Refills the input buffer.
*
* @return <code>false</code>, iff there was new input.
*
* @exception java.io.IOException if any I/O-Error occurs
*/
private boolean zzRefill() throws java.io.IOException {
/* first: make room (if you can) */
if (zzStartRead > 0) {
System.arraycopy(zzBuffer, zzStartRead,
zzBuffer, 0,
zzEndRead-zzStartRead);
/* translate stored positions */
zzEndRead-= zzStartRead;
zzCurrentPos-= zzStartRead;
zzMarkedPos-= zzStartRead;
zzStartRead = 0;
}
/* is the buffer big enough? */
if (zzCurrentPos >= zzBuffer.length) {
/* if not: blow it up */
char newBuffer[] = new char[zzCurrentPos*2];
System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length);
zzBuffer = newBuffer;
}
/* finally: fill the buffer with new input */
int numRead = zzReader.read(zzBuffer, zzEndRead,
zzBuffer.length-zzEndRead);
if (numRead > 0) {
zzEndRead+= numRead;
return false;
}
// unlikely but not impossible: read 0 characters, but not at end of stream
if (numRead == 0) {
int c = zzReader.read();
if (c == -1) {
return true;
} else {
zzBuffer[zzEndRead++] = (char) c;
return false;
}
}
// numRead < 0
return true;
}
/**
* Closes the input stream.
*/
public final void yyclose() throws java.io.IOException {
zzAtEOF = true; /* indicate end of file */
zzEndRead = zzStartRead; /* invalidate buffer */
if (zzReader != null)
zzReader.close();
}
/**
* Resets the scanner to read from a new input stream.
* Does not close the old reader.
*
* All internal variables are reset, the old input stream
* <b>cannot</b> be reused (internal buffer is discarded and lost).
* Lexical state is set to <tt>ZZ_INITIAL</tt>.
*
* @param reader the new input stream
*/
public final void yyreset(java.io.Reader reader) {
zzReader = reader;
zzAtBOL = true;
zzAtEOF = false;
zzEndRead = zzStartRead = 0;
zzCurrentPos = zzMarkedPos = 0;
yyline = yychar = yycolumn = 0;
zzLexicalState = YYINITIAL;
}
/**
* Returns the current lexical state.
*/
public final int yystate() {
return zzLexicalState;
}
/**
* Enters a new lexical state
*
* @param newState the new lexical state
*/
public final void yybegin(int newState) {
zzLexicalState = newState;
}
/**
* Returns the text matched by the current regular expression.
*/
public final String yytext() {
return new String( zzBuffer, zzStartRead, zzMarkedPos-zzStartRead );
}
/**
* Returns the character at position <tt>pos</tt> from the
* matched text.
*
* It is equivalent to yytext().charAt(pos), but faster
*
* @param pos the position of the character to fetch.
* A value from 0 to yylength()-1.
*
* @return the character at position pos
*/
public final char yycharat(int pos) {
return zzBuffer[zzStartRead+pos];
}
/**
* Returns the length of the matched text region.
*/
public final int yylength() {
return zzMarkedPos-zzStartRead;
}
/**
* Reports an error that occured while scanning.
*
* In a wellformed scanner (no or only correct usage of
* yypushback(int) and a match-all fallback rule) this method
* will only be called with things that "Can't Possibly Happen".
* If this method is called, something is seriously wrong
* (e.g. a JFlex bug producing a faulty scanner etc.).
*
* Usual syntax/scanner level error handling should be done
* in error fallback rules.
*
* @param errorCode the code of the errormessage to display
*/
private void zzScanError(int errorCode) {
String message;
try {
message = ZZ_ERROR_MSG[errorCode];
}
catch (ArrayIndexOutOfBoundsException e) {
message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR];
}
throw new Error(message);
}
/**
* Pushes the specified amount of characters back into the input stream.
*
* They will be read again by then next call of the scanning method
*
* @param number the number of characters to be read again.
* This number must not be greater than yylength()!
*/
public void yypushback(int number) {
if ( number > yylength() )
zzScanError(ZZ_PUSHBACK_2BIG);
zzMarkedPos -= number;
}
/**
* Resumes scanning until the next regular expression is matched,
* the end of input is encountered or an I/O-Error occurs.
*
* @return the next token
* @exception java.io.IOException if any I/O-Error occurs
*/
public Yytoken yylex() throws java.io.IOException, ParseException {
int zzInput;
int zzAction;
// cached fields:
int zzCurrentPosL;
int zzMarkedPosL;
int zzEndReadL = zzEndRead;
char [] zzBufferL = zzBuffer;
char [] zzCMapL = ZZ_CMAP;
int [] zzTransL = ZZ_TRANS;
int [] zzRowMapL = ZZ_ROWMAP;
int [] zzAttrL = ZZ_ATTRIBUTE;
while (true) {
zzMarkedPosL = zzMarkedPos;
yychar+= zzMarkedPosL-zzStartRead;
zzAction = -1;
zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL;
zzState = ZZ_LEXSTATE[zzLexicalState];
zzForAction: {
while (true) {
if (zzCurrentPosL < zzEndReadL)
zzInput = zzBufferL[zzCurrentPosL++];
else if (zzAtEOF) {
zzInput = YYEOF;
break zzForAction;
}
else {
// store back cached positions
zzCurrentPos = zzCurrentPosL;
zzMarkedPos = zzMarkedPosL;
boolean eof = zzRefill();
// get translated positions and possibly new buffer
zzCurrentPosL = zzCurrentPos;
zzMarkedPosL = zzMarkedPos;
zzBufferL = zzBuffer;
zzEndReadL = zzEndRead;
if (eof) {
zzInput = YYEOF;
break zzForAction;
}
else {
zzInput = zzBufferL[zzCurrentPosL++];
}
}
int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ];
if (zzNext == -1) break zzForAction;
zzState = zzNext;
int zzAttributes = zzAttrL[zzState];
if ( (zzAttributes & 1) == 1 ) {
zzAction = zzState;
zzMarkedPosL = zzCurrentPosL;
if ( (zzAttributes & 8) == 8 ) break zzForAction;
}
}
}
// store back cached position
zzMarkedPos = zzMarkedPosL;
switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) {
case 11:
{ sb.append(yytext());
}
case 25: break;
case 4:
- { sb.delete(0, sb.length());yybegin(STRING_BEGIN);
+ { sb = null; sb = new StringBuffer(); yybegin(STRING_BEGIN);
}
case 26: break;
case 16:
{ sb.append('\b');
}
case 27: break;
case 6:
{ return new Yytoken(Yytoken.TYPE_RIGHT_BRACE,null);
}
case 28: break;
case 23:
{ Boolean val=Boolean.valueOf(yytext()); return new Yytoken(Yytoken.TYPE_VALUE, val);
}
case 29: break;
case 22:
{ return new Yytoken(Yytoken.TYPE_VALUE, null);
}
case 30: break;
case 13:
{ yybegin(YYINITIAL);return new Yytoken(Yytoken.TYPE_VALUE, sb.toString());
}
case 31: break;
case 12:
{ sb.append('\\');
}
case 32: break;
case 21:
{ Double val=Double.valueOf(yytext()); return new Yytoken(Yytoken.TYPE_VALUE, val);
}
case 33: break;
case 1:
{ throw new ParseException(yychar, ParseException.ERROR_UNEXPECTED_CHAR, new Character(yycharat(0)));
}
case 34: break;
case 8:
{ return new Yytoken(Yytoken.TYPE_RIGHT_SQUARE,null);
}
case 35: break;
case 19:
{ sb.append('\r');
}
case 36: break;
case 15:
{ sb.append('/');
}
case 37: break;
case 10:
{ return new Yytoken(Yytoken.TYPE_COLON,null);
}
case 38: break;
case 14:
{ sb.append('"');
}
case 39: break;
case 5:
{ return new Yytoken(Yytoken.TYPE_LEFT_BRACE,null);
}
case 40: break;
case 17:
{ sb.append('\f');
}
case 41: break;
case 24:
{ try{
int ch=Integer.parseInt(yytext().substring(2),16);
sb.append((char)ch);
}
catch(Exception e){
throw new ParseException(yychar, ParseException.ERROR_UNEXPECTED_EXCEPTION, e);
}
}
case 42: break;
case 20:
{ sb.append('\t');
}
case 43: break;
case 7:
{ return new Yytoken(Yytoken.TYPE_LEFT_SQUARE,null);
}
case 44: break;
case 2:
{ Long val=Long.valueOf(yytext()); return new Yytoken(Yytoken.TYPE_VALUE, val);
}
case 45: break;
case 18:
{ sb.append('\n');
}
case 46: break;
case 9:
{ return new Yytoken(Yytoken.TYPE_COMMA,null);
}
case 47: break;
case 3:
{
}
case 48: break;
default:
if (zzInput == YYEOF && zzStartRead == zzCurrentPos) {
zzAtEOF = true;
return null;
}
else {
zzScanError(ZZ_NO_MATCH);
}
}
}
}
}
| true | true | public Yytoken yylex() throws java.io.IOException, ParseException {
int zzInput;
int zzAction;
// cached fields:
int zzCurrentPosL;
int zzMarkedPosL;
int zzEndReadL = zzEndRead;
char [] zzBufferL = zzBuffer;
char [] zzCMapL = ZZ_CMAP;
int [] zzTransL = ZZ_TRANS;
int [] zzRowMapL = ZZ_ROWMAP;
int [] zzAttrL = ZZ_ATTRIBUTE;
while (true) {
zzMarkedPosL = zzMarkedPos;
yychar+= zzMarkedPosL-zzStartRead;
zzAction = -1;
zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL;
zzState = ZZ_LEXSTATE[zzLexicalState];
zzForAction: {
while (true) {
if (zzCurrentPosL < zzEndReadL)
zzInput = zzBufferL[zzCurrentPosL++];
else if (zzAtEOF) {
zzInput = YYEOF;
break zzForAction;
}
else {
// store back cached positions
zzCurrentPos = zzCurrentPosL;
zzMarkedPos = zzMarkedPosL;
boolean eof = zzRefill();
// get translated positions and possibly new buffer
zzCurrentPosL = zzCurrentPos;
zzMarkedPosL = zzMarkedPos;
zzBufferL = zzBuffer;
zzEndReadL = zzEndRead;
if (eof) {
zzInput = YYEOF;
break zzForAction;
}
else {
zzInput = zzBufferL[zzCurrentPosL++];
}
}
int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ];
if (zzNext == -1) break zzForAction;
zzState = zzNext;
int zzAttributes = zzAttrL[zzState];
if ( (zzAttributes & 1) == 1 ) {
zzAction = zzState;
zzMarkedPosL = zzCurrentPosL;
if ( (zzAttributes & 8) == 8 ) break zzForAction;
}
}
}
// store back cached position
zzMarkedPos = zzMarkedPosL;
switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) {
case 11:
{ sb.append(yytext());
}
case 25: break;
case 4:
{ sb.delete(0, sb.length());yybegin(STRING_BEGIN);
}
case 26: break;
case 16:
{ sb.append('\b');
}
case 27: break;
case 6:
{ return new Yytoken(Yytoken.TYPE_RIGHT_BRACE,null);
}
case 28: break;
case 23:
{ Boolean val=Boolean.valueOf(yytext()); return new Yytoken(Yytoken.TYPE_VALUE, val);
}
case 29: break;
case 22:
{ return new Yytoken(Yytoken.TYPE_VALUE, null);
}
case 30: break;
case 13:
{ yybegin(YYINITIAL);return new Yytoken(Yytoken.TYPE_VALUE, sb.toString());
}
case 31: break;
case 12:
{ sb.append('\\');
}
case 32: break;
case 21:
{ Double val=Double.valueOf(yytext()); return new Yytoken(Yytoken.TYPE_VALUE, val);
}
case 33: break;
case 1:
{ throw new ParseException(yychar, ParseException.ERROR_UNEXPECTED_CHAR, new Character(yycharat(0)));
}
case 34: break;
case 8:
{ return new Yytoken(Yytoken.TYPE_RIGHT_SQUARE,null);
}
case 35: break;
case 19:
{ sb.append('\r');
}
case 36: break;
case 15:
{ sb.append('/');
}
case 37: break;
case 10:
{ return new Yytoken(Yytoken.TYPE_COLON,null);
}
case 38: break;
case 14:
{ sb.append('"');
}
case 39: break;
case 5:
{ return new Yytoken(Yytoken.TYPE_LEFT_BRACE,null);
}
case 40: break;
case 17:
{ sb.append('\f');
}
case 41: break;
case 24:
{ try{
int ch=Integer.parseInt(yytext().substring(2),16);
sb.append((char)ch);
}
catch(Exception e){
throw new ParseException(yychar, ParseException.ERROR_UNEXPECTED_EXCEPTION, e);
}
}
case 42: break;
case 20:
{ sb.append('\t');
}
case 43: break;
case 7:
{ return new Yytoken(Yytoken.TYPE_LEFT_SQUARE,null);
}
case 44: break;
case 2:
{ Long val=Long.valueOf(yytext()); return new Yytoken(Yytoken.TYPE_VALUE, val);
}
case 45: break;
case 18:
{ sb.append('\n');
}
case 46: break;
case 9:
{ return new Yytoken(Yytoken.TYPE_COMMA,null);
}
case 47: break;
case 3:
{
}
case 48: break;
default:
if (zzInput == YYEOF && zzStartRead == zzCurrentPos) {
zzAtEOF = true;
return null;
}
else {
zzScanError(ZZ_NO_MATCH);
}
}
}
}
| public Yytoken yylex() throws java.io.IOException, ParseException {
int zzInput;
int zzAction;
// cached fields:
int zzCurrentPosL;
int zzMarkedPosL;
int zzEndReadL = zzEndRead;
char [] zzBufferL = zzBuffer;
char [] zzCMapL = ZZ_CMAP;
int [] zzTransL = ZZ_TRANS;
int [] zzRowMapL = ZZ_ROWMAP;
int [] zzAttrL = ZZ_ATTRIBUTE;
while (true) {
zzMarkedPosL = zzMarkedPos;
yychar+= zzMarkedPosL-zzStartRead;
zzAction = -1;
zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL;
zzState = ZZ_LEXSTATE[zzLexicalState];
zzForAction: {
while (true) {
if (zzCurrentPosL < zzEndReadL)
zzInput = zzBufferL[zzCurrentPosL++];
else if (zzAtEOF) {
zzInput = YYEOF;
break zzForAction;
}
else {
// store back cached positions
zzCurrentPos = zzCurrentPosL;
zzMarkedPos = zzMarkedPosL;
boolean eof = zzRefill();
// get translated positions and possibly new buffer
zzCurrentPosL = zzCurrentPos;
zzMarkedPosL = zzMarkedPos;
zzBufferL = zzBuffer;
zzEndReadL = zzEndRead;
if (eof) {
zzInput = YYEOF;
break zzForAction;
}
else {
zzInput = zzBufferL[zzCurrentPosL++];
}
}
int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ];
if (zzNext == -1) break zzForAction;
zzState = zzNext;
int zzAttributes = zzAttrL[zzState];
if ( (zzAttributes & 1) == 1 ) {
zzAction = zzState;
zzMarkedPosL = zzCurrentPosL;
if ( (zzAttributes & 8) == 8 ) break zzForAction;
}
}
}
// store back cached position
zzMarkedPos = zzMarkedPosL;
switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) {
case 11:
{ sb.append(yytext());
}
case 25: break;
case 4:
{ sb = null; sb = new StringBuffer(); yybegin(STRING_BEGIN);
}
case 26: break;
case 16:
{ sb.append('\b');
}
case 27: break;
case 6:
{ return new Yytoken(Yytoken.TYPE_RIGHT_BRACE,null);
}
case 28: break;
case 23:
{ Boolean val=Boolean.valueOf(yytext()); return new Yytoken(Yytoken.TYPE_VALUE, val);
}
case 29: break;
case 22:
{ return new Yytoken(Yytoken.TYPE_VALUE, null);
}
case 30: break;
case 13:
{ yybegin(YYINITIAL);return new Yytoken(Yytoken.TYPE_VALUE, sb.toString());
}
case 31: break;
case 12:
{ sb.append('\\');
}
case 32: break;
case 21:
{ Double val=Double.valueOf(yytext()); return new Yytoken(Yytoken.TYPE_VALUE, val);
}
case 33: break;
case 1:
{ throw new ParseException(yychar, ParseException.ERROR_UNEXPECTED_CHAR, new Character(yycharat(0)));
}
case 34: break;
case 8:
{ return new Yytoken(Yytoken.TYPE_RIGHT_SQUARE,null);
}
case 35: break;
case 19:
{ sb.append('\r');
}
case 36: break;
case 15:
{ sb.append('/');
}
case 37: break;
case 10:
{ return new Yytoken(Yytoken.TYPE_COLON,null);
}
case 38: break;
case 14:
{ sb.append('"');
}
case 39: break;
case 5:
{ return new Yytoken(Yytoken.TYPE_LEFT_BRACE,null);
}
case 40: break;
case 17:
{ sb.append('\f');
}
case 41: break;
case 24:
{ try{
int ch=Integer.parseInt(yytext().substring(2),16);
sb.append((char)ch);
}
catch(Exception e){
throw new ParseException(yychar, ParseException.ERROR_UNEXPECTED_EXCEPTION, e);
}
}
case 42: break;
case 20:
{ sb.append('\t');
}
case 43: break;
case 7:
{ return new Yytoken(Yytoken.TYPE_LEFT_SQUARE,null);
}
case 44: break;
case 2:
{ Long val=Long.valueOf(yytext()); return new Yytoken(Yytoken.TYPE_VALUE, val);
}
case 45: break;
case 18:
{ sb.append('\n');
}
case 46: break;
case 9:
{ return new Yytoken(Yytoken.TYPE_COMMA,null);
}
case 47: break;
case 3:
{
}
case 48: break;
default:
if (zzInput == YYEOF && zzStartRead == zzCurrentPos) {
zzAtEOF = true;
return null;
}
else {
zzScanError(ZZ_NO_MATCH);
}
}
}
}
|
diff --git a/db/src/main/java/com/psddev/dari/db/DatabaseEnvironment.java b/db/src/main/java/com/psddev/dari/db/DatabaseEnvironment.java
index bcae4582..f6cdc56c 100644
--- a/db/src/main/java/com/psddev/dari/db/DatabaseEnvironment.java
+++ b/db/src/main/java/com/psddev/dari/db/DatabaseEnvironment.java
@@ -1,766 +1,766 @@
package com.psddev.dari.db;
import java.util.ArrayList;
import java.util.Date;
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.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.psddev.dari.util.CodeUtils;
import com.psddev.dari.util.ObjectUtils;
import com.psddev.dari.util.PeriodicCache;
import com.psddev.dari.util.PullThroughValue;
import com.psddev.dari.util.Task;
import com.psddev.dari.util.TypeDefinition;
public class DatabaseEnvironment implements ObjectStruct {
public static final String GLOBAL_FIELDS_FIELD = "globalFields";
public static final String GLOBAL_INDEXES_FIELD = "globalIndexes";
private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseEnvironment.class);
private final Database database;
private final boolean initializeClasses;
{
CodeUtils.addRedefineClassesListener(new CodeUtils.RedefineClassesListener() {
@Override
public void redefined(Set<Class<?>> classes) {
for (Class<?> c : classes) {
if (Recordable.class.isAssignableFrom(c)) {
TypeDefinition.Static.invalidateAll();
refreshTypes();
break;
}
}
}
});
}
/** Creates a new instance backed by the given {@code database}. */
public DatabaseEnvironment(Database database, boolean initializeClasses) {
this.database = database;
this.initializeClasses = initializeClasses;
}
/** Creates a new instance backed by the given {@code database}. */
public DatabaseEnvironment(Database database) {
this(database, true);
}
/** Returns the backing database. */
public Database getDatabase() {
return database;
}
// --- Globals and types cache ---
/** Globals are stored at FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF. */
private static final UUID GLOBALS_ID = new UUID(-1L, -1L);
/** Field where the root type is stored within the globals. */
private static final String ROOT_TYPE_FIELD = "rootType";
private volatile State globals;
private volatile Date lastGlobalsUpdate;
private volatile Date lastTypesUpdate;
private volatile TypesCache permanentTypes = new TypesCache();
private final ThreadLocal<TypesCache> temporaryTypesLocal = new ThreadLocal<TypesCache>();
/** Aggregate of all maps used to cache type information. */
private static class TypesCache {
public final Map<String, ObjectType> byClassName = new HashMap<String, ObjectType>();
public final Map<UUID, ObjectType> byId = new HashMap<UUID, ObjectType>();
public final Map<String, ObjectType> byName = new HashMap<String, ObjectType>();
public final Map<String, Set<ObjectType>> byGroup = new HashMap<String, Set<ObjectType>>();
public final Set<UUID> changed = new HashSet<UUID>();
/** Adds the given {@code type} to all type cache maps. */
public void add(ObjectType type) {
String className = type.getObjectClassName();
if (!ObjectUtils.isBlank(className)) {
byClassName.put(className, type);
}
byId.put(type.getId(), type);
String internalName = type.getInternalName();
if (!ObjectUtils.isBlank(internalName)) {
byName.put(internalName, type);
}
for (String group : type.getGroups()) {
Set<ObjectType> groupTypes = byGroup.get(group);
if (groupTypes == null) {
groupTypes = new HashSet<ObjectType>();
byGroup.put(group, groupTypes);
}
groupTypes.remove(type);
groupTypes.add(type);
}
}
}
private final AtomicBoolean bootstrapDone = new AtomicBoolean();
private final AtomicReference<Thread> bootstrapThread = new AtomicReference<Thread>();
// Bootstraps the globals and types for the first time. Most methods
// in this class should call this before performing any action.
private void bootstrap() {
if (bootstrapDone.get()) {
return;
}
Thread currentThread = Thread.currentThread();
while (true) {
if (currentThread.equals(bootstrapThread.get())) {
return;
} else if (bootstrapThread.compareAndSet(null, currentThread)) {
break;
} else {
synchronized (bootstrapThread) {
while (bootstrapThread.get() != null) {
try {
bootstrapThread.wait();
} catch (InterruptedException ex) {
return;
}
}
}
}
}
try {
// Fetch the globals, which includes a reference to the root
// type. References to other objects can't be resolved,
// because the type definitions haven't been loaded yet.
refreshGlobals();
ObjectType rootType = getRootType();
if (rootType != null) {
// This isn't cleared later, because that's done within
// {@link refreshTypes} anyway.
TypesCache temporaryTypes = temporaryTypesLocal.get();
if (temporaryTypes == null) {
temporaryTypes = new TypesCache();
temporaryTypesLocal.set(temporaryTypes);
}
temporaryTypes.add(rootType);
LOGGER.info(
"Root type ID for [{}] is [{}]",
getDatabase().getName(),
rootType.getId());
}
// Load all other types based on the root type. Then globals
// again in case they reference other typed objects. Then
// types again using the information from the fully resolved
// globals.
refreshTypes();
refreshGlobals();
refreshTypes();
refresher.scheduleWithFixedDelay(5.0, 5.0);
bootstrapDone.set(true);
} finally {
bootstrapThread.set(null);
synchronized (bootstrapThread) {
bootstrapThread.notifyAll();
}
}
}
/** Task for updating the globals and the types periodically. */
private final Task refresher = new Task(PeriodicCache.TASK_EXECUTOR_NAME, null) {
@Override
public void doTask() {
Database database = getDatabase();
Date newGlobalsUpdate = Query.
from(Object.class).
where("_id = ?", GLOBALS_ID).
using(database).
lastUpdate();
if (newGlobalsUpdate != null &&
(lastGlobalsUpdate == null ||
newGlobalsUpdate.after(lastGlobalsUpdate))) {
refreshGlobals();
}
Date newTypesUpdate = Query.
from(ObjectType.class).
using(database).
lastUpdate();
if (newTypesUpdate != null &&
(lastTypesUpdate == null ||
newTypesUpdate.after(lastTypesUpdate))) {
refreshTypes();
}
}
};
/** Immediately refreshes all globals using the backing database. */
public synchronized void refreshGlobals() {
bootstrap();
Database database = getDatabase();
LOGGER.info("Loading globals from [{}]", database.getName());
State newGlobals = State.getInstance(Query.
from(Object.class).
where("_id = ?", GLOBALS_ID).
using(database).
first());
if (newGlobals == null) {
newGlobals = new State();
newGlobals.setDatabase(database);
newGlobals.setId(GLOBALS_ID);
newGlobals.save();
}
globals = newGlobals;
lastGlobalsUpdate = new Date();
fieldsCache.invalidate();
indexesCache.invalidate();
}
/** Immediately refreshes all types using the backing database. */
public synchronized void refreshTypes() {
bootstrap();
Database database = getDatabase();
try {
TypesCache temporaryTypes = temporaryTypesLocal.get();
if (temporaryTypes == null) {
temporaryTypes = new TypesCache();
temporaryTypesLocal.set(temporaryTypes);
}
List<ObjectType> types = Query.
from(ObjectType.class).
using(database).
selectAll();
int typesSize = types.size();
LOGGER.info("Loading [{}] types from [{}]", typesSize, database.getName());
// Load all types from the database first.
for (ObjectType type : types) {
type.getFields().size(); // Pre-fetch.
temporaryTypes.add(type);
}
if (initializeClasses) {
// Make sure that the root type exists.
ObjectType rootType = getRootType();
State rootTypeState;
if (rootType != null) {
rootTypeState = rootType.getState();
} else {
rootType = new ObjectType();
rootTypeState = rootType.getState();
rootTypeState.setDatabase(database);
}
Map<String, Object> rootTypeOriginals = rootTypeState.getSimpleValues();
UUID rootTypeId = rootTypeState.getId();
rootTypeState.setTypeId(rootTypeId);
- rootTypeState.clear();
+ // rootTypeState.clear();
rootType.setObjectClassName(ObjectType.class.getName());
rootType.initialize();
temporaryTypes.add(rootType);
try {
database.beginWrites();
// Make the new root type available to other types.
temporaryTypes.add(rootType);
if (rootTypeState.isNew()) {
State globals = getGlobals();
globals.put(ROOT_TYPE_FIELD, rootType);
globals.save();
} else if (!rootTypeState.getSimpleValues().equals(rootTypeOriginals)) {
temporaryTypes.changed.add(rootTypeId);
}
Set<Class<? extends Recordable>> objectClasses = ObjectUtils.findClasses(Recordable.class);
for (Iterator<Class<? extends Recordable>> i = objectClasses.iterator(); i.hasNext(); ) {
Class<? extends Recordable> objectClass = i.next();
if (objectClass.isAnonymousClass()) {
i.remove();
}
}
Set<Class<?>> globalModifications = new HashSet<Class<?>>();
Map<ObjectType, List<Class<?>>> typeModifications = new HashMap<ObjectType, List<Class<?>>>();
// Make sure all types are accessible to the rest of the
// system as soon as possible, so that references can be
// resolved properly later.
for (Class<?> objectClass : objectClasses) {
ObjectType type = getTypeByClass(objectClass);
if (type == null) {
type = new ObjectType();
type.getState().setDatabase(database);
} else {
- type.getState().clear();
+ // type.getState().clear();
}
type.setObjectClassName(objectClass.getName());
typeModifications.put(type, new ArrayList<Class<?>>());
temporaryTypes.add(type);
}
// Separate out all modifications from regular types.
for (Class<?> objectClass : objectClasses) {
if (!Modification.class.isAssignableFrom(objectClass)) {
continue;
}
@SuppressWarnings("unchecked")
Set<Class<?>> modifiedClasses = Modification.Static.getModifiedClasses((Class<? extends Modification<?>>) objectClass);
if (modifiedClasses.contains(Object.class)) {
globalModifications.add(objectClass);
continue;
}
for (Class<?> modifiedClass : modifiedClasses) {
List<Class<?>> assignableClasses = new ArrayList<Class<?>>();
for (Class<?> c : objectClasses) {
if (modifiedClass.isAssignableFrom(c)) {
assignableClasses.add(c);
}
}
for (Class<?> assignableClass : assignableClasses) {
ObjectType type = getTypeByClass(assignableClass);
if (type != null) {
List<Class<?>> modifications = typeModifications.get(type);
if (modifications == null) {
modifications = new ArrayList<Class<?>>();
typeModifications.put(type, modifications);
}
modifications.add(objectClass);
}
}
}
}
// Apply global modifications.
for (Class<?> modification : globalModifications) {
ObjectType.modifyAll(database, modification);
}
// Initialize all types.
List<Class<?>> rootTypeModifications = typeModifications.remove(rootType);
initializeAndModify(temporaryTypes, rootType, rootTypeModifications);
if (rootTypeModifications != null) {
for (Class<?> modification : rootTypeModifications) {
ObjectType t = getTypeByClass(modification);
initializeAndModify(temporaryTypes, t, typeModifications.remove(t));
}
}
ObjectType fieldType = getTypeByClass(ObjectField.class);
List<Class<?>> fieldModifications = typeModifications.remove(fieldType);
initializeAndModify(temporaryTypes, fieldType, fieldModifications);
if (fieldModifications != null) {
for (Class<?> modification : fieldModifications) {
ObjectType t = getTypeByClass(modification);
initializeAndModify(temporaryTypes, t, typeModifications.remove(t));
}
}
for (Map.Entry<ObjectType, List<Class<?>>> entry : typeModifications.entrySet()) {
initializeAndModify(temporaryTypes, entry.getKey(), entry.getValue());
}
database.commitWrites();
} finally {
database.endWrites();
}
}
// Merge temporary types into new permanent types.
TypesCache newPermanentTypes = new TypesCache();
for (ObjectType type : permanentTypes.byId.values()) {
newPermanentTypes.add(type);
}
for (ObjectType type : temporaryTypes.byId.values()) {
newPermanentTypes.add(type);
}
newPermanentTypes.changed.addAll(temporaryTypes.changed);
newPermanentTypes.changed.addAll(permanentTypes.changed);
permanentTypes = newPermanentTypes;
lastTypesUpdate = new Date();
} finally {
temporaryTypesLocal.remove();
}
ObjectType singletonType = getTypeByClass(Singleton.class);
if (singletonType != null) {
for (ObjectType type : singletonType.findConcreteTypes()) {
if (!Query.fromType(type).hasMoreThan(0)) {
try {
State.getInstance(type.createObject(null)).save();
} catch (Exception error) {
LOGGER.warn(String.format("Can't save [%s] singleton!", type.getLabel()), error);
}
}
}
}
}
private static void initializeAndModify(TypesCache temporaryTypes, ObjectType type, List<Class<?>> modifications) {
State typeState = type.getState();
Map<String, Object> typeOriginals = typeState.getSimpleValues();
try {
type.initialize();
temporaryTypes.add(type);
// Apply type-specific modifications.
if (modifications != null) {
for (Class<?> modification : modifications) {
type.modify(modification);
}
}
} catch (IncompatibleClassChangeError ex) {
LOGGER.info(
"Skipped initializing [{}] because its class is in an inconsistent state! ([{}])",
type.getInternalName(),
ex.getMessage());
}
if (typeState.isNew()) {
type.save();
} else if (!typeState.getSimpleValues().equals(typeOriginals)) {
temporaryTypes.changed.add(type.getId());
}
}
/**
* Returns all global values.
*
* @return May be {@code null}.
*/
public State getGlobals() {
bootstrap();
return globals;
}
// Returns the root type from the globals.
private ObjectType getRootType() {
State globals = getGlobals();
if (globals != null) {
Object rootType = globals.get(ROOT_TYPE_FIELD);
if (rootType == null) {
rootType = globals.get("rootRecordType");
}
if (rootType instanceof ObjectType) {
return (ObjectType) rootType;
}
}
return null;
}
// --- ObjectStruct support ---
@Override
public DatabaseEnvironment getEnvironment() {
return this;
}
@Override
public List<ObjectField> getFields() {
return new ArrayList<ObjectField>(fieldsCache.get().values());
}
private final PullThroughValue<Map<String, ObjectField>> fieldsCache = new PullThroughValue<Map<String, ObjectField>>() {
@Override
@SuppressWarnings("unchecked")
protected Map<String, ObjectField> produce() {
State globals = getGlobals();
Object definitions = globals != null ? globals.get(GLOBAL_FIELDS_FIELD) : null;
return ObjectField.Static.convertDefinitionsToInstances(
DatabaseEnvironment.this,
definitions instanceof List ?
(List<Map<String, Object>>) definitions :
null);
}
};
@Override
public ObjectField getField(String name) {
return fieldsCache.get().get(name);
}
@Override
public void setFields(List<ObjectField> fields) {
getGlobals().put(GLOBAL_FIELDS_FIELD, ObjectField.Static.convertInstancesToDefinitions(fields));
fieldsCache.invalidate();
}
@Override
public List<ObjectIndex> getIndexes() {
return new ArrayList<ObjectIndex>(indexesCache.get().values());
}
private final PullThroughValue<Map<String, ObjectIndex>> indexesCache = new PullThroughValue<Map<String, ObjectIndex>>() {
@Override
@SuppressWarnings("unchecked")
protected Map<String, ObjectIndex> produce() {
State globals = getGlobals();
Object definitions = globals != null ? globals.get(GLOBAL_INDEXES_FIELD) : null;
return ObjectIndex.Static.convertDefinitionsToInstances(
DatabaseEnvironment.this,
definitions instanceof List ?
(List<Map<String, Object>>) definitions :
null);
}
};
@Override
public ObjectIndex getIndex(String name) {
return indexesCache.get().get(name);
}
@Override
public void setIndexes(List<ObjectIndex> indexes) {
getGlobals().put(GLOBAL_INDEXES_FIELD, ObjectIndex.Static.convertInstancesToDefinitions(indexes));
indexesCache.invalidate();
}
/**
* Initializes the given {@code objectClasses} so that they are
* usable as {@linkplain ObjectType types}.
*/
public void initializeTypes(Iterable<Class<?>> objectClasses) {
bootstrap();
Set<String> classNames = new HashSet<String>();
for (Class<?> objectClass : objectClasses) {
classNames.add(objectClass.getName());
}
for (ObjectType type : getTypes()) {
UUID id = type.getId();
if (classNames.contains(type.getObjectClassName())) {
TypesCache temporaryTypes = temporaryTypesLocal.get();
if ((temporaryTypes != null &&
temporaryTypesLocal.get().changed.contains(id)) ||
permanentTypes.changed.contains(id)) {
type.save();
}
}
}
}
/**
* Returns all types.
* @return Never {@code null}. May be modified without any side effects.
*/
public Set<ObjectType> getTypes() {
bootstrap();
Set<ObjectType> types = new HashSet<ObjectType>();
TypesCache temporaryTypes = temporaryTypesLocal.get();
if (temporaryTypes != null) {
types.addAll(temporaryTypes.byId.values());
}
types.addAll(permanentTypes.byId.values());
return types;
}
/**
* Returns the type associated with the given {@code id}.
* @return May be {@code null}.
*/
public ObjectType getTypeById(UUID id) {
bootstrap();
TypesCache temporaryTypes = temporaryTypesLocal.get();
if (temporaryTypes != null) {
ObjectType type = temporaryTypes.byId.get(id);
if (type != null) {
return type;
}
}
return permanentTypes.byId.get(id);
}
/**
* Returns the type associated with the given {@code objectClass}.
* @return May be {@code null}.
*/
public ObjectType getTypeByName(String name) {
bootstrap();
TypesCache temporaryTypes = temporaryTypesLocal.get();
if (temporaryTypes != null) {
ObjectType type = temporaryTypes.byName.get(name);
if (type != null) {
return type;
}
}
return permanentTypes.byName.get(name);
}
/**
* Returns a set of types associated with the given {@code group}.
* @return Never {@code null}. May be modified without any side effects.
*/
public Set<ObjectType> getTypesByGroup(String group) {
bootstrap();
TypesCache temporaryTypes = temporaryTypesLocal.get();
Set<ObjectType> tTypes;
if (temporaryTypes != null) {
tTypes = temporaryTypes.byGroup.get(group);
} else {
tTypes = null;
}
Set<ObjectType> pTypes = permanentTypes.byGroup.get(group);
if (tTypes == null) {
return pTypes == null ?
new HashSet<ObjectType>() :
new HashSet<ObjectType>(pTypes);
} else {
tTypes = new HashSet<ObjectType>(tTypes);
if (pTypes != null) {
tTypes.addAll(pTypes);
}
return tTypes;
}
}
/**
* Returns the type associated with the given {@code objectClass}.
* @return May be {@code null}.
*/
public ObjectType getTypeByClass(Class<?> objectClass) {
bootstrap();
String className = objectClass.getName();
TypesCache temporaryTypes = temporaryTypesLocal.get();
if (temporaryTypes != null) {
ObjectType type = temporaryTypes.byClassName.get(className);
if (type != null) {
return type;
}
}
return permanentTypes.byClassName.get(className);
}
/**
* Creates an object represented by the given {@code typeId} and
* {@code id}.
*/
public Object createObject(UUID typeId, UUID id) {
bootstrap();
Class<?> objectClass = null;
ObjectType type = null;
if (typeId != null && !GLOBALS_ID.equals(id)) {
if (typeId.equals(id)) {
objectClass = ObjectType.class;
} else {
type = getTypeById(typeId);
if (type != null) {
objectClass = type.isAbstract() ?
Record.class :
type.getObjectClass();
}
}
}
boolean hasClass = true;
if (objectClass == null) {
objectClass = Record.class;
hasClass = false;
}
Object object = TypeDefinition.getInstance(objectClass).newInstance();
State state = State.getInstance(object);
state.setDatabase(getDatabase());
state.setId(id);
state.setTypeId(typeId);
if (type != null && !hasClass) {
for (ObjectField field : type.getFields()) {
Object defaultValue = field.getDefaultValue();
if (defaultValue != null) {
state.put(field.getInternalName(), defaultValue);
}
}
}
return object;
}
// --- Deprecated ---
/** @deprecated Use {@link #getGlobals} instead. */
@Deprecated
public Object getGlobal(String key) {
State globals = getGlobals();
return globals != null ? globals.getValue(key) : null;
}
/** @deprecated Use {@link #getGlobals} instead. */
@Deprecated
public void putGlobal(String key, Object value) {
State globals = getGlobals();
globals.putValue(key, value);
globals.save();
}
}
| false | true | public synchronized void refreshTypes() {
bootstrap();
Database database = getDatabase();
try {
TypesCache temporaryTypes = temporaryTypesLocal.get();
if (temporaryTypes == null) {
temporaryTypes = new TypesCache();
temporaryTypesLocal.set(temporaryTypes);
}
List<ObjectType> types = Query.
from(ObjectType.class).
using(database).
selectAll();
int typesSize = types.size();
LOGGER.info("Loading [{}] types from [{}]", typesSize, database.getName());
// Load all types from the database first.
for (ObjectType type : types) {
type.getFields().size(); // Pre-fetch.
temporaryTypes.add(type);
}
if (initializeClasses) {
// Make sure that the root type exists.
ObjectType rootType = getRootType();
State rootTypeState;
if (rootType != null) {
rootTypeState = rootType.getState();
} else {
rootType = new ObjectType();
rootTypeState = rootType.getState();
rootTypeState.setDatabase(database);
}
Map<String, Object> rootTypeOriginals = rootTypeState.getSimpleValues();
UUID rootTypeId = rootTypeState.getId();
rootTypeState.setTypeId(rootTypeId);
rootTypeState.clear();
rootType.setObjectClassName(ObjectType.class.getName());
rootType.initialize();
temporaryTypes.add(rootType);
try {
database.beginWrites();
// Make the new root type available to other types.
temporaryTypes.add(rootType);
if (rootTypeState.isNew()) {
State globals = getGlobals();
globals.put(ROOT_TYPE_FIELD, rootType);
globals.save();
} else if (!rootTypeState.getSimpleValues().equals(rootTypeOriginals)) {
temporaryTypes.changed.add(rootTypeId);
}
Set<Class<? extends Recordable>> objectClasses = ObjectUtils.findClasses(Recordable.class);
for (Iterator<Class<? extends Recordable>> i = objectClasses.iterator(); i.hasNext(); ) {
Class<? extends Recordable> objectClass = i.next();
if (objectClass.isAnonymousClass()) {
i.remove();
}
}
Set<Class<?>> globalModifications = new HashSet<Class<?>>();
Map<ObjectType, List<Class<?>>> typeModifications = new HashMap<ObjectType, List<Class<?>>>();
// Make sure all types are accessible to the rest of the
// system as soon as possible, so that references can be
// resolved properly later.
for (Class<?> objectClass : objectClasses) {
ObjectType type = getTypeByClass(objectClass);
if (type == null) {
type = new ObjectType();
type.getState().setDatabase(database);
} else {
type.getState().clear();
}
type.setObjectClassName(objectClass.getName());
typeModifications.put(type, new ArrayList<Class<?>>());
temporaryTypes.add(type);
}
// Separate out all modifications from regular types.
for (Class<?> objectClass : objectClasses) {
if (!Modification.class.isAssignableFrom(objectClass)) {
continue;
}
@SuppressWarnings("unchecked")
Set<Class<?>> modifiedClasses = Modification.Static.getModifiedClasses((Class<? extends Modification<?>>) objectClass);
if (modifiedClasses.contains(Object.class)) {
globalModifications.add(objectClass);
continue;
}
for (Class<?> modifiedClass : modifiedClasses) {
List<Class<?>> assignableClasses = new ArrayList<Class<?>>();
for (Class<?> c : objectClasses) {
if (modifiedClass.isAssignableFrom(c)) {
assignableClasses.add(c);
}
}
for (Class<?> assignableClass : assignableClasses) {
ObjectType type = getTypeByClass(assignableClass);
if (type != null) {
List<Class<?>> modifications = typeModifications.get(type);
if (modifications == null) {
modifications = new ArrayList<Class<?>>();
typeModifications.put(type, modifications);
}
modifications.add(objectClass);
}
}
}
}
// Apply global modifications.
for (Class<?> modification : globalModifications) {
ObjectType.modifyAll(database, modification);
}
// Initialize all types.
List<Class<?>> rootTypeModifications = typeModifications.remove(rootType);
initializeAndModify(temporaryTypes, rootType, rootTypeModifications);
if (rootTypeModifications != null) {
for (Class<?> modification : rootTypeModifications) {
ObjectType t = getTypeByClass(modification);
initializeAndModify(temporaryTypes, t, typeModifications.remove(t));
}
}
ObjectType fieldType = getTypeByClass(ObjectField.class);
List<Class<?>> fieldModifications = typeModifications.remove(fieldType);
initializeAndModify(temporaryTypes, fieldType, fieldModifications);
if (fieldModifications != null) {
for (Class<?> modification : fieldModifications) {
ObjectType t = getTypeByClass(modification);
initializeAndModify(temporaryTypes, t, typeModifications.remove(t));
}
}
for (Map.Entry<ObjectType, List<Class<?>>> entry : typeModifications.entrySet()) {
initializeAndModify(temporaryTypes, entry.getKey(), entry.getValue());
}
database.commitWrites();
} finally {
database.endWrites();
}
}
// Merge temporary types into new permanent types.
TypesCache newPermanentTypes = new TypesCache();
for (ObjectType type : permanentTypes.byId.values()) {
newPermanentTypes.add(type);
}
for (ObjectType type : temporaryTypes.byId.values()) {
newPermanentTypes.add(type);
}
newPermanentTypes.changed.addAll(temporaryTypes.changed);
newPermanentTypes.changed.addAll(permanentTypes.changed);
permanentTypes = newPermanentTypes;
lastTypesUpdate = new Date();
} finally {
temporaryTypesLocal.remove();
}
ObjectType singletonType = getTypeByClass(Singleton.class);
if (singletonType != null) {
for (ObjectType type : singletonType.findConcreteTypes()) {
if (!Query.fromType(type).hasMoreThan(0)) {
try {
State.getInstance(type.createObject(null)).save();
} catch (Exception error) {
LOGGER.warn(String.format("Can't save [%s] singleton!", type.getLabel()), error);
}
}
}
}
}
| public synchronized void refreshTypes() {
bootstrap();
Database database = getDatabase();
try {
TypesCache temporaryTypes = temporaryTypesLocal.get();
if (temporaryTypes == null) {
temporaryTypes = new TypesCache();
temporaryTypesLocal.set(temporaryTypes);
}
List<ObjectType> types = Query.
from(ObjectType.class).
using(database).
selectAll();
int typesSize = types.size();
LOGGER.info("Loading [{}] types from [{}]", typesSize, database.getName());
// Load all types from the database first.
for (ObjectType type : types) {
type.getFields().size(); // Pre-fetch.
temporaryTypes.add(type);
}
if (initializeClasses) {
// Make sure that the root type exists.
ObjectType rootType = getRootType();
State rootTypeState;
if (rootType != null) {
rootTypeState = rootType.getState();
} else {
rootType = new ObjectType();
rootTypeState = rootType.getState();
rootTypeState.setDatabase(database);
}
Map<String, Object> rootTypeOriginals = rootTypeState.getSimpleValues();
UUID rootTypeId = rootTypeState.getId();
rootTypeState.setTypeId(rootTypeId);
// rootTypeState.clear();
rootType.setObjectClassName(ObjectType.class.getName());
rootType.initialize();
temporaryTypes.add(rootType);
try {
database.beginWrites();
// Make the new root type available to other types.
temporaryTypes.add(rootType);
if (rootTypeState.isNew()) {
State globals = getGlobals();
globals.put(ROOT_TYPE_FIELD, rootType);
globals.save();
} else if (!rootTypeState.getSimpleValues().equals(rootTypeOriginals)) {
temporaryTypes.changed.add(rootTypeId);
}
Set<Class<? extends Recordable>> objectClasses = ObjectUtils.findClasses(Recordable.class);
for (Iterator<Class<? extends Recordable>> i = objectClasses.iterator(); i.hasNext(); ) {
Class<? extends Recordable> objectClass = i.next();
if (objectClass.isAnonymousClass()) {
i.remove();
}
}
Set<Class<?>> globalModifications = new HashSet<Class<?>>();
Map<ObjectType, List<Class<?>>> typeModifications = new HashMap<ObjectType, List<Class<?>>>();
// Make sure all types are accessible to the rest of the
// system as soon as possible, so that references can be
// resolved properly later.
for (Class<?> objectClass : objectClasses) {
ObjectType type = getTypeByClass(objectClass);
if (type == null) {
type = new ObjectType();
type.getState().setDatabase(database);
} else {
// type.getState().clear();
}
type.setObjectClassName(objectClass.getName());
typeModifications.put(type, new ArrayList<Class<?>>());
temporaryTypes.add(type);
}
// Separate out all modifications from regular types.
for (Class<?> objectClass : objectClasses) {
if (!Modification.class.isAssignableFrom(objectClass)) {
continue;
}
@SuppressWarnings("unchecked")
Set<Class<?>> modifiedClasses = Modification.Static.getModifiedClasses((Class<? extends Modification<?>>) objectClass);
if (modifiedClasses.contains(Object.class)) {
globalModifications.add(objectClass);
continue;
}
for (Class<?> modifiedClass : modifiedClasses) {
List<Class<?>> assignableClasses = new ArrayList<Class<?>>();
for (Class<?> c : objectClasses) {
if (modifiedClass.isAssignableFrom(c)) {
assignableClasses.add(c);
}
}
for (Class<?> assignableClass : assignableClasses) {
ObjectType type = getTypeByClass(assignableClass);
if (type != null) {
List<Class<?>> modifications = typeModifications.get(type);
if (modifications == null) {
modifications = new ArrayList<Class<?>>();
typeModifications.put(type, modifications);
}
modifications.add(objectClass);
}
}
}
}
// Apply global modifications.
for (Class<?> modification : globalModifications) {
ObjectType.modifyAll(database, modification);
}
// Initialize all types.
List<Class<?>> rootTypeModifications = typeModifications.remove(rootType);
initializeAndModify(temporaryTypes, rootType, rootTypeModifications);
if (rootTypeModifications != null) {
for (Class<?> modification : rootTypeModifications) {
ObjectType t = getTypeByClass(modification);
initializeAndModify(temporaryTypes, t, typeModifications.remove(t));
}
}
ObjectType fieldType = getTypeByClass(ObjectField.class);
List<Class<?>> fieldModifications = typeModifications.remove(fieldType);
initializeAndModify(temporaryTypes, fieldType, fieldModifications);
if (fieldModifications != null) {
for (Class<?> modification : fieldModifications) {
ObjectType t = getTypeByClass(modification);
initializeAndModify(temporaryTypes, t, typeModifications.remove(t));
}
}
for (Map.Entry<ObjectType, List<Class<?>>> entry : typeModifications.entrySet()) {
initializeAndModify(temporaryTypes, entry.getKey(), entry.getValue());
}
database.commitWrites();
} finally {
database.endWrites();
}
}
// Merge temporary types into new permanent types.
TypesCache newPermanentTypes = new TypesCache();
for (ObjectType type : permanentTypes.byId.values()) {
newPermanentTypes.add(type);
}
for (ObjectType type : temporaryTypes.byId.values()) {
newPermanentTypes.add(type);
}
newPermanentTypes.changed.addAll(temporaryTypes.changed);
newPermanentTypes.changed.addAll(permanentTypes.changed);
permanentTypes = newPermanentTypes;
lastTypesUpdate = new Date();
} finally {
temporaryTypesLocal.remove();
}
ObjectType singletonType = getTypeByClass(Singleton.class);
if (singletonType != null) {
for (ObjectType type : singletonType.findConcreteTypes()) {
if (!Query.fromType(type).hasMoreThan(0)) {
try {
State.getInstance(type.createObject(null)).save();
} catch (Exception error) {
LOGGER.warn(String.format("Can't save [%s] singleton!", type.getLabel()), error);
}
}
}
}
}
|
diff --git a/cebu-server/app/utils/DistanceCache.java b/cebu-server/app/utils/DistanceCache.java
index a584406..5425a48 100644
--- a/cebu-server/app/utils/DistanceCache.java
+++ b/cebu-server/app/utils/DistanceCache.java
@@ -1,101 +1,101 @@
package utils;
import java.util.HashMap;
import java.util.List;
import javax.persistence.Query;
import org.codehaus.groovy.tools.shell.util.Logger;
import org.geotools.geometry.jts.JTS;
import com.vividsolutions.jts.geom.Coordinate;
import akka.event.Logging;
import models.Phone;
import models.StreetEdge;
import models.Vehicle;
import models.VehicleDistance;
public class DistanceCache {
HashMap<Vehicle,Coordinate> vechiclePositions = new HashMap<Vehicle,Coordinate>();
HashMap<Vehicle,Double> vehicleDistance = new HashMap<Vehicle,Double>();
HashMap<String,Vehicle> vehicleImeiLinks = new HashMap<String,Vehicle>();
public void linkImeiToVehicle(String imei, Vehicle vehicle)
{
vehicleImeiLinks.put(imei, vehicle);
}
public Double updateDistance(String imei, Coordinate newCoord, Double error)
{
Double distance = 0.0;
Vehicle vehicle = vehicleImeiLinks.get(imei);
if(vehicle == null)
{
Phone phone = Phone.find("imei = ?", imei).first();
if(phone == null)
return 0.0;
vehicle = phone.vehicle;
vehicleImeiLinks.put(imei, vehicle);
}
if(vechiclePositions.containsKey(vehicle))
{
Coordinate oldCoord = vechiclePositions.get(vehicle);
try
{
distance = JTS.orthodromicDistance(newCoord,oldCoord,org.geotools.referencing.crs.DefaultGeographicCRS.WGS84);
}
catch(Exception e)
{
}
play.Logger.info("Distance traveled for IMEI " + imei + ": " + distance + "(" + error + ")");
- if(distance < (error * 2))
+ if(distance < (error * 4))
distance = 0.0;
else
vechiclePositions.put(vehicle, newCoord);
synchronized(vehicleDistance)
{
if(vehicleDistance.containsKey(vehicle))
vehicleDistance.put(vehicle, vehicleDistance.get(vehicle) + distance);
else
vehicleDistance.put(vehicle, distance);
}
}
else
vechiclePositions.put(vehicle, newCoord);
flushDistances();
return distance;
}
public void flushDistances()
{
synchronized(vehicleDistance)
{
for(Vehicle vehicle : vehicleDistance.keySet())
{
VehicleDistance.updateDistanceTraveled(vehicle, vehicleDistance.get(vehicle));
vehicleDistance.remove(vehicle);
}
}
}
}
| true | true | public Double updateDistance(String imei, Coordinate newCoord, Double error)
{
Double distance = 0.0;
Vehicle vehicle = vehicleImeiLinks.get(imei);
if(vehicle == null)
{
Phone phone = Phone.find("imei = ?", imei).first();
if(phone == null)
return 0.0;
vehicle = phone.vehicle;
vehicleImeiLinks.put(imei, vehicle);
}
if(vechiclePositions.containsKey(vehicle))
{
Coordinate oldCoord = vechiclePositions.get(vehicle);
try
{
distance = JTS.orthodromicDistance(newCoord,oldCoord,org.geotools.referencing.crs.DefaultGeographicCRS.WGS84);
}
catch(Exception e)
{
}
play.Logger.info("Distance traveled for IMEI " + imei + ": " + distance + "(" + error + ")");
if(distance < (error * 2))
distance = 0.0;
else
vechiclePositions.put(vehicle, newCoord);
synchronized(vehicleDistance)
{
if(vehicleDistance.containsKey(vehicle))
vehicleDistance.put(vehicle, vehicleDistance.get(vehicle) + distance);
else
vehicleDistance.put(vehicle, distance);
}
}
else
vechiclePositions.put(vehicle, newCoord);
flushDistances();
return distance;
}
| public Double updateDistance(String imei, Coordinate newCoord, Double error)
{
Double distance = 0.0;
Vehicle vehicle = vehicleImeiLinks.get(imei);
if(vehicle == null)
{
Phone phone = Phone.find("imei = ?", imei).first();
if(phone == null)
return 0.0;
vehicle = phone.vehicle;
vehicleImeiLinks.put(imei, vehicle);
}
if(vechiclePositions.containsKey(vehicle))
{
Coordinate oldCoord = vechiclePositions.get(vehicle);
try
{
distance = JTS.orthodromicDistance(newCoord,oldCoord,org.geotools.referencing.crs.DefaultGeographicCRS.WGS84);
}
catch(Exception e)
{
}
play.Logger.info("Distance traveled for IMEI " + imei + ": " + distance + "(" + error + ")");
if(distance < (error * 4))
distance = 0.0;
else
vechiclePositions.put(vehicle, newCoord);
synchronized(vehicleDistance)
{
if(vehicleDistance.containsKey(vehicle))
vehicleDistance.put(vehicle, vehicleDistance.get(vehicle) + distance);
else
vehicleDistance.put(vehicle, distance);
}
}
else
vechiclePositions.put(vehicle, newCoord);
flushDistances();
return distance;
}
|
diff --git a/src/java/net/sf/jabref/imports/IEEEXploreFetcher.java b/src/java/net/sf/jabref/imports/IEEEXploreFetcher.java
index d132579b9..57dc6c5b6 100644
--- a/src/java/net/sf/jabref/imports/IEEEXploreFetcher.java
+++ b/src/java/net/sf/jabref/imports/IEEEXploreFetcher.java
@@ -1,774 +1,777 @@
/* Copyright (C) 2003-2011 JabRef contributors.
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 net.sf.jabref.imports;
import java.awt.BorderLayout;
import java.io.BufferedReader;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ConnectException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBox;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import net.sf.jabref.BibtexDatabase;
import net.sf.jabref.BibtexEntry;
import net.sf.jabref.BibtexEntryType;
import net.sf.jabref.GUIGlobals;
import net.sf.jabref.Globals;
import net.sf.jabref.OutputPrinter;
import net.sf.jabref.Util;
public class IEEEXploreFetcher implements EntryFetcher {
final CaseKeeperList caseKeeperList = new CaseKeeperList();
final CaseKeeper caseKeeper = new CaseKeeper();
ImportInspector dialog = null;
OutputPrinter status;
final HTMLConverter htmlConverter = new HTMLConverter();
private JCheckBox absCheckBox = new JCheckBox(Globals.lang("Include abstracts"), false);
private JRadioButton htmlButton = new JRadioButton(Globals.lang("HTML parser"));
private JRadioButton bibButton = new JRadioButton(Globals.lang("BibTeX importer"));
private static final int MAX_FETCH = 100;
private int perPage = MAX_FETCH, hits = 0, unparseable = 0, parsed = 0;
private int piv = 0;
private boolean shouldContinue = false;
private boolean includeAbstract = false;
private boolean importBibtex = false;
private String terms;
private final String startUrl = "http://ieeexplore.ieee.org/search/freesearchresult.jsp?queryText=";
private final String endUrl = "&rowsPerPage=" + Integer.toString(perPage) + "&pageNumber=";
private String searchUrl;
private final String importUrl = "http://ieeexplore.ieee.org/xpls/downloadCitations";
private final Pattern hitsPattern = Pattern.compile("([0-9,]+) Results");
private final Pattern idPattern = Pattern.compile("<input name=\'\' title=\'.*\' type=\'checkbox\'" +
"value=\'\'\\s*id=\'([0-9]+)\'/>");
private final Pattern typePattern = Pattern.compile("<span class=\"type\">\\s*(.+)");
private HashMap<String, String> fieldPatterns = new HashMap<String, String>();
private final Pattern absPattern = Pattern.compile("<p>\\s*(.+)");
Pattern stdEntryPattern = Pattern.compile(".*<strong>(.+)</strong><br>"
+ "\\s+(.+)");
Pattern publicationPattern = Pattern.compile("(.*), \\d*\\.*\\s?(.*)");
Pattern proceedingPattern = Pattern.compile("(.*?)\\.?\\s?Proceedings\\s?(.*)");
Pattern abstractLinkPattern = Pattern.compile(
"<a href=\'(.+)\'>\\s*<span class=\"more\">View full.*</span> </a>");
String abrvPattern = ".*[^,] '?\\d+\\)?";
Pattern ieeeArticleNumberPattern = Pattern.compile("<a href=\".*arnumber=(\\d+).*\">");
// Common words in IEEE Xplore that should always be
public IEEEXploreFetcher() {
super();
fieldPatterns.put("title", "<a\\s*href=[^<]+>\\s*(.+)\\s*</a>");
fieldPatterns.put("author", "</h3>\\s*(.+)");
fieldPatterns.put("volume", "Volume:\\s*([A-Za-z-]*\\d+)");
fieldPatterns.put("number", "Issue:\\s*(\\d+)");
//fieldPatterns.put("part", "Part (\\d+), (.+)");
fieldPatterns.put("year", "(?:Copyright|Publication) Year:\\s*(\\d{4})");
fieldPatterns.put("pages", "Page\\(s\\):\\s*(\\d+)\\s*-\\s*(\\d*)");
//fieldPatterns.put("doi", "Digital Object Identifier:\\s*<a href=.*>(.+)</a>");
fieldPatterns.put("doi", "<a href=\"http://dx.doi.org/(.+)\" target");
fieldPatterns.put("url", "<a href=\"(/stamp/stamp[^\"]+)");
}
public JPanel getOptionsPanel() {
JPanel pan = new JPanel();
pan.setLayout(new BorderLayout());
htmlButton.setSelected(true);
htmlButton.setEnabled(false);
bibButton.setEnabled(false);
ButtonGroup group = new ButtonGroup();
group.add(htmlButton);
group.add(bibButton);
pan.add(absCheckBox, BorderLayout.NORTH);
pan.add(htmlButton, BorderLayout.CENTER);
pan.add(bibButton, BorderLayout.EAST);
return pan;
}
public boolean processQuery(String query, ImportInspector dialog, OutputPrinter status) {
this.dialog = dialog;
this.status = status;
terms = query;
piv = 0;
shouldContinue = true;
parsed = 0;
unparseable = 0;
int pageNumber = 1;
searchUrl = makeUrl(pageNumber);//start at page 1
try {
URL url = new URL(searchUrl);
String page = getResults(url);
if (page.indexOf("You have entered an invalid search") >= 0) {
status.showMessage(Globals.lang("You have entered an invalid search '%0'.",
terms),
Globals.lang("Search IEEEXplore"), JOptionPane.INFORMATION_MESSAGE);
return false;
}
if (page.indexOf("Bad request") >= 0) {
status.showMessage(Globals.lang("Bad Request '%0'.",
terms),
Globals.lang("Search IEEEXplore"), JOptionPane.INFORMATION_MESSAGE);
return false;
}
if (page.indexOf("No results were found.") >= 0) {
status.showMessage(Globals.lang("No entries found for the search string '%0'",
terms),
Globals.lang("Search IEEEXplore"), JOptionPane.INFORMATION_MESSAGE);
return false;
}
if (page.indexOf("Error Page") >= 0) {
status.showMessage(Globals.lang("Intermittent errors on the IEEE Xplore server. Please try again in a while."),
Globals.lang("Search IEEEXplore"), JOptionPane.INFORMATION_MESSAGE);
return false;
}
hits = getNumberOfHits(page, "display-status", hitsPattern);
includeAbstract = absCheckBox.isSelected();
importBibtex = bibButton.isSelected();
if (hits > MAX_FETCH) {
status.showMessage(Globals.lang("%0 entries found. To reduce server load, "
+"only %1 will be downloaded.",
new String[] {String.valueOf(hits), String.valueOf(MAX_FETCH)}),
Globals.lang("Search IEEEXplore"), JOptionPane.INFORMATION_MESSAGE);
hits = MAX_FETCH;
}
parse(dialog, page, 0, 1);
int firstEntry = perPage;
while (shouldContinue && firstEntry < hits) {
pageNumber++;
searchUrl = makeUrl(pageNumber);
page = getResults(new URL(searchUrl));
if (!shouldContinue)
break;
parse(dialog, page, 0, firstEntry + 1);
firstEntry += perPage;
}
return true;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ConnectException e) {
status.showMessage(Globals.lang("Connection to IEEEXplore failed"),
Globals.lang("Search IEEEXplore"), JOptionPane.ERROR_MESSAGE);
} catch (IOException e) {
status.showMessage(Globals.lang(e.getMessage()),
Globals.lang("Search IEEEXplore"), JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
return false;
}
public String getTitle() {
return "IEEEXplore";
}
public URL getIcon() {
return GUIGlobals.getIconUrl("www");
}
public String getHelpPage() {
return "IEEEXploreHelp.html";
}
public String getKeyName() {
return "IEEEXplore";
}
/**
* This method is called by the dialog when the user has cancelled the import.
*/
public void stopFetching() {
shouldContinue = false;
}
private String makeUrl(int startIndex) {
StringBuffer sb = new StringBuffer(startUrl);
sb.append(terms.replaceAll(" ", "+"));
sb.append(endUrl);
sb.append(String.valueOf(startIndex));
return sb.toString();
}
private void parse(ImportInspector dialog, String text, int startIndex, int firstEntryNumber) {
piv = startIndex;
int entryNumber = firstEntryNumber;
if (importBibtex) {
//TODO: Login
ArrayList<String> idSelected = new ArrayList<String>();
String id;
while ((id = parseNextEntryId(text, piv)) != null && shouldContinue) {
idSelected.add(id);
entryNumber++;
}
try {
BibtexDatabase dbase = parseBibtexDatabase(idSelected, includeAbstract);
Collection<BibtexEntry> items = dbase.getEntries();
Iterator<BibtexEntry> iter = items.iterator();
while (iter.hasNext()) {
BibtexEntry entry = iter.next();
dialog.addEntry(cleanup(entry));
dialog.setProgress(parsed + unparseable, hits);
parsed++;
}
} catch (IOException e) {
e.printStackTrace();
}
//for
} else {
BibtexEntry entry;
while (((entry = parseNextEntry(text, piv)) != null) && shouldContinue) {
if (entry.getField("title") != null) {
dialog.addEntry(entry);
dialog.setProgress(parsed + unparseable, hits);
parsed++;
}
entryNumber++;
}
}
}
private BibtexDatabase parseBibtexDatabase(List<String> id, boolean abs) throws IOException {
if (id.isEmpty())
return null;
URL url;
URLConnection conn;
try {
url = new URL(importUrl);
conn = url.openConnection();
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
}
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
conn.setRequestProperty("Referer", searchUrl);
PrintWriter out = new PrintWriter(
conn.getOutputStream());
String recordIds = "";
Iterator<String> iter = id.iterator();
while (iter.hasNext()) {
recordIds += iter.next() + " ";
}
recordIds = recordIds.trim();
String citation = abs ? "citation-abstract" : "citation-only";
String content = "recordIds=" + recordIds.replaceAll(" ", "%20") + "&fromPageName=&citations-format=" + citation + "&download-format=download-bibtex";
System.out.println(content);
out.write(content);
out.flush();
out.close();
BufferedReader bufr = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer();
char[] buffer = new char[256];
while(true) {
int bytesRead = bufr.read(buffer);
if(bytesRead == -1) break;
for (int i=0; i<bytesRead; i++)
sb.append((char)buffer[i]);
}
System.out.println(sb.toString());
ParserResult results = new BibtexParser(bufr).parse();
bufr.close();
return results.getDatabase();
}
private BibtexEntry cleanup(BibtexEntry entry) {
if (entry == null)
return null;
// clean up title
String title = (String)entry.getField("title");
if (title != null) {
// USe the alt-text and replace image links
title = title.replaceAll("[ ]?img src=[^ ]+ alt=\"([^\"]+)\">[ ]?", "\\$$1\\$");
// Try to sort out most of the /spl / conversions
// Deal with this specific nested type first
title = title.replaceAll("/sub /spl infin//", "\\$_\\\\infty\\$");
title = title.replaceAll("/sup /spl infin//", "\\$\\^\\\\infty\\$");
// Replace general expressions
title = title.replaceAll("/[sS]pl ([^/]+)/", "\\$\\\\$1\\$");
// Deal with subscripts and superscripts
if (Globals.prefs.getBoolean("useConvertToEquation")) {
title = title.replaceAll("/sup ([^/]+)/", "\\$\\^\\{$1\\}\\$");
title = title.replaceAll("/sub ([^/]+)/", "\\$_\\{$1\\}\\$");
title = title.replaceAll("\\(sup\\)([^(]+)\\(/sup\\)", "\\$\\^\\{$1\\}\\$");
title = title.replaceAll("\\(sub\\)([^(]+)\\(/sub\\)", "\\_\\{$1\\}\\$");
} else {
title = title.replaceAll("/sup ([^/]+)/", "\\\\textsuperscript\\{$1\\}");
title = title.replaceAll("/sub ([^/]+)/", "\\\\textsubscript\\{$1\\}");
title = title.replaceAll("\\(sup\\)([^(]+)\\(/sup\\)", "\\\\textsuperscript\\{$1\\}");
title = title.replaceAll("\\(sub\\)([^(]+)\\(/sub\\)", "\\\\textsubscript\\{$1\\}");
}
// Replace \infin with \infty
title = title.replaceAll("\\\\infin", "\\\\infty");
// Automatic case keeping
if (Globals.prefs.getBoolean("useCaseKeeperOnSearch")) {
title = caseKeeper.format(title, caseKeeperList.wordListIEEEXplore);
}
// Write back
entry.setField("title", title);
}
// clean up author
String author = (String)entry.getField("author");
if (author != null) {
if (author.indexOf("a href=") >= 0) { // Author parsing failed because it was empty
entry.setField("author",""); // Maybe not needed anymore due to another change
} else {
author = author.replaceAll("\\.", ". ");
+ author = author.replaceAll("([^;]+),([^;]+),([^;]+)","$1,$3,$2"); // Change order in case of Jr. etc
author = author.replaceAll(" ", " ");
author = author.replaceAll("\\. -", ".-");
- author = author.replaceAll("; ", " and ");
- author = author.replaceAll("[,;]$", "");
+ author = author.replaceAll("; ", " and ");
+ author = author.replaceAll(" ,", ",");
+ author = author.replaceAll(" ", " ");
+ author = author.replaceAll("[ ,;]+$", "");
entry.setField("author", author);
}
}
// clean up month
String month = (String)entry.getField("month");
if ((month != null) && (month.length() > 0)) {
month = month.replaceAll("\\.", "");
month = month.toLowerCase();
Pattern monthPattern = Pattern.compile("(\\d*+)\\s*([a-z]*+)-*(\\d*+)\\s*([a-z]*+)");
Matcher mm = monthPattern.matcher(month);
String date = month;
if (mm.find()) {
if (mm.group(3).length() == 0) {
if (mm.group(2).length() > 0) {
date = "#" + mm.group(2).substring(0, 3) + "#";
if (mm.group(1).length() > 0) {
date += " " + mm.group(1) + ",";
}
} else {
date = mm.group(1) + ",";
}
} else if (mm.group(2).length() == 0) {
if (mm.group(4).length() > 0) {
date = "#" + mm.group(4).substring(0, 3) + "# " + mm.group(1) + "--" + mm.group(3) + ",";
} else
date += ",";
} else {
date = "#" + mm.group(2).substring(0, 3) + "# " + mm.group(1) + "--#" + mm.group(4).substring(0, 3) + "# " + mm.group(3) + ",";
}
}
//date = date.trim();
//if (!date.isEmpty()) {
entry.setField("month", date);
//}
}
// clean up pages
String field = "pages";
String pages = entry.getField(field);
if (pages != null) {
String [] pageNumbers = pages.split("-");
if (pageNumbers.length == 2) {
if (pageNumbers[0].equals(pageNumbers[1])) {// single page
entry.setField(field, pageNumbers[0]);
} else {
entry.setField(field, pages.replaceAll("-", "--"));
}
}
}
// clean up publication field
BibtexEntryType type = entry.getType();
String sourceField = "";
if (type.getName() == "Article") {
sourceField = "journal";
entry.clearField("booktitle");
} else if (type.getName() == "Inproceedings"){
sourceField = "booktitle";
}
String fullName = entry.getField(sourceField);
if (fullName != null) {
if (type.getName() == "Article") {
int ind = fullName.indexOf(": Accepted for future publication");
if (ind > 0) {
fullName = fullName.substring(0, ind);
entry.setField("year", "to be published");
entry.clearField("month");
entry.clearField("pages");
entry.clearField("number");
}
String[] parts = fullName.split("[\\[\\]]"); //[see also...], [legacy...]
fullName = parts[0];
if (parts.length == 3) {
fullName += parts[2];
}
if(entry.getField("note") == "Early Access") {
entry.setField("year", "to be published");
entry.clearField("month");
entry.clearField("pages");
entry.clearField("number");
}
} else {
fullName = fullName.replace("Conference Proceedings", "Proceedings").
replace("Proceedings of", "Proceedings").replace("Proceedings.", "Proceedings");
fullName = fullName.replaceAll("International", "Int.");
fullName = fullName.replaceAll("Symposium", "Symp.");
fullName = fullName.replaceAll("Conference", "Conf.");
fullName = fullName.replaceAll(" on", " ").replace(" ", " ");
}
Matcher m1 = publicationPattern.matcher(fullName);
if (m1.find()) {
String prefix = m1.group(2).trim();
String postfix = m1.group(1).trim();
String abrv = "";
String[] parts = prefix.split("\\. ", 2);
if (parts.length == 2) {
if (parts[0].matches(abrvPattern)) {
prefix = parts[1];
abrv = parts[0];
} else {
prefix = parts[0];
abrv = parts[1];
}
}
if (prefix.matches(abrvPattern) == false) {
fullName = prefix + " " + postfix + " " + abrv;
fullName = fullName.trim();
} else {
fullName = postfix + " " + prefix;
}
}
if (type.getName() == "Article") {
fullName = fullName.replace(" - ", "-"); //IEE Proceedings-
fullName = fullName.trim();
if (Globals.prefs.getBoolean("useIEEEAbrv")) {
String id = Globals.journalAbbrev.getAbbreviatedName(fullName, false);
if (id != null)
fullName = id;
}
}
if (type.getName() == "Inproceedings") {
Matcher m2 = proceedingPattern.matcher(fullName);
if (m2.find()) {
String prefix = m2.group(2);
String postfix = m2.group(1).replaceAll("\\.$", "");
if (prefix.matches(abrvPattern) == false) {
String abrv = "";
String[] parts = postfix.split("\\. ", 2);
if (parts.length == 2) {
if (parts[0].matches(abrvPattern)) {
postfix = parts[1];
abrv = parts[0];
} else {
postfix = parts[0];
abrv = parts[1];
}
}
fullName = prefix.trim() + " " + postfix.trim() + " " + abrv;
} else {
fullName = postfix.trim() + " " + prefix.trim();
}
}
fullName = fullName.trim();
fullName = fullName.replaceAll("^[tT]he ", "").replaceAll("^\\d{4} ", "").replaceAll("[,.]$", "");
String year = entry.getField("year");
fullName = fullName.replaceAll(", " + year + "\\.?", "");
if (fullName.contains("Abstract") == false && fullName.contains("Summaries") == false && fullName.contains("Conference Record") == false)
fullName = "Proc. " + fullName;
}
entry.setField(sourceField, fullName);
}
// clean up abstract
String abstr = (String) entry.getField("abstract");
if (abstr != null) {
// Try to sort out most of the /spl / conversions
// Deal with this specific nested type first
abstr = abstr.replaceAll("/sub /spl infin//", "\\$_\\\\infty\\$");
abstr = abstr.replaceAll("/sup /spl infin//", "\\$\\^\\\\infty\\$");
// Replace general expressions
abstr = abstr.replaceAll("/[sS]pl ([^/]+)/", "\\$\\\\$1\\$");
// Deal with subscripts and superscripts
if (Globals.prefs.getBoolean("useConvertToEquation")) {
abstr = abstr.replaceAll("/sup ([^/]+)/", "\\$\\^\\{$1\\}\\$");
abstr = abstr.replaceAll("/sub ([^/]+)/", "\\$_\\{$1\\}\\$");
abstr = abstr.replaceAll("\\(sup\\)([^(]+)\\(/sup\\)", "\\$\\^\\{$1\\}\\$");
abstr = abstr.replaceAll("\\(sub\\)([^(]+)\\(/sub\\)", "\\_\\{$1\\}\\$");
} else {
abstr = abstr.replaceAll("/sup ([^/]+)/", "\\\\textsuperscript\\{$1\\}");
abstr = abstr.replaceAll("/sub ([^/]+)/", "\\\\textsubscript\\{$1\\}");
abstr = abstr.replaceAll("\\(sup\\)([^(]+)\\(/sup\\)", "\\\\textsuperscript\\{$1\\}");
abstr = abstr.replaceAll("\\(sub\\)([^(]+)\\(/sub\\)", "\\\\textsubscript\\{$1\\}");
}
// Replace \infin with \infty
abstr = abstr.replaceAll("\\\\infin", "\\\\infty");
// Write back
entry.setField("abstract", abstr);
}
// Clean up url
String url = (String) entry.getField("url");
if (url != null) {
entry.setField("url","http://ieeexplore.ieee.org"+url);
}
return entry;
}
private String parseNextEntryId(String allText, int startIndex) {
int index = allText.indexOf("<div class=\"select", startIndex);
int endIndex = allText.indexOf("</div>", index);
if (index >= 0 && endIndex > 0) {
String text = allText.substring(index, endIndex);
endIndex += 6;
piv = endIndex;
//parse id
Matcher idMatcher = idPattern.matcher(text);
//add id into a vector
if (idMatcher.find()) {
return idMatcher.group(1);
}
}
return null;
}
private BibtexEntry parseNextEntry(String allText, int startIndex) {
BibtexEntry entry = null;
int index = allText.indexOf("<div class=\"detail", piv);
int endIndex = allText.indexOf("</div>", index);
if (index >= 0 && endIndex > 0) {
endIndex += 6;
piv = endIndex;
String text = allText.substring(index, endIndex);
BibtexEntryType type = null;
String sourceField = null;
String typeName = "";
Matcher typeMatcher = typePattern.matcher(text);
if (typeMatcher.find()) {
typeName = typeMatcher.group(1);
if (typeName.equalsIgnoreCase("IEEE Journals & Magazines") || typeName.equalsIgnoreCase("IEEE Early Access Articles") ||
typeName.equalsIgnoreCase("IET Journals & Magazines") || typeName.equalsIgnoreCase("AIP Journals & Magazines") ||
typeName.equalsIgnoreCase("AVS Journals & Magazines") || typeName.equalsIgnoreCase("IBM Journals & Magazines") ||
typeName.equalsIgnoreCase("TUP Journals & Magazines") || typeName.equalsIgnoreCase("BIAI Journals & Magazines")) {
type = BibtexEntryType.getType("article");
sourceField = "journal";
} else if (typeName.equalsIgnoreCase("IEEE Conference Publications") || typeName.equalsIgnoreCase("IET Conference Publications") || typeName.equalsIgnoreCase("VDE Conference Publications")) {
type = BibtexEntryType.getType("inproceedings");
sourceField = "booktitle";
} else if (typeName.equalsIgnoreCase("IEEE Standards") || typeName.equalsIgnoreCase("Standards")) {
type = BibtexEntryType.getType("standard");
sourceField = "number";
} else if (typeName.equalsIgnoreCase("IEEE eLearning Library Courses")) {
type = BibtexEntryType.getType("Electronic");
sourceField = "note";
} else if (typeName.equalsIgnoreCase("Wiley-IEEE Press eBook Chapters") || typeName.equalsIgnoreCase("MIT Press eBook Chapters")) {
type = BibtexEntryType.getType("inCollection");
sourceField = "booktitle";
}
}
if (type == null) {
type = BibtexEntryType.getType("misc");
sourceField = "note";
System.err.println("Type detection failed. Use MISC instead.");
unparseable++;
System.err.println(text);
}
entry = new BibtexEntry(Util.createNeutralId(), type);
if (typeName.equalsIgnoreCase("IEEE Standards")) {
entry.setField("organization", "IEEE");
}
if (typeName.equalsIgnoreCase("Wiley-IEEE Press eBook Chapters")) {
entry.setField("publisher", "Wiley-IEEE Press");
} else if(typeName.equalsIgnoreCase("MIT Press eBook Chapters")) {
entry.setField("publisher", "MIT Press");
}
if (typeName.equalsIgnoreCase("IEEE Early Access Articles")) {
entry.setField("note", "Early Access");
}
Set<String> fields = fieldPatterns.keySet();
for (String field: fields) {
Matcher fieldMatcher = Pattern.compile(fieldPatterns.get(field)).matcher(text);
if (fieldMatcher.find()) {
entry.setField(field, htmlConverter.format(fieldMatcher.group(1)));
if (field.equals("title") && fieldMatcher.find()) {
String sec_title = htmlConverter.format(fieldMatcher.group(1));
if (entry.getType() == BibtexEntryType.getStandardType("standard")) {
sec_title = sec_title.replaceAll("IEEE Std ", "");
}
entry.setField(sourceField, sec_title);
}
if (field.equals("pages") && fieldMatcher.groupCount() == 2) {
entry.setField(field, fieldMatcher.group(1) + "-" + fieldMatcher.group(2));
}
}
}
if (entry.getField("author") == null || entry.getField("author").startsWith("a href")) { // Fix for some documents without authors
entry.setField("author","");
}
if (entry.getType() == BibtexEntryType.getStandardType("inproceedings") && entry.getField("author").equals("")) {
entry.setType(BibtexEntryType.getStandardType("proceedings"));
}
if (includeAbstract) {
index = text.indexOf("id=\"abstract");
if (index >= 0) {
endIndex = text.indexOf("</div>", index) + 6;
text = text.substring(index, endIndex);
Matcher absMatcher = absPattern.matcher(text);
if (absMatcher.find()) {
// Clean-up abstract
String abstr=absMatcher.group(1);
abstr = abstr.replaceAll("<span class='snippet'>([\\w]+)</span>","$1");
entry.setField("abstract", htmlConverter.format(abstr));
}
}
}
}
if (entry == null) {
return null;
} else {
return cleanup(entry);
}
}
/**
* Find out how many hits were found.
* @param page
*/
private int getNumberOfHits(String page, String marker, Pattern pattern) throws IOException {
int ind = page.indexOf(marker);
if (ind < 0) {
System.out.println(page);
throw new IOException(Globals.lang("Could not parse number of hits"));
}
String substring = page.substring(ind, page.length());
Matcher m = pattern.matcher(substring);
if (m.find())
return Integer.parseInt(m.group(1));
else
throw new IOException(Globals.lang("Could not parse number of hits"));
}
/**
* Download the URL and return contents as a String.
* @param source
* @return
* @throws IOException
*/
public String getResults(URL source) throws IOException {
InputStream in = source.openStream();
StringBuffer sb = new StringBuffer();
byte[] buffer = new byte[256];
while(true) {
int bytesRead = in.read(buffer);
if(bytesRead == -1) break;
for (int i=0; i<bytesRead; i++)
sb.append((char)buffer[i]);
}
return sb.toString();
}
/**
* Read results from a file instead of an URL. Just for faster debugging.
* @param f
* @return
* @throws IOException
*/
public String getResultsFromFile(File f) throws IOException {
InputStream in = new BufferedInputStream(new FileInputStream(f));
StringBuffer sb = new StringBuffer();
byte[] buffer = new byte[256];
while(true) {
int bytesRead = in.read(buffer);
if(bytesRead == -1) break;
for (int i=0; i<bytesRead; i++)
sb.append((char)buffer[i]);
}
return sb.toString();
}
}
| false | true | private BibtexEntry cleanup(BibtexEntry entry) {
if (entry == null)
return null;
// clean up title
String title = (String)entry.getField("title");
if (title != null) {
// USe the alt-text and replace image links
title = title.replaceAll("[ ]?img src=[^ ]+ alt=\"([^\"]+)\">[ ]?", "\\$$1\\$");
// Try to sort out most of the /spl / conversions
// Deal with this specific nested type first
title = title.replaceAll("/sub /spl infin//", "\\$_\\\\infty\\$");
title = title.replaceAll("/sup /spl infin//", "\\$\\^\\\\infty\\$");
// Replace general expressions
title = title.replaceAll("/[sS]pl ([^/]+)/", "\\$\\\\$1\\$");
// Deal with subscripts and superscripts
if (Globals.prefs.getBoolean("useConvertToEquation")) {
title = title.replaceAll("/sup ([^/]+)/", "\\$\\^\\{$1\\}\\$");
title = title.replaceAll("/sub ([^/]+)/", "\\$_\\{$1\\}\\$");
title = title.replaceAll("\\(sup\\)([^(]+)\\(/sup\\)", "\\$\\^\\{$1\\}\\$");
title = title.replaceAll("\\(sub\\)([^(]+)\\(/sub\\)", "\\_\\{$1\\}\\$");
} else {
title = title.replaceAll("/sup ([^/]+)/", "\\\\textsuperscript\\{$1\\}");
title = title.replaceAll("/sub ([^/]+)/", "\\\\textsubscript\\{$1\\}");
title = title.replaceAll("\\(sup\\)([^(]+)\\(/sup\\)", "\\\\textsuperscript\\{$1\\}");
title = title.replaceAll("\\(sub\\)([^(]+)\\(/sub\\)", "\\\\textsubscript\\{$1\\}");
}
// Replace \infin with \infty
title = title.replaceAll("\\\\infin", "\\\\infty");
// Automatic case keeping
if (Globals.prefs.getBoolean("useCaseKeeperOnSearch")) {
title = caseKeeper.format(title, caseKeeperList.wordListIEEEXplore);
}
// Write back
entry.setField("title", title);
}
// clean up author
String author = (String)entry.getField("author");
if (author != null) {
if (author.indexOf("a href=") >= 0) { // Author parsing failed because it was empty
entry.setField("author",""); // Maybe not needed anymore due to another change
} else {
author = author.replaceAll("\\.", ". ");
author = author.replaceAll(" ", " ");
author = author.replaceAll("\\. -", ".-");
author = author.replaceAll("; ", " and ");
author = author.replaceAll("[,;]$", "");
entry.setField("author", author);
}
}
// clean up month
String month = (String)entry.getField("month");
if ((month != null) && (month.length() > 0)) {
month = month.replaceAll("\\.", "");
month = month.toLowerCase();
Pattern monthPattern = Pattern.compile("(\\d*+)\\s*([a-z]*+)-*(\\d*+)\\s*([a-z]*+)");
Matcher mm = monthPattern.matcher(month);
String date = month;
if (mm.find()) {
if (mm.group(3).length() == 0) {
if (mm.group(2).length() > 0) {
date = "#" + mm.group(2).substring(0, 3) + "#";
if (mm.group(1).length() > 0) {
date += " " + mm.group(1) + ",";
}
} else {
date = mm.group(1) + ",";
}
} else if (mm.group(2).length() == 0) {
if (mm.group(4).length() > 0) {
date = "#" + mm.group(4).substring(0, 3) + "# " + mm.group(1) + "--" + mm.group(3) + ",";
} else
date += ",";
} else {
date = "#" + mm.group(2).substring(0, 3) + "# " + mm.group(1) + "--#" + mm.group(4).substring(0, 3) + "# " + mm.group(3) + ",";
}
}
//date = date.trim();
//if (!date.isEmpty()) {
entry.setField("month", date);
//}
}
// clean up pages
String field = "pages";
String pages = entry.getField(field);
if (pages != null) {
String [] pageNumbers = pages.split("-");
if (pageNumbers.length == 2) {
if (pageNumbers[0].equals(pageNumbers[1])) {// single page
entry.setField(field, pageNumbers[0]);
} else {
entry.setField(field, pages.replaceAll("-", "--"));
}
}
}
// clean up publication field
BibtexEntryType type = entry.getType();
String sourceField = "";
if (type.getName() == "Article") {
sourceField = "journal";
entry.clearField("booktitle");
} else if (type.getName() == "Inproceedings"){
sourceField = "booktitle";
}
String fullName = entry.getField(sourceField);
if (fullName != null) {
if (type.getName() == "Article") {
int ind = fullName.indexOf(": Accepted for future publication");
if (ind > 0) {
fullName = fullName.substring(0, ind);
entry.setField("year", "to be published");
entry.clearField("month");
entry.clearField("pages");
entry.clearField("number");
}
String[] parts = fullName.split("[\\[\\]]"); //[see also...], [legacy...]
fullName = parts[0];
if (parts.length == 3) {
fullName += parts[2];
}
if(entry.getField("note") == "Early Access") {
entry.setField("year", "to be published");
entry.clearField("month");
entry.clearField("pages");
entry.clearField("number");
}
} else {
fullName = fullName.replace("Conference Proceedings", "Proceedings").
replace("Proceedings of", "Proceedings").replace("Proceedings.", "Proceedings");
fullName = fullName.replaceAll("International", "Int.");
fullName = fullName.replaceAll("Symposium", "Symp.");
fullName = fullName.replaceAll("Conference", "Conf.");
fullName = fullName.replaceAll(" on", " ").replace(" ", " ");
}
Matcher m1 = publicationPattern.matcher(fullName);
if (m1.find()) {
String prefix = m1.group(2).trim();
String postfix = m1.group(1).trim();
String abrv = "";
String[] parts = prefix.split("\\. ", 2);
if (parts.length == 2) {
if (parts[0].matches(abrvPattern)) {
prefix = parts[1];
abrv = parts[0];
} else {
prefix = parts[0];
abrv = parts[1];
}
}
if (prefix.matches(abrvPattern) == false) {
fullName = prefix + " " + postfix + " " + abrv;
fullName = fullName.trim();
} else {
fullName = postfix + " " + prefix;
}
}
if (type.getName() == "Article") {
fullName = fullName.replace(" - ", "-"); //IEE Proceedings-
fullName = fullName.trim();
if (Globals.prefs.getBoolean("useIEEEAbrv")) {
String id = Globals.journalAbbrev.getAbbreviatedName(fullName, false);
if (id != null)
fullName = id;
}
}
if (type.getName() == "Inproceedings") {
Matcher m2 = proceedingPattern.matcher(fullName);
if (m2.find()) {
String prefix = m2.group(2);
String postfix = m2.group(1).replaceAll("\\.$", "");
if (prefix.matches(abrvPattern) == false) {
String abrv = "";
String[] parts = postfix.split("\\. ", 2);
if (parts.length == 2) {
if (parts[0].matches(abrvPattern)) {
postfix = parts[1];
abrv = parts[0];
} else {
postfix = parts[0];
abrv = parts[1];
}
}
fullName = prefix.trim() + " " + postfix.trim() + " " + abrv;
} else {
fullName = postfix.trim() + " " + prefix.trim();
}
}
fullName = fullName.trim();
fullName = fullName.replaceAll("^[tT]he ", "").replaceAll("^\\d{4} ", "").replaceAll("[,.]$", "");
String year = entry.getField("year");
fullName = fullName.replaceAll(", " + year + "\\.?", "");
if (fullName.contains("Abstract") == false && fullName.contains("Summaries") == false && fullName.contains("Conference Record") == false)
fullName = "Proc. " + fullName;
}
entry.setField(sourceField, fullName);
}
// clean up abstract
String abstr = (String) entry.getField("abstract");
if (abstr != null) {
// Try to sort out most of the /spl / conversions
// Deal with this specific nested type first
abstr = abstr.replaceAll("/sub /spl infin//", "\\$_\\\\infty\\$");
abstr = abstr.replaceAll("/sup /spl infin//", "\\$\\^\\\\infty\\$");
// Replace general expressions
abstr = abstr.replaceAll("/[sS]pl ([^/]+)/", "\\$\\\\$1\\$");
// Deal with subscripts and superscripts
if (Globals.prefs.getBoolean("useConvertToEquation")) {
abstr = abstr.replaceAll("/sup ([^/]+)/", "\\$\\^\\{$1\\}\\$");
abstr = abstr.replaceAll("/sub ([^/]+)/", "\\$_\\{$1\\}\\$");
abstr = abstr.replaceAll("\\(sup\\)([^(]+)\\(/sup\\)", "\\$\\^\\{$1\\}\\$");
abstr = abstr.replaceAll("\\(sub\\)([^(]+)\\(/sub\\)", "\\_\\{$1\\}\\$");
} else {
abstr = abstr.replaceAll("/sup ([^/]+)/", "\\\\textsuperscript\\{$1\\}");
abstr = abstr.replaceAll("/sub ([^/]+)/", "\\\\textsubscript\\{$1\\}");
abstr = abstr.replaceAll("\\(sup\\)([^(]+)\\(/sup\\)", "\\\\textsuperscript\\{$1\\}");
abstr = abstr.replaceAll("\\(sub\\)([^(]+)\\(/sub\\)", "\\\\textsubscript\\{$1\\}");
}
// Replace \infin with \infty
abstr = abstr.replaceAll("\\\\infin", "\\\\infty");
// Write back
entry.setField("abstract", abstr);
}
// Clean up url
String url = (String) entry.getField("url");
if (url != null) {
entry.setField("url","http://ieeexplore.ieee.org"+url);
}
return entry;
}
| private BibtexEntry cleanup(BibtexEntry entry) {
if (entry == null)
return null;
// clean up title
String title = (String)entry.getField("title");
if (title != null) {
// USe the alt-text and replace image links
title = title.replaceAll("[ ]?img src=[^ ]+ alt=\"([^\"]+)\">[ ]?", "\\$$1\\$");
// Try to sort out most of the /spl / conversions
// Deal with this specific nested type first
title = title.replaceAll("/sub /spl infin//", "\\$_\\\\infty\\$");
title = title.replaceAll("/sup /spl infin//", "\\$\\^\\\\infty\\$");
// Replace general expressions
title = title.replaceAll("/[sS]pl ([^/]+)/", "\\$\\\\$1\\$");
// Deal with subscripts and superscripts
if (Globals.prefs.getBoolean("useConvertToEquation")) {
title = title.replaceAll("/sup ([^/]+)/", "\\$\\^\\{$1\\}\\$");
title = title.replaceAll("/sub ([^/]+)/", "\\$_\\{$1\\}\\$");
title = title.replaceAll("\\(sup\\)([^(]+)\\(/sup\\)", "\\$\\^\\{$1\\}\\$");
title = title.replaceAll("\\(sub\\)([^(]+)\\(/sub\\)", "\\_\\{$1\\}\\$");
} else {
title = title.replaceAll("/sup ([^/]+)/", "\\\\textsuperscript\\{$1\\}");
title = title.replaceAll("/sub ([^/]+)/", "\\\\textsubscript\\{$1\\}");
title = title.replaceAll("\\(sup\\)([^(]+)\\(/sup\\)", "\\\\textsuperscript\\{$1\\}");
title = title.replaceAll("\\(sub\\)([^(]+)\\(/sub\\)", "\\\\textsubscript\\{$1\\}");
}
// Replace \infin with \infty
title = title.replaceAll("\\\\infin", "\\\\infty");
// Automatic case keeping
if (Globals.prefs.getBoolean("useCaseKeeperOnSearch")) {
title = caseKeeper.format(title, caseKeeperList.wordListIEEEXplore);
}
// Write back
entry.setField("title", title);
}
// clean up author
String author = (String)entry.getField("author");
if (author != null) {
if (author.indexOf("a href=") >= 0) { // Author parsing failed because it was empty
entry.setField("author",""); // Maybe not needed anymore due to another change
} else {
author = author.replaceAll("\\.", ". ");
author = author.replaceAll("([^;]+),([^;]+),([^;]+)","$1,$3,$2"); // Change order in case of Jr. etc
author = author.replaceAll(" ", " ");
author = author.replaceAll("\\. -", ".-");
author = author.replaceAll("; ", " and ");
author = author.replaceAll(" ,", ",");
author = author.replaceAll(" ", " ");
author = author.replaceAll("[ ,;]+$", "");
entry.setField("author", author);
}
}
// clean up month
String month = (String)entry.getField("month");
if ((month != null) && (month.length() > 0)) {
month = month.replaceAll("\\.", "");
month = month.toLowerCase();
Pattern monthPattern = Pattern.compile("(\\d*+)\\s*([a-z]*+)-*(\\d*+)\\s*([a-z]*+)");
Matcher mm = monthPattern.matcher(month);
String date = month;
if (mm.find()) {
if (mm.group(3).length() == 0) {
if (mm.group(2).length() > 0) {
date = "#" + mm.group(2).substring(0, 3) + "#";
if (mm.group(1).length() > 0) {
date += " " + mm.group(1) + ",";
}
} else {
date = mm.group(1) + ",";
}
} else if (mm.group(2).length() == 0) {
if (mm.group(4).length() > 0) {
date = "#" + mm.group(4).substring(0, 3) + "# " + mm.group(1) + "--" + mm.group(3) + ",";
} else
date += ",";
} else {
date = "#" + mm.group(2).substring(0, 3) + "# " + mm.group(1) + "--#" + mm.group(4).substring(0, 3) + "# " + mm.group(3) + ",";
}
}
//date = date.trim();
//if (!date.isEmpty()) {
entry.setField("month", date);
//}
}
// clean up pages
String field = "pages";
String pages = entry.getField(field);
if (pages != null) {
String [] pageNumbers = pages.split("-");
if (pageNumbers.length == 2) {
if (pageNumbers[0].equals(pageNumbers[1])) {// single page
entry.setField(field, pageNumbers[0]);
} else {
entry.setField(field, pages.replaceAll("-", "--"));
}
}
}
// clean up publication field
BibtexEntryType type = entry.getType();
String sourceField = "";
if (type.getName() == "Article") {
sourceField = "journal";
entry.clearField("booktitle");
} else if (type.getName() == "Inproceedings"){
sourceField = "booktitle";
}
String fullName = entry.getField(sourceField);
if (fullName != null) {
if (type.getName() == "Article") {
int ind = fullName.indexOf(": Accepted for future publication");
if (ind > 0) {
fullName = fullName.substring(0, ind);
entry.setField("year", "to be published");
entry.clearField("month");
entry.clearField("pages");
entry.clearField("number");
}
String[] parts = fullName.split("[\\[\\]]"); //[see also...], [legacy...]
fullName = parts[0];
if (parts.length == 3) {
fullName += parts[2];
}
if(entry.getField("note") == "Early Access") {
entry.setField("year", "to be published");
entry.clearField("month");
entry.clearField("pages");
entry.clearField("number");
}
} else {
fullName = fullName.replace("Conference Proceedings", "Proceedings").
replace("Proceedings of", "Proceedings").replace("Proceedings.", "Proceedings");
fullName = fullName.replaceAll("International", "Int.");
fullName = fullName.replaceAll("Symposium", "Symp.");
fullName = fullName.replaceAll("Conference", "Conf.");
fullName = fullName.replaceAll(" on", " ").replace(" ", " ");
}
Matcher m1 = publicationPattern.matcher(fullName);
if (m1.find()) {
String prefix = m1.group(2).trim();
String postfix = m1.group(1).trim();
String abrv = "";
String[] parts = prefix.split("\\. ", 2);
if (parts.length == 2) {
if (parts[0].matches(abrvPattern)) {
prefix = parts[1];
abrv = parts[0];
} else {
prefix = parts[0];
abrv = parts[1];
}
}
if (prefix.matches(abrvPattern) == false) {
fullName = prefix + " " + postfix + " " + abrv;
fullName = fullName.trim();
} else {
fullName = postfix + " " + prefix;
}
}
if (type.getName() == "Article") {
fullName = fullName.replace(" - ", "-"); //IEE Proceedings-
fullName = fullName.trim();
if (Globals.prefs.getBoolean("useIEEEAbrv")) {
String id = Globals.journalAbbrev.getAbbreviatedName(fullName, false);
if (id != null)
fullName = id;
}
}
if (type.getName() == "Inproceedings") {
Matcher m2 = proceedingPattern.matcher(fullName);
if (m2.find()) {
String prefix = m2.group(2);
String postfix = m2.group(1).replaceAll("\\.$", "");
if (prefix.matches(abrvPattern) == false) {
String abrv = "";
String[] parts = postfix.split("\\. ", 2);
if (parts.length == 2) {
if (parts[0].matches(abrvPattern)) {
postfix = parts[1];
abrv = parts[0];
} else {
postfix = parts[0];
abrv = parts[1];
}
}
fullName = prefix.trim() + " " + postfix.trim() + " " + abrv;
} else {
fullName = postfix.trim() + " " + prefix.trim();
}
}
fullName = fullName.trim();
fullName = fullName.replaceAll("^[tT]he ", "").replaceAll("^\\d{4} ", "").replaceAll("[,.]$", "");
String year = entry.getField("year");
fullName = fullName.replaceAll(", " + year + "\\.?", "");
if (fullName.contains("Abstract") == false && fullName.contains("Summaries") == false && fullName.contains("Conference Record") == false)
fullName = "Proc. " + fullName;
}
entry.setField(sourceField, fullName);
}
// clean up abstract
String abstr = (String) entry.getField("abstract");
if (abstr != null) {
// Try to sort out most of the /spl / conversions
// Deal with this specific nested type first
abstr = abstr.replaceAll("/sub /spl infin//", "\\$_\\\\infty\\$");
abstr = abstr.replaceAll("/sup /spl infin//", "\\$\\^\\\\infty\\$");
// Replace general expressions
abstr = abstr.replaceAll("/[sS]pl ([^/]+)/", "\\$\\\\$1\\$");
// Deal with subscripts and superscripts
if (Globals.prefs.getBoolean("useConvertToEquation")) {
abstr = abstr.replaceAll("/sup ([^/]+)/", "\\$\\^\\{$1\\}\\$");
abstr = abstr.replaceAll("/sub ([^/]+)/", "\\$_\\{$1\\}\\$");
abstr = abstr.replaceAll("\\(sup\\)([^(]+)\\(/sup\\)", "\\$\\^\\{$1\\}\\$");
abstr = abstr.replaceAll("\\(sub\\)([^(]+)\\(/sub\\)", "\\_\\{$1\\}\\$");
} else {
abstr = abstr.replaceAll("/sup ([^/]+)/", "\\\\textsuperscript\\{$1\\}");
abstr = abstr.replaceAll("/sub ([^/]+)/", "\\\\textsubscript\\{$1\\}");
abstr = abstr.replaceAll("\\(sup\\)([^(]+)\\(/sup\\)", "\\\\textsuperscript\\{$1\\}");
abstr = abstr.replaceAll("\\(sub\\)([^(]+)\\(/sub\\)", "\\\\textsubscript\\{$1\\}");
}
// Replace \infin with \infty
abstr = abstr.replaceAll("\\\\infin", "\\\\infty");
// Write back
entry.setField("abstract", abstr);
}
// Clean up url
String url = (String) entry.getField("url");
if (url != null) {
entry.setField("url","http://ieeexplore.ieee.org"+url);
}
return entry;
}
|
diff --git a/liveDemo/core/source/org/openfaces/demo/beans/daytable/DayTableBean2.java b/liveDemo/core/source/org/openfaces/demo/beans/daytable/DayTableBean2.java
index 2e85a157d..459dff704 100644
--- a/liveDemo/core/source/org/openfaces/demo/beans/daytable/DayTableBean2.java
+++ b/liveDemo/core/source/org/openfaces/demo/beans/daytable/DayTableBean2.java
@@ -1,161 +1,161 @@
/*
* OpenFaces - JSF Component Library 2.0
* Copyright (C) 2007-2010, TeamDev Ltd.
* [email protected]
* Unless agreed in writing the contents of this file are subject to
* the GNU Lesser General Public License Version 2.1 (the "LGPL" License).
* 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.
* Please visit http://openfaces.org/licensing/ for more details.
*/
package org.openfaces.demo.beans.daytable;
import org.openfaces.util.Faces;
import org.openfaces.component.timetable.AbstractTimetableEvent;
import org.openfaces.component.timetable.TimetableChangeEvent;
import org.openfaces.component.timetable.TimetableEvent;
import org.openfaces.component.timetable.TimetableResource;
import org.openfaces.component.timetable.ReservedTimeEvent;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.awt.Color;
/**
* @author Dmitry Pikhulya
*/
public class DayTableBean2 extends DayTableBean implements Serializable {
private static int eventIdCounter = 0;
List<AbstractTimetableEvent> events = new ArrayList<AbstractTimetableEvent>();
private List<TimetableResource> resources = new ArrayList<TimetableResource>();
public DayTableBean2() {
Color green = new Color(41, 142, 1);
Color blue = new Color(2, 105, 220);
Color orange = new Color(232, 65, 2);
Resource andrew = new Resource("Andrew", "#0269dc");
Resource lucie = new Resource("Lucie", "#df4c11");
Resource alex = new Resource("Alex", "#298e01");
// today
events.add(new TimetableEvent(generateEventId(), todayAt(9, 0), todayAt(19, 30), "WORK", "Usual day, nothing special", blue, andrew.getId()));
events.add(new TimetableEvent(generateEventId(), todayAt(20, 0), todayAt(23, 0), "ALEX BIRTHDAY PARTY", "Dress-code: Harry Potter", blue, andrew.getId()));
events.add(new TimetableEvent(generateEventId(), todayAt(7, 0), todayAt(9, 0), "SUNRISE AT THE ROOF", "Don't forget the camera", orange, lucie.getId()));
events.add(new TimetableEvent(generateEventId(), todayAt(9, 30), todayAt(13, 0), "PAINTING", "...", orange, lucie.getId()));
events.add(new TimetableEvent(generateEventId(), todayAt(14, 0), todayAt(19, 30), "LOOKING FOR A PRESENT", "Alex loves sweet honey", orange, lucie.getId()));
events.add(new TimetableEvent(generateEventId(), todayAt(20, 0), todayAt(23, 0), "ALEX BIRTHDAY PARTY", "Dress-code: Harry Potter", orange, lucie.getId()));
events.add(new TimetableEvent(generateEventId(), todayAt(6, 0), todayAt(20, 0), "PREPARING FOR BIRTHDAY", "Oh my God!", green, alex.getId()));
events.add(new TimetableEvent(generateEventId(), todayAt(20, 0), todayAt(23, 0), "MY BIRTHDAY", "There will be a lot of magic wands", green, alex.getId()));
// yesterday
events.add(new TimetableEvent(generateEventId(), yesterdayAt(9, 0), yesterdayAt(15, 30), "WORK", "Short day, will visit a doctor", blue, andrew.getId()));
events.add(new TimetableEvent(generateEventId(), yesterdayAt(16, 30), yesterdayAt(17, 30), "DOCTOR CONSULTATION", "Once-a-year visit", blue, andrew.getId()));
events.add(new ReservedTimeEvent(generateEventId(), andrew.getId(), yesterdayAt(18, 30), yesterdayAt(19, 30)));
- events.add(new TimetableEvent(generateEventId(), yesterdayAt(10, 0), yesterdayAt(12, 30), "IREN FOTOSET", "Cute Iren with mother.<br>Iren's mother phone: +1 (555) 987 98 12", orange, lucie.getId()));
+ events.add(new TimetableEvent(generateEventId(), yesterdayAt(10, 0), yesterdayAt(12, 30), "IREN FOTOSET", "Cute Iren with mother.<br/>Iren's mother phone: +1 (555) 987 98 12", orange, lucie.getId()));
events.add(new TimetableEvent(generateEventId(), yesterdayAt(16, 30), yesterdayAt(19, 0), "NATIONAL GEOGRAPHIC", "Show photos to NG and close the deal.", orange, lucie.getId()));
events.add(new TimetableEvent(generateEventId(), yesterdayAt(9, 0), yesterdayAt(11, 30), "BUY FOOD", "Beer, bread and circuses", green, alex.getId()));
events.add(new TimetableEvent(generateEventId(), yesterdayAt(13, 30), yesterdayAt(21, 0), "VISIT PARENTS", "Mom asked for my old cell phone.", green, alex.getId()));
// tomorrow
events.add(new ReservedTimeEvent(generateEventId(), andrew.getId(), tomorrowAt(6, 0), tomorrowAt(8, 30)));
events.add(new TimetableEvent(generateEventId(), tomorrowAt(9, 0), tomorrowAt(19, 30), "WORK", "As usual", blue, andrew.getId()));
events.add(new TimetableEvent(generateEventId(), tomorrowAt(20, 30), tomorrowAt(23, 30), "WENDY", "Table is reserved at Potato House", blue, andrew.getId()));
events.add(new ReservedTimeEvent(generateEventId(), lucie.getId(), tomorrowAt(6, 0), tomorrowAt(12, 30)));
events.add(new TimetableEvent(generateEventId(), tomorrowAt(14, 0), tomorrowAt(15, 0), "BRUCE ECKEL PRESS CONFERENCE", "Take 50D with EF 28-300", orange, lucie.getId()));
events.add(new TimetableEvent(generateEventId(), tomorrowAt(17, 30), tomorrowAt(20, 0), "SIGN CONTEST", "", orange, lucie.getId()));
events.add(new TimetableEvent(generateEventId(), tomorrowAt(8, 30), tomorrowAt(11, 30), "CLEAN HOUSE FROM GUESTS", "Andrew will go the first", green, alex.getId()));
events.add(new TimetableEvent(generateEventId(), tomorrowAt(13, 0), tomorrowAt(16, 0), "CHECK NEW KITE VIDEO", "Lucie promised to give me the \"Lines\".", green, alex.getId()));
events.add(new TimetableEvent(generateEventId(), tomorrowAt(19, 30), tomorrowAt(21, 0), "COUNTER-STRIKE", "The Spawn team wants to repeat.", green, alex.getId()));
resources.add(new TimetableResource(andrew, andrew.getId(), andrew.getName()));
resources.add(new TimetableResource(lucie, lucie.getId(), lucie.getName()));
resources.add(new TimetableResource(alex, alex.getId(), alex.getName()));
}
private String generateEventId() {
return String.valueOf(eventIdCounter++);
}
public List<AbstractTimetableEvent> getEvents() {
Date startTime = Faces.var("startTime", Date.class);
Date endTime = Faces.var("endTime", Date.class);
List<AbstractTimetableEvent> result = retrieveEventsForPeriod(startTime, endTime);
return result;
}
private List<AbstractTimetableEvent> retrieveEventsForPeriod(Date startTime, Date endTime) {
List<AbstractTimetableEvent> result = new ArrayList<AbstractTimetableEvent>();
for (AbstractTimetableEvent event : events) {
if (event.getStart().before(endTime) && event.getEnd().after(startTime))
result.add(event);
}
return result;
}
public List<TimetableResource> getResources() {
return resources;
}
public void removeEvent(List<AbstractTimetableEvent> events, String id) {
events.remove(eventById(events, id));
}
public void addEvent(List<AbstractTimetableEvent> events, TimetableEvent event) {
event.setId(generateEventId());
if(event.getColor() == null) {
event.setColor(new Color(0, 0x6e, 0xbb));
}
events.add(event);
}
public void updateEvent(List<AbstractTimetableEvent> events, TimetableEvent editedEvent) {
TimetableEvent event = (TimetableEvent) eventById(events, editedEvent.getId());
event.setName(editedEvent.getName());
event.setStart(editedEvent.getStart());
event.setEnd(editedEvent.getEnd());
event.setDescription(editedEvent.getDescription());
event.setResourceId(editedEvent.getResourceId());
event.setColor(editedEvent.getColor());
}
public void processTimetableChanges(TimetableChangeEvent tce) {
TimetableEvent[] addedEvents = tce.getAddedEvents();
for (TimetableEvent event : addedEvents) {
addEvent(events, event);
}
TimetableEvent[] editedEvents = tce.getChangedEvents();
for (TimetableEvent event : editedEvents) {
updateEvent(events, event);
}
String[] removedEventIds = tce.getRemovedEventIds();
for (String eventId : removedEventIds) {
removeEvent(events, eventId);
}
}
public void remove() {
TimetableEvent event = getEvent();
removeEvent(events, event.getId());
}
private TimetableEvent getEvent() {
return Faces.var("event", TimetableEvent.class);
}
}
| true | true | public DayTableBean2() {
Color green = new Color(41, 142, 1);
Color blue = new Color(2, 105, 220);
Color orange = new Color(232, 65, 2);
Resource andrew = new Resource("Andrew", "#0269dc");
Resource lucie = new Resource("Lucie", "#df4c11");
Resource alex = new Resource("Alex", "#298e01");
// today
events.add(new TimetableEvent(generateEventId(), todayAt(9, 0), todayAt(19, 30), "WORK", "Usual day, nothing special", blue, andrew.getId()));
events.add(new TimetableEvent(generateEventId(), todayAt(20, 0), todayAt(23, 0), "ALEX BIRTHDAY PARTY", "Dress-code: Harry Potter", blue, andrew.getId()));
events.add(new TimetableEvent(generateEventId(), todayAt(7, 0), todayAt(9, 0), "SUNRISE AT THE ROOF", "Don't forget the camera", orange, lucie.getId()));
events.add(new TimetableEvent(generateEventId(), todayAt(9, 30), todayAt(13, 0), "PAINTING", "...", orange, lucie.getId()));
events.add(new TimetableEvent(generateEventId(), todayAt(14, 0), todayAt(19, 30), "LOOKING FOR A PRESENT", "Alex loves sweet honey", orange, lucie.getId()));
events.add(new TimetableEvent(generateEventId(), todayAt(20, 0), todayAt(23, 0), "ALEX BIRTHDAY PARTY", "Dress-code: Harry Potter", orange, lucie.getId()));
events.add(new TimetableEvent(generateEventId(), todayAt(6, 0), todayAt(20, 0), "PREPARING FOR BIRTHDAY", "Oh my God!", green, alex.getId()));
events.add(new TimetableEvent(generateEventId(), todayAt(20, 0), todayAt(23, 0), "MY BIRTHDAY", "There will be a lot of magic wands", green, alex.getId()));
// yesterday
events.add(new TimetableEvent(generateEventId(), yesterdayAt(9, 0), yesterdayAt(15, 30), "WORK", "Short day, will visit a doctor", blue, andrew.getId()));
events.add(new TimetableEvent(generateEventId(), yesterdayAt(16, 30), yesterdayAt(17, 30), "DOCTOR CONSULTATION", "Once-a-year visit", blue, andrew.getId()));
events.add(new ReservedTimeEvent(generateEventId(), andrew.getId(), yesterdayAt(18, 30), yesterdayAt(19, 30)));
events.add(new TimetableEvent(generateEventId(), yesterdayAt(10, 0), yesterdayAt(12, 30), "IREN FOTOSET", "Cute Iren with mother.<br>Iren's mother phone: +1 (555) 987 98 12", orange, lucie.getId()));
events.add(new TimetableEvent(generateEventId(), yesterdayAt(16, 30), yesterdayAt(19, 0), "NATIONAL GEOGRAPHIC", "Show photos to NG and close the deal.", orange, lucie.getId()));
events.add(new TimetableEvent(generateEventId(), yesterdayAt(9, 0), yesterdayAt(11, 30), "BUY FOOD", "Beer, bread and circuses", green, alex.getId()));
events.add(new TimetableEvent(generateEventId(), yesterdayAt(13, 30), yesterdayAt(21, 0), "VISIT PARENTS", "Mom asked for my old cell phone.", green, alex.getId()));
// tomorrow
events.add(new ReservedTimeEvent(generateEventId(), andrew.getId(), tomorrowAt(6, 0), tomorrowAt(8, 30)));
events.add(new TimetableEvent(generateEventId(), tomorrowAt(9, 0), tomorrowAt(19, 30), "WORK", "As usual", blue, andrew.getId()));
events.add(new TimetableEvent(generateEventId(), tomorrowAt(20, 30), tomorrowAt(23, 30), "WENDY", "Table is reserved at Potato House", blue, andrew.getId()));
events.add(new ReservedTimeEvent(generateEventId(), lucie.getId(), tomorrowAt(6, 0), tomorrowAt(12, 30)));
events.add(new TimetableEvent(generateEventId(), tomorrowAt(14, 0), tomorrowAt(15, 0), "BRUCE ECKEL PRESS CONFERENCE", "Take 50D with EF 28-300", orange, lucie.getId()));
events.add(new TimetableEvent(generateEventId(), tomorrowAt(17, 30), tomorrowAt(20, 0), "SIGN CONTEST", "", orange, lucie.getId()));
events.add(new TimetableEvent(generateEventId(), tomorrowAt(8, 30), tomorrowAt(11, 30), "CLEAN HOUSE FROM GUESTS", "Andrew will go the first", green, alex.getId()));
events.add(new TimetableEvent(generateEventId(), tomorrowAt(13, 0), tomorrowAt(16, 0), "CHECK NEW KITE VIDEO", "Lucie promised to give me the \"Lines\".", green, alex.getId()));
events.add(new TimetableEvent(generateEventId(), tomorrowAt(19, 30), tomorrowAt(21, 0), "COUNTER-STRIKE", "The Spawn team wants to repeat.", green, alex.getId()));
resources.add(new TimetableResource(andrew, andrew.getId(), andrew.getName()));
resources.add(new TimetableResource(lucie, lucie.getId(), lucie.getName()));
resources.add(new TimetableResource(alex, alex.getId(), alex.getName()));
}
| public DayTableBean2() {
Color green = new Color(41, 142, 1);
Color blue = new Color(2, 105, 220);
Color orange = new Color(232, 65, 2);
Resource andrew = new Resource("Andrew", "#0269dc");
Resource lucie = new Resource("Lucie", "#df4c11");
Resource alex = new Resource("Alex", "#298e01");
// today
events.add(new TimetableEvent(generateEventId(), todayAt(9, 0), todayAt(19, 30), "WORK", "Usual day, nothing special", blue, andrew.getId()));
events.add(new TimetableEvent(generateEventId(), todayAt(20, 0), todayAt(23, 0), "ALEX BIRTHDAY PARTY", "Dress-code: Harry Potter", blue, andrew.getId()));
events.add(new TimetableEvent(generateEventId(), todayAt(7, 0), todayAt(9, 0), "SUNRISE AT THE ROOF", "Don't forget the camera", orange, lucie.getId()));
events.add(new TimetableEvent(generateEventId(), todayAt(9, 30), todayAt(13, 0), "PAINTING", "...", orange, lucie.getId()));
events.add(new TimetableEvent(generateEventId(), todayAt(14, 0), todayAt(19, 30), "LOOKING FOR A PRESENT", "Alex loves sweet honey", orange, lucie.getId()));
events.add(new TimetableEvent(generateEventId(), todayAt(20, 0), todayAt(23, 0), "ALEX BIRTHDAY PARTY", "Dress-code: Harry Potter", orange, lucie.getId()));
events.add(new TimetableEvent(generateEventId(), todayAt(6, 0), todayAt(20, 0), "PREPARING FOR BIRTHDAY", "Oh my God!", green, alex.getId()));
events.add(new TimetableEvent(generateEventId(), todayAt(20, 0), todayAt(23, 0), "MY BIRTHDAY", "There will be a lot of magic wands", green, alex.getId()));
// yesterday
events.add(new TimetableEvent(generateEventId(), yesterdayAt(9, 0), yesterdayAt(15, 30), "WORK", "Short day, will visit a doctor", blue, andrew.getId()));
events.add(new TimetableEvent(generateEventId(), yesterdayAt(16, 30), yesterdayAt(17, 30), "DOCTOR CONSULTATION", "Once-a-year visit", blue, andrew.getId()));
events.add(new ReservedTimeEvent(generateEventId(), andrew.getId(), yesterdayAt(18, 30), yesterdayAt(19, 30)));
events.add(new TimetableEvent(generateEventId(), yesterdayAt(10, 0), yesterdayAt(12, 30), "IREN FOTOSET", "Cute Iren with mother.<br/>Iren's mother phone: +1 (555) 987 98 12", orange, lucie.getId()));
events.add(new TimetableEvent(generateEventId(), yesterdayAt(16, 30), yesterdayAt(19, 0), "NATIONAL GEOGRAPHIC", "Show photos to NG and close the deal.", orange, lucie.getId()));
events.add(new TimetableEvent(generateEventId(), yesterdayAt(9, 0), yesterdayAt(11, 30), "BUY FOOD", "Beer, bread and circuses", green, alex.getId()));
events.add(new TimetableEvent(generateEventId(), yesterdayAt(13, 30), yesterdayAt(21, 0), "VISIT PARENTS", "Mom asked for my old cell phone.", green, alex.getId()));
// tomorrow
events.add(new ReservedTimeEvent(generateEventId(), andrew.getId(), tomorrowAt(6, 0), tomorrowAt(8, 30)));
events.add(new TimetableEvent(generateEventId(), tomorrowAt(9, 0), tomorrowAt(19, 30), "WORK", "As usual", blue, andrew.getId()));
events.add(new TimetableEvent(generateEventId(), tomorrowAt(20, 30), tomorrowAt(23, 30), "WENDY", "Table is reserved at Potato House", blue, andrew.getId()));
events.add(new ReservedTimeEvent(generateEventId(), lucie.getId(), tomorrowAt(6, 0), tomorrowAt(12, 30)));
events.add(new TimetableEvent(generateEventId(), tomorrowAt(14, 0), tomorrowAt(15, 0), "BRUCE ECKEL PRESS CONFERENCE", "Take 50D with EF 28-300", orange, lucie.getId()));
events.add(new TimetableEvent(generateEventId(), tomorrowAt(17, 30), tomorrowAt(20, 0), "SIGN CONTEST", "", orange, lucie.getId()));
events.add(new TimetableEvent(generateEventId(), tomorrowAt(8, 30), tomorrowAt(11, 30), "CLEAN HOUSE FROM GUESTS", "Andrew will go the first", green, alex.getId()));
events.add(new TimetableEvent(generateEventId(), tomorrowAt(13, 0), tomorrowAt(16, 0), "CHECK NEW KITE VIDEO", "Lucie promised to give me the \"Lines\".", green, alex.getId()));
events.add(new TimetableEvent(generateEventId(), tomorrowAt(19, 30), tomorrowAt(21, 0), "COUNTER-STRIKE", "The Spawn team wants to repeat.", green, alex.getId()));
resources.add(new TimetableResource(andrew, andrew.getId(), andrew.getName()));
resources.add(new TimetableResource(lucie, lucie.getId(), lucie.getName()));
resources.add(new TimetableResource(alex, alex.getId(), alex.getName()));
}
|
diff --git a/src/de/podfetcher/activity/MediaplayerActivity.java b/src/de/podfetcher/activity/MediaplayerActivity.java
index dd192673..85921729 100644
--- a/src/de/podfetcher/activity/MediaplayerActivity.java
+++ b/src/de/podfetcher/activity/MediaplayerActivity.java
@@ -1,366 +1,366 @@
package de.podfetcher.activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import de.podfetcher.PodcastApp;
import de.podfetcher.R;
import de.podfetcher.feed.FeedManager;
import de.podfetcher.feed.FeedMedia;
import de.podfetcher.service.PlaybackService;
import de.podfetcher.service.PlayerStatus;
import de.podfetcher.util.Converter;
public class MediaplayerActivity extends SherlockActivity {
private final String TAG = "MediaplayerActivity";
private static final int DEFAULT_SEEK_DELTA = 30000; // Seek-Delta to use
// when using FF or
// Rev Buttons
private PlaybackService playbackService;
private MediaPositionObserver positionObserver;
private FeedMedia media;
private PlayerStatus status;
private FeedManager manager;
// Widgets
private ImageView imgvCover;
private TextView txtvStatus;
private TextView txtvPosition;
private TextView txtvLength;
private SeekBar sbPosition;
private ImageButton butPlay;
private ImageButton butRev;
private ImageButton butFF;
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "Activity stopped");
try {
unregisterReceiver(statusUpdate);
} catch (IllegalArgumentException e) {
// ignore
}
try {
unbindService(mConnection);
} catch (IllegalArgumentException e) {
// ignore
}
if (positionObserver != null) {
positionObserver.cancel(true);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
return super.onCreateOptionsMenu(menu);
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "Resuming Activity");
bindToService();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "Creating Activity");
this.setContentView(R.layout.mediaplayer_activity);
manager = FeedManager.getInstance();
setupGUI();
bindToService();
}
private void bindToService() {
Intent serviceIntent = new Intent(this, PlaybackService.class);
boolean bound = false;
if (!PlaybackService.isRunning) {
Log.d(TAG, "Trying to restore last played media");
SharedPreferences prefs = getApplicationContext()
.getSharedPreferences(PodcastApp.PREF_NAME, 0);
long mediaId = prefs.getLong(PlaybackService.PREF_LAST_PLAYED_ID,
-1);
long feedId = prefs.getLong(
PlaybackService.PREF_LAST_PLAYED_FEED_ID, -1);
if (mediaId != -1 && feedId != -1) {
serviceIntent.putExtra(PlaybackService.EXTRA_FEED_ID, feedId);
serviceIntent.putExtra(PlaybackService.EXTRA_MEDIA_ID, mediaId);
serviceIntent.putExtra(
PlaybackService.EXTRA_START_WHEN_PREPARED, false);
serviceIntent.putExtra(PlaybackService.EXTRA_SHOULD_STREAM,
prefs.getBoolean(PlaybackService.PREF_LAST_IS_STREAM,
true));
startService(serviceIntent);
bound = bindService(serviceIntent, mConnection,
Context.BIND_AUTO_CREATE);
} else {
Log.d(TAG, "No last played media found");
status = PlayerStatus.STOPPED;
handleStatus();
}
} else {
bound = bindService(serviceIntent, mConnection, 0);
}
Log.d(TAG, "Result for service binding: " + bound);
}
private void handleStatus() {
switch (status) {
case ERROR:
setStatusMsg(R.string.player_error_msg, View.VISIBLE);
handleError();
break;
case PAUSED:
setStatusMsg(R.string.player_paused_msg, View.VISIBLE);
loadMediaInfo();
if (positionObserver != null) {
positionObserver.cancel(true);
positionObserver = null;
}
butPlay.setImageResource(android.R.drawable.ic_media_play);
break;
case PLAYING:
setStatusMsg(R.string.player_playing_msg, View.INVISIBLE);
loadMediaInfo();
setupPositionObserver();
butPlay.setImageResource(android.R.drawable.ic_media_pause);
break;
case PREPARING:
setStatusMsg(R.string.player_preparing_msg, View.VISIBLE);
break;
case STOPPED:
setStatusMsg(R.string.player_stopped_msg, View.VISIBLE);
imgvCover.setImageBitmap(null);
break;
case PREPARED:
loadMediaInfo();
setStatusMsg(R.string.player_ready_msg, View.VISIBLE);
butPlay.setImageResource(android.R.drawable.ic_media_play);
break;
case SEEKING:
setStatusMsg(R.string.player_seeking_msg, View.VISIBLE);
}
}
private void setStatusMsg(int resId, int visibility) {
if (visibility == View.VISIBLE) {
txtvStatus.setText(resId);
}
txtvStatus.setVisibility(visibility);
}
private void setupPositionObserver() {
if (positionObserver == null || positionObserver.isCancelled()) {
positionObserver = new MediaPositionObserver() {
@Override
protected void onProgressUpdate(Void... v) {
super.onProgressUpdate();
txtvPosition.setText(Converter
.getDurationStringLong(playbackService.getPlayer()
.getCurrentPosition()));
updateProgressbarPosition();
}
};
positionObserver.execute(playbackService.getPlayer());
}
}
private void updateProgressbarPosition() {
MediaPlayer player = playbackService.getPlayer();
float progress = ((float) player.getCurrentPosition())
/ player.getDuration();
sbPosition.setProgress((int) (progress * sbPosition.getMax()));
}
private void loadMediaInfo() {
if (media != null) {
MediaPlayer player = playbackService.getPlayer();
getSupportActionBar().setSubtitle(media.getItem().getTitle());
getSupportActionBar()
.setTitle(media.getItem().getFeed().getTitle());
imgvCover.setImageBitmap(media.getItem().getFeed().getImage()
.getImageBitmap());
txtvPosition.setText(Converter.getDurationStringLong((player
.getCurrentPosition())));
txtvLength.setText(Converter.getDurationStringLong(player
.getDuration()));
if (playbackService != null) {
updateProgressbarPosition();
} else {
sbPosition.setProgress(0);
}
}
}
private void setupGUI() {
imgvCover = (ImageView) findViewById(R.id.imgvCover);
txtvPosition = (TextView) findViewById(R.id.txtvPosition);
txtvLength = (TextView) findViewById(R.id.txtvLength);
txtvStatus = (TextView) findViewById(R.id.txtvStatus);
sbPosition = (SeekBar) findViewById(R.id.sbPosition);
butPlay = (ImageButton) findViewById(R.id.butPlay);
butRev = (ImageButton) findViewById(R.id.butRev);
butFF = (ImageButton) findViewById(R.id.butFF);
sbPosition.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
int duration;
float prog;
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if (fromUser) {
- prog = progress / 100.0f;
+ prog = progress / ((float) seekBar.getMax());
duration = playbackService.getPlayer().getDuration();
txtvPosition.setText(Converter
.getDurationStringLong((int) (prog * duration)));
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// interrupt position Observer, restart later
if (positionObserver != null) {
positionObserver.cancel(true);
positionObserver = null;
}
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
playbackService.seek((int) (prog * duration));
setupPositionObserver();
}
});
butPlay.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (status == PlayerStatus.PLAYING) {
playbackService.pause();
} else if (status == PlayerStatus.PAUSED
|| status == PlayerStatus.PREPARED) {
playbackService.play();
}
}
});
butFF.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (status == PlayerStatus.PLAYING) {
playbackService.seekDelta(DEFAULT_SEEK_DELTA);
}
}
});
butRev.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (status == PlayerStatus.PLAYING) {
playbackService.seekDelta(-DEFAULT_SEEK_DELTA);
}
}
});
}
private void handleError() {
// TODO implement
}
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
playbackService = ((PlaybackService.LocalBinder) service)
.getService();
status = playbackService.getStatus();
media = playbackService.getMedia();
registerReceiver(statusUpdate, new IntentFilter(
PlaybackService.ACTION_PLAYER_STATUS_CHANGED));
handleStatus();
Log.d(TAG, "Connection to Service established");
}
@Override
public void onServiceDisconnected(ComponentName name) {
playbackService = null;
Log.d(TAG, "Disconnected from Service");
}
};
private BroadcastReceiver statusUpdate = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "Received statusUpdate Intent.");
status = playbackService.getStatus();
handleStatus();
}
};
/** Refreshes the current position of the media file that is playing. */
public class MediaPositionObserver extends
AsyncTask<MediaPlayer, Void, Void> {
private static final int WAITING_INTERVALL = 1000;
private MediaPlayer player;
@Override
protected void onCancelled() {
Log.d(TAG, "Task was cancelled");
}
@Override
protected Void doInBackground(MediaPlayer... p) {
Log.d(TAG, "Background Task started");
player = p[0];
while (player.isPlaying() && !isCancelled()) {
try {
Thread.sleep(WAITING_INTERVALL);
} catch (InterruptedException e) {
Log.d(TAG,
"Thread was interrupted while waiting. Finishing now");
}
publishProgress();
}
Log.d(TAG, "Background Task finished");
return null;
}
}
}
| true | true | private void setupGUI() {
imgvCover = (ImageView) findViewById(R.id.imgvCover);
txtvPosition = (TextView) findViewById(R.id.txtvPosition);
txtvLength = (TextView) findViewById(R.id.txtvLength);
txtvStatus = (TextView) findViewById(R.id.txtvStatus);
sbPosition = (SeekBar) findViewById(R.id.sbPosition);
butPlay = (ImageButton) findViewById(R.id.butPlay);
butRev = (ImageButton) findViewById(R.id.butRev);
butFF = (ImageButton) findViewById(R.id.butFF);
sbPosition.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
int duration;
float prog;
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if (fromUser) {
prog = progress / 100.0f;
duration = playbackService.getPlayer().getDuration();
txtvPosition.setText(Converter
.getDurationStringLong((int) (prog * duration)));
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// interrupt position Observer, restart later
if (positionObserver != null) {
positionObserver.cancel(true);
positionObserver = null;
}
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
playbackService.seek((int) (prog * duration));
setupPositionObserver();
}
});
butPlay.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (status == PlayerStatus.PLAYING) {
playbackService.pause();
} else if (status == PlayerStatus.PAUSED
|| status == PlayerStatus.PREPARED) {
playbackService.play();
}
}
});
butFF.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (status == PlayerStatus.PLAYING) {
playbackService.seekDelta(DEFAULT_SEEK_DELTA);
}
}
});
butRev.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (status == PlayerStatus.PLAYING) {
playbackService.seekDelta(-DEFAULT_SEEK_DELTA);
}
}
});
}
| private void setupGUI() {
imgvCover = (ImageView) findViewById(R.id.imgvCover);
txtvPosition = (TextView) findViewById(R.id.txtvPosition);
txtvLength = (TextView) findViewById(R.id.txtvLength);
txtvStatus = (TextView) findViewById(R.id.txtvStatus);
sbPosition = (SeekBar) findViewById(R.id.sbPosition);
butPlay = (ImageButton) findViewById(R.id.butPlay);
butRev = (ImageButton) findViewById(R.id.butRev);
butFF = (ImageButton) findViewById(R.id.butFF);
sbPosition.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
int duration;
float prog;
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if (fromUser) {
prog = progress / ((float) seekBar.getMax());
duration = playbackService.getPlayer().getDuration();
txtvPosition.setText(Converter
.getDurationStringLong((int) (prog * duration)));
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// interrupt position Observer, restart later
if (positionObserver != null) {
positionObserver.cancel(true);
positionObserver = null;
}
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
playbackService.seek((int) (prog * duration));
setupPositionObserver();
}
});
butPlay.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (status == PlayerStatus.PLAYING) {
playbackService.pause();
} else if (status == PlayerStatus.PAUSED
|| status == PlayerStatus.PREPARED) {
playbackService.play();
}
}
});
butFF.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (status == PlayerStatus.PLAYING) {
playbackService.seekDelta(DEFAULT_SEEK_DELTA);
}
}
});
butRev.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (status == PlayerStatus.PLAYING) {
playbackService.seekDelta(-DEFAULT_SEEK_DELTA);
}
}
});
}
|
diff --git a/VodiSmetka/src/com/vodismetka/activities/AddNewReceiptActivity.java b/VodiSmetka/src/com/vodismetka/activities/AddNewReceiptActivity.java
index e4d1a52..f57bdb4 100644
--- a/VodiSmetka/src/com/vodismetka/activities/AddNewReceiptActivity.java
+++ b/VodiSmetka/src/com/vodismetka/activities/AddNewReceiptActivity.java
@@ -1,151 +1,151 @@
package com.vodismetka.activities;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.vodismetka.R;
import com.vodismetka.sql.ReceiptDAO;
import com.vodismetka.workers.ImageFactory;
public class AddNewReceiptActivity extends Activity {
public static final String TAG = "AddNewReceiptActivity";
static final int DATE_DIALOG_ID = 0;
private ImageView receiptPhoto;
private EditText dateText;
private EditText priceText;
private Button submit;
private ReceiptDAO dbDao;
private int extractedPrice;
private String extractedDate;
private String imgId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_purchase);
//set up a data access object
dbDao = new ReceiptDAO(getApplicationContext());
//get references to the views
receiptPhoto = (ImageView) findViewById(R.id.newReceipt);
dateText = (EditText) findViewById(R.id.newReceiptDate);
priceText = (EditText) findViewById(R.id.newReceiptTotalAmount);
submit = (Button) findViewById(R.id.confirm);
//get the calling intent so we can set the initially recognized price and date
Intent callingIntent = getIntent();
extractedPrice = callingIntent.getExtras().getInt(LaunchActivity.PRICE_KEY);
extractedDate = callingIntent.getExtras().getString(LaunchActivity.DATE_KEY);
- extractedDate = callingIntent.getExtras().getString(LaunchActivity.IMG_KEY);
+ imgId = callingIntent.getExtras().getString(LaunchActivity.IMG_KEY);
//set the initial price and date
priceText.setText(Integer.toString(extractedPrice));
dateText.setText(extractedDate);
//load and set the image
receiptPhoto.setImageBitmap(ImageFactory.loadImage(ImageFactory.IMAGES_PATH + imgId));
//view the full receipt
receiptPhoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent viewFullImg = new Intent(getApplicationContext(), ViewReceiptActivity.class);
viewFullImg.putExtra(LaunchActivity.IMG_KEY, imgId);
startActivity(viewFullImg);
}
});
//remind the user to check and correct the price
priceText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Please verify the correct price of the receipt...", Toast.LENGTH_SHORT).show();
}
});
//insert the new receipt in the database
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int rPrice = Integer.parseInt(priceText.getText().toString());
String rDate = dateText.getText().toString();
- String[] dateParts = extractedDate.split("(\\W{1})");
+ String[] dateParts = rDate.split("(\\W{1})");
int rMonth = Integer.parseInt(dateParts[1]);
dbDao.insertNewItem(rPrice, rDate, imgId, rMonth);
}
});
//show a datePicker dialog to correct the date
dateText.setOnTouchListener(new OnTouchListener(){
public boolean onTouch(View v, MotionEvent event) {
if(v == dateText)
showDialog(DATE_DIALOG_ID);
return false;
}
});
}
@Override
protected Dialog onCreateDialog(int id) {
DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
// onDateSet method
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
String date_selected = String.valueOf(dayOfMonth)+"/"+String.valueOf(monthOfYear+1)+"/"+String.valueOf(year);
//Toast.makeText(getApplicationContext(), "Selected Date is ="+date_selected, Toast.LENGTH_SHORT).show();
dateText.setText(date_selected);
}
};
int year = 2014;
int month = 1;
int day = 1;
try{
String[] dateParts = extractedDate.split("(\\W{1})");
day = Integer.parseInt(dateParts[0]);
month = Integer.parseInt(dateParts[1]);
year = Integer.parseInt(dateParts[2]);
}catch(Exception e) {
Toast.makeText(getApplicationContext(), "Sorry... The date of the receipt could not be recognized...", Toast.LENGTH_LONG).show();
year = 2014;
month = 1;
day = 1;
}
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this, mDateSetListener, year, month, day);
}
return null;
}
@Override
protected void onResume() {
super.onResume();
}
}
| false | true | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_purchase);
//set up a data access object
dbDao = new ReceiptDAO(getApplicationContext());
//get references to the views
receiptPhoto = (ImageView) findViewById(R.id.newReceipt);
dateText = (EditText) findViewById(R.id.newReceiptDate);
priceText = (EditText) findViewById(R.id.newReceiptTotalAmount);
submit = (Button) findViewById(R.id.confirm);
//get the calling intent so we can set the initially recognized price and date
Intent callingIntent = getIntent();
extractedPrice = callingIntent.getExtras().getInt(LaunchActivity.PRICE_KEY);
extractedDate = callingIntent.getExtras().getString(LaunchActivity.DATE_KEY);
extractedDate = callingIntent.getExtras().getString(LaunchActivity.IMG_KEY);
//set the initial price and date
priceText.setText(Integer.toString(extractedPrice));
dateText.setText(extractedDate);
//load and set the image
receiptPhoto.setImageBitmap(ImageFactory.loadImage(ImageFactory.IMAGES_PATH + imgId));
//view the full receipt
receiptPhoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent viewFullImg = new Intent(getApplicationContext(), ViewReceiptActivity.class);
viewFullImg.putExtra(LaunchActivity.IMG_KEY, imgId);
startActivity(viewFullImg);
}
});
//remind the user to check and correct the price
priceText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Please verify the correct price of the receipt...", Toast.LENGTH_SHORT).show();
}
});
//insert the new receipt in the database
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int rPrice = Integer.parseInt(priceText.getText().toString());
String rDate = dateText.getText().toString();
String[] dateParts = extractedDate.split("(\\W{1})");
int rMonth = Integer.parseInt(dateParts[1]);
dbDao.insertNewItem(rPrice, rDate, imgId, rMonth);
}
});
//show a datePicker dialog to correct the date
dateText.setOnTouchListener(new OnTouchListener(){
public boolean onTouch(View v, MotionEvent event) {
if(v == dateText)
showDialog(DATE_DIALOG_ID);
return false;
}
});
}
| protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_purchase);
//set up a data access object
dbDao = new ReceiptDAO(getApplicationContext());
//get references to the views
receiptPhoto = (ImageView) findViewById(R.id.newReceipt);
dateText = (EditText) findViewById(R.id.newReceiptDate);
priceText = (EditText) findViewById(R.id.newReceiptTotalAmount);
submit = (Button) findViewById(R.id.confirm);
//get the calling intent so we can set the initially recognized price and date
Intent callingIntent = getIntent();
extractedPrice = callingIntent.getExtras().getInt(LaunchActivity.PRICE_KEY);
extractedDate = callingIntent.getExtras().getString(LaunchActivity.DATE_KEY);
imgId = callingIntent.getExtras().getString(LaunchActivity.IMG_KEY);
//set the initial price and date
priceText.setText(Integer.toString(extractedPrice));
dateText.setText(extractedDate);
//load and set the image
receiptPhoto.setImageBitmap(ImageFactory.loadImage(ImageFactory.IMAGES_PATH + imgId));
//view the full receipt
receiptPhoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent viewFullImg = new Intent(getApplicationContext(), ViewReceiptActivity.class);
viewFullImg.putExtra(LaunchActivity.IMG_KEY, imgId);
startActivity(viewFullImg);
}
});
//remind the user to check and correct the price
priceText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Please verify the correct price of the receipt...", Toast.LENGTH_SHORT).show();
}
});
//insert the new receipt in the database
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int rPrice = Integer.parseInt(priceText.getText().toString());
String rDate = dateText.getText().toString();
String[] dateParts = rDate.split("(\\W{1})");
int rMonth = Integer.parseInt(dateParts[1]);
dbDao.insertNewItem(rPrice, rDate, imgId, rMonth);
}
});
//show a datePicker dialog to correct the date
dateText.setOnTouchListener(new OnTouchListener(){
public boolean onTouch(View v, MotionEvent event) {
if(v == dateText)
showDialog(DATE_DIALOG_ID);
return false;
}
});
}
|
diff --git a/core/vdmj/src/main/java/org/overturetool/vdmj/expressions/NewExpression.java b/core/vdmj/src/main/java/org/overturetool/vdmj/expressions/NewExpression.java
index f9e16ccf06..2967ae35ad 100644
--- a/core/vdmj/src/main/java/org/overturetool/vdmj/expressions/NewExpression.java
+++ b/core/vdmj/src/main/java/org/overturetool/vdmj/expressions/NewExpression.java
@@ -1,176 +1,181 @@
/*******************************************************************************
*
* Copyright (c) 2008 Fujitsu Services Ltd.
*
* Author: Nick Battle
*
* This file is part of VDMJ.
*
* VDMJ 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.
*
* VDMJ 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 VDMJ. If not, see <http://www.gnu.org/licenses/>.
*
******************************************************************************/
package org.overturetool.vdmj.expressions;
import org.overturetool.vdmj.definitions.ClassDefinition;
import org.overturetool.vdmj.definitions.Definition;
import org.overturetool.vdmj.lex.LexIdentifierToken;
import org.overturetool.vdmj.lex.LexLocation;
import org.overturetool.vdmj.pog.POContextStack;
import org.overturetool.vdmj.pog.ProofObligationList;
import org.overturetool.vdmj.runtime.Context;
import org.overturetool.vdmj.runtime.ValueException;
import org.overturetool.vdmj.typechecker.Environment;
import org.overturetool.vdmj.typechecker.NameScope;
import org.overturetool.vdmj.types.Type;
import org.overturetool.vdmj.types.TypeList;
import org.overturetool.vdmj.types.UnknownType;
import org.overturetool.vdmj.util.Utils;
import org.overturetool.vdmj.values.ObjectValue;
import org.overturetool.vdmj.values.Value;
import org.overturetool.vdmj.values.ValueList;
public class NewExpression extends Expression
{
private static final long serialVersionUID = 1L;
public final LexIdentifierToken classname;
public final ExpressionList args;
private ClassDefinition classdef;
private Definition ctorDefinition = null;
public NewExpression(LexLocation location,
LexIdentifierToken classname, ExpressionList args)
{
super(location);
this.classname = classname;
this.args = args;
}
@Override
public String toString()
{
return "new " + classname + "("+ Utils.listToString(args) + ")";
}
@Override
public Type typeCheck(Environment env, TypeList qualifiers, NameScope scope)
{
Definition cdef = env.findType(classname.getClassName());
if (cdef == null || !(cdef instanceof ClassDefinition))
{
report(3133, "Class name " + classname + " not in scope");
return new UnknownType(location);
}
classdef = (ClassDefinition)cdef;
if (classdef.isSystem)
{
report(3279, "Cannot instantiate system class " + classdef.name);
}
TypeList argtypes = new TypeList();
for (Expression a: args)
{
argtypes.add(a.typeCheck(env, null, scope));
}
Definition opdef = classdef.findConstructor(argtypes);
if (opdef == null)
{
if (!args.isEmpty()) // Not having a default ctor is OK
{
report(3134, "Class has no constructor with these parameter types");
detail("Called", classdef.getCtorName(argtypes));
}
}
else
{
if (!opdef.isCallableOperation())
{
report(3135, "Class has no constructor with these parameter types");
detail("Called", classdef.getCtorName(argtypes));
}
+ else if (!ClassDefinition.isAccessible(env, opdef, false))
+ {
+ report(3292, "Constructor is not accessible");
+ detail("Called", classdef.getCtorName(argtypes));
+ }
else
{
ctorDefinition = opdef;
}
}
return classdef.getType();
}
@Override
public Value eval(Context ctxt)
{
breakpoint.check(location, ctxt);
try
{
ValueList argvals = new ValueList();
for (Expression arg: args)
{
argvals.add(arg.eval(ctxt));
}
if (classdef.invlistener != null)
{
// Suppress during construction
classdef.invlistener.doInvariantChecks = false;
}
ObjectValue objval =
classdef.newInstance(ctorDefinition, argvals, ctxt);
if (classdef.invlistener != null)
{
// Check the initial values of the object's fields
classdef.invlistener.doInvariantChecks = true;
classdef.invlistener.changedValue(location, objval, ctxt);
}
return objval;
}
catch (ValueException e)
{
return abort(e);
}
}
@Override
public Expression findExpression(int lineno)
{
Expression found = super.findExpression(lineno);
if (found != null) return found;
return args.findExpression(lineno);
}
@Override
public ProofObligationList getProofObligations(POContextStack ctxt)
{
return args.getProofObligations(ctxt);
}
@Override
public String kind()
{
return "new";
}
}
| true | true | public Type typeCheck(Environment env, TypeList qualifiers, NameScope scope)
{
Definition cdef = env.findType(classname.getClassName());
if (cdef == null || !(cdef instanceof ClassDefinition))
{
report(3133, "Class name " + classname + " not in scope");
return new UnknownType(location);
}
classdef = (ClassDefinition)cdef;
if (classdef.isSystem)
{
report(3279, "Cannot instantiate system class " + classdef.name);
}
TypeList argtypes = new TypeList();
for (Expression a: args)
{
argtypes.add(a.typeCheck(env, null, scope));
}
Definition opdef = classdef.findConstructor(argtypes);
if (opdef == null)
{
if (!args.isEmpty()) // Not having a default ctor is OK
{
report(3134, "Class has no constructor with these parameter types");
detail("Called", classdef.getCtorName(argtypes));
}
}
else
{
if (!opdef.isCallableOperation())
{
report(3135, "Class has no constructor with these parameter types");
detail("Called", classdef.getCtorName(argtypes));
}
else
{
ctorDefinition = opdef;
}
}
return classdef.getType();
}
| public Type typeCheck(Environment env, TypeList qualifiers, NameScope scope)
{
Definition cdef = env.findType(classname.getClassName());
if (cdef == null || !(cdef instanceof ClassDefinition))
{
report(3133, "Class name " + classname + " not in scope");
return new UnknownType(location);
}
classdef = (ClassDefinition)cdef;
if (classdef.isSystem)
{
report(3279, "Cannot instantiate system class " + classdef.name);
}
TypeList argtypes = new TypeList();
for (Expression a: args)
{
argtypes.add(a.typeCheck(env, null, scope));
}
Definition opdef = classdef.findConstructor(argtypes);
if (opdef == null)
{
if (!args.isEmpty()) // Not having a default ctor is OK
{
report(3134, "Class has no constructor with these parameter types");
detail("Called", classdef.getCtorName(argtypes));
}
}
else
{
if (!opdef.isCallableOperation())
{
report(3135, "Class has no constructor with these parameter types");
detail("Called", classdef.getCtorName(argtypes));
}
else if (!ClassDefinition.isAccessible(env, opdef, false))
{
report(3292, "Constructor is not accessible");
detail("Called", classdef.getCtorName(argtypes));
}
else
{
ctorDefinition = opdef;
}
}
return classdef.getType();
}
|
diff --git a/GAE/src/org/waterforpeople/mapping/dataexport/RawDataExporter.java b/GAE/src/org/waterforpeople/mapping/dataexport/RawDataExporter.java
index a52867108..12dc68502 100644
--- a/GAE/src/org/waterforpeople/mapping/dataexport/RawDataExporter.java
+++ b/GAE/src/org/waterforpeople/mapping/dataexport/RawDataExporter.java
@@ -1,231 +1,232 @@
package org.waterforpeople.mapping.dataexport;
import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.Map.Entry;
import org.json.JSONArray;
import org.json.JSONObject;
import org.waterforpeople.mapping.app.gwt.client.survey.QuestionDto;
import org.waterforpeople.mapping.app.gwt.client.survey.QuestionGroupDto;
import org.waterforpeople.mapping.app.web.dto.DataBackoutRequest;
import org.waterforpeople.mapping.app.web.dto.SurveyRestRequest;
/**
* exports raw data based on a date
*
* @author Christopher Fagiani
*
*/
public class RawDataExporter extends AbstractDataExporter {
private static final String DATA_SERVLET_PATH = "/databackout?action=";
public static final String RESPONSE_KEY = "dtoList";
private static final String SURVEY_SERVLET_PATH = "/surveyrestapi?action=";
private String serverBase;
private String surveyId;
public static final String SURVEY_ID = "surveyId";
private Map<String, String> questionMap;
@Override
public void export(Map<String, String> criteria, File fileName,
String serverBase) {
this.serverBase = serverBase;
surveyId = criteria.get(SURVEY_ID);
PrintWriter pw = null;
try {
questionMap = loadQuestions();
pw = new PrintWriter(fileName);
List<String> ids = writeHeader(pw, questionMap);
exportInstances(pw, ids);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (pw != null) {
pw.close();
}
}
}
private List<String> writeHeader(PrintWriter pw,
Map<String, String> questions) {
List<String> idList = new ArrayList<String>();
pw.print("Instance\tSubmission Date");
for (Entry<String, String> qEntry : questions.entrySet()) {
pw.print("\t");
pw.write(qEntry.getValue());
idList.add(qEntry.getKey());
}
pw.print("\n");
return idList;
}
private Map<String, String> loadQuestions() throws Exception {
Map<String, String> questions = new HashMap<String, String>();
List<QuestionGroupDto> groups = fetchQuestionGroups(serverBase,
surveyId);
if (groups != null) {
for (QuestionGroupDto group : groups) {
List<QuestionDto> questionDtos = fetchQuestions(serverBase,
group.getKeyId());
if (questionDtos != null) {
for (QuestionDto question : questionDtos) {
questions.put(question.getKeyId().toString(), question
.getText());
}
}
}
}
return questions;
}
private List<QuestionDto> fetchQuestions(String serverBase, Long groupId)
throws Exception {
return parseQuestions(fetchDataFromServer(serverBase
+ SURVEY_SERVLET_PATH + SurveyRestRequest.LIST_QUESTION_ACTION
+ "&" + SurveyRestRequest.QUESTION_GROUP_ID_PARAM + "="
+ groupId));
}
private List<QuestionGroupDto> fetchQuestionGroups(String serverBase,
String surveyId) throws Exception {
return parseQuestionGroups(fetchDataFromServer(serverBase
+ SURVEY_SERVLET_PATH + SurveyRestRequest.LIST_GROUP_ACTION
+ "&" + SurveyRestRequest.SURVEY_ID_PARAM + "=" + surveyId));
}
private List<QuestionGroupDto> parseQuestionGroups(String response)
throws Exception {
List<QuestionGroupDto> dtoList = new ArrayList<QuestionGroupDto>();
JSONArray arr = getJsonArray(response);
if (arr != null) {
for (int i = 0; i < arr.length(); i++) {
JSONObject json = arr.getJSONObject(i);
if (json != null) {
QuestionGroupDto dto = new QuestionGroupDto();
try {
if (json.has("code")) {
dto.setCode(json.getString("code"));
}
if (json.has("keyId")) {
dto.setKeyId(json.getLong("keyId"));
}
dtoList.add(dto);
} catch (Exception e) {
System.out.println("Error in json parsing: " + e);
e.printStackTrace();
}
}
}
}
return dtoList;
}
private List<QuestionDto> parseQuestions(String response) throws Exception {
List<QuestionDto> dtoList = new ArrayList<QuestionDto>();
JSONArray arr = getJsonArray(response);
if (arr != null) {
for (int i = 0; i < arr.length(); i++) {
JSONObject json = arr.getJSONObject(i);
if (json != null) {
QuestionDto dto = new QuestionDto();
try {
if (json.has("text")) {
dto.setText(json.getString("text"));
}
if (json.has("keyId")) {
dto.setKeyId(json.getLong("keyId"));
}
dtoList.add(dto);
} catch (Exception e) {
System.out.println("Error in json parsing: " + e);
e.printStackTrace();
}
}
}
}
return dtoList;
}
private void exportInstances(PrintWriter pw, List<String> idList)
throws Exception {
String instanceString = fetchDataFromServer(serverBase
+ DATA_SERVLET_PATH + DataBackoutRequest.LIST_INSTANCE_ACTION
+ "&" + DataBackoutRequest.SURVEY_ID_PARAM + "=" + surveyId+"&"+DataBackoutRequest.INCLUDE_DATE_PARAM+"=true");
if (instanceString != null) {
StringTokenizer strTok = new StringTokenizer(instanceString, ",");
while (strTok.hasMoreTokens()) {
String instanceId = strTok.nextToken();
String dateString = "";
if(instanceId.contains("|")){
dateString = instanceId.substring(instanceId.indexOf("|")+1);
instanceId = instanceId.substring(0,instanceId.indexOf("|"));
}
if (instanceId != null && instanceId.trim().length() > 0) {
String instanceValues = fetchDataFromServer(serverBase
+ DATA_SERVLET_PATH
+ DataBackoutRequest.LIST_INSTANCE_RESPONSE_ACTION
+ "&" + DataBackoutRequest.SURVEY_INSTANCE_ID_PARAM
+ "=" + instanceId);
Map<String, String> responses = parseInstanceValues(instanceValues);
if (responses != null) {
pw.print(instanceId);
+ pw.print("\t");
pw.print(dateString);
for (String key : idList) {
String val = responses.get(key);
pw.print("\t");
if (val != null) {
pw.print(val.trim());
}
}
pw.print("\n");
}
}
}
}
}
private Map<String, String> parseInstanceValues(String data) {
Map<String, String> responseMap = new HashMap<String, String>();
if (data != null) {
StringTokenizer strTok = new StringTokenizer(data, ",\n");
while (strTok.hasMoreTokens()) {
String key = strTok.nextToken();
String val = strTok.nextToken();
String oldVal = responseMap.get(key);
if (oldVal != null) {
if (val != null) {
if (oldVal.trim().length() < val.trim().length()) {
responseMap.put(key, val);
}
}
} else {
responseMap.put(key, val);
}
}
}
return responseMap;
}
/**
* converts the string into a JSON array object.
*/
private JSONArray getJsonArray(String response) throws Exception {
System.out.println("response: " + response);
if (response != null) {
JSONObject json = new JSONObject(response);
if (json != null) {
return json.getJSONArray(RESPONSE_KEY);
}
}
return null;
}
}
| true | true | private void exportInstances(PrintWriter pw, List<String> idList)
throws Exception {
String instanceString = fetchDataFromServer(serverBase
+ DATA_SERVLET_PATH + DataBackoutRequest.LIST_INSTANCE_ACTION
+ "&" + DataBackoutRequest.SURVEY_ID_PARAM + "=" + surveyId+"&"+DataBackoutRequest.INCLUDE_DATE_PARAM+"=true");
if (instanceString != null) {
StringTokenizer strTok = new StringTokenizer(instanceString, ",");
while (strTok.hasMoreTokens()) {
String instanceId = strTok.nextToken();
String dateString = "";
if(instanceId.contains("|")){
dateString = instanceId.substring(instanceId.indexOf("|")+1);
instanceId = instanceId.substring(0,instanceId.indexOf("|"));
}
if (instanceId != null && instanceId.trim().length() > 0) {
String instanceValues = fetchDataFromServer(serverBase
+ DATA_SERVLET_PATH
+ DataBackoutRequest.LIST_INSTANCE_RESPONSE_ACTION
+ "&" + DataBackoutRequest.SURVEY_INSTANCE_ID_PARAM
+ "=" + instanceId);
Map<String, String> responses = parseInstanceValues(instanceValues);
if (responses != null) {
pw.print(instanceId);
pw.print(dateString);
for (String key : idList) {
String val = responses.get(key);
pw.print("\t");
if (val != null) {
pw.print(val.trim());
}
}
pw.print("\n");
}
}
}
}
}
| private void exportInstances(PrintWriter pw, List<String> idList)
throws Exception {
String instanceString = fetchDataFromServer(serverBase
+ DATA_SERVLET_PATH + DataBackoutRequest.LIST_INSTANCE_ACTION
+ "&" + DataBackoutRequest.SURVEY_ID_PARAM + "=" + surveyId+"&"+DataBackoutRequest.INCLUDE_DATE_PARAM+"=true");
if (instanceString != null) {
StringTokenizer strTok = new StringTokenizer(instanceString, ",");
while (strTok.hasMoreTokens()) {
String instanceId = strTok.nextToken();
String dateString = "";
if(instanceId.contains("|")){
dateString = instanceId.substring(instanceId.indexOf("|")+1);
instanceId = instanceId.substring(0,instanceId.indexOf("|"));
}
if (instanceId != null && instanceId.trim().length() > 0) {
String instanceValues = fetchDataFromServer(serverBase
+ DATA_SERVLET_PATH
+ DataBackoutRequest.LIST_INSTANCE_RESPONSE_ACTION
+ "&" + DataBackoutRequest.SURVEY_INSTANCE_ID_PARAM
+ "=" + instanceId);
Map<String, String> responses = parseInstanceValues(instanceValues);
if (responses != null) {
pw.print(instanceId);
pw.print("\t");
pw.print(dateString);
for (String key : idList) {
String val = responses.get(key);
pw.print("\t");
if (val != null) {
pw.print(val.trim());
}
}
pw.print("\n");
}
}
}
}
}
|
diff --git a/src/de/schildbach/pte/VbbProvider.java b/src/de/schildbach/pte/VbbProvider.java
index a6f8a98c..8a48fa2b 100644
--- a/src/de/schildbach/pte/VbbProvider.java
+++ b/src/de/schildbach/pte/VbbProvider.java
@@ -1,730 +1,730 @@
/*
* Copyright 2010 the original author or authors.
*
* 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.schildbach.pte;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author Andreas Schildbach
*/
public final class VbbProvider implements NetworkProvider
{
public static final String NETWORK_ID = "mobil.bvg.de";
private static final long PARSER_DAY_ROLLOVER_THRESHOLD_MS = 12 * 60 * 60 * 1000;
private static final long PARSER_DAY_ROLLDOWN_THRESHOLD_MS = 6 * 60 * 60 * 1000;
private static final String BVG_BASE_URL = "http://mobil.bvg.de";
public boolean hasCapabilities(Capability... capabilities)
{
for (final Capability capability : capabilities)
if (capability == Capability.NEARBY_STATIONS)
return false;
return true;
}
private static final Pattern P_AUTOCOMPLETE_IS_MAST = Pattern.compile("\\d{6}");
private static final String AUTOCOMPLETE_NAME_URL = "http://mobil.bvg.de/Fahrinfo/bin/stboard.bin/dox/dox?input=";
private static final Pattern P_SINGLE_NAME = Pattern.compile(".*Haltestelleninfo.*?<strong>(.*?)</strong>.*", Pattern.DOTALL);
private static final Pattern P_MULTI_NAME = Pattern.compile("<a href=\\\"/Fahrinfo/bin/stboard.*?\\\">\\s*(.*?)\\s*</a>", Pattern.DOTALL);
private static final String AUTOCOMPLETE_MASTID_URL = "http://mobil.bvg.de/IstAbfahrtzeiten/index/mobil?input=";
private static final Pattern P_SINGLE_MASTID = Pattern.compile(".*Ist-Abfahrtzeiten.*?<strong>(.*?)</strong>.*", Pattern.DOTALL);
public List<String> autoCompleteStationName(CharSequence constraint) throws IOException
{
final List<String> names = new ArrayList<String>();
if (P_AUTOCOMPLETE_IS_MAST.matcher(constraint).matches())
{
final CharSequence page = ParserUtils.scrape(AUTOCOMPLETE_MASTID_URL + ParserUtils.urlEncode(constraint.toString()));
final Matcher mSingle = P_SINGLE_MASTID.matcher(page);
if (mSingle.matches())
{
names.add(ParserUtils.resolveEntities(mSingle.group(1)));
}
}
else
{
final CharSequence page = ParserUtils.scrape(AUTOCOMPLETE_NAME_URL + ParserUtils.urlEncode(constraint.toString()));
final Matcher mSingle = P_SINGLE_NAME.matcher(page);
if (mSingle.matches())
{
names.add(ParserUtils.resolveEntities(mSingle.group(1)));
}
else
{
final Matcher mMulti = P_MULTI_NAME.matcher(page);
while (mMulti.find())
names.add(ParserUtils.resolveEntities(mMulti.group(1)));
}
}
return names;
}
public List<Station> nearbyStations(final double lat, final double lon, final int maxDistance, final int maxStations) throws IOException
{
throw new UnsupportedOperationException();
}
private static Pattern P_STATION_LOCATION = Pattern.compile("<Station name=\"(.*?)\" x=\"(\\d+)\" y=\"(\\d+)\" type=\"WGS84\"");
private static Pattern P_STATION_LOCATION_ERROR = Pattern.compile("(No trains in result)|(No Response from Server)");
public StationLocationResult stationLocation(final String stationId) throws IOException
{
final boolean live = stationId.length() == 6;
if (live)
throw new UnsupportedOperationException();
final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd");
final DateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm");
final Date now = new Date();
final String request = "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?><ReqC lang=\"DE\" prod=\"testsystem\" ver=\"1.1\" accessId=\"VBB-STD\"><STBReq boardType='DEP'><Time>"
+ TIME_FORMAT.format(now)
+ "</Time><Period><DateBegin>"
+ DATE_FORMAT.format(now)
+ "</DateBegin><DateEnd>"
+ DATE_FORMAT.format(now) + "</DateEnd></Period><TableStation externalId='" + stationId + "'/></STBReq></ReqC>";
final String uri = "http://www.vbb-fahrinfo.de/hafas/extxml/extxml.exe/dn";
final CharSequence page = ParserUtils.scrape(uri, request);
final Matcher mError = P_STATION_LOCATION_ERROR.matcher(page);
if (mError.find())
{
if (mError.group(1) != null)
return null;
if (mError.group(2) != null)
throw new RuntimeException("timeout error");
}
final Matcher m = P_STATION_LOCATION.matcher(page);
if (m.find())
{
final String name = ParserUtils.resolveEntities(m.group(1));
final double lon = latLonToDouble(Integer.parseInt(m.group(2)));
final double lat = latLonToDouble(Integer.parseInt(m.group(3)));
return new StationLocationResult(lat, lon, name);
}
else
{
throw new IllegalArgumentException("cannot parse '" + page + "' on " + uri);
}
}
private static double latLonToDouble(int value)
{
return (double) value / 1000000;
}
public static final String STATION_URL_CONNECTION = "http://mobil.bvg.de/Fahrinfo/bin/query.bin/dox";
private String connectionsQueryUri(final String from, final String via, final String to, final Date date, final boolean dep)
{
final DateFormat DATE_FORMAT = new SimpleDateFormat("dd.MM.yy");
final DateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm");
final StringBuilder uri = new StringBuilder();
uri.append("http://mobil.bvg.de/Fahrinfo/bin/query.bin/dox");
uri.append("?REQ0HafasInitialSelection=0");
uri.append("&REQ0JourneyStopsS0A=255");
uri.append("&REQ0JourneyStopsS0G=").append(ParserUtils.urlEncode(from));
if (via != null)
{
uri.append("&REQ0JourneyStops1A=1");
uri.append("&REQ0JourneyStops1G=").append(ParserUtils.urlEncode(via));
}
uri.append("&REQ0JourneyStopsZ0A=255");
uri.append("&REQ0JourneyStopsZ0G=").append(ParserUtils.urlEncode(to));
uri.append("&REQ0HafasSearchForw=").append(dep ? "1" : "0");
uri.append("&REQ0JourneyDate=").append(ParserUtils.urlEncode(DATE_FORMAT.format(date)));
uri.append("&REQ0JourneyTime=").append(ParserUtils.urlEncode(TIME_FORMAT.format(date)));
uri.append("&start=Suchen");
return uri.toString();
}
private static final Pattern P_CHECK_ADDRESS = Pattern.compile("<option.*?>\\s*(.*?)\\s*</option>", Pattern.DOTALL);
private static final Pattern P_CHECK_FROM = Pattern.compile("Von:");
private static final Pattern P_CHECK_TO = Pattern.compile("Nach:");
private static final Pattern P_CHECK_CONNECTIONS_ERROR = Pattern.compile("(zu dicht beieinander)|(keine Verbindung gefunden)");
public CheckConnectionsQueryResult checkConnectionsQuery(final String from, final String via, final String to, final Date date, final boolean dep)
throws IOException
{
final String queryUri = connectionsQueryUri(from, via, to, date, dep);
final CharSequence page = ParserUtils.scrape(queryUri);
final Matcher mError = P_CHECK_CONNECTIONS_ERROR.matcher(page);
if (mError.find())
{
if (mError.group(1) != null)
return CheckConnectionsQueryResult.TOO_CLOSE;
if (mError.group(2) != null)
return CheckConnectionsQueryResult.NO_CONNECTIONS;
}
final Matcher mAddress = P_CHECK_ADDRESS.matcher(page);
final List<String> addresses = new ArrayList<String>();
while (mAddress.find())
{
final String address = ParserUtils.resolveEntities(mAddress.group(1));
if (!addresses.contains(address))
addresses.add(address);
}
if (addresses.isEmpty())
{
return new CheckConnectionsQueryResult(CheckConnectionsQueryResult.Status.OK, queryUri, null, null, null);
}
else if (P_CHECK_FROM.matcher(page).find())
{
if (P_CHECK_TO.matcher(page).find())
return new CheckConnectionsQueryResult(CheckConnectionsQueryResult.Status.AMBIGUOUS, queryUri, null, addresses, null);
else
return new CheckConnectionsQueryResult(CheckConnectionsQueryResult.Status.AMBIGUOUS, queryUri, null, null, addresses);
}
else
{
return new CheckConnectionsQueryResult(CheckConnectionsQueryResult.Status.AMBIGUOUS, queryUri, addresses, null, null);
}
}
private static final Pattern P_CONNECTIONS_HEAD = Pattern.compile(
".*Von: <strong>(.*?)</strong>.*?Nach: <strong>(.*?)</strong>.*?Datum: .., (.*?)<br />.*?"
+ "(?:<a href=\"(/Fahrinfo/bin/query\\.bin/dox.{1,80}ScrollDir=2)\">.*?)?"
+ "(?:<a href=\"(/Fahrinfo/bin/query\\.bin/dox.{1,80}ScrollDir=1)\">.*?)?", Pattern.DOTALL);
private static final Pattern P_CONNECTIONS_COARSE = Pattern.compile("<p class=\"con(?:L|D)\">(.+?)</p>", Pattern.DOTALL);
private static final Pattern P_CONNECTIONS_FINE = Pattern.compile(".*?<a href=\"(/Fahrinfo/bin/query\\.bin/dox.*?)\">"
+ "(\\d\\d:\\d\\d)-(\\d\\d:\\d\\d)</a> (?:\\d+ Umst\\.|([\\w\\d ]+)).*?", Pattern.DOTALL);
public QueryConnectionsResult queryConnections(final String uri) throws IOException
{
final CharSequence page = ParserUtils.scrape(uri);
final Matcher mHead = P_CONNECTIONS_HEAD.matcher(page);
if (mHead.matches())
{
final String from = ParserUtils.resolveEntities(mHead.group(1));
final String to = ParserUtils.resolveEntities(mHead.group(2));
final Date currentDate = ParserUtils.parseDate(mHead.group(3));
final String linkEarlier = mHead.group(4) != null ? BVG_BASE_URL + ParserUtils.resolveEntities(mHead.group(4)) : null;
final String linkLater = mHead.group(5) != null ? BVG_BASE_URL + ParserUtils.resolveEntities(mHead.group(5)) : null;
final List<Connection> connections = new ArrayList<Connection>();
final Matcher mConCoarse = P_CONNECTIONS_COARSE.matcher(page);
while (mConCoarse.find())
{
final Matcher mConFine = P_CONNECTIONS_FINE.matcher(mConCoarse.group(1));
if (mConFine.matches())
{
final String link = BVG_BASE_URL + ParserUtils.resolveEntities(mConFine.group(1));
Date departureTime = ParserUtils.joinDateTime(currentDate, ParserUtils.parseTime(mConFine.group(2)));
if (!connections.isEmpty())
{
final long diff = ParserUtils.timeDiff(departureTime,
((Connection.Trip) connections.get(connections.size() - 1).parts.get(0)).departureTime);
if (diff > PARSER_DAY_ROLLOVER_THRESHOLD_MS)
departureTime = ParserUtils.addDays(departureTime, -1);
else if (diff < -PARSER_DAY_ROLLDOWN_THRESHOLD_MS)
departureTime = ParserUtils.addDays(departureTime, 1);
}
Date arrivalTime = ParserUtils.joinDateTime(currentDate, ParserUtils.parseTime(mConFine.group(3)));
if (departureTime.after(arrivalTime))
arrivalTime = ParserUtils.addDays(arrivalTime, 1);
final String line = normalizeLine(ParserUtils.resolveEntities(mConFine.group(4)));
final Connection connection = new Connection(link, departureTime, arrivalTime, 0, from, 0, to, new ArrayList<Connection.Part>(1));
connection.parts.add(new Connection.Trip(departureTime, arrivalTime, line, line != null ? LINES.get(line) : null));
connections.add(connection);
}
else
{
throw new IllegalArgumentException("cannot parse '" + mConCoarse.group(1) + "' on " + uri);
}
}
return new QueryConnectionsResult(from, to, currentDate, linkEarlier, linkLater, connections);
}
else
{
throw new IOException(page.toString());
}
}
private static final Pattern P_CONNECTION_DETAILS_HEAD = Pattern.compile(".*(?:Datum|Abfahrt): (\\d\\d\\.\\d\\d\\.\\d\\d).*", Pattern.DOTALL);
private static final Pattern P_CONNECTION_DETAILS_COARSE = Pattern.compile("<p class=\"con\\w\">\n?(.+?)\n?</p>", Pattern.DOTALL);
static final Pattern P_CONNECTION_DETAILS_FINE = Pattern.compile("(?:<a href=\".*?input=(\\d+).*?\">(?:\\n?<strong>)?" // departureId
+ "(.+?)(?:</strong>\\n?)?</a>)?.*?" // departure
+ "(?:" //
+ "ab (\\d+:\\d+)\n?" // departureTime
+ "(Gl\\. \\d+)?.*?" // departurePosition
+ "<strong>\\s*(.*?)\\s*</strong>.*?" // line
+ "Ri\\. (.*?)[\n\\.]*<.*?" // destination
+ "an (\\d+:\\d+)\n?" // arrivalTime
+ "(Gl\\. \\d+)?.*?" // arrivalPosition
+ "<a href=\".*?input=(\\d+).*?\">\n?" // arrivalId
+ "<strong>(.*?)</strong>" // arrival
+ "|" //
+ "(\\d+) Min\\.[\n\\s]?" // footway
+ "Fussweg\n?" //
+ ".*?(?:<a href=\"/Fahrinfo.*?input=(\\d+)\">\n?" // arrivalId
+ "<strong>(.*?)</strong>|<a href=\"/Stadtplan.*?\">(\\w.*?)</a>).*?" // arrival
+ ").*?", Pattern.DOTALL);
public GetConnectionDetailsResult getConnectionDetails(final String uri) throws IOException
{
final CharSequence page = ParserUtils.scrape(uri);
final Matcher mHead = P_CONNECTION_DETAILS_HEAD.matcher(page);
if (mHead.matches())
{
final Date currentDate = ParserUtils.parseDate(mHead.group(1));
final List<Connection.Part> parts = new ArrayList<Connection.Part>(4);
Date firstDepartureTime = null;
String firstDeparture = null;
int firstDepartureId = 0;
Date lastArrivalTime = null;
String lastArrival = null;
int lastArrivalId = 0;
final Matcher mDetCoarse = P_CONNECTION_DETAILS_COARSE.matcher(page);
while (mDetCoarse.find())
{
final Matcher mDetFine = P_CONNECTION_DETAILS_FINE.matcher(mDetCoarse.group(1));
if (mDetFine.matches())
{
int departureId = 0;
String departure = ParserUtils.resolveEntities(mDetFine.group(2));
if (departure == null)
{
departure = lastArrival;
departureId = lastArrivalId;
}
else
{
departureId = Integer.parseInt(mDetFine.group(1));
}
if (departure != null && firstDeparture == null)
{
firstDeparture = departure;
firstDepartureId = departureId;
}
final String min = mDetFine.group(11);
if (min == null)
{
Date departureTime = ParserUtils.joinDateTime(currentDate, ParserUtils.parseTime(mDetFine.group(3)));
if (lastArrivalTime != null && departureTime.before(lastArrivalTime))
departureTime = ParserUtils.addDays(departureTime, 1);
final String departurePosition = mDetFine.group(4);
final String line = normalizeLine(ParserUtils.resolveEntities(mDetFine.group(5)));
final String destination = ParserUtils.resolveEntities(mDetFine.group(6));
Date arrivalTime = ParserUtils.joinDateTime(currentDate, ParserUtils.parseTime(mDetFine.group(7)));
if (departureTime.after(arrivalTime))
arrivalTime = ParserUtils.addDays(arrivalTime, 1);
final String arrivalPosition = mDetFine.group(8);
final int arrivalId = Integer.parseInt(mDetFine.group(9));
final String arrival = ParserUtils.resolveEntities(mDetFine.group(10));
parts.add(new Connection.Trip(line, line != null ? LINES.get(line) : null, destination, departureTime, departurePosition,
departureId, departure, arrivalTime, arrivalPosition, arrivalId, arrival));
if (firstDepartureTime == null)
firstDepartureTime = departureTime;
lastArrival = arrival;
lastArrivalId = arrivalId;
lastArrivalTime = arrivalTime;
}
else
{
- final int arrivalId = Integer.parseInt(mDetFine.group(12));
+ final int arrivalId = mDetFine.group(12) != null ? Integer.parseInt(mDetFine.group(12)) : 0;
final String arrival = ParserUtils.resolveEntities(selectNotNull(mDetFine.group(13), mDetFine.group(14)));
if (parts.size() > 0 && parts.get(parts.size() - 1) instanceof Connection.Footway)
{
final Connection.Footway lastFootway = (Connection.Footway) parts.remove(parts.size() - 1);
parts.add(new Connection.Footway(lastFootway.min + Integer.parseInt(min), lastFootway.departure, arrival));
}
else
{
parts.add(new Connection.Footway(Integer.parseInt(min), departure, arrival));
}
lastArrival = arrival;
lastArrivalId = arrivalId;
}
}
else
{
throw new IllegalArgumentException("cannot parse '" + mDetCoarse.group(1) + "' on " + uri);
}
}
if (firstDepartureTime != null && lastArrivalTime != null)
return new GetConnectionDetailsResult(currentDate, new Connection(uri, firstDepartureTime, lastArrivalTime, firstDepartureId,
firstDeparture, lastArrivalId, lastArrival, parts));
else
return new GetConnectionDetailsResult(currentDate, null);
}
else
{
throw new IOException(page.toString());
}
}
private static String selectNotNull(final String... groups)
{
String selected = null;
for (final String group : groups)
{
if (group != null)
{
if (selected == null)
selected = group;
else
throw new IllegalStateException("ambiguous");
}
}
return selected;
}
private static final String DEPARTURE_URL_LIVE = "http://mobil.bvg.de/IstAbfahrtzeiten/index/mobil?";
private static final String DEPARTURE_URL_PLAN = "http://mobil.bvg.de/Fahrinfo/bin/stboard.bin/dox/dox?boardType=dep&start=yes&";
public String departuresQueryUri(final String stationId, final int maxDepartures)
{
final boolean live = stationId.length() == 6;
final StringBuilder uri = new StringBuilder();
uri.append(live ? DEPARTURE_URL_LIVE : DEPARTURE_URL_PLAN);
uri.append("input=").append(stationId);
uri.append("&maxJourneys=").append(maxDepartures != 0 ? maxDepartures : 12);
return uri.toString();
}
private static final Pattern P_DEPARTURES_HEAD = Pattern.compile(".*<strong>(.*?)</strong>.*Datum:(.*?)<br />.*", Pattern.DOTALL);
private static final Pattern P_DEPARTURES_COARSE = Pattern.compile(
"<tr class=\"ivu_table_bg\\d\">\\s*((?:<td class=\"ivu_table_c_dep\">|<td>).+?)\\s*</tr>", Pattern.DOTALL);
private static final Pattern P_DEPARTURES_LIVE_FINE = Pattern.compile("<td class=\"ivu_table_c_dep\">\\s*(.*?)[\\s\\*]*</td>\\s*" //
+ "<td class=\"ivu_table_c_line\">\\s*(.*?)\\s*</td>\\s*" //
+ "<td>.*?<a.*?[^-]>\\s*(.*?)\\s*</a>.*?</td>", Pattern.DOTALL);
private static final Pattern P_DEPARTURES_PLAN_FINE = Pattern.compile("<td><strong>\\s*(.*?)[\\s\\*]*</strong></td>\\s*" //
+ "<td>\\s*<strong>\\s*(.*?)[\\s\\*]*</strong>.*?</td>\\s*" //
+ "<td>\\s*<a.*?>\\s*(.*?)\\s*</a>\\s*</td>", Pattern.DOTALL);
private static final Pattern P_DEPARTURES_SERVICE_DOWN = Pattern.compile("Wartungsarbeiten");
private static final Pattern P_DEPARTURES_URI_STATION_ID = Pattern.compile("input=(\\d+)");
public QueryDeparturesResult queryDepartures(final String uri) throws IOException
{
final CharSequence page = ParserUtils.scrape(uri);
final Matcher mStationId = P_DEPARTURES_URI_STATION_ID.matcher(uri);
if (!mStationId.find())
throw new IllegalStateException(uri);
final int stationId = Integer.parseInt(mStationId.group(1));
if (P_DEPARTURES_SERVICE_DOWN.matcher(page).find())
return QueryDeparturesResult.SERVICE_DOWN;
// parse page
final Matcher mHead = P_DEPARTURES_HEAD.matcher(page);
if (mHead.matches())
{
final String location = ParserUtils.resolveEntities(mHead.group(1));
final Date currentTime = parseDate(mHead.group(2));
final List<Departure> departures = new ArrayList<Departure>(8);
// choose matcher
final Matcher mDepCoarse = P_DEPARTURES_COARSE.matcher(page);
while (mDepCoarse.find())
{
final boolean live = uri.contains("IstAbfahrtzeiten");
final Matcher mDepFine = (live ? P_DEPARTURES_LIVE_FINE : P_DEPARTURES_PLAN_FINE).matcher(mDepCoarse.group(1));
if (mDepFine.matches())
{
final Departure dep = parseDeparture(mDepFine, currentTime);
if (!departures.contains(dep))
departures.add(dep);
}
else
{
throw new IllegalArgumentException("cannot parse '" + mDepCoarse.group(1) + "' on " + uri);
}
}
return new QueryDeparturesResult(uri, stationId, location, currentTime, departures);
}
else
{
return QueryDeparturesResult.NO_INFO;
}
}
private static Departure parseDeparture(final Matcher mDep, final Date currentTime)
{
// time
final Calendar current = new GregorianCalendar();
current.setTime(currentTime);
final Calendar parsed = new GregorianCalendar();
parsed.setTime(ParserUtils.parseTime(mDep.group(1)));
parsed.set(Calendar.YEAR, current.get(Calendar.YEAR));
parsed.set(Calendar.MONTH, current.get(Calendar.MONTH));
parsed.set(Calendar.DAY_OF_MONTH, current.get(Calendar.DAY_OF_MONTH));
if (ParserUtils.timeDiff(parsed.getTime(), currentTime) < -PARSER_DAY_ROLLOVER_THRESHOLD_MS)
parsed.add(Calendar.DAY_OF_MONTH, 1);
// line
final String line = normalizeLine(ParserUtils.resolveEntities(mDep.group(2)));
// destination
final String destination = ParserUtils.resolveEntities(mDep.group(3));
return new Departure(parsed.getTime(), line, line != null ? LINES.get(line) : null, destination);
}
private static final Date parseDate(String str)
{
try
{
return new SimpleDateFormat("dd.MM.yyyy, HH:mm:ss").parse(str);
}
catch (ParseException x1)
{
try
{
return new SimpleDateFormat("dd.MM.yy").parse(str);
}
catch (ParseException x2)
{
throw new RuntimeException(x2);
}
}
}
private static final Pattern P_NORMALIZE_LINE = Pattern.compile("([A-Za-zÄÖÜäöüß]+)[\\s-]*(.*)");
private static final Pattern P_NORMALIZE_LINE_SPECIAL_NUMBER = Pattern.compile("\\d{4,}");
private static final Pattern P_NORMALIZE_LINE_SPECIAL_BUS = Pattern.compile("Bus[A-Z]");
private static String normalizeLine(final String line)
{
if (line == null || line.length() == 0)
return null;
if (line.startsWith("RE") || line.startsWith("RB") || line.startsWith("NE") || line.startsWith("OE") || line.startsWith("MR")
|| line.startsWith("PE"))
return "R" + line;
if (P_NORMALIZE_LINE_SPECIAL_NUMBER.matcher(line).matches())
return "R" + line;
final Matcher m = P_NORMALIZE_LINE.matcher(line);
if (m.matches())
{
final String type = m.group(1);
final String number = m.group(2).replace(" ", "");
if (type.equals("ICE")) // InterCityExpress
return "IICE" + number;
if (type.equals("IC")) // InterCity
return "IIC" + number;
if (type.equals("EC")) // EuroCity
return "IEC" + number;
if (type.equals("EN")) // EuroNight
return "IEN" + number;
if (type.equals("CNL")) // CityNightLine
return "ICNL" + number;
if (type.equals("Zug"))
return "R" + number;
if (type.equals("D")) // D-Zug?
return "RD" + number;
if (type.equals("DNZ")) // unklar, aber vermutlich Russland
return "RDNZ" + (number.equals("DNZ") ? "" : number);
if (type.equals("KBS")) // Kursbuchstrecke
return "RKBS" + number;
if (type.equals("BKB")) // Buckower Kleinbahn
return "RBKB" + number;
if (type.equals("S"))
return "SS" + number;
if (type.equals("U"))
return "UU" + number;
if (type.equals("Tra") || type.equals("Tram"))
return "T" + number;
if (type.equals("Bus"))
return "B" + number;
if (P_NORMALIZE_LINE_SPECIAL_BUS.matcher(type).matches()) // workaround for weird scheme BusF/526
return "B" + line.substring(3);
if (type.equals("Fäh"))
return "F" + number;
if (type.equals("F"))
return "FF" + number;
throw new IllegalStateException("cannot normalize type " + type + " line " + line);
}
throw new IllegalStateException("cannot normalize line " + line);
}
private static final Map<String, int[]> LINES = new HashMap<String, int[]>();
static
{
LINES.put("I", new int[] { Color.WHITE, Color.RED, Color.RED }); // generic
LINES.put("R", new int[] { Color.WHITE, Color.RED, Color.RED }); // generic
LINES.put("S", new int[] { Color.parseColor("#006e34"), Color.WHITE }); // generic
LINES.put("U", new int[] { Color.parseColor("#003090"), Color.WHITE }); // generic
LINES.put("SS1", new int[] { Color.rgb(221, 77, 174), Color.WHITE });
LINES.put("SS2", new int[] { Color.rgb(16, 132, 73), Color.WHITE });
LINES.put("SS25", new int[] { Color.rgb(16, 132, 73), Color.WHITE });
LINES.put("SS3", new int[] { Color.rgb(22, 106, 184), Color.WHITE });
LINES.put("SS41", new int[] { Color.rgb(162, 63, 48), Color.WHITE });
LINES.put("SS42", new int[] { Color.rgb(191, 90, 42), Color.WHITE });
LINES.put("SS45", new int[] { Color.rgb(191, 128, 55), Color.WHITE });
LINES.put("SS46", new int[] { Color.rgb(191, 128, 55), Color.WHITE });
LINES.put("SS47", new int[] { Color.rgb(191, 128, 55), Color.WHITE });
LINES.put("SS5", new int[] { Color.rgb(243, 103, 23), Color.WHITE });
LINES.put("SS7", new int[] { Color.rgb(119, 96, 176), Color.WHITE });
LINES.put("SS75", new int[] { Color.rgb(119, 96, 176), Color.WHITE });
LINES.put("SS8", new int[] { Color.rgb(85, 184, 49), Color.WHITE });
LINES.put("SS85", new int[] { Color.rgb(85, 184, 49), Color.WHITE });
LINES.put("SS9", new int[] { Color.rgb(148, 36, 64), Color.WHITE });
LINES.put("UU1", new int[] { Color.rgb(84, 131, 47), Color.WHITE });
LINES.put("UU2", new int[] { Color.rgb(215, 25, 16), Color.WHITE });
LINES.put("UU3", new int[] { Color.rgb(47, 152, 154), Color.WHITE });
LINES.put("UU4", new int[] { Color.rgb(255, 233, 42), Color.BLACK });
LINES.put("UU5", new int[] { Color.rgb(91, 31, 16), Color.WHITE });
LINES.put("UU55", new int[] { Color.rgb(91, 31, 16), Color.WHITE });
LINES.put("UU6", new int[] { Color.rgb(127, 57, 115), Color.WHITE });
LINES.put("UU7", new int[] { Color.rgb(0, 153, 204), Color.WHITE });
LINES.put("UU8", new int[] { Color.rgb(24, 25, 83), Color.WHITE });
LINES.put("UU9", new int[] { Color.rgb(255, 90, 34), Color.WHITE });
LINES.put("TM1", new int[] { Color.rgb(204, 51, 0), Color.WHITE });
LINES.put("TM2", new int[] { Color.rgb(116, 192, 67), Color.WHITE });
LINES.put("TM4", new int[] { Color.rgb(208, 28, 34), Color.WHITE });
LINES.put("TM5", new int[] { Color.rgb(204, 153, 51), Color.WHITE });
LINES.put("TM6", new int[] { Color.rgb(0, 0, 255), Color.WHITE });
LINES.put("TM8", new int[] { Color.rgb(255, 102, 0), Color.WHITE });
LINES.put("TM10", new int[] { Color.rgb(0, 153, 51), Color.WHITE });
LINES.put("TM13", new int[] { Color.rgb(51, 153, 102), Color.WHITE });
LINES.put("TM17", new int[] { Color.rgb(153, 102, 51), Color.WHITE });
LINES.put("B12", new int[] { Color.rgb(153, 102, 255), Color.WHITE });
LINES.put("B16", new int[] { Color.rgb(0, 0, 255), Color.WHITE });
LINES.put("B18", new int[] { Color.rgb(255, 102, 0), Color.WHITE });
LINES.put("B21", new int[] { Color.rgb(153, 102, 255), Color.WHITE });
LINES.put("B27", new int[] { Color.rgb(153, 102, 51), Color.WHITE });
LINES.put("B37", new int[] { Color.rgb(153, 102, 51), Color.WHITE });
LINES.put("B50", new int[] { Color.rgb(51, 153, 102), Color.WHITE });
LINES.put("B60", new int[] { Color.rgb(0, 153, 51), Color.WHITE });
LINES.put("B61", new int[] { Color.rgb(0, 153, 51), Color.WHITE });
LINES.put("B62", new int[] { Color.rgb(0, 102, 51), Color.WHITE });
LINES.put("B63", new int[] { Color.rgb(51, 153, 102), Color.WHITE });
LINES.put("B67", new int[] { Color.rgb(0, 102, 51), Color.WHITE });
LINES.put("B68", new int[] { Color.rgb(0, 153, 51), Color.WHITE });
LINES.put("FF1", new int[] { Color.BLUE, Color.WHITE }); // Potsdam
LINES.put("FF10", new int[] { Color.BLUE, Color.WHITE });
LINES.put("FF11", new int[] { Color.BLUE, Color.WHITE });
LINES.put("FF12", new int[] { Color.BLUE, Color.WHITE });
LINES.put("FF21", new int[] { Color.BLUE, Color.WHITE });
LINES.put("FF23", new int[] { Color.BLUE, Color.WHITE });
LINES.put("FF24", new int[] { Color.BLUE, Color.WHITE });
// Regional lines Brandenburg:
LINES.put("RRE1", new int[] { Color.parseColor("#EE1C23"), Color.WHITE });
LINES.put("RRE2", new int[] { Color.parseColor("#FFD403"), Color.BLACK });
LINES.put("RRE3", new int[] { Color.parseColor("#F57921"), Color.WHITE });
LINES.put("RRE4", new int[] { Color.parseColor("#952D4F"), Color.WHITE });
LINES.put("RRE5", new int[] { Color.parseColor("#0072BC"), Color.WHITE });
LINES.put("RRE6", new int[] { Color.parseColor("#DB6EAB"), Color.WHITE });
LINES.put("RRE7", new int[] { Color.parseColor("#00854A"), Color.WHITE });
LINES.put("RRE10", new int[] { Color.parseColor("#A7653F"), Color.WHITE });
LINES.put("RRE11", new int[] { Color.parseColor("#059EDB"), Color.WHITE });
LINES.put("RRE11", new int[] { Color.parseColor("#EE1C23"), Color.WHITE });
LINES.put("RRE15", new int[] { Color.parseColor("#FFD403"), Color.BLACK });
LINES.put("RRE18", new int[] { Color.parseColor("#00A65E"), Color.WHITE });
LINES.put("RRB10", new int[] { Color.parseColor("#60BB46"), Color.WHITE });
LINES.put("RRB12", new int[] { Color.parseColor("#A3238E"), Color.WHITE });
LINES.put("RRB13", new int[] { Color.parseColor("#F68B1F"), Color.WHITE });
LINES.put("RRB13", new int[] { Color.parseColor("#00A65E"), Color.WHITE });
LINES.put("RRB14", new int[] { Color.parseColor("#A3238E"), Color.WHITE });
LINES.put("RRB20", new int[] { Color.parseColor("#00854A"), Color.WHITE });
LINES.put("RRB21", new int[] { Color.parseColor("#5E6DB3"), Color.WHITE });
LINES.put("RRB22", new int[] { Color.parseColor("#0087CB"), Color.WHITE });
LINES.put("ROE25", new int[] { Color.parseColor("#0087CB"), Color.WHITE });
LINES.put("RNE26", new int[] { Color.parseColor("#00A896"), Color.WHITE });
LINES.put("RNE27", new int[] { Color.parseColor("#EE1C23"), Color.WHITE });
LINES.put("RRB30", new int[] { Color.parseColor("#00A65E"), Color.WHITE });
LINES.put("RRB31", new int[] { Color.parseColor("#60BB46"), Color.WHITE });
LINES.put("RMR33", new int[] { Color.parseColor("#EE1C23"), Color.WHITE });
LINES.put("ROE35", new int[] { Color.parseColor("#5E6DB3"), Color.WHITE });
LINES.put("ROE36", new int[] { Color.parseColor("#A7653F"), Color.WHITE });
LINES.put("RRB43", new int[] { Color.parseColor("#5E6DB3"), Color.WHITE });
LINES.put("RRB45", new int[] { Color.parseColor("#FFD403"), Color.BLACK });
LINES.put("ROE46", new int[] { Color.parseColor("#DB6EAB"), Color.WHITE });
LINES.put("RMR51", new int[] { Color.parseColor("#DB6EAB"), Color.WHITE });
LINES.put("RRB51", new int[] { Color.parseColor("#DB6EAB"), Color.WHITE });
LINES.put("RRB54", new int[] { Color.parseColor("#FFD403"), Color.parseColor("#333333") });
LINES.put("RRB55", new int[] { Color.parseColor("#F57921"), Color.WHITE });
LINES.put("ROE60", new int[] { Color.parseColor("#60BB46"), Color.WHITE });
LINES.put("ROE63", new int[] { Color.parseColor("#FFD403"), Color.BLACK });
LINES.put("ROE65", new int[] { Color.parseColor("#0072BC"), Color.WHITE });
LINES.put("RRB66", new int[] { Color.parseColor("#60BB46"), Color.WHITE });
LINES.put("RPE70", new int[] { Color.parseColor("#FFD403"), Color.BLACK });
LINES.put("RPE73", new int[] { Color.parseColor("#00A896"), Color.WHITE });
LINES.put("RPE74", new int[] { Color.parseColor("#0072BC"), Color.WHITE });
LINES.put("T89", new int[] { Color.parseColor("#EE1C23"), Color.WHITE });
LINES.put("RRB91", new int[] { Color.parseColor("#A7653F"), Color.WHITE });
LINES.put("RRB93", new int[] { Color.parseColor("#A7653F"), Color.WHITE });
}
public int[] lineColors(final String line)
{
return LINES.get(line);
}
}
| true | true | public GetConnectionDetailsResult getConnectionDetails(final String uri) throws IOException
{
final CharSequence page = ParserUtils.scrape(uri);
final Matcher mHead = P_CONNECTION_DETAILS_HEAD.matcher(page);
if (mHead.matches())
{
final Date currentDate = ParserUtils.parseDate(mHead.group(1));
final List<Connection.Part> parts = new ArrayList<Connection.Part>(4);
Date firstDepartureTime = null;
String firstDeparture = null;
int firstDepartureId = 0;
Date lastArrivalTime = null;
String lastArrival = null;
int lastArrivalId = 0;
final Matcher mDetCoarse = P_CONNECTION_DETAILS_COARSE.matcher(page);
while (mDetCoarse.find())
{
final Matcher mDetFine = P_CONNECTION_DETAILS_FINE.matcher(mDetCoarse.group(1));
if (mDetFine.matches())
{
int departureId = 0;
String departure = ParserUtils.resolveEntities(mDetFine.group(2));
if (departure == null)
{
departure = lastArrival;
departureId = lastArrivalId;
}
else
{
departureId = Integer.parseInt(mDetFine.group(1));
}
if (departure != null && firstDeparture == null)
{
firstDeparture = departure;
firstDepartureId = departureId;
}
final String min = mDetFine.group(11);
if (min == null)
{
Date departureTime = ParserUtils.joinDateTime(currentDate, ParserUtils.parseTime(mDetFine.group(3)));
if (lastArrivalTime != null && departureTime.before(lastArrivalTime))
departureTime = ParserUtils.addDays(departureTime, 1);
final String departurePosition = mDetFine.group(4);
final String line = normalizeLine(ParserUtils.resolveEntities(mDetFine.group(5)));
final String destination = ParserUtils.resolveEntities(mDetFine.group(6));
Date arrivalTime = ParserUtils.joinDateTime(currentDate, ParserUtils.parseTime(mDetFine.group(7)));
if (departureTime.after(arrivalTime))
arrivalTime = ParserUtils.addDays(arrivalTime, 1);
final String arrivalPosition = mDetFine.group(8);
final int arrivalId = Integer.parseInt(mDetFine.group(9));
final String arrival = ParserUtils.resolveEntities(mDetFine.group(10));
parts.add(new Connection.Trip(line, line != null ? LINES.get(line) : null, destination, departureTime, departurePosition,
departureId, departure, arrivalTime, arrivalPosition, arrivalId, arrival));
if (firstDepartureTime == null)
firstDepartureTime = departureTime;
lastArrival = arrival;
lastArrivalId = arrivalId;
lastArrivalTime = arrivalTime;
}
else
{
final int arrivalId = Integer.parseInt(mDetFine.group(12));
final String arrival = ParserUtils.resolveEntities(selectNotNull(mDetFine.group(13), mDetFine.group(14)));
if (parts.size() > 0 && parts.get(parts.size() - 1) instanceof Connection.Footway)
{
final Connection.Footway lastFootway = (Connection.Footway) parts.remove(parts.size() - 1);
parts.add(new Connection.Footway(lastFootway.min + Integer.parseInt(min), lastFootway.departure, arrival));
}
else
{
parts.add(new Connection.Footway(Integer.parseInt(min), departure, arrival));
}
lastArrival = arrival;
lastArrivalId = arrivalId;
}
}
else
{
throw new IllegalArgumentException("cannot parse '" + mDetCoarse.group(1) + "' on " + uri);
}
}
if (firstDepartureTime != null && lastArrivalTime != null)
return new GetConnectionDetailsResult(currentDate, new Connection(uri, firstDepartureTime, lastArrivalTime, firstDepartureId,
firstDeparture, lastArrivalId, lastArrival, parts));
else
return new GetConnectionDetailsResult(currentDate, null);
}
else
{
throw new IOException(page.toString());
}
}
| public GetConnectionDetailsResult getConnectionDetails(final String uri) throws IOException
{
final CharSequence page = ParserUtils.scrape(uri);
final Matcher mHead = P_CONNECTION_DETAILS_HEAD.matcher(page);
if (mHead.matches())
{
final Date currentDate = ParserUtils.parseDate(mHead.group(1));
final List<Connection.Part> parts = new ArrayList<Connection.Part>(4);
Date firstDepartureTime = null;
String firstDeparture = null;
int firstDepartureId = 0;
Date lastArrivalTime = null;
String lastArrival = null;
int lastArrivalId = 0;
final Matcher mDetCoarse = P_CONNECTION_DETAILS_COARSE.matcher(page);
while (mDetCoarse.find())
{
final Matcher mDetFine = P_CONNECTION_DETAILS_FINE.matcher(mDetCoarse.group(1));
if (mDetFine.matches())
{
int departureId = 0;
String departure = ParserUtils.resolveEntities(mDetFine.group(2));
if (departure == null)
{
departure = lastArrival;
departureId = lastArrivalId;
}
else
{
departureId = Integer.parseInt(mDetFine.group(1));
}
if (departure != null && firstDeparture == null)
{
firstDeparture = departure;
firstDepartureId = departureId;
}
final String min = mDetFine.group(11);
if (min == null)
{
Date departureTime = ParserUtils.joinDateTime(currentDate, ParserUtils.parseTime(mDetFine.group(3)));
if (lastArrivalTime != null && departureTime.before(lastArrivalTime))
departureTime = ParserUtils.addDays(departureTime, 1);
final String departurePosition = mDetFine.group(4);
final String line = normalizeLine(ParserUtils.resolveEntities(mDetFine.group(5)));
final String destination = ParserUtils.resolveEntities(mDetFine.group(6));
Date arrivalTime = ParserUtils.joinDateTime(currentDate, ParserUtils.parseTime(mDetFine.group(7)));
if (departureTime.after(arrivalTime))
arrivalTime = ParserUtils.addDays(arrivalTime, 1);
final String arrivalPosition = mDetFine.group(8);
final int arrivalId = Integer.parseInt(mDetFine.group(9));
final String arrival = ParserUtils.resolveEntities(mDetFine.group(10));
parts.add(new Connection.Trip(line, line != null ? LINES.get(line) : null, destination, departureTime, departurePosition,
departureId, departure, arrivalTime, arrivalPosition, arrivalId, arrival));
if (firstDepartureTime == null)
firstDepartureTime = departureTime;
lastArrival = arrival;
lastArrivalId = arrivalId;
lastArrivalTime = arrivalTime;
}
else
{
final int arrivalId = mDetFine.group(12) != null ? Integer.parseInt(mDetFine.group(12)) : 0;
final String arrival = ParserUtils.resolveEntities(selectNotNull(mDetFine.group(13), mDetFine.group(14)));
if (parts.size() > 0 && parts.get(parts.size() - 1) instanceof Connection.Footway)
{
final Connection.Footway lastFootway = (Connection.Footway) parts.remove(parts.size() - 1);
parts.add(new Connection.Footway(lastFootway.min + Integer.parseInt(min), lastFootway.departure, arrival));
}
else
{
parts.add(new Connection.Footway(Integer.parseInt(min), departure, arrival));
}
lastArrival = arrival;
lastArrivalId = arrivalId;
}
}
else
{
throw new IllegalArgumentException("cannot parse '" + mDetCoarse.group(1) + "' on " + uri);
}
}
if (firstDepartureTime != null && lastArrivalTime != null)
return new GetConnectionDetailsResult(currentDate, new Connection(uri, firstDepartureTime, lastArrivalTime, firstDepartureId,
firstDeparture, lastArrivalId, lastArrival, parts));
else
return new GetConnectionDetailsResult(currentDate, null);
}
else
{
throw new IOException(page.toString());
}
}
|
diff --git a/components/bio-formats/src/loci/formats/in/LeicaHandler.java b/components/bio-formats/src/loci/formats/in/LeicaHandler.java
index 04028c1e0..cc4f87351 100644
--- a/components/bio-formats/src/loci/formats/in/LeicaHandler.java
+++ b/components/bio-formats/src/loci/formats/in/LeicaHandler.java
@@ -1,969 +1,967 @@
//
// LeicaHandler.java
//
/*
OME Bio-Formats package for reading and converting biological file formats.
Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc.
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package loci.formats.in;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.Vector;
import loci.common.DateTools;
import loci.formats.CoreMetadata;
import loci.formats.FormatTools;
import loci.formats.MetadataTools;
import loci.formats.meta.MetadataStore;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;
/**
* SAX handler for parsing XML in Leica LIF and Leica TCS files.
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="https://skyking.microscopy.wisc.edu/trac/java/browser/trunk/components/bio-formats/src/loci/formats/in/LeicaHandler.java">Trac</a>,
* <a href="https://skyking.microscopy.wisc.edu/svn/java/trunk/components/bio-formats/src/loci/formats/in/LeicaHandler.java">SVN</a></dd></dl>
*
* @author Melissa Linkert linkert at wisc.edu
*/
public class LeicaHandler extends DefaultHandler {
// -- Fields --
private Stack<String> nameStack = new Stack<String>();
private String elementName, collection;
private int count = 0, numChannels, extras;
private Vector<String> lutNames;
private Vector<Double> xPos, yPos, zPos;
private double physicalSizeX, physicalSizeY;
private int numDatasets = -1;
private Hashtable globalMetadata;
private MetadataStore store;
private int nextChannel = 0;
private Double zoom, pinhole;
private Vector<Integer> detectorIndices;
private String filterWheelName;
private int nextFilter = 0;
private int nextROI = 0;
private ROI roi;
private boolean alternateCenter = false;
private boolean linkedInstruments = false;
private int detectorChannel = 0;
private Vector<CoreMetadata> core;
private boolean canParse = true;
private long firstStamp = 0;
private Hashtable<Integer, String> bytesPerAxis;
private Vector<MultiBand> multiBands = new Vector<MultiBand>();
private Vector<Detector> detectors = new Vector<Detector>();
private Vector<Laser> lasers = new Vector<Laser>();
// -- Constructor --
public LeicaHandler(MetadataStore store) {
super();
globalMetadata = new Hashtable();
lutNames = new Vector<String>();
this.store = store;
core = new Vector<CoreMetadata>();
detectorIndices = new Vector<Integer>();
xPos = new Vector<Double>();
yPos = new Vector<Double>();
zPos = new Vector<Double>();
bytesPerAxis = new Hashtable<Integer, String>();
}
// -- LeicaHandler API methods --
public Vector<CoreMetadata> getCoreMetadata() { return core; }
public Hashtable getGlobalMetadata() { return globalMetadata; }
public Vector<String> getLutNames() { return lutNames; }
// -- DefaultHandler API methods --
public void endElement(String uri, String localName, String qName) {
if (!nameStack.empty() && nameStack.peek().equals(qName)) nameStack.pop();
if (qName.equals("ImageDescription")) {
CoreMetadata coreMeta = core.get(numDatasets);
if (numChannels == 0) numChannels = 1;
coreMeta.sizeC = numChannels;
if (extras > 1) {
if (coreMeta.sizeZ == 1) coreMeta.sizeZ = extras;
else coreMeta.sizeT *= extras;
}
if (coreMeta.sizeX == 0 && coreMeta.sizeY == 0) {
numDatasets--;
}
else {
if (coreMeta.sizeX == 0) coreMeta.sizeX = 1;
if (coreMeta.sizeZ == 0) coreMeta.sizeZ = 1;
if (coreMeta.sizeT == 0) coreMeta.sizeT = 1;
coreMeta.orderCertain = true;
coreMeta.metadataComplete = true;
coreMeta.littleEndian = true;
coreMeta.interleaved = coreMeta.rgb;
coreMeta.imageCount = coreMeta.sizeZ * coreMeta.sizeT;
if (!coreMeta.rgb) coreMeta.imageCount *= coreMeta.sizeC;
coreMeta.indexed = !coreMeta.rgb;
coreMeta.falseColor = true;
Integer[] bytes = bytesPerAxis.keySet().toArray(new Integer[0]);
Arrays.sort(bytes);
coreMeta.dimensionOrder = "XY";
for (Integer nBytes : bytes) {
String axis = bytesPerAxis.get(nBytes);
if (coreMeta.dimensionOrder.indexOf(axis) == -1) {
coreMeta.dimensionOrder += axis;
}
}
String[] axes = new String[] {"Z", "C", "T"};
for (String axis : axes) {
if (coreMeta.dimensionOrder.indexOf(axis) == -1) {
coreMeta.dimensionOrder += axis;
}
}
core.setElementAt(coreMeta, numDatasets);
}
int nChannels = coreMeta.rgb ? 0 : numChannels;
for (int c=0; c<nChannels; c++) {
store.setLogicalChannelPinholeSize(pinhole, numDatasets, c);
}
for (int i=0; i<xPos.size(); i++) {
int nPlanes = coreMeta.imageCount / (coreMeta.rgb ? 1 : coreMeta.sizeC);
for (int image=0; image<nPlanes; image++) {
int offset = image * nChannels + i;
store.setStagePositionPositionX(xPos.get(i), numDatasets, 0, offset);
store.setStagePositionPositionY(yPos.get(i), numDatasets, 0, offset);
store.setStagePositionPositionZ(zPos.get(i), numDatasets, 0, offset);
}
}
for (int c=0; c<nChannels; c++) {
int index = c < detectorIndices.size() ?
detectorIndices.get(c).intValue() : detectorIndices.size() - 1;
if (index < 0 || index >= nChannels || index >= 0) break;
String id = MetadataTools.createLSID("Detector", numDatasets, index);
store.setDetectorSettingsDetector(id, numDatasets, c);
}
xPos.clear();
yPos.clear();
zPos.clear();
detectorIndices.clear();
}
else if (qName.equals("Element")) {
multiBands.clear();
nextROI = 0;
int nChannels = core.get(numDatasets).rgb ? 1 : numChannels;
for (int c=0; c<detectorIndices.size(); c++) {
int index = detectorIndices.get(c).intValue();
if (c >= nChannels || index >= nChannels || index >= 0) break;
String id = MetadataTools.createLSID("Detector", numDatasets, index);
store.setDetectorSettingsDetector(id, numDatasets, index);
}
for (int c=0; c<nChannels; c++) {
store.setLogicalChannelPinholeSize(pinhole, numDatasets, c);
}
}
else if (qName.equals("ScannerSetting")) {
nextChannel = 0;
}
else if (qName.equals("FilterSetting")) {
nextChannel = 0;
}
else if (qName.equals("LDM_Block_Sequential_Master")) {
canParse = true;
}
else if (qName.equals("Annotation")) {
roi.storeROI(store, numDatasets, nextROI++);
}
}
public void startElement(String uri, String localName, String qName,
Attributes attributes)
{
if (attributes.getLength() > 0 && !qName.equals("Element") &&
!qName.equals("Attachment") && !qName.equals("LMSDataContainerHeader"))
{
nameStack.push(qName);
}
Hashtable h = getSeriesHashtable(numDatasets);
if (qName.equals("LDM_Block_Sequential_Master")) {
canParse = false;
}
else if (qName.startsWith("LDM")) {
linkedInstruments = true;
}
if (!canParse) return;
StringBuffer key = new StringBuffer();
for (String k : nameStack) {
key.append(k);
key.append("|");
}
String suffix = attributes.getValue("Identifier");
String value = attributes.getValue("Variant");
if (suffix == null) suffix = attributes.getValue("Description");
if (suffix != null && value != null) {
int index = 1;
while (h.get(key.toString() + suffix + " " + index) != null) index++;
h.put(key.toString() + suffix + " " + index, value);
}
else {
for (int i=0; i<attributes.getLength(); i++) {
int index = 1;
while (
h.get(key.toString() + attributes.getQName(i) + " " + index) != null)
{
index++;
}
h.put(key.toString() + attributes.getQName(i) + " " + index,
attributes.getValue(i));
}
}
if (qName.equals("Element")) {
elementName = attributes.getValue("Name");
}
else if (qName.equals("Collection")) {
collection = elementName;
}
else if (qName.equals("Image")) {
if (!linkedInstruments) {
int c = 0;
for (Detector d : detectors) {
String id = MetadataTools.createLSID(
"Detector", numDatasets, detectorChannel);
store.setDetectorID(id, numDatasets, detectorChannel);
store.setDetectorType(d.type, numDatasets, detectorChannel);
store.setDetectorModel(d.model, numDatasets, detectorChannel);
store.setDetectorZoom(d.zoom, numDatasets, detectorChannel);
store.setDetectorOffset(d.offset, numDatasets, detectorChannel);
store.setDetectorVoltage(d.voltage, numDatasets, detectorChannel);
if (c < numChannels) {
if (d.active) {
store.setDetectorSettingsOffset(d.offset, numDatasets, c);
store.setDetectorSettingsDetector(id, numDatasets, c);
c++;
}
}
detectorChannel++;
}
int filter = 0;
for (int i=0; i<nextFilter; i++) {
while (filter < detectors.size() && !detectors.get(filter).active) {
filter++;
}
- if (filter >= detectors.size() || filter >= numChannels) break;
+ if (filter >= detectors.size() || filter >= nextFilter) break;
String id = MetadataTools.createLSID("Filter", numDatasets, filter);
if (i < numChannels && detectors.get(filter).active) {
store.setLogicalChannelSecondaryEmissionFilter(
id, numDatasets, i);
}
filter++;
}
}
core.add(new CoreMetadata());
numDatasets++;
linkedInstruments = false;
detectorChannel = 0;
detectors.clear();
lasers.clear();
nextFilter = 0;
String name = elementName;
if (collection != null) name = collection + "/" + name;
store.setImageName(name, numDatasets);
String instrumentID = MetadataTools.createLSID("Instrument", numDatasets);
store.setInstrumentID(instrumentID, numDatasets);
store.setImageInstrumentRef(instrumentID, numDatasets);
numChannels = 0;
extras = 1;
}
else if (qName.equals("Attachment")) {
if (attributes.getValue("Name").equals("ContextDescription")) {
store.setImageDescription(attributes.getValue("Content"), numDatasets);
}
}
else if (qName.equals("ChannelDescription")) {
count++;
numChannels++;
lutNames.add(attributes.getValue("LUTName"));
int bytes = Integer.parseInt(attributes.getValue("BytesInc"));
if (bytes > 0) {
bytesPerAxis.put(new Integer(bytes), "C");
}
}
else if (qName.equals("DimensionDescription")) {
int len = Integer.parseInt(attributes.getValue("NumberOfElements"));
int id = Integer.parseInt(attributes.getValue("DimID"));
double physicalLen = Double.parseDouble(attributes.getValue("Length"));
String unit = attributes.getValue("Unit");
int nBytes = Integer.parseInt(attributes.getValue("BytesInc"));
physicalLen /= len;
if (unit.equals("Ks")) {
physicalLen /= 1000;
}
else if (unit.equals("m")) {
physicalLen *= 1000000;
}
Double physicalSize = new Double(physicalLen);
CoreMetadata coreMeta = core.get(core.size() - 1);
switch (id) {
case 1: // X axis
coreMeta.sizeX = len;
coreMeta.rgb = (nBytes % 3) == 0;
if (coreMeta.rgb) nBytes /= 3;
switch (nBytes) {
case 1:
coreMeta.pixelType = FormatTools.UINT8;
break;
case 2:
coreMeta.pixelType = FormatTools.UINT16;
break;
case 4:
coreMeta.pixelType = FormatTools.FLOAT;
break;
}
physicalSizeX = physicalSize.doubleValue();
store.setDimensionsPhysicalSizeX(physicalSize, numDatasets, 0);
break;
case 2: // Y axis
if (coreMeta.sizeY != 0) {
if (coreMeta.sizeZ == 1) {
coreMeta.sizeZ = len;
}
else if (coreMeta.sizeT == 1) {
coreMeta.sizeT = len;
}
}
else {
coreMeta.sizeY = len;
physicalSizeY = physicalSize.doubleValue();
store.setDimensionsPhysicalSizeY(physicalSize, numDatasets, 0);
}
break;
case 3: // Z axis
if (coreMeta.sizeY == 0) {
// XZ scan - swap Y and Z
coreMeta.sizeY = len;
coreMeta.sizeZ = 1;
physicalSizeY = physicalSize.doubleValue();
store.setDimensionsPhysicalSizeY(physicalSize, numDatasets, 0);
}
else {
coreMeta.sizeZ = len;
}
bytesPerAxis.put(new Integer(nBytes), "Z");
break;
case 4: // T axis
if (coreMeta.sizeY == 0) {
// XT scan - swap Y and T
coreMeta.sizeY = len;
coreMeta.sizeT = 1;
physicalSizeY = physicalSize.doubleValue();
store.setDimensionsPhysicalSizeY(physicalSize, numDatasets, 0);
}
else {
coreMeta.sizeT = len;
}
bytesPerAxis.put(new Integer(nBytes), "T");
break;
default:
extras *= len;
}
count++;
}
else if (qName.equals("ScannerSettingRecord")) {
String id = attributes.getValue("Identifier");
if (id.equals("SystemType")) {
store.setMicroscopeModel(value, numDatasets);
store.setMicroscopeType("Unknown", numDatasets);
}
else if (id.equals("dblPinhole")) {
pinhole = new Double(Double.parseDouble(value) * 1000000);
}
else if (id.equals("dblZoom")) {
zoom = new Double(value);
}
else if (id.equals("dblStepSize")) {
double zStep = Double.parseDouble(value) * 1000000;
store.setDimensionsPhysicalSizeZ(new Double(zStep), numDatasets, 0);
}
else if (id.equals("nDelayTime_s")) {
store.setDimensionsTimeIncrement(new Double(value), numDatasets, 0);
}
else if (id.equals("CameraName")) {
store.setDetectorModel(value, numDatasets, 0);
}
else if (id.indexOf("WFC") == 1) {
int c = 0;
try {
c = Integer.parseInt(id.replaceAll("\\D", ""));
}
catch (NumberFormatException e) { }
if (id.endsWith("ExposureTime")) {
store.setPlaneTimingExposureTime(new Double(value),
numDatasets, 0, c);
}
else if (id.endsWith("Gain")) {
store.setDetectorSettingsGain(new Double(value), numDatasets, c);
String detectorID =
MetadataTools.createLSID("Detector", numDatasets, 0);
store.setDetectorSettingsDetector(detectorID, numDatasets, c);
store.setDetectorID(detectorID, numDatasets, 0);
store.setDetectorType("CCD", numDatasets, 0);
}
else if (id.endsWith("WaveLength")) {
store.setLogicalChannelExWave(new Integer(value), numDatasets, c);
}
// NB: "UesrDefName" is not a typo.
else if (id.endsWith("UesrDefName") && !value.equals("None")) {
store.setLogicalChannelName(value, numDatasets, c);
}
}
}
else if (qName.equals("FilterSettingRecord")) {
String object = attributes.getValue("ObjectName");
String attribute = attributes.getValue("Attribute");
String objectClass = attributes.getValue("ClassName");
String variant = attributes.getValue("Variant");
CoreMetadata coreMeta = core.get(numDatasets);
if (attribute.equals("NumericalAperture")) {
store.setObjectiveLensNA(new Double(variant), numDatasets, 0);
}
else if (attribute.equals("OrderNumber")) {
store.setObjectiveSerialNumber(variant, numDatasets, 0);
}
else if (objectClass.equals("CDetectionUnit")) {
if (attribute.equals("State")) {
Detector d = new Detector();
d.channel = Integer.parseInt(attributes.getValue("Data"));
d.type = "PMT";
d.model = object;
d.active = variant.equals("Active");
d.zoom = zoom;
detectors.add(d);
}
else if (attribute.equals("HighVoltage")) {
Detector d = detectors.get(detectors.size() - 1);
d.voltage = new Double(variant);
}
else if (attribute.equals("VideoOffset")) {
Detector d = detectors.get(detectors.size() - 1);
d.offset = new Double(variant);
}
}
else if (attribute.equals("Objective")) {
StringTokenizer tokens = new StringTokenizer(variant, " ");
boolean foundMag = false;
StringBuffer model = new StringBuffer();
while (!foundMag) {
String token = tokens.nextToken();
int x = token.indexOf("x");
if (x != -1) {
foundMag = true;
int mag = (int) Double.parseDouble(token.substring(0, x));
String na = token.substring(x + 1);
store.setObjectiveNominalMagnification(
new Integer(mag), numDatasets, 0);
store.setObjectiveLensNA(new Double(na), numDatasets, 0);
}
else {
model.append(token);
model.append(" ");
}
}
if (tokens.hasMoreTokens()) {
String immersion = tokens.nextToken();
if (immersion == null || immersion.trim().equals("")) {
immersion = "Unknown";
}
store.setObjectiveImmersion(immersion, numDatasets, 0);
}
if (tokens.hasMoreTokens()) {
String correction = tokens.nextToken();
if (correction == null || correction.trim().equals("")) {
correction = "Unknown";
}
store.setObjectiveCorrection(correction, numDatasets, 0);
}
store.setObjectiveModel(model.toString().trim(), numDatasets, 0);
}
else if (attribute.equals("RefractionIndex")) {
String id = MetadataTools.createLSID("Objective", numDatasets, 0);
store.setObjectiveID(id, numDatasets, 0);
store.setObjectiveSettingsObjective(id, numDatasets);
store.setObjectiveSettingsRefractiveIndex(new Double(variant),
numDatasets);
}
else if (attribute.equals("XPos")) {
int c = coreMeta.rgb || coreMeta.sizeC == 0 ? 1 : coreMeta.sizeC;
int nPlanes = coreMeta.imageCount / c;
Double posX = new Double(variant);
for (int image=0; image<nPlanes; image++) {
int index = image * (coreMeta.rgb ? 1 : coreMeta.sizeC);
if (index >= nPlanes) continue;
store.setStagePositionPositionX(posX, numDatasets, 0, index);
}
if (numChannels == 0) xPos.add(posX);
}
else if (attribute.equals("YPos")) {
int c = coreMeta.rgb || coreMeta.sizeC == 0 ? 1 : coreMeta.sizeC;
int nPlanes = coreMeta.imageCount / c;
Double posY = new Double(variant);
for (int image=0; image<nPlanes; image++) {
int index = image * (coreMeta.rgb ? 1 : coreMeta.sizeC);
if (index >= nPlanes) continue;
store.setStagePositionPositionY(posY, numDatasets, 0, index);
}
if (numChannels == 0) yPos.add(posY);
}
else if (attribute.equals("ZPos")) {
int c = coreMeta.rgb || coreMeta.sizeC == 0 ? 1 : coreMeta.sizeC;
int nPlanes = coreMeta.imageCount / c;
Double posZ = new Double(variant);
for (int image=0; image<nPlanes; image++) {
int index = image * (coreMeta.rgb ? 1 : coreMeta.sizeC);
if (index >= nPlanes) continue;
store.setStagePositionPositionZ(posZ, numDatasets, 0, index);
}
if (numChannels == 0) zPos.add(posZ);
}
else if (objectClass.equals("CSpectrophotometerUnit")) {
Integer v = null;
try {
v = new Integer((int) Double.parseDouble(variant));
}
catch (NumberFormatException e) { }
if (attributes.getValue("Description").endsWith("(left)")) {
String id =
MetadataTools.createLSID("Filter", numDatasets, nextFilter);
store.setFilterID(id, numDatasets, nextFilter);
store.setFilterModel(object, numDatasets, nextFilter);
if (v != null) {
store.setTransmittanceRangeCutIn(v, numDatasets, nextFilter);
}
}
else if (attributes.getValue("Description").endsWith("(right)")) {
if (v != null) {
store.setTransmittanceRangeCutOut(v, numDatasets, nextFilter);
nextFilter++;
}
}
}
}
else if (qName.equals("Detector")) {
Double gain = new Double(attributes.getValue("Gain"));
Double offset = new Double(attributes.getValue("Offset"));
boolean active = attributes.getValue("IsActive").equals("1");
if (active) {
// find the corresponding MultiBand and Detector
MultiBand m = null;
Detector detector = null;
Laser laser = lasers.size() == 0 ? null : lasers.get(lasers.size() - 1);
int channel = Integer.parseInt(attributes.getValue("Channel"));
for (MultiBand mb : multiBands) {
if (mb.channel == channel) {
m = mb;
break;
}
}
for (Detector d : detectors) {
if (d.channel == channel) {
detector = d;
break;
}
}
String id =
MetadataTools.createLSID("Detector", numDatasets, nextChannel);
if (m != null) {
store.setLogicalChannelName(m.dyeName, numDatasets, nextChannel);
String filter =
MetadataTools.createLSID("Filter", numDatasets, nextFilter);
store.setFilterID(filter, numDatasets, nextFilter);
store.setTransmittanceRangeCutIn(new Integer(m.cutIn), numDatasets,
nextFilter);
store.setTransmittanceRangeCutOut(new Integer(m.cutOut), numDatasets,
nextFilter);
- /* debug */ System.out.println("(648) linking " + filter + " to " +
- nextChannel);
store.setLogicalChannelSecondaryEmissionFilter(filter, numDatasets,
nextChannel);
nextFilter++;
store.setDetectorID(id, numDatasets, nextChannel);
store.setDetectorType("PMT", numDatasets, nextChannel);
store.setDetectorSettingsGain(gain, numDatasets, nextChannel);
store.setDetectorSettingsOffset(offset, numDatasets, nextChannel);
store.setDetectorSettingsDetector(id, numDatasets, nextChannel);
}
if (detector != null) {
store.setDetectorID(id, numDatasets, nextChannel);
store.setDetectorSettingsGain(gain, numDatasets, nextChannel);
store.setDetectorSettingsOffset(offset, numDatasets, nextChannel);
store.setDetectorSettingsDetector(id, numDatasets, nextChannel);
store.setDetectorType(detector.type, numDatasets, nextChannel);
store.setDetectorModel(detector.model, numDatasets, nextChannel);
store.setDetectorZoom(detector.zoom, numDatasets, nextChannel);
store.setDetectorOffset(detector.offset, numDatasets, nextChannel);
store.setDetectorVoltage(detector.voltage, numDatasets,
nextChannel);
}
if (laser != null && laser.intensity > 0) {
store.setLightSourceSettingsLightSource(laser.id, numDatasets,
nextChannel);
store.setLightSourceSettingsAttenuation(
new Double(laser.intensity / 100.0), numDatasets, nextChannel);
store.setLogicalChannelExWave(laser.wavelength, numDatasets,
nextChannel);
}
nextChannel++;
}
}
else if (qName.equals("LaserLineSetting")) {
Laser l = new Laser();
l.index = Integer.parseInt(attributes.getValue("LineIndex"));
int qualifier = Integer.parseInt(attributes.getValue("Qualifier"));
l.index += (2 - (qualifier / 10));
if (l.index < 0) l.index = 0;
l.id = MetadataTools.createLSID("LightSource", numDatasets, l.index);
l.wavelength = new Integer(attributes.getValue("LaserLine"));
store.setLightSourceID(l.id, numDatasets, l.index);
store.setLaserWavelength(l.wavelength, numDatasets, l.index);
store.setLaserType("Unknown", numDatasets, l.index);
store.setLaserLaserMedium("Unknown", numDatasets, l.index);
l.intensity = Double.parseDouble(attributes.getValue("IntensityDev"));
if (l.intensity > 0) lasers.add(l);
}
else if (qName.equals("TimeStamp")) {
long high = Long.parseLong(attributes.getValue("HighInteger"));
long low = Long.parseLong(attributes.getValue("LowInteger"));
long ms = DateTools.getMillisFromTicks(high, low);
if (count == 0) {
String date = DateTools.convertDate(ms, DateTools.COBOL);
if (DateTools.getTime(date, DateTools.ISO8601_FORMAT) <
System.currentTimeMillis())
{
store.setImageCreationDate(date, numDatasets);
}
firstStamp = ms;
store.setPlaneTimingDeltaT(new Double(0), numDatasets, 0, count);
}
else {
CoreMetadata coreMeta = core.get(numDatasets);
int nImages = coreMeta.sizeZ * coreMeta.sizeT * coreMeta.sizeC;
if (count < nImages) {
ms -= firstStamp;
store.setPlaneTimingDeltaT(
new Double(ms / 1000.0), numDatasets, 0, count);
}
}
count++;
}
else if (qName.equals("RelTimeStamp")) {
CoreMetadata coreMeta = core.get(numDatasets);
int nImages = coreMeta.sizeZ * coreMeta.sizeT * coreMeta.sizeC;
if (count < nImages) {
Double time = new Double(attributes.getValue("Time"));
store.setPlaneTimingDeltaT(time, numDatasets, 0, count++);
}
}
else if (qName.equals("Annotation")) {
roi = new ROI();
String type = attributes.getValue("type");
if (type != null) roi.type = Integer.parseInt(type);
String color = attributes.getValue("color");
if (color != null) roi.color = Integer.parseInt(color);
roi.name = attributes.getValue("name");
roi.fontName = attributes.getValue("fontName");
roi.fontSize = attributes.getValue("fontSize");
roi.transX = parseDouble(attributes.getValue("transTransX"));
roi.transY = parseDouble(attributes.getValue("transTransY"));
roi.scaleX = parseDouble(attributes.getValue("transScalingX"));
roi.scaleY = parseDouble(attributes.getValue("transScalingY"));
roi.rotation = parseDouble(attributes.getValue("transRotation"));
String linewidth = attributes.getValue("linewidth");
if (linewidth != null) roi.linewidth = Integer.parseInt(linewidth);
roi.text = attributes.getValue("text");
}
else if (qName.equals("Vertex")) {
String x = attributes.getValue("x").replaceAll(",", ".");
String y = attributes.getValue("y").replaceAll(",", ".");
roi.x.add(new Double(x));
roi.y.add(new Double(y));
}
else if (qName.equals("ROI")) {
alternateCenter = true;
}
else if (qName.equals("MultiBand")) {
MultiBand m = new MultiBand();
m.dyeName = attributes.getValue("DyeName");
m.channel = Integer.parseInt(attributes.getValue("Channel"));
m.cutIn = (int)
Math.round(Double.parseDouble(attributes.getValue("LeftWorld")));
m.cutOut = (int)
Math.round(Double.parseDouble(attributes.getValue("RightWorld")));
multiBands.add(m);
}
else count = 0;
storeSeriesHashtable(numDatasets, h);
}
// -- Helper methods --
private Hashtable getSeriesHashtable(int series) {
if (series < 0 || series >= core.size()) return new Hashtable();
return core.get(series).seriesMetadata;
}
private void storeSeriesHashtable(int series, Hashtable h) {
if (series < 0) return;
CoreMetadata coreMeta = core.get(series);
coreMeta.seriesMetadata = h;
core.setElementAt(coreMeta, series);
}
// -- Helper class --
class ROI {
// -- Constants --
public static final int TEXT = 512;
public static final int SCALE_BAR = 8192;
public static final int POLYGON = 32;
public static final int RECTANGLE = 16;
public static final int LINE = 256;
public static final int ARROW = 2;
// -- Fields --
public int type;
public Vector<Double> x = new Vector<Double>();
public Vector<Double> y = new Vector<Double>();
// center point of the ROI
public double transX, transY;
// transformation parameters
public double scaleX, scaleY;
public double rotation;
public int color;
public int linewidth;
public String text;
public String fontName;
public String fontSize;
public String name;
private boolean normalized = false;
// -- ROI API methods --
public void storeROI(MetadataStore store, int series, int roi) {
// keep in mind that vertices are given relative to the center
// point of the ROI and the transX/transY values are relative to
// the center point of the image
if (text != null) store.setShapeText(text, series, roi, 0);
if (fontName != null) store.setShapeFontFamily(fontName, series, roi, 0);
if (fontSize != null) {
store.setShapeFontSize(
new Integer((int) Double.parseDouble(fontSize)), series, roi, 0);
}
store.setShapeStrokeColor(String.valueOf(color), series, roi, 0);
store.setShapeStrokeWidth(new Integer(linewidth), series, roi, 0);
if (!normalized) normalize();
double cornerX = x.get(0).doubleValue();
double cornerY = y.get(0).doubleValue();
int centerX = (core.get(series).sizeX / 2) - 1;
int centerY = (core.get(series).sizeY / 2) - 1;
double roiX = centerX + transX;
double roiY = centerY + transY;
if (alternateCenter) {
roiX = transX - 2 * cornerX;
roiY = transY - 2 * cornerY;
}
// TODO : rotation/scaling not populated
switch (type) {
case POLYGON:
StringBuffer points = new StringBuffer();
for (int i=0; i<x.size(); i++) {
points.append(x.get(i).doubleValue() + roiX);
points.append(",");
points.append(y.get(i).doubleValue() + roiY);
if (i < x.size() - 1) points.append(" ");
}
store.setPolygonPoints(points.toString(), series, roi, 0);
break;
case TEXT:
case RECTANGLE:
store.setRectX(
String.valueOf(roiX - Math.abs(cornerX)), series, roi, 0);
store.setRectY(
String.valueOf(roiY - Math.abs(cornerY)), series, roi, 0);
double width = 2 * Math.abs(cornerX);
double height = 2 * Math.abs(cornerY);
store.setRectWidth(String.valueOf(width), series, roi, 0);
store.setRectHeight(String.valueOf(height), series, roi, 0);
break;
case SCALE_BAR:
case ARROW:
case LINE:
store.setLineX1(String.valueOf(roiX + x.get(0)), series, roi, 0);
store.setLineY1(String.valueOf(roiY + y.get(0)), series, roi, 0);
store.setLineX2(String.valueOf(roiX + x.get(1)), series, roi, 0);
store.setLineY2(String.valueOf(roiY + y.get(1)), series, roi, 0);
break;
}
}
// -- Helper methods --
/**
* Vertices and transformation values are not stored in pixel coordinates.
* We need to convert them from physical coordinates to pixel coordinates
* so that they can be stored in a MetadataStore.
*/
private void normalize() {
if (normalized) return;
// coordinates are in meters
transX *= 1000000;
transY *= 1000000;
transX *= (1 / physicalSizeX);
transY *= (1 / physicalSizeY);
for (int i=0; i<x.size(); i++) {
double coordinate = x.get(i).doubleValue() * 1000000;
coordinate *= (1 / physicalSizeX);
x.setElementAt(new Double(coordinate), i);
}
for (int i=0; i<y.size(); i++) {
double coordinate = y.get(i).doubleValue() * 1000000;
coordinate *= (1 / physicalSizeY);
y.setElementAt(new Double(coordinate), i);
}
normalized = true;
}
}
private double parseDouble(String number) {
if (number != null) {
number = number.replaceAll(",", ".");
return Double.parseDouble(number);
}
return 0;
}
// -- Helper classes --
class MultiBand {
public int channel;
public int cutIn;
public int cutOut;
public String dyeName;
}
class Detector {
public int channel;
public Double zoom;
public String type;
public String model;
public boolean active;
public Double voltage;
public Double offset;
}
class Laser {
public Integer wavelength;
public double intensity;
public String id;
public int index;
}
}
| false | true | public void startElement(String uri, String localName, String qName,
Attributes attributes)
{
if (attributes.getLength() > 0 && !qName.equals("Element") &&
!qName.equals("Attachment") && !qName.equals("LMSDataContainerHeader"))
{
nameStack.push(qName);
}
Hashtable h = getSeriesHashtable(numDatasets);
if (qName.equals("LDM_Block_Sequential_Master")) {
canParse = false;
}
else if (qName.startsWith("LDM")) {
linkedInstruments = true;
}
if (!canParse) return;
StringBuffer key = new StringBuffer();
for (String k : nameStack) {
key.append(k);
key.append("|");
}
String suffix = attributes.getValue("Identifier");
String value = attributes.getValue("Variant");
if (suffix == null) suffix = attributes.getValue("Description");
if (suffix != null && value != null) {
int index = 1;
while (h.get(key.toString() + suffix + " " + index) != null) index++;
h.put(key.toString() + suffix + " " + index, value);
}
else {
for (int i=0; i<attributes.getLength(); i++) {
int index = 1;
while (
h.get(key.toString() + attributes.getQName(i) + " " + index) != null)
{
index++;
}
h.put(key.toString() + attributes.getQName(i) + " " + index,
attributes.getValue(i));
}
}
if (qName.equals("Element")) {
elementName = attributes.getValue("Name");
}
else if (qName.equals("Collection")) {
collection = elementName;
}
else if (qName.equals("Image")) {
if (!linkedInstruments) {
int c = 0;
for (Detector d : detectors) {
String id = MetadataTools.createLSID(
"Detector", numDatasets, detectorChannel);
store.setDetectorID(id, numDatasets, detectorChannel);
store.setDetectorType(d.type, numDatasets, detectorChannel);
store.setDetectorModel(d.model, numDatasets, detectorChannel);
store.setDetectorZoom(d.zoom, numDatasets, detectorChannel);
store.setDetectorOffset(d.offset, numDatasets, detectorChannel);
store.setDetectorVoltage(d.voltage, numDatasets, detectorChannel);
if (c < numChannels) {
if (d.active) {
store.setDetectorSettingsOffset(d.offset, numDatasets, c);
store.setDetectorSettingsDetector(id, numDatasets, c);
c++;
}
}
detectorChannel++;
}
int filter = 0;
for (int i=0; i<nextFilter; i++) {
while (filter < detectors.size() && !detectors.get(filter).active) {
filter++;
}
if (filter >= detectors.size() || filter >= numChannels) break;
String id = MetadataTools.createLSID("Filter", numDatasets, filter);
if (i < numChannels && detectors.get(filter).active) {
store.setLogicalChannelSecondaryEmissionFilter(
id, numDatasets, i);
}
filter++;
}
}
core.add(new CoreMetadata());
numDatasets++;
linkedInstruments = false;
detectorChannel = 0;
detectors.clear();
lasers.clear();
nextFilter = 0;
String name = elementName;
if (collection != null) name = collection + "/" + name;
store.setImageName(name, numDatasets);
String instrumentID = MetadataTools.createLSID("Instrument", numDatasets);
store.setInstrumentID(instrumentID, numDatasets);
store.setImageInstrumentRef(instrumentID, numDatasets);
numChannels = 0;
extras = 1;
}
else if (qName.equals("Attachment")) {
if (attributes.getValue("Name").equals("ContextDescription")) {
store.setImageDescription(attributes.getValue("Content"), numDatasets);
}
}
else if (qName.equals("ChannelDescription")) {
count++;
numChannels++;
lutNames.add(attributes.getValue("LUTName"));
int bytes = Integer.parseInt(attributes.getValue("BytesInc"));
if (bytes > 0) {
bytesPerAxis.put(new Integer(bytes), "C");
}
}
else if (qName.equals("DimensionDescription")) {
int len = Integer.parseInt(attributes.getValue("NumberOfElements"));
int id = Integer.parseInt(attributes.getValue("DimID"));
double physicalLen = Double.parseDouble(attributes.getValue("Length"));
String unit = attributes.getValue("Unit");
int nBytes = Integer.parseInt(attributes.getValue("BytesInc"));
physicalLen /= len;
if (unit.equals("Ks")) {
physicalLen /= 1000;
}
else if (unit.equals("m")) {
physicalLen *= 1000000;
}
Double physicalSize = new Double(physicalLen);
CoreMetadata coreMeta = core.get(core.size() - 1);
switch (id) {
case 1: // X axis
coreMeta.sizeX = len;
coreMeta.rgb = (nBytes % 3) == 0;
if (coreMeta.rgb) nBytes /= 3;
switch (nBytes) {
case 1:
coreMeta.pixelType = FormatTools.UINT8;
break;
case 2:
coreMeta.pixelType = FormatTools.UINT16;
break;
case 4:
coreMeta.pixelType = FormatTools.FLOAT;
break;
}
physicalSizeX = physicalSize.doubleValue();
store.setDimensionsPhysicalSizeX(physicalSize, numDatasets, 0);
break;
case 2: // Y axis
if (coreMeta.sizeY != 0) {
if (coreMeta.sizeZ == 1) {
coreMeta.sizeZ = len;
}
else if (coreMeta.sizeT == 1) {
coreMeta.sizeT = len;
}
}
else {
coreMeta.sizeY = len;
physicalSizeY = physicalSize.doubleValue();
store.setDimensionsPhysicalSizeY(physicalSize, numDatasets, 0);
}
break;
case 3: // Z axis
if (coreMeta.sizeY == 0) {
// XZ scan - swap Y and Z
coreMeta.sizeY = len;
coreMeta.sizeZ = 1;
physicalSizeY = physicalSize.doubleValue();
store.setDimensionsPhysicalSizeY(physicalSize, numDatasets, 0);
}
else {
coreMeta.sizeZ = len;
}
bytesPerAxis.put(new Integer(nBytes), "Z");
break;
case 4: // T axis
if (coreMeta.sizeY == 0) {
// XT scan - swap Y and T
coreMeta.sizeY = len;
coreMeta.sizeT = 1;
physicalSizeY = physicalSize.doubleValue();
store.setDimensionsPhysicalSizeY(physicalSize, numDatasets, 0);
}
else {
coreMeta.sizeT = len;
}
bytesPerAxis.put(new Integer(nBytes), "T");
break;
default:
extras *= len;
}
count++;
}
else if (qName.equals("ScannerSettingRecord")) {
String id = attributes.getValue("Identifier");
if (id.equals("SystemType")) {
store.setMicroscopeModel(value, numDatasets);
store.setMicroscopeType("Unknown", numDatasets);
}
else if (id.equals("dblPinhole")) {
pinhole = new Double(Double.parseDouble(value) * 1000000);
}
else if (id.equals("dblZoom")) {
zoom = new Double(value);
}
else if (id.equals("dblStepSize")) {
double zStep = Double.parseDouble(value) * 1000000;
store.setDimensionsPhysicalSizeZ(new Double(zStep), numDatasets, 0);
}
else if (id.equals("nDelayTime_s")) {
store.setDimensionsTimeIncrement(new Double(value), numDatasets, 0);
}
else if (id.equals("CameraName")) {
store.setDetectorModel(value, numDatasets, 0);
}
else if (id.indexOf("WFC") == 1) {
int c = 0;
try {
c = Integer.parseInt(id.replaceAll("\\D", ""));
}
catch (NumberFormatException e) { }
if (id.endsWith("ExposureTime")) {
store.setPlaneTimingExposureTime(new Double(value),
numDatasets, 0, c);
}
else if (id.endsWith("Gain")) {
store.setDetectorSettingsGain(new Double(value), numDatasets, c);
String detectorID =
MetadataTools.createLSID("Detector", numDatasets, 0);
store.setDetectorSettingsDetector(detectorID, numDatasets, c);
store.setDetectorID(detectorID, numDatasets, 0);
store.setDetectorType("CCD", numDatasets, 0);
}
else if (id.endsWith("WaveLength")) {
store.setLogicalChannelExWave(new Integer(value), numDatasets, c);
}
// NB: "UesrDefName" is not a typo.
else if (id.endsWith("UesrDefName") && !value.equals("None")) {
store.setLogicalChannelName(value, numDatasets, c);
}
}
}
else if (qName.equals("FilterSettingRecord")) {
String object = attributes.getValue("ObjectName");
String attribute = attributes.getValue("Attribute");
String objectClass = attributes.getValue("ClassName");
String variant = attributes.getValue("Variant");
CoreMetadata coreMeta = core.get(numDatasets);
if (attribute.equals("NumericalAperture")) {
store.setObjectiveLensNA(new Double(variant), numDatasets, 0);
}
else if (attribute.equals("OrderNumber")) {
store.setObjectiveSerialNumber(variant, numDatasets, 0);
}
else if (objectClass.equals("CDetectionUnit")) {
if (attribute.equals("State")) {
Detector d = new Detector();
d.channel = Integer.parseInt(attributes.getValue("Data"));
d.type = "PMT";
d.model = object;
d.active = variant.equals("Active");
d.zoom = zoom;
detectors.add(d);
}
else if (attribute.equals("HighVoltage")) {
Detector d = detectors.get(detectors.size() - 1);
d.voltage = new Double(variant);
}
else if (attribute.equals("VideoOffset")) {
Detector d = detectors.get(detectors.size() - 1);
d.offset = new Double(variant);
}
}
else if (attribute.equals("Objective")) {
StringTokenizer tokens = new StringTokenizer(variant, " ");
boolean foundMag = false;
StringBuffer model = new StringBuffer();
while (!foundMag) {
String token = tokens.nextToken();
int x = token.indexOf("x");
if (x != -1) {
foundMag = true;
int mag = (int) Double.parseDouble(token.substring(0, x));
String na = token.substring(x + 1);
store.setObjectiveNominalMagnification(
new Integer(mag), numDatasets, 0);
store.setObjectiveLensNA(new Double(na), numDatasets, 0);
}
else {
model.append(token);
model.append(" ");
}
}
if (tokens.hasMoreTokens()) {
String immersion = tokens.nextToken();
if (immersion == null || immersion.trim().equals("")) {
immersion = "Unknown";
}
store.setObjectiveImmersion(immersion, numDatasets, 0);
}
if (tokens.hasMoreTokens()) {
String correction = tokens.nextToken();
if (correction == null || correction.trim().equals("")) {
correction = "Unknown";
}
store.setObjectiveCorrection(correction, numDatasets, 0);
}
store.setObjectiveModel(model.toString().trim(), numDatasets, 0);
}
else if (attribute.equals("RefractionIndex")) {
String id = MetadataTools.createLSID("Objective", numDatasets, 0);
store.setObjectiveID(id, numDatasets, 0);
store.setObjectiveSettingsObjective(id, numDatasets);
store.setObjectiveSettingsRefractiveIndex(new Double(variant),
numDatasets);
}
else if (attribute.equals("XPos")) {
int c = coreMeta.rgb || coreMeta.sizeC == 0 ? 1 : coreMeta.sizeC;
int nPlanes = coreMeta.imageCount / c;
Double posX = new Double(variant);
for (int image=0; image<nPlanes; image++) {
int index = image * (coreMeta.rgb ? 1 : coreMeta.sizeC);
if (index >= nPlanes) continue;
store.setStagePositionPositionX(posX, numDatasets, 0, index);
}
if (numChannels == 0) xPos.add(posX);
}
else if (attribute.equals("YPos")) {
int c = coreMeta.rgb || coreMeta.sizeC == 0 ? 1 : coreMeta.sizeC;
int nPlanes = coreMeta.imageCount / c;
Double posY = new Double(variant);
for (int image=0; image<nPlanes; image++) {
int index = image * (coreMeta.rgb ? 1 : coreMeta.sizeC);
if (index >= nPlanes) continue;
store.setStagePositionPositionY(posY, numDatasets, 0, index);
}
if (numChannels == 0) yPos.add(posY);
}
else if (attribute.equals("ZPos")) {
int c = coreMeta.rgb || coreMeta.sizeC == 0 ? 1 : coreMeta.sizeC;
int nPlanes = coreMeta.imageCount / c;
Double posZ = new Double(variant);
for (int image=0; image<nPlanes; image++) {
int index = image * (coreMeta.rgb ? 1 : coreMeta.sizeC);
if (index >= nPlanes) continue;
store.setStagePositionPositionZ(posZ, numDatasets, 0, index);
}
if (numChannels == 0) zPos.add(posZ);
}
else if (objectClass.equals("CSpectrophotometerUnit")) {
Integer v = null;
try {
v = new Integer((int) Double.parseDouble(variant));
}
catch (NumberFormatException e) { }
if (attributes.getValue("Description").endsWith("(left)")) {
String id =
MetadataTools.createLSID("Filter", numDatasets, nextFilter);
store.setFilterID(id, numDatasets, nextFilter);
store.setFilterModel(object, numDatasets, nextFilter);
if (v != null) {
store.setTransmittanceRangeCutIn(v, numDatasets, nextFilter);
}
}
else if (attributes.getValue("Description").endsWith("(right)")) {
if (v != null) {
store.setTransmittanceRangeCutOut(v, numDatasets, nextFilter);
nextFilter++;
}
}
}
}
else if (qName.equals("Detector")) {
Double gain = new Double(attributes.getValue("Gain"));
Double offset = new Double(attributes.getValue("Offset"));
boolean active = attributes.getValue("IsActive").equals("1");
if (active) {
// find the corresponding MultiBand and Detector
MultiBand m = null;
Detector detector = null;
Laser laser = lasers.size() == 0 ? null : lasers.get(lasers.size() - 1);
int channel = Integer.parseInt(attributes.getValue("Channel"));
for (MultiBand mb : multiBands) {
if (mb.channel == channel) {
m = mb;
break;
}
}
for (Detector d : detectors) {
if (d.channel == channel) {
detector = d;
break;
}
}
String id =
MetadataTools.createLSID("Detector", numDatasets, nextChannel);
if (m != null) {
store.setLogicalChannelName(m.dyeName, numDatasets, nextChannel);
String filter =
MetadataTools.createLSID("Filter", numDatasets, nextFilter);
store.setFilterID(filter, numDatasets, nextFilter);
store.setTransmittanceRangeCutIn(new Integer(m.cutIn), numDatasets,
nextFilter);
store.setTransmittanceRangeCutOut(new Integer(m.cutOut), numDatasets,
nextFilter);
/* debug */ System.out.println("(648) linking " + filter + " to " +
nextChannel);
store.setLogicalChannelSecondaryEmissionFilter(filter, numDatasets,
nextChannel);
nextFilter++;
store.setDetectorID(id, numDatasets, nextChannel);
store.setDetectorType("PMT", numDatasets, nextChannel);
store.setDetectorSettingsGain(gain, numDatasets, nextChannel);
store.setDetectorSettingsOffset(offset, numDatasets, nextChannel);
store.setDetectorSettingsDetector(id, numDatasets, nextChannel);
}
if (detector != null) {
store.setDetectorID(id, numDatasets, nextChannel);
store.setDetectorSettingsGain(gain, numDatasets, nextChannel);
store.setDetectorSettingsOffset(offset, numDatasets, nextChannel);
store.setDetectorSettingsDetector(id, numDatasets, nextChannel);
store.setDetectorType(detector.type, numDatasets, nextChannel);
store.setDetectorModel(detector.model, numDatasets, nextChannel);
store.setDetectorZoom(detector.zoom, numDatasets, nextChannel);
store.setDetectorOffset(detector.offset, numDatasets, nextChannel);
store.setDetectorVoltage(detector.voltage, numDatasets,
nextChannel);
}
if (laser != null && laser.intensity > 0) {
store.setLightSourceSettingsLightSource(laser.id, numDatasets,
nextChannel);
store.setLightSourceSettingsAttenuation(
new Double(laser.intensity / 100.0), numDatasets, nextChannel);
store.setLogicalChannelExWave(laser.wavelength, numDatasets,
nextChannel);
}
nextChannel++;
}
}
else if (qName.equals("LaserLineSetting")) {
Laser l = new Laser();
l.index = Integer.parseInt(attributes.getValue("LineIndex"));
int qualifier = Integer.parseInt(attributes.getValue("Qualifier"));
l.index += (2 - (qualifier / 10));
if (l.index < 0) l.index = 0;
l.id = MetadataTools.createLSID("LightSource", numDatasets, l.index);
l.wavelength = new Integer(attributes.getValue("LaserLine"));
store.setLightSourceID(l.id, numDatasets, l.index);
store.setLaserWavelength(l.wavelength, numDatasets, l.index);
store.setLaserType("Unknown", numDatasets, l.index);
store.setLaserLaserMedium("Unknown", numDatasets, l.index);
l.intensity = Double.parseDouble(attributes.getValue("IntensityDev"));
if (l.intensity > 0) lasers.add(l);
}
else if (qName.equals("TimeStamp")) {
long high = Long.parseLong(attributes.getValue("HighInteger"));
long low = Long.parseLong(attributes.getValue("LowInteger"));
long ms = DateTools.getMillisFromTicks(high, low);
if (count == 0) {
String date = DateTools.convertDate(ms, DateTools.COBOL);
if (DateTools.getTime(date, DateTools.ISO8601_FORMAT) <
System.currentTimeMillis())
{
store.setImageCreationDate(date, numDatasets);
}
firstStamp = ms;
store.setPlaneTimingDeltaT(new Double(0), numDatasets, 0, count);
}
else {
CoreMetadata coreMeta = core.get(numDatasets);
int nImages = coreMeta.sizeZ * coreMeta.sizeT * coreMeta.sizeC;
if (count < nImages) {
ms -= firstStamp;
store.setPlaneTimingDeltaT(
new Double(ms / 1000.0), numDatasets, 0, count);
}
}
count++;
}
else if (qName.equals("RelTimeStamp")) {
CoreMetadata coreMeta = core.get(numDatasets);
int nImages = coreMeta.sizeZ * coreMeta.sizeT * coreMeta.sizeC;
if (count < nImages) {
Double time = new Double(attributes.getValue("Time"));
store.setPlaneTimingDeltaT(time, numDatasets, 0, count++);
}
}
else if (qName.equals("Annotation")) {
roi = new ROI();
String type = attributes.getValue("type");
if (type != null) roi.type = Integer.parseInt(type);
String color = attributes.getValue("color");
if (color != null) roi.color = Integer.parseInt(color);
roi.name = attributes.getValue("name");
roi.fontName = attributes.getValue("fontName");
roi.fontSize = attributes.getValue("fontSize");
roi.transX = parseDouble(attributes.getValue("transTransX"));
roi.transY = parseDouble(attributes.getValue("transTransY"));
roi.scaleX = parseDouble(attributes.getValue("transScalingX"));
roi.scaleY = parseDouble(attributes.getValue("transScalingY"));
roi.rotation = parseDouble(attributes.getValue("transRotation"));
String linewidth = attributes.getValue("linewidth");
if (linewidth != null) roi.linewidth = Integer.parseInt(linewidth);
roi.text = attributes.getValue("text");
}
else if (qName.equals("Vertex")) {
String x = attributes.getValue("x").replaceAll(",", ".");
String y = attributes.getValue("y").replaceAll(",", ".");
roi.x.add(new Double(x));
roi.y.add(new Double(y));
}
else if (qName.equals("ROI")) {
alternateCenter = true;
}
else if (qName.equals("MultiBand")) {
MultiBand m = new MultiBand();
m.dyeName = attributes.getValue("DyeName");
m.channel = Integer.parseInt(attributes.getValue("Channel"));
m.cutIn = (int)
Math.round(Double.parseDouble(attributes.getValue("LeftWorld")));
m.cutOut = (int)
Math.round(Double.parseDouble(attributes.getValue("RightWorld")));
multiBands.add(m);
}
else count = 0;
storeSeriesHashtable(numDatasets, h);
}
| public void startElement(String uri, String localName, String qName,
Attributes attributes)
{
if (attributes.getLength() > 0 && !qName.equals("Element") &&
!qName.equals("Attachment") && !qName.equals("LMSDataContainerHeader"))
{
nameStack.push(qName);
}
Hashtable h = getSeriesHashtable(numDatasets);
if (qName.equals("LDM_Block_Sequential_Master")) {
canParse = false;
}
else if (qName.startsWith("LDM")) {
linkedInstruments = true;
}
if (!canParse) return;
StringBuffer key = new StringBuffer();
for (String k : nameStack) {
key.append(k);
key.append("|");
}
String suffix = attributes.getValue("Identifier");
String value = attributes.getValue("Variant");
if (suffix == null) suffix = attributes.getValue("Description");
if (suffix != null && value != null) {
int index = 1;
while (h.get(key.toString() + suffix + " " + index) != null) index++;
h.put(key.toString() + suffix + " " + index, value);
}
else {
for (int i=0; i<attributes.getLength(); i++) {
int index = 1;
while (
h.get(key.toString() + attributes.getQName(i) + " " + index) != null)
{
index++;
}
h.put(key.toString() + attributes.getQName(i) + " " + index,
attributes.getValue(i));
}
}
if (qName.equals("Element")) {
elementName = attributes.getValue("Name");
}
else if (qName.equals("Collection")) {
collection = elementName;
}
else if (qName.equals("Image")) {
if (!linkedInstruments) {
int c = 0;
for (Detector d : detectors) {
String id = MetadataTools.createLSID(
"Detector", numDatasets, detectorChannel);
store.setDetectorID(id, numDatasets, detectorChannel);
store.setDetectorType(d.type, numDatasets, detectorChannel);
store.setDetectorModel(d.model, numDatasets, detectorChannel);
store.setDetectorZoom(d.zoom, numDatasets, detectorChannel);
store.setDetectorOffset(d.offset, numDatasets, detectorChannel);
store.setDetectorVoltage(d.voltage, numDatasets, detectorChannel);
if (c < numChannels) {
if (d.active) {
store.setDetectorSettingsOffset(d.offset, numDatasets, c);
store.setDetectorSettingsDetector(id, numDatasets, c);
c++;
}
}
detectorChannel++;
}
int filter = 0;
for (int i=0; i<nextFilter; i++) {
while (filter < detectors.size() && !detectors.get(filter).active) {
filter++;
}
if (filter >= detectors.size() || filter >= nextFilter) break;
String id = MetadataTools.createLSID("Filter", numDatasets, filter);
if (i < numChannels && detectors.get(filter).active) {
store.setLogicalChannelSecondaryEmissionFilter(
id, numDatasets, i);
}
filter++;
}
}
core.add(new CoreMetadata());
numDatasets++;
linkedInstruments = false;
detectorChannel = 0;
detectors.clear();
lasers.clear();
nextFilter = 0;
String name = elementName;
if (collection != null) name = collection + "/" + name;
store.setImageName(name, numDatasets);
String instrumentID = MetadataTools.createLSID("Instrument", numDatasets);
store.setInstrumentID(instrumentID, numDatasets);
store.setImageInstrumentRef(instrumentID, numDatasets);
numChannels = 0;
extras = 1;
}
else if (qName.equals("Attachment")) {
if (attributes.getValue("Name").equals("ContextDescription")) {
store.setImageDescription(attributes.getValue("Content"), numDatasets);
}
}
else if (qName.equals("ChannelDescription")) {
count++;
numChannels++;
lutNames.add(attributes.getValue("LUTName"));
int bytes = Integer.parseInt(attributes.getValue("BytesInc"));
if (bytes > 0) {
bytesPerAxis.put(new Integer(bytes), "C");
}
}
else if (qName.equals("DimensionDescription")) {
int len = Integer.parseInt(attributes.getValue("NumberOfElements"));
int id = Integer.parseInt(attributes.getValue("DimID"));
double physicalLen = Double.parseDouble(attributes.getValue("Length"));
String unit = attributes.getValue("Unit");
int nBytes = Integer.parseInt(attributes.getValue("BytesInc"));
physicalLen /= len;
if (unit.equals("Ks")) {
physicalLen /= 1000;
}
else if (unit.equals("m")) {
physicalLen *= 1000000;
}
Double physicalSize = new Double(physicalLen);
CoreMetadata coreMeta = core.get(core.size() - 1);
switch (id) {
case 1: // X axis
coreMeta.sizeX = len;
coreMeta.rgb = (nBytes % 3) == 0;
if (coreMeta.rgb) nBytes /= 3;
switch (nBytes) {
case 1:
coreMeta.pixelType = FormatTools.UINT8;
break;
case 2:
coreMeta.pixelType = FormatTools.UINT16;
break;
case 4:
coreMeta.pixelType = FormatTools.FLOAT;
break;
}
physicalSizeX = physicalSize.doubleValue();
store.setDimensionsPhysicalSizeX(physicalSize, numDatasets, 0);
break;
case 2: // Y axis
if (coreMeta.sizeY != 0) {
if (coreMeta.sizeZ == 1) {
coreMeta.sizeZ = len;
}
else if (coreMeta.sizeT == 1) {
coreMeta.sizeT = len;
}
}
else {
coreMeta.sizeY = len;
physicalSizeY = physicalSize.doubleValue();
store.setDimensionsPhysicalSizeY(physicalSize, numDatasets, 0);
}
break;
case 3: // Z axis
if (coreMeta.sizeY == 0) {
// XZ scan - swap Y and Z
coreMeta.sizeY = len;
coreMeta.sizeZ = 1;
physicalSizeY = physicalSize.doubleValue();
store.setDimensionsPhysicalSizeY(physicalSize, numDatasets, 0);
}
else {
coreMeta.sizeZ = len;
}
bytesPerAxis.put(new Integer(nBytes), "Z");
break;
case 4: // T axis
if (coreMeta.sizeY == 0) {
// XT scan - swap Y and T
coreMeta.sizeY = len;
coreMeta.sizeT = 1;
physicalSizeY = physicalSize.doubleValue();
store.setDimensionsPhysicalSizeY(physicalSize, numDatasets, 0);
}
else {
coreMeta.sizeT = len;
}
bytesPerAxis.put(new Integer(nBytes), "T");
break;
default:
extras *= len;
}
count++;
}
else if (qName.equals("ScannerSettingRecord")) {
String id = attributes.getValue("Identifier");
if (id.equals("SystemType")) {
store.setMicroscopeModel(value, numDatasets);
store.setMicroscopeType("Unknown", numDatasets);
}
else if (id.equals("dblPinhole")) {
pinhole = new Double(Double.parseDouble(value) * 1000000);
}
else if (id.equals("dblZoom")) {
zoom = new Double(value);
}
else if (id.equals("dblStepSize")) {
double zStep = Double.parseDouble(value) * 1000000;
store.setDimensionsPhysicalSizeZ(new Double(zStep), numDatasets, 0);
}
else if (id.equals("nDelayTime_s")) {
store.setDimensionsTimeIncrement(new Double(value), numDatasets, 0);
}
else if (id.equals("CameraName")) {
store.setDetectorModel(value, numDatasets, 0);
}
else if (id.indexOf("WFC") == 1) {
int c = 0;
try {
c = Integer.parseInt(id.replaceAll("\\D", ""));
}
catch (NumberFormatException e) { }
if (id.endsWith("ExposureTime")) {
store.setPlaneTimingExposureTime(new Double(value),
numDatasets, 0, c);
}
else if (id.endsWith("Gain")) {
store.setDetectorSettingsGain(new Double(value), numDatasets, c);
String detectorID =
MetadataTools.createLSID("Detector", numDatasets, 0);
store.setDetectorSettingsDetector(detectorID, numDatasets, c);
store.setDetectorID(detectorID, numDatasets, 0);
store.setDetectorType("CCD", numDatasets, 0);
}
else if (id.endsWith("WaveLength")) {
store.setLogicalChannelExWave(new Integer(value), numDatasets, c);
}
// NB: "UesrDefName" is not a typo.
else if (id.endsWith("UesrDefName") && !value.equals("None")) {
store.setLogicalChannelName(value, numDatasets, c);
}
}
}
else if (qName.equals("FilterSettingRecord")) {
String object = attributes.getValue("ObjectName");
String attribute = attributes.getValue("Attribute");
String objectClass = attributes.getValue("ClassName");
String variant = attributes.getValue("Variant");
CoreMetadata coreMeta = core.get(numDatasets);
if (attribute.equals("NumericalAperture")) {
store.setObjectiveLensNA(new Double(variant), numDatasets, 0);
}
else if (attribute.equals("OrderNumber")) {
store.setObjectiveSerialNumber(variant, numDatasets, 0);
}
else if (objectClass.equals("CDetectionUnit")) {
if (attribute.equals("State")) {
Detector d = new Detector();
d.channel = Integer.parseInt(attributes.getValue("Data"));
d.type = "PMT";
d.model = object;
d.active = variant.equals("Active");
d.zoom = zoom;
detectors.add(d);
}
else if (attribute.equals("HighVoltage")) {
Detector d = detectors.get(detectors.size() - 1);
d.voltage = new Double(variant);
}
else if (attribute.equals("VideoOffset")) {
Detector d = detectors.get(detectors.size() - 1);
d.offset = new Double(variant);
}
}
else if (attribute.equals("Objective")) {
StringTokenizer tokens = new StringTokenizer(variant, " ");
boolean foundMag = false;
StringBuffer model = new StringBuffer();
while (!foundMag) {
String token = tokens.nextToken();
int x = token.indexOf("x");
if (x != -1) {
foundMag = true;
int mag = (int) Double.parseDouble(token.substring(0, x));
String na = token.substring(x + 1);
store.setObjectiveNominalMagnification(
new Integer(mag), numDatasets, 0);
store.setObjectiveLensNA(new Double(na), numDatasets, 0);
}
else {
model.append(token);
model.append(" ");
}
}
if (tokens.hasMoreTokens()) {
String immersion = tokens.nextToken();
if (immersion == null || immersion.trim().equals("")) {
immersion = "Unknown";
}
store.setObjectiveImmersion(immersion, numDatasets, 0);
}
if (tokens.hasMoreTokens()) {
String correction = tokens.nextToken();
if (correction == null || correction.trim().equals("")) {
correction = "Unknown";
}
store.setObjectiveCorrection(correction, numDatasets, 0);
}
store.setObjectiveModel(model.toString().trim(), numDatasets, 0);
}
else if (attribute.equals("RefractionIndex")) {
String id = MetadataTools.createLSID("Objective", numDatasets, 0);
store.setObjectiveID(id, numDatasets, 0);
store.setObjectiveSettingsObjective(id, numDatasets);
store.setObjectiveSettingsRefractiveIndex(new Double(variant),
numDatasets);
}
else if (attribute.equals("XPos")) {
int c = coreMeta.rgb || coreMeta.sizeC == 0 ? 1 : coreMeta.sizeC;
int nPlanes = coreMeta.imageCount / c;
Double posX = new Double(variant);
for (int image=0; image<nPlanes; image++) {
int index = image * (coreMeta.rgb ? 1 : coreMeta.sizeC);
if (index >= nPlanes) continue;
store.setStagePositionPositionX(posX, numDatasets, 0, index);
}
if (numChannels == 0) xPos.add(posX);
}
else if (attribute.equals("YPos")) {
int c = coreMeta.rgb || coreMeta.sizeC == 0 ? 1 : coreMeta.sizeC;
int nPlanes = coreMeta.imageCount / c;
Double posY = new Double(variant);
for (int image=0; image<nPlanes; image++) {
int index = image * (coreMeta.rgb ? 1 : coreMeta.sizeC);
if (index >= nPlanes) continue;
store.setStagePositionPositionY(posY, numDatasets, 0, index);
}
if (numChannels == 0) yPos.add(posY);
}
else if (attribute.equals("ZPos")) {
int c = coreMeta.rgb || coreMeta.sizeC == 0 ? 1 : coreMeta.sizeC;
int nPlanes = coreMeta.imageCount / c;
Double posZ = new Double(variant);
for (int image=0; image<nPlanes; image++) {
int index = image * (coreMeta.rgb ? 1 : coreMeta.sizeC);
if (index >= nPlanes) continue;
store.setStagePositionPositionZ(posZ, numDatasets, 0, index);
}
if (numChannels == 0) zPos.add(posZ);
}
else if (objectClass.equals("CSpectrophotometerUnit")) {
Integer v = null;
try {
v = new Integer((int) Double.parseDouble(variant));
}
catch (NumberFormatException e) { }
if (attributes.getValue("Description").endsWith("(left)")) {
String id =
MetadataTools.createLSID("Filter", numDatasets, nextFilter);
store.setFilterID(id, numDatasets, nextFilter);
store.setFilterModel(object, numDatasets, nextFilter);
if (v != null) {
store.setTransmittanceRangeCutIn(v, numDatasets, nextFilter);
}
}
else if (attributes.getValue("Description").endsWith("(right)")) {
if (v != null) {
store.setTransmittanceRangeCutOut(v, numDatasets, nextFilter);
nextFilter++;
}
}
}
}
else if (qName.equals("Detector")) {
Double gain = new Double(attributes.getValue("Gain"));
Double offset = new Double(attributes.getValue("Offset"));
boolean active = attributes.getValue("IsActive").equals("1");
if (active) {
// find the corresponding MultiBand and Detector
MultiBand m = null;
Detector detector = null;
Laser laser = lasers.size() == 0 ? null : lasers.get(lasers.size() - 1);
int channel = Integer.parseInt(attributes.getValue("Channel"));
for (MultiBand mb : multiBands) {
if (mb.channel == channel) {
m = mb;
break;
}
}
for (Detector d : detectors) {
if (d.channel == channel) {
detector = d;
break;
}
}
String id =
MetadataTools.createLSID("Detector", numDatasets, nextChannel);
if (m != null) {
store.setLogicalChannelName(m.dyeName, numDatasets, nextChannel);
String filter =
MetadataTools.createLSID("Filter", numDatasets, nextFilter);
store.setFilterID(filter, numDatasets, nextFilter);
store.setTransmittanceRangeCutIn(new Integer(m.cutIn), numDatasets,
nextFilter);
store.setTransmittanceRangeCutOut(new Integer(m.cutOut), numDatasets,
nextFilter);
store.setLogicalChannelSecondaryEmissionFilter(filter, numDatasets,
nextChannel);
nextFilter++;
store.setDetectorID(id, numDatasets, nextChannel);
store.setDetectorType("PMT", numDatasets, nextChannel);
store.setDetectorSettingsGain(gain, numDatasets, nextChannel);
store.setDetectorSettingsOffset(offset, numDatasets, nextChannel);
store.setDetectorSettingsDetector(id, numDatasets, nextChannel);
}
if (detector != null) {
store.setDetectorID(id, numDatasets, nextChannel);
store.setDetectorSettingsGain(gain, numDatasets, nextChannel);
store.setDetectorSettingsOffset(offset, numDatasets, nextChannel);
store.setDetectorSettingsDetector(id, numDatasets, nextChannel);
store.setDetectorType(detector.type, numDatasets, nextChannel);
store.setDetectorModel(detector.model, numDatasets, nextChannel);
store.setDetectorZoom(detector.zoom, numDatasets, nextChannel);
store.setDetectorOffset(detector.offset, numDatasets, nextChannel);
store.setDetectorVoltage(detector.voltage, numDatasets,
nextChannel);
}
if (laser != null && laser.intensity > 0) {
store.setLightSourceSettingsLightSource(laser.id, numDatasets,
nextChannel);
store.setLightSourceSettingsAttenuation(
new Double(laser.intensity / 100.0), numDatasets, nextChannel);
store.setLogicalChannelExWave(laser.wavelength, numDatasets,
nextChannel);
}
nextChannel++;
}
}
else if (qName.equals("LaserLineSetting")) {
Laser l = new Laser();
l.index = Integer.parseInt(attributes.getValue("LineIndex"));
int qualifier = Integer.parseInt(attributes.getValue("Qualifier"));
l.index += (2 - (qualifier / 10));
if (l.index < 0) l.index = 0;
l.id = MetadataTools.createLSID("LightSource", numDatasets, l.index);
l.wavelength = new Integer(attributes.getValue("LaserLine"));
store.setLightSourceID(l.id, numDatasets, l.index);
store.setLaserWavelength(l.wavelength, numDatasets, l.index);
store.setLaserType("Unknown", numDatasets, l.index);
store.setLaserLaserMedium("Unknown", numDatasets, l.index);
l.intensity = Double.parseDouble(attributes.getValue("IntensityDev"));
if (l.intensity > 0) lasers.add(l);
}
else if (qName.equals("TimeStamp")) {
long high = Long.parseLong(attributes.getValue("HighInteger"));
long low = Long.parseLong(attributes.getValue("LowInteger"));
long ms = DateTools.getMillisFromTicks(high, low);
if (count == 0) {
String date = DateTools.convertDate(ms, DateTools.COBOL);
if (DateTools.getTime(date, DateTools.ISO8601_FORMAT) <
System.currentTimeMillis())
{
store.setImageCreationDate(date, numDatasets);
}
firstStamp = ms;
store.setPlaneTimingDeltaT(new Double(0), numDatasets, 0, count);
}
else {
CoreMetadata coreMeta = core.get(numDatasets);
int nImages = coreMeta.sizeZ * coreMeta.sizeT * coreMeta.sizeC;
if (count < nImages) {
ms -= firstStamp;
store.setPlaneTimingDeltaT(
new Double(ms / 1000.0), numDatasets, 0, count);
}
}
count++;
}
else if (qName.equals("RelTimeStamp")) {
CoreMetadata coreMeta = core.get(numDatasets);
int nImages = coreMeta.sizeZ * coreMeta.sizeT * coreMeta.sizeC;
if (count < nImages) {
Double time = new Double(attributes.getValue("Time"));
store.setPlaneTimingDeltaT(time, numDatasets, 0, count++);
}
}
else if (qName.equals("Annotation")) {
roi = new ROI();
String type = attributes.getValue("type");
if (type != null) roi.type = Integer.parseInt(type);
String color = attributes.getValue("color");
if (color != null) roi.color = Integer.parseInt(color);
roi.name = attributes.getValue("name");
roi.fontName = attributes.getValue("fontName");
roi.fontSize = attributes.getValue("fontSize");
roi.transX = parseDouble(attributes.getValue("transTransX"));
roi.transY = parseDouble(attributes.getValue("transTransY"));
roi.scaleX = parseDouble(attributes.getValue("transScalingX"));
roi.scaleY = parseDouble(attributes.getValue("transScalingY"));
roi.rotation = parseDouble(attributes.getValue("transRotation"));
String linewidth = attributes.getValue("linewidth");
if (linewidth != null) roi.linewidth = Integer.parseInt(linewidth);
roi.text = attributes.getValue("text");
}
else if (qName.equals("Vertex")) {
String x = attributes.getValue("x").replaceAll(",", ".");
String y = attributes.getValue("y").replaceAll(",", ".");
roi.x.add(new Double(x));
roi.y.add(new Double(y));
}
else if (qName.equals("ROI")) {
alternateCenter = true;
}
else if (qName.equals("MultiBand")) {
MultiBand m = new MultiBand();
m.dyeName = attributes.getValue("DyeName");
m.channel = Integer.parseInt(attributes.getValue("Channel"));
m.cutIn = (int)
Math.round(Double.parseDouble(attributes.getValue("LeftWorld")));
m.cutOut = (int)
Math.round(Double.parseDouble(attributes.getValue("RightWorld")));
multiBands.add(m);
}
else count = 0;
storeSeriesHashtable(numDatasets, h);
}
|
diff --git a/src/org/apache/fop/fo/StandardElementMapping.java b/src/org/apache/fop/fo/StandardElementMapping.java
index 9104b0fa0..ac4837c52 100644
--- a/src/org/apache/fop/fo/StandardElementMapping.java
+++ b/src/org/apache/fop/fo/StandardElementMapping.java
@@ -1,110 +1,109 @@
/*-- $Id$ --
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
Redistribution and use in source and binary forms, with or without modifica-
tion, 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. The end-user documentation included with the redistribution, if any, must
include the following acknowledgment: "This product includes software
developed by the Apache Software Foundation (http://www.apache.org/)."
Alternately, this acknowledgment may appear in the software itself, if
and wherever such third-party acknowledgments normally appear.
4. The names "FOP" and "Apache Software Foundation" must not be used to
endorse or promote products derived from this software without prior
written permission. For written permission, please contact
[email protected].
5. Products derived from this software may not be called "Apache", nor may
"Apache" appear in their name, without prior written permission of the
Apache Software Foundation.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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
APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
DING, 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.
This software consists of voluntary contributions made by many individuals
on behalf of the Apache Software Foundation and was originally created by
James Tauber <[email protected]>. For more information on the Apache
Software Foundation, please see <http://www.apache.org/>.
*/
package org.apache.fop.fo;
import org.apache.fop.fo.flow.*;
import org.apache.fop.fo.pagination.*;
public class StandardElementMapping implements ElementMapping {
public void addToBuilder(FOTreeBuilder builder) {
String uri = "http://www.w3.org/1999/XSL/Format";
builder.addMapping(uri, "root", Root.maker());
builder.addMapping(uri, "layout-master-set",
LayoutMasterSet.maker());
builder.addMapping(uri, "simple-page-master",
SimplePageMaster.maker());
builder.addMapping(uri, "region-body", RegionBody.maker());
builder.addMapping(uri, "region-before", RegionBefore.maker());
builder.addMapping(uri, "region-after", RegionAfter.maker());
builder.addMapping(uri, "page-sequence", PageSequence.maker());
builder.addMapping(uri, "page-sequence-master",
PageSequenceMaster.maker());
builder.addMapping(uri, "single-page-master-reference",
SinglePageMasterReference.maker());
builder.addMapping(uri, "repeatable-page-master-reference",
RepeatablePageMasterReference.maker());
builder.addMapping(uri, "conditional-page-master-reference",
ConditionalPageMasterReference.maker());
builder.addMapping(uri, "repeatable-page-master-alternatives",
RepeatablePageMasterAlternatives.maker());
builder.addMapping(uri, "flow", Flow.maker());
builder.addMapping(uri, "static-content",
StaticContent.maker());
builder.addMapping(uri, "block", Block.maker());
builder.addMapping(uri, "block-container", BlockContainer.maker());
builder.addMapping(uri, "list-block", ListBlock.maker());
builder.addMapping(uri, "list-item", ListItem.maker());
builder.addMapping(uri, "list-item-label",
ListItemLabel.maker());
builder.addMapping(uri, "list-item-body", ListItemBody.maker());
builder.addMapping(uri, "page-number", PageNumber.maker());
builder.addMapping(uri, "page-number-citation", PageNumberCitation.maker());
builder.addMapping(uri, "display-sequence",
DisplaySequence.maker());
builder.addMapping(uri, "inline-sequence",
InlineSequence.maker());
- builder.addMapping(uri, "display-rule", DisplayRule.maker());
builder.addMapping(uri, "external-graphic",
ExternalGraphic.maker());
builder.addMapping(uri, "table", Table.maker());
builder.addMapping(uri, "table-column", TableColumn.maker());
builder.addMapping(uri, "table-body", TableBody.maker());
builder.addMapping(uri, "table-row", TableRow.maker());
builder.addMapping(uri, "table-cell", TableCell.maker());
builder.addMapping(uri, "simple-link", SimpleLink.maker());
builder.addMapping(uri, "instream-foreign-object", InstreamForeignObject.maker());
builder.addMapping(uri, "leader", Leader.maker());
}
}
| true | true | public void addToBuilder(FOTreeBuilder builder) {
String uri = "http://www.w3.org/1999/XSL/Format";
builder.addMapping(uri, "root", Root.maker());
builder.addMapping(uri, "layout-master-set",
LayoutMasterSet.maker());
builder.addMapping(uri, "simple-page-master",
SimplePageMaster.maker());
builder.addMapping(uri, "region-body", RegionBody.maker());
builder.addMapping(uri, "region-before", RegionBefore.maker());
builder.addMapping(uri, "region-after", RegionAfter.maker());
builder.addMapping(uri, "page-sequence", PageSequence.maker());
builder.addMapping(uri, "page-sequence-master",
PageSequenceMaster.maker());
builder.addMapping(uri, "single-page-master-reference",
SinglePageMasterReference.maker());
builder.addMapping(uri, "repeatable-page-master-reference",
RepeatablePageMasterReference.maker());
builder.addMapping(uri, "conditional-page-master-reference",
ConditionalPageMasterReference.maker());
builder.addMapping(uri, "repeatable-page-master-alternatives",
RepeatablePageMasterAlternatives.maker());
builder.addMapping(uri, "flow", Flow.maker());
builder.addMapping(uri, "static-content",
StaticContent.maker());
builder.addMapping(uri, "block", Block.maker());
builder.addMapping(uri, "block-container", BlockContainer.maker());
builder.addMapping(uri, "list-block", ListBlock.maker());
builder.addMapping(uri, "list-item", ListItem.maker());
builder.addMapping(uri, "list-item-label",
ListItemLabel.maker());
builder.addMapping(uri, "list-item-body", ListItemBody.maker());
builder.addMapping(uri, "page-number", PageNumber.maker());
builder.addMapping(uri, "page-number-citation", PageNumberCitation.maker());
builder.addMapping(uri, "display-sequence",
DisplaySequence.maker());
builder.addMapping(uri, "inline-sequence",
InlineSequence.maker());
builder.addMapping(uri, "display-rule", DisplayRule.maker());
builder.addMapping(uri, "external-graphic",
ExternalGraphic.maker());
builder.addMapping(uri, "table", Table.maker());
builder.addMapping(uri, "table-column", TableColumn.maker());
builder.addMapping(uri, "table-body", TableBody.maker());
builder.addMapping(uri, "table-row", TableRow.maker());
builder.addMapping(uri, "table-cell", TableCell.maker());
builder.addMapping(uri, "simple-link", SimpleLink.maker());
builder.addMapping(uri, "instream-foreign-object", InstreamForeignObject.maker());
builder.addMapping(uri, "leader", Leader.maker());
}
| public void addToBuilder(FOTreeBuilder builder) {
String uri = "http://www.w3.org/1999/XSL/Format";
builder.addMapping(uri, "root", Root.maker());
builder.addMapping(uri, "layout-master-set",
LayoutMasterSet.maker());
builder.addMapping(uri, "simple-page-master",
SimplePageMaster.maker());
builder.addMapping(uri, "region-body", RegionBody.maker());
builder.addMapping(uri, "region-before", RegionBefore.maker());
builder.addMapping(uri, "region-after", RegionAfter.maker());
builder.addMapping(uri, "page-sequence", PageSequence.maker());
builder.addMapping(uri, "page-sequence-master",
PageSequenceMaster.maker());
builder.addMapping(uri, "single-page-master-reference",
SinglePageMasterReference.maker());
builder.addMapping(uri, "repeatable-page-master-reference",
RepeatablePageMasterReference.maker());
builder.addMapping(uri, "conditional-page-master-reference",
ConditionalPageMasterReference.maker());
builder.addMapping(uri, "repeatable-page-master-alternatives",
RepeatablePageMasterAlternatives.maker());
builder.addMapping(uri, "flow", Flow.maker());
builder.addMapping(uri, "static-content",
StaticContent.maker());
builder.addMapping(uri, "block", Block.maker());
builder.addMapping(uri, "block-container", BlockContainer.maker());
builder.addMapping(uri, "list-block", ListBlock.maker());
builder.addMapping(uri, "list-item", ListItem.maker());
builder.addMapping(uri, "list-item-label",
ListItemLabel.maker());
builder.addMapping(uri, "list-item-body", ListItemBody.maker());
builder.addMapping(uri, "page-number", PageNumber.maker());
builder.addMapping(uri, "page-number-citation", PageNumberCitation.maker());
builder.addMapping(uri, "display-sequence",
DisplaySequence.maker());
builder.addMapping(uri, "inline-sequence",
InlineSequence.maker());
builder.addMapping(uri, "external-graphic",
ExternalGraphic.maker());
builder.addMapping(uri, "table", Table.maker());
builder.addMapping(uri, "table-column", TableColumn.maker());
builder.addMapping(uri, "table-body", TableBody.maker());
builder.addMapping(uri, "table-row", TableRow.maker());
builder.addMapping(uri, "table-cell", TableCell.maker());
builder.addMapping(uri, "simple-link", SimpleLink.maker());
builder.addMapping(uri, "instream-foreign-object", InstreamForeignObject.maker());
builder.addMapping(uri, "leader", Leader.maker());
}
|
diff --git a/test/org/encog/neural/activation/TestActivationSoftMax.java b/test/org/encog/neural/activation/TestActivationSoftMax.java
index ffa12e9e4..bdee091aa 100644
--- a/test/org/encog/neural/activation/TestActivationSoftMax.java
+++ b/test/org/encog/neural/activation/TestActivationSoftMax.java
@@ -1,53 +1,45 @@
package org.encog.neural.activation;
import junit.framework.TestCase;
import org.encog.EncogError;
import org.encog.persist.persistors.ActivationBiPolarPersistor;
import org.encog.persist.persistors.ActivationSoftMaxPersistor;
import org.junit.Assert;
import org.junit.Test;
public class TestActivationSoftMax extends TestCase {
@Test
public void testSoftMax() throws Throwable
{
ActivationSoftMax activation = new ActivationSoftMax();
Assert.assertFalse(activation.hasDerivative());
ActivationSoftMax clone = (ActivationSoftMax)activation.clone();
Assert.assertNotNull(clone);
double[] input = {1.0,1.0,1.0,1.0 };
activation.activationFunction(input);
Assert.assertEquals(0.25,input[0],0.1);
Assert.assertEquals(0.25,input[1],0.1);
// this will throw an error if it does not work
ActivationSoftMaxPersistor p = (ActivationSoftMaxPersistor)activation.createPersistor();
- // test derivative, should throw an error
- try
- {
- activation.derivativeFunction(input);
- Assert.assertTrue(false);// mark an error
- }
- catch(EncogError e)
- {
- // good, this should happen
- }
+ // test derivative
+ activation.derivativeFunction(input);
// test name and description
// names and descriptions are not stored for these
activation.setName("name");
activation.setDescription("name");
Assert.assertEquals(null, activation.getName());
Assert.assertEquals(null, activation.getDescription() );
}
}
| true | true | public void testSoftMax() throws Throwable
{
ActivationSoftMax activation = new ActivationSoftMax();
Assert.assertFalse(activation.hasDerivative());
ActivationSoftMax clone = (ActivationSoftMax)activation.clone();
Assert.assertNotNull(clone);
double[] input = {1.0,1.0,1.0,1.0 };
activation.activationFunction(input);
Assert.assertEquals(0.25,input[0],0.1);
Assert.assertEquals(0.25,input[1],0.1);
// this will throw an error if it does not work
ActivationSoftMaxPersistor p = (ActivationSoftMaxPersistor)activation.createPersistor();
// test derivative, should throw an error
try
{
activation.derivativeFunction(input);
Assert.assertTrue(false);// mark an error
}
catch(EncogError e)
{
// good, this should happen
}
// test name and description
// names and descriptions are not stored for these
activation.setName("name");
activation.setDescription("name");
Assert.assertEquals(null, activation.getName());
Assert.assertEquals(null, activation.getDescription() );
}
| public void testSoftMax() throws Throwable
{
ActivationSoftMax activation = new ActivationSoftMax();
Assert.assertFalse(activation.hasDerivative());
ActivationSoftMax clone = (ActivationSoftMax)activation.clone();
Assert.assertNotNull(clone);
double[] input = {1.0,1.0,1.0,1.0 };
activation.activationFunction(input);
Assert.assertEquals(0.25,input[0],0.1);
Assert.assertEquals(0.25,input[1],0.1);
// this will throw an error if it does not work
ActivationSoftMaxPersistor p = (ActivationSoftMaxPersistor)activation.createPersistor();
// test derivative
activation.derivativeFunction(input);
// test name and description
// names and descriptions are not stored for these
activation.setName("name");
activation.setDescription("name");
Assert.assertEquals(null, activation.getName());
Assert.assertEquals(null, activation.getDescription() );
}
|
diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/simple/TestSerializedFactory.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/simple/TestSerializedFactory.java
index 9b3cb26a0..c08517982 100644
--- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/simple/TestSerializedFactory.java
+++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/simple/TestSerializedFactory.java
@@ -1,97 +1,100 @@
/*
* 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.openjpa.persistence.simple;
import java.io.*;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import junit.textui.TestRunner;
import org.apache.openjpa.persistence.OpenJPAEntityManager;
import org.apache.openjpa.persistence.test.SingleEMFTestCase;
/**
* Tests that a EntityManagerFactory can be used after serialization.
*
* @author David Ezzio
*/
public class TestSerializedFactory
extends SingleEMFTestCase {
public void setUp() {
setUp(AllFieldTypes.class);
}
/**
* This test case assumes that OpenJPA creates EMF objects that are
* instances of the Serializable interface. If this changes, the test
* logic has to change.
* <p>
* Currently, although the EMF objects implement Serializable, they
* do not successfully pass through serialization. Once they do
* (assuming they should), the catch block in the test and the
* fail method invocation can be removed.
*/
public void testSerializedEntityManagerFactory() throws Exception {
// correct the logic if and when EMFs do not implement
// the serializable interface
assertTrue("EntityManagerFactory object is not serializable",
emf instanceof Serializable);
// serialize and deserialize the entity manager factory
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(emf);
EntityManagerFactory emf2 =
(EntityManagerFactory) new ObjectInputStream(
new ByteArrayInputStream(baos.toByteArray())).readObject();
try {
// use the deserialized entity manager factory
assertTrue("The deserialized entity manager factory is not open",
- emf2.isOpen());
+ emf2.isOpen());
EntityManager em = emf2.createEntityManager();
- assertTrue("The newly created entity manager is not open", em.isOpen());
+ assertTrue("The newly created entity manager is not open",
+ em.isOpen());
// exercise the entity manager produced from the deserialized EMF
em.getTransaction().begin();
em.persist(new AllFieldTypes());
em.getTransaction().commit();
// close the extra resources
em.close();
assertFalse("The entity manager is not closed", em.isOpen());
emf2.close();
- assertFalse("The entity manager factory is not closed", emf2.isOpen());
+ assertFalse("The entity manager factory is not closed",
+ emf2.isOpen());
// Correct the logic when EMF's are supposed to serialize
- fail("This test is expected to fail until the issue of serializing an EMF is settled");
+ fail("This test is expected to fail until the issue of " +
+ "serializing an EMF is settled");
}
catch (Exception e) {
// failure is currently expected
}
}
public static void main(String[] args) {
TestRunner.run(TestSerializedFactory.class);
}
}
| false | true | public void testSerializedEntityManagerFactory() throws Exception {
// correct the logic if and when EMFs do not implement
// the serializable interface
assertTrue("EntityManagerFactory object is not serializable",
emf instanceof Serializable);
// serialize and deserialize the entity manager factory
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(emf);
EntityManagerFactory emf2 =
(EntityManagerFactory) new ObjectInputStream(
new ByteArrayInputStream(baos.toByteArray())).readObject();
try {
// use the deserialized entity manager factory
assertTrue("The deserialized entity manager factory is not open",
emf2.isOpen());
EntityManager em = emf2.createEntityManager();
assertTrue("The newly created entity manager is not open", em.isOpen());
// exercise the entity manager produced from the deserialized EMF
em.getTransaction().begin();
em.persist(new AllFieldTypes());
em.getTransaction().commit();
// close the extra resources
em.close();
assertFalse("The entity manager is not closed", em.isOpen());
emf2.close();
assertFalse("The entity manager factory is not closed", emf2.isOpen());
// Correct the logic when EMF's are supposed to serialize
fail("This test is expected to fail until the issue of serializing an EMF is settled");
}
catch (Exception e) {
// failure is currently expected
}
}
| public void testSerializedEntityManagerFactory() throws Exception {
// correct the logic if and when EMFs do not implement
// the serializable interface
assertTrue("EntityManagerFactory object is not serializable",
emf instanceof Serializable);
// serialize and deserialize the entity manager factory
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(emf);
EntityManagerFactory emf2 =
(EntityManagerFactory) new ObjectInputStream(
new ByteArrayInputStream(baos.toByteArray())).readObject();
try {
// use the deserialized entity manager factory
assertTrue("The deserialized entity manager factory is not open",
emf2.isOpen());
EntityManager em = emf2.createEntityManager();
assertTrue("The newly created entity manager is not open",
em.isOpen());
// exercise the entity manager produced from the deserialized EMF
em.getTransaction().begin();
em.persist(new AllFieldTypes());
em.getTransaction().commit();
// close the extra resources
em.close();
assertFalse("The entity manager is not closed", em.isOpen());
emf2.close();
assertFalse("The entity manager factory is not closed",
emf2.isOpen());
// Correct the logic when EMF's are supposed to serialize
fail("This test is expected to fail until the issue of " +
"serializing an EMF is settled");
}
catch (Exception e) {
// failure is currently expected
}
}
|
diff --git a/web-frontend/src/main/java/org/bazhenov/logging/web/tags/EntryTag.java b/web-frontend/src/main/java/org/bazhenov/logging/web/tags/EntryTag.java
index e7b684a..7b532de 100644
--- a/web-frontend/src/main/java/org/bazhenov/logging/web/tags/EntryTag.java
+++ b/web-frontend/src/main/java/org/bazhenov/logging/web/tags/EntryTag.java
@@ -1,174 +1,174 @@
package org.bazhenov.logging.web.tags;
import static org.apache.commons.lang.StringEscapeUtils.escapeHtml;
import static org.apache.commons.lang.StringUtils.join;
import org.bazhenov.logging.AggregatedLogEntry;
import org.bazhenov.logging.LogEntry;
import org.bazhenov.logging.Cause;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
import java.io.IOException;
import static java.lang.Math.abs;
import java.text.DateFormat;
import java.text.FieldPosition;
import static java.text.MessageFormat.format;
import java.text.SimpleDateFormat;
import java.util.Set;
import java.util.TreeSet;
public class EntryTag extends TagSupport {
private final int MAX_LENGTH = 80;
private AggregatedLogEntry entry;
DateFormat shortFormat = new DateTimeFormat();
DateFormat fullFormat = new SimpleDateFormat("d MMMM yyyy, HH:mm:ss zz");
private static final String JIRA_LINK_FORMAT = "http://jira.dev.loc/jira/secure/CreateIssueDetails.jspa?pid=10000&issuetype=1&summary={0}&description={1}&priority=3";
public void setEntry(AggregatedLogEntry entry) {
this.entry = entry;
}
@Override
public int doEndTag() throws JspException {
JspWriter out = pageContext.getOut();
LogEntry sampleEntry = entry.getSampleEntry();
String title = sampleEntry.getMessage();
String applicationId = sampleEntry.getApplicationId();
int count = entry.getCount();
boolean withStacktrace = sampleEntry.getCause() != null;
boolean isTitleTooLong = title.length() > MAX_LENGTH;
boolean hasMessage = withStacktrace || isTitleTooLong;
String message = (!withStacktrace && isTitleTooLong)
? sampleEntry.getMessage()
: formatCause(sampleEntry.getCause());
Set<String> classes = new TreeSet<String>();
classes.add("entry");
String severety = sampleEntry.getSeverity().toString();
classes.add(severety);
if ( hasMessage ) {
classes.add("withStacktrace");
}
boolean isExceptionNew = entry.getLastTime().plusMinute(30).isInFuture();
Set<String> additionalInfoClasses = new TreeSet<String>();
additionalInfoClasses.add("additionalInfo");
if ( isExceptionNew ) {
additionalInfoClasses.add("warningMarker");
}
Set<String> markerClasses = new TreeSet<String>();
markerClasses.add("marker");
if ( !hasMessage ) {
markerClasses.add("emptyMarker");
}
FieldPosition fieldPosition = new FieldPosition(DateFormat.HOUR0_FIELD);
StringBuffer buffer = new StringBuffer();
shortFormat.format(entry.getLastTime().asDate(), buffer, fieldPosition);
String fullDate = fullFormat.format(entry.getLastTime().asDate());
/**
* Не забываем, что теги надо вставлять в обратной последовательности, чтобы не допустить
* смещения индексов в FieldPosition
*/
buffer.insert(fieldPosition.getEndIndex(), "</span>");
String startTag = "<span class='" + join(additionalInfoClasses,
" ") + "' title='" + fullDate + "'>";
buffer.insert(fieldPosition.getBeginIndex(), startTag);
String lastOccurenceInfo = buffer.toString();
String timesInfo = pluralize(count, "- times times");
if ( count > 10000 ) {
timesInfo = "<span class='additionalInfo' title='" + timesInfo + "'>more than 10 000 times</span>";
} else if ( count > 5000 ) {
timesInfo = "<span class='additionalInfo' title='" + timesInfo + "'>more than 5 000 times</span>";
} else if ( count > 1000 ) {
timesInfo = "<span class='additionalInfo' title='" + timesInfo + "'>more than 1 000 times</span>";
}
title = escapeHtml(title);
message = escapeHtml(message);
String jiraLink = format(JIRA_LINK_FORMAT, title, message);
try {
out.write("<a name='" + sampleEntry.getChecksum() + "'></a>");
out.write(
"<div class='" + join(classes, " ") + "' checksum='" + sampleEntry.getChecksum() + "'>");
out.write("<div class='entryHeader'>");
out.write("<span class='" + join(markerClasses, " ") + "'>" + (hasMessage
? "•"
: "") + "</span>");
out.write("<div class='message'>" + title + "</div>");
out.write("<div class='messageOverlay'></div>");
out.write("<div class='times'>");
- out.write("<span class='applicationId'>" + applicationId + "</span> &mdash ");
+ out.write("<span class='applicationId'>" + applicationId + "</span> — ");
out.write((count > 1
? timesInfo + ", last time "
: ""));
out.write(lastOccurenceInfo);
out.write("</div>");
if ( hasMessage ) {
out.write("<div class='entryContent'>");
out.write("<pre class='stacktrace'>" + message + "</pre>");
out.write("</div>");
}
out.write("<div class='operations'>");
out.write("<a href='" + jiraLink + "' target='_blank'>create task</a>");
out.write(" or ");
out.write("<a class='removeEntry asynchronous' href='#'>remove</a> ");
out.write("<a href='./" + entry.getLastTime()
.getDate() + "?severity=" + sampleEntry.getSeverity() + "#" + sampleEntry.getChecksum() + "'>");
out.write(" <img src='./images/link-icon.png' /></a>");
out.write("</div>");
out.write("</div>");
out.write("</div>");
} catch ( IOException e ) {
throw new RuntimeException(e);
}
return EVAL_PAGE;
}
private static String formatCause(Cause rootCause) {
StringBuilder prefix = new StringBuilder();
StringBuilder stackTrace = new StringBuilder();
if ( rootCause != null ) {
Cause cause = rootCause;
while ( cause != null ) {
if ( cause != rootCause ) {
stackTrace.append("\n\n").append(prefix).append("Caused by ");
}
String iStack = cause.getStackTrace().replaceAll("\n", "\n" + prefix);
stackTrace.append(cause.getType())
.append(": ")
.append(cause.getMessage())
.append("\n")
.append(prefix)
.append(iStack);
cause = cause.getCause();
prefix.append(" ");
}
}
return stackTrace.toString();
}
public static String pluralize(int number, String titles) {
int abs = abs(number);
int[] cases = new int[]{2, 0, 1, 1, 1, 2};
String[] strings = titles.split(" ");
String result = strings[(abs % 100 > 4 && abs % 100 < 20)
? 2
: cases[Math.min(abs % 10, 5)]];
return number + " " + result;
}
}
| true | true | public int doEndTag() throws JspException {
JspWriter out = pageContext.getOut();
LogEntry sampleEntry = entry.getSampleEntry();
String title = sampleEntry.getMessage();
String applicationId = sampleEntry.getApplicationId();
int count = entry.getCount();
boolean withStacktrace = sampleEntry.getCause() != null;
boolean isTitleTooLong = title.length() > MAX_LENGTH;
boolean hasMessage = withStacktrace || isTitleTooLong;
String message = (!withStacktrace && isTitleTooLong)
? sampleEntry.getMessage()
: formatCause(sampleEntry.getCause());
Set<String> classes = new TreeSet<String>();
classes.add("entry");
String severety = sampleEntry.getSeverity().toString();
classes.add(severety);
if ( hasMessage ) {
classes.add("withStacktrace");
}
boolean isExceptionNew = entry.getLastTime().plusMinute(30).isInFuture();
Set<String> additionalInfoClasses = new TreeSet<String>();
additionalInfoClasses.add("additionalInfo");
if ( isExceptionNew ) {
additionalInfoClasses.add("warningMarker");
}
Set<String> markerClasses = new TreeSet<String>();
markerClasses.add("marker");
if ( !hasMessage ) {
markerClasses.add("emptyMarker");
}
FieldPosition fieldPosition = new FieldPosition(DateFormat.HOUR0_FIELD);
StringBuffer buffer = new StringBuffer();
shortFormat.format(entry.getLastTime().asDate(), buffer, fieldPosition);
String fullDate = fullFormat.format(entry.getLastTime().asDate());
/**
* Не забываем, что теги надо вставлять в обратной последовательности, чтобы не допустить
* смещения индексов в FieldPosition
*/
buffer.insert(fieldPosition.getEndIndex(), "</span>");
String startTag = "<span class='" + join(additionalInfoClasses,
" ") + "' title='" + fullDate + "'>";
buffer.insert(fieldPosition.getBeginIndex(), startTag);
String lastOccurenceInfo = buffer.toString();
String timesInfo = pluralize(count, "- times times");
if ( count > 10000 ) {
timesInfo = "<span class='additionalInfo' title='" + timesInfo + "'>more than 10 000 times</span>";
} else if ( count > 5000 ) {
timesInfo = "<span class='additionalInfo' title='" + timesInfo + "'>more than 5 000 times</span>";
} else if ( count > 1000 ) {
timesInfo = "<span class='additionalInfo' title='" + timesInfo + "'>more than 1 000 times</span>";
}
title = escapeHtml(title);
message = escapeHtml(message);
String jiraLink = format(JIRA_LINK_FORMAT, title, message);
try {
out.write("<a name='" + sampleEntry.getChecksum() + "'></a>");
out.write(
"<div class='" + join(classes, " ") + "' checksum='" + sampleEntry.getChecksum() + "'>");
out.write("<div class='entryHeader'>");
out.write("<span class='" + join(markerClasses, " ") + "'>" + (hasMessage
? "•"
: "") + "</span>");
out.write("<div class='message'>" + title + "</div>");
out.write("<div class='messageOverlay'></div>");
out.write("<div class='times'>");
out.write("<span class='applicationId'>" + applicationId + "</span> &mdash ");
out.write((count > 1
? timesInfo + ", last time "
: ""));
out.write(lastOccurenceInfo);
out.write("</div>");
if ( hasMessage ) {
out.write("<div class='entryContent'>");
out.write("<pre class='stacktrace'>" + message + "</pre>");
out.write("</div>");
}
out.write("<div class='operations'>");
out.write("<a href='" + jiraLink + "' target='_blank'>create task</a>");
out.write(" or ");
out.write("<a class='removeEntry asynchronous' href='#'>remove</a> ");
out.write("<a href='./" + entry.getLastTime()
.getDate() + "?severity=" + sampleEntry.getSeverity() + "#" + sampleEntry.getChecksum() + "'>");
out.write(" <img src='./images/link-icon.png' /></a>");
out.write("</div>");
out.write("</div>");
out.write("</div>");
} catch ( IOException e ) {
throw new RuntimeException(e);
}
return EVAL_PAGE;
}
| public int doEndTag() throws JspException {
JspWriter out = pageContext.getOut();
LogEntry sampleEntry = entry.getSampleEntry();
String title = sampleEntry.getMessage();
String applicationId = sampleEntry.getApplicationId();
int count = entry.getCount();
boolean withStacktrace = sampleEntry.getCause() != null;
boolean isTitleTooLong = title.length() > MAX_LENGTH;
boolean hasMessage = withStacktrace || isTitleTooLong;
String message = (!withStacktrace && isTitleTooLong)
? sampleEntry.getMessage()
: formatCause(sampleEntry.getCause());
Set<String> classes = new TreeSet<String>();
classes.add("entry");
String severety = sampleEntry.getSeverity().toString();
classes.add(severety);
if ( hasMessage ) {
classes.add("withStacktrace");
}
boolean isExceptionNew = entry.getLastTime().plusMinute(30).isInFuture();
Set<String> additionalInfoClasses = new TreeSet<String>();
additionalInfoClasses.add("additionalInfo");
if ( isExceptionNew ) {
additionalInfoClasses.add("warningMarker");
}
Set<String> markerClasses = new TreeSet<String>();
markerClasses.add("marker");
if ( !hasMessage ) {
markerClasses.add("emptyMarker");
}
FieldPosition fieldPosition = new FieldPosition(DateFormat.HOUR0_FIELD);
StringBuffer buffer = new StringBuffer();
shortFormat.format(entry.getLastTime().asDate(), buffer, fieldPosition);
String fullDate = fullFormat.format(entry.getLastTime().asDate());
/**
* Не забываем, что теги надо вставлять в обратной последовательности, чтобы не допустить
* смещения индексов в FieldPosition
*/
buffer.insert(fieldPosition.getEndIndex(), "</span>");
String startTag = "<span class='" + join(additionalInfoClasses,
" ") + "' title='" + fullDate + "'>";
buffer.insert(fieldPosition.getBeginIndex(), startTag);
String lastOccurenceInfo = buffer.toString();
String timesInfo = pluralize(count, "- times times");
if ( count > 10000 ) {
timesInfo = "<span class='additionalInfo' title='" + timesInfo + "'>more than 10 000 times</span>";
} else if ( count > 5000 ) {
timesInfo = "<span class='additionalInfo' title='" + timesInfo + "'>more than 5 000 times</span>";
} else if ( count > 1000 ) {
timesInfo = "<span class='additionalInfo' title='" + timesInfo + "'>more than 1 000 times</span>";
}
title = escapeHtml(title);
message = escapeHtml(message);
String jiraLink = format(JIRA_LINK_FORMAT, title, message);
try {
out.write("<a name='" + sampleEntry.getChecksum() + "'></a>");
out.write(
"<div class='" + join(classes, " ") + "' checksum='" + sampleEntry.getChecksum() + "'>");
out.write("<div class='entryHeader'>");
out.write("<span class='" + join(markerClasses, " ") + "'>" + (hasMessage
? "•"
: "") + "</span>");
out.write("<div class='message'>" + title + "</div>");
out.write("<div class='messageOverlay'></div>");
out.write("<div class='times'>");
out.write("<span class='applicationId'>" + applicationId + "</span> — ");
out.write((count > 1
? timesInfo + ", last time "
: ""));
out.write(lastOccurenceInfo);
out.write("</div>");
if ( hasMessage ) {
out.write("<div class='entryContent'>");
out.write("<pre class='stacktrace'>" + message + "</pre>");
out.write("</div>");
}
out.write("<div class='operations'>");
out.write("<a href='" + jiraLink + "' target='_blank'>create task</a>");
out.write(" or ");
out.write("<a class='removeEntry asynchronous' href='#'>remove</a> ");
out.write("<a href='./" + entry.getLastTime()
.getDate() + "?severity=" + sampleEntry.getSeverity() + "#" + sampleEntry.getChecksum() + "'>");
out.write(" <img src='./images/link-icon.png' /></a>");
out.write("</div>");
out.write("</div>");
out.write("</div>");
} catch ( IOException e ) {
throw new RuntimeException(e);
}
return EVAL_PAGE;
}
|
diff --git a/org.openscada.core.net/src/org/openscada/core/net/ConnectionHelper.java b/org.openscada.core.net/src/org/openscada/core/net/ConnectionHelper.java
index 3245d301e..55eb3d29b 100644
--- a/org.openscada.core.net/src/org/openscada/core/net/ConnectionHelper.java
+++ b/org.openscada.core.net/src/org/openscada/core/net/ConnectionHelper.java
@@ -1,242 +1,242 @@
/*
* This file is part of the OpenSCADA project
* Copyright (C) 2006-2012 TH4 SYSTEMS GmbH (http://th4-systems.com)
*
* OpenSCADA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenSCADA 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenSCADA. If not, see
* <http://opensource.org/licenses/lgpl-3.0.html> for a copy of the LGPLv3 License.
*/
package org.openscada.core.net;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.compression.CompressionFilter;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.filter.ssl.SslFilter;
import org.openscada.core.ConnectionInformation;
import org.openscada.net.mina.GMPPProtocolDecoder;
import org.openscada.net.mina.GMPPProtocolEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ConnectionHelper
{
private final static Logger logger = LoggerFactory.getLogger ( ConnectionHelper.class );
private static final class X509TrustManagerImplementation implements X509TrustManager
{
@Override
public void checkClientTrusted ( final X509Certificate[] arg0, final String arg1 ) throws CertificateException
{
logger.info ( "checkClientTrusted: " + arg0 + "/" + arg1 );
}
@Override
public void checkServerTrusted ( final X509Certificate[] arg0, final String arg1 ) throws CertificateException
{
logger.info ( "checkServerTrusted: " + arg0 + "/" + arg1 );
}
@Override
public X509Certificate[] getAcceptedIssuers ()
{
logger.info ( "getAcceptedIssuers" );
return new X509Certificate[0];
}
}
/**
* Setup the filter chain of a NET/GMPP connection
*
* @param connectionInformation
* the connection information to use
* @param filterChainBuilder
* the chain builder
*/
public static void setupFilterChain ( final ConnectionInformation connectionInformation, final DefaultIoFilterChainBuilder filterChainBuilder, final boolean isClient )
{
// set up compression
final String compress = connectionInformation.getProperties ().get ( "compress" );
if ( compress != null )
{
int level = CompressionFilter.COMPRESSION_DEFAULT;
try
{
level = Integer.parseInt ( compress );
}
catch ( final Exception e )
{
logger.warn ( "Failed to parse 'compress' property", e );
}
- if ( level < CompressionFilter.COMPRESSION_NONE || level > CompressionFilter.COMPRESSION_MAX )
+ if ( level < CompressionFilter.COMPRESSION_DEFAULT || level > CompressionFilter.COMPRESSION_MAX )
{
logger.warn ( "Compression ({}) outside of valid range. Setting to default", level );
level = CompressionFilter.COMPRESSION_DEFAULT;
}
filterChainBuilder.addLast ( "compress", new CompressionFilter ( level ) );
}
// set up ssl
final String ssl = connectionInformation.getProperties ().get ( "ssl" );
if ( ssl != null )
{
initSsl ( connectionInformation, filterChainBuilder, isClient );
}
// set up logging
final String trace = connectionInformation.getProperties ().get ( "trace" );
if ( trace != null )
{
filterChainBuilder.addLast ( "logging", new LoggingFilter () );
}
// add the main codec
filterChainBuilder.addLast ( "codec", new ProtocolCodecFilter ( new GMPPProtocolEncoder (), new GMPPProtocolDecoder () ) );
}
/**
* FIXME: still need to implement correctly
*
* @param connectionInformation
* @param filterChainBuilder
* @param isClient
*/
protected static void initSsl ( final ConnectionInformation connectionInformation, final DefaultIoFilterChainBuilder filterChainBuilder, final boolean isClient )
{
SSLContext sslContext = null;
try
{
sslContext = createContext ( connectionInformation );
sslContext.init ( getKeyManagers ( connectionInformation, isClient ), getTrustManagers ( connectionInformation ), getRandom ( connectionInformation ) );
}
catch ( final Throwable e )
{
logger.warn ( "Failed to enable SSL", e );
}
if ( sslContext != null )
{
final SslFilter filter = new SslFilter ( sslContext );
filter.setUseClientMode ( isClient );
filterChainBuilder.addFirst ( "sslFilter", filter );
}
}
private static SSLContext createContext ( final ConnectionInformation connectionInformation ) throws NoSuchAlgorithmException
{
String sslProtocol = connectionInformation.getProperties ().get ( "sslProtocol" );
if ( sslProtocol == null || sslProtocol.length () == 0 )
{
sslProtocol = "SSLv3";
}
return SSLContext.getInstance ( sslProtocol );
}
private static SecureRandom getRandom ( final ConnectionInformation connectionInformation ) throws NoSuchAlgorithmException
{
final String sslRandom = connectionInformation.getProperties ().get ( "sslRandom" );
SecureRandom random = null;
if ( sslRandom != null && sslRandom.length () > 0 )
{
random = SecureRandom.getInstance ( sslRandom );
return random;
}
return null;
}
private static TrustManager[] getTrustManagers ( final ConnectionInformation connectionInformation )
{
return new TrustManager[] { new X509TrustManagerImplementation () };
}
private static KeyManager[] getKeyManagers ( final ConnectionInformation connectionInformation, final boolean isClient ) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException, CertificateException, IOException
{
if ( isClient )
{
return null;
}
final KeyStore keyStore;
keyStore = createKeyStore ( connectionInformation );
final String keyManagerFactory = KeyManagerFactory.getDefaultAlgorithm ();
final KeyManagerFactory kmf = KeyManagerFactory.getInstance ( keyManagerFactory );
kmf.init ( keyStore, getPassword ( connectionInformation, "sslCertPassword" ) );
return kmf.getKeyManagers ();
}
private static KeyStore createKeyStore ( final ConnectionInformation connectionInformation ) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException
{
final KeyStore keyStore;
final String keyStoreType = connectionInformation.getProperties ().get ( "sslKeyStoreType" );
if ( keyStoreType != null )
{
keyStore = KeyStore.getInstance ( keyStoreType );
}
else
{
keyStore = KeyStore.getInstance ( KeyStore.getDefaultType () );
}
keyStore.load ( getKeyStoreStream ( connectionInformation ), getPassword ( connectionInformation, "sslKeyStorePassword" ) );
return keyStore;
}
private static InputStream getKeyStoreStream ( final ConnectionInformation connectionInformation ) throws IOException
{
final String uri = connectionInformation.getProperties ().get ( "sslKeyStoreUri" );
final URL url = new URL ( uri );
return url.openStream ();
}
private static char[] getPassword ( final ConnectionInformation connectionInformation, final String propertyName )
{
final char[] passwordChars;
final String password = connectionInformation.getProperties ().get ( propertyName );
if ( password != null )
{
passwordChars = password.toCharArray ();
}
else
{
passwordChars = null;
}
return passwordChars;
}
}
| true | true | public static void setupFilterChain ( final ConnectionInformation connectionInformation, final DefaultIoFilterChainBuilder filterChainBuilder, final boolean isClient )
{
// set up compression
final String compress = connectionInformation.getProperties ().get ( "compress" );
if ( compress != null )
{
int level = CompressionFilter.COMPRESSION_DEFAULT;
try
{
level = Integer.parseInt ( compress );
}
catch ( final Exception e )
{
logger.warn ( "Failed to parse 'compress' property", e );
}
if ( level < CompressionFilter.COMPRESSION_NONE || level > CompressionFilter.COMPRESSION_MAX )
{
logger.warn ( "Compression ({}) outside of valid range. Setting to default", level );
level = CompressionFilter.COMPRESSION_DEFAULT;
}
filterChainBuilder.addLast ( "compress", new CompressionFilter ( level ) );
}
// set up ssl
final String ssl = connectionInformation.getProperties ().get ( "ssl" );
if ( ssl != null )
{
initSsl ( connectionInformation, filterChainBuilder, isClient );
}
// set up logging
final String trace = connectionInformation.getProperties ().get ( "trace" );
if ( trace != null )
{
filterChainBuilder.addLast ( "logging", new LoggingFilter () );
}
// add the main codec
filterChainBuilder.addLast ( "codec", new ProtocolCodecFilter ( new GMPPProtocolEncoder (), new GMPPProtocolDecoder () ) );
}
| public static void setupFilterChain ( final ConnectionInformation connectionInformation, final DefaultIoFilterChainBuilder filterChainBuilder, final boolean isClient )
{
// set up compression
final String compress = connectionInformation.getProperties ().get ( "compress" );
if ( compress != null )
{
int level = CompressionFilter.COMPRESSION_DEFAULT;
try
{
level = Integer.parseInt ( compress );
}
catch ( final Exception e )
{
logger.warn ( "Failed to parse 'compress' property", e );
}
if ( level < CompressionFilter.COMPRESSION_DEFAULT || level > CompressionFilter.COMPRESSION_MAX )
{
logger.warn ( "Compression ({}) outside of valid range. Setting to default", level );
level = CompressionFilter.COMPRESSION_DEFAULT;
}
filterChainBuilder.addLast ( "compress", new CompressionFilter ( level ) );
}
// set up ssl
final String ssl = connectionInformation.getProperties ().get ( "ssl" );
if ( ssl != null )
{
initSsl ( connectionInformation, filterChainBuilder, isClient );
}
// set up logging
final String trace = connectionInformation.getProperties ().get ( "trace" );
if ( trace != null )
{
filterChainBuilder.addLast ( "logging", new LoggingFilter () );
}
// add the main codec
filterChainBuilder.addLast ( "codec", new ProtocolCodecFilter ( new GMPPProtocolEncoder (), new GMPPProtocolDecoder () ) );
}
|
diff --git a/src/main/java/net/pms/network/RequestV2.java b/src/main/java/net/pms/network/RequestV2.java
index ea8e17476..429b4c144 100644
--- a/src/main/java/net/pms/network/RequestV2.java
+++ b/src/main/java/net/pms/network/RequestV2.java
@@ -1,969 +1,969 @@
/*
* PS3 Media Server, for streaming any medias to your PS3.
* Copyright (C) 2008 A.Brochard
*
* 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; version 2
* of the License only.
*
* 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 net.pms.network;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;
import net.pms.PMS;
import net.pms.configuration.PmsConfiguration;
import net.pms.configuration.RendererConfiguration;
import net.pms.dlna.*;
import net.pms.external.StartStopListenerDelegate;
import static org.apache.commons.lang.StringUtils.isNotBlank;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.handler.codec.http.HttpHeaders;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.jboss.netty.handler.stream.ChunkedStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class handles all forms of incoming HTTP requests by constructing a proper HTTP response.
*/
public class RequestV2 extends HTTPResource {
private static final Logger LOGGER = LoggerFactory.getLogger(RequestV2.class);
private final static String CRLF = "\r\n";
private static SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss", Locale.US);
private static int BUFFER_SIZE = 8 * 1024;
private static final int[] MULTIPLIER = new int[] { 1, 60, 3600, 24*3600};
private final String method;
private static final PmsConfiguration configuration = PMS.getConfiguration();
/**
* A {@link String} that contains the argument with which this {@link RequestV2} was
* created. It contains a command, a unique resource id and a resource name, all
* separated by slashes. For example: "get/0$0$2$17/big_buck_bunny_1080p_h264.mov" or
* "get/0$0$2$13/thumbnail0000Sintel.2010.1080p.mkv"
*/
private String argument;
private String soapaction;
private String content;
private String objectID;
private int startingIndex;
private int requestCount;
private String browseFlag;
/**
* When sending an input stream, the lowRange indicates which byte to start from.
*/
private long lowRange;
private InputStream inputStream;
private RendererConfiguration mediaRenderer;
private String transferMode;
private String contentFeatures;
private final Range.Time range = new Range.Time();
/**
* When sending an input stream, the highRange indicates which byte to stop at.
*/
private long highRange;
private boolean http10;
public RendererConfiguration getMediaRenderer() {
return mediaRenderer;
}
public void setMediaRenderer(RendererConfiguration mediaRenderer) {
this.mediaRenderer = mediaRenderer;
}
public InputStream getInputStream() {
return inputStream;
}
/**
* When sending an input stream, the lowRange indicates which byte to start from.
* @return The byte to start from
*/
public long getLowRange() {
return lowRange;
}
/**
* Set the byte from which to start when sending an input stream. This value will
* be used to send a CONTENT_RANGE header with the response.
* @param lowRange The byte to start from.
*/
public void setLowRange(long lowRange) {
this.lowRange = lowRange;
}
public String getTransferMode() {
return transferMode;
}
public void setTransferMode(String transferMode) {
this.transferMode = transferMode;
}
public String getContentFeatures() {
return contentFeatures;
}
public void setContentFeatures(String contentFeatures) {
this.contentFeatures = contentFeatures;
}
public void setTimeRangeStart(Double timeseek) {
this.range.setStart(timeseek);
}
public void setTimeRangeStartString(String str) {
setTimeRangeStart(convertTime(str));
}
public void setTimeRangeEnd(Double rangeEnd) {
this.range.setEnd(rangeEnd);
}
public void setTimeRangeEndString(String str) {
setTimeRangeEnd(convertTime(str));
}
/**
* When sending an input stream, the highRange indicates which byte to stop at.
* @return The byte to stop at.
*/
public long getHighRange() {
return highRange;
}
/**
* Set the byte at which to stop when sending an input stream. This value will
* be used to send a CONTENT_RANGE header with the response.
* @param highRange The byte to stop at.
*/
public void setHighRange(long highRange) {
this.highRange = highRange;
}
public boolean isHttp10() {
return http10;
}
public void setHttp10(boolean http10) {
this.http10 = http10;
}
/**
* This class will construct and transmit a proper HTTP response to a given HTTP request.
* Rewritten version of the {@link Request} class.
* @param method The {@link String} that defines the HTTP method to be used.
* @param argument The {@link String} containing instructions for PMS. It contains a command,
* a unique resource id and a resource name, all separated by slashes.
*/
public RequestV2(String method, String argument) {
this.method = method;
this.argument = argument;
}
public String getSoapaction() {
return soapaction;
}
public void setSoapaction(String soapaction) {
this.soapaction = soapaction;
}
public String getTextContent() {
return content;
}
public void setTextContent(String content) {
this.content = content;
}
/**
* Retrieves the HTTP method with which this {@link RequestV2} was created.
* @return The (@link String} containing the HTTP method.
*/
public String getMethod() {
return method;
}
/**
* Retrieves the argument with which this {@link RequestV2} was created. It contains
* a command, a unique resource id and a resource name, all separated by slashes. For
* example: "get/0$0$2$17/big_buck_bunny_1080p_h264.mov" or "get/0$0$2$13/thumbnail0000Sintel.2010.1080p.mkv"
* @return The {@link String} containing the argument.
*/
public String getArgument() {
return argument;
}
/**
* Construct a proper HTTP response to a received request. After the response has been
* created, it is sent and the resulting {@link ChannelFuture} object is returned.
* See <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html">RFC-2616</a>
* for HTTP header field definitions.
* @param output The {@link HttpResponse} object that will be used to construct the response.
* @param e The {@link MessageEvent} object used to communicate with the client that sent
* the request.
* @param close Set to true to close the channel after sending the response. By default the
* channel is not closed after sending.
* @param startStopListenerDelegate The {@link StartStopListenerDelegate} object that is used
* to notify plugins that the {@link DLNAResource} is about to start playing.
* @return The {@link ChannelFuture} object via which the response was sent.
* @throws IOException
*/
public ChannelFuture answer(
HttpResponse output,
MessageEvent e,
final boolean close,
final StartStopListenerDelegate startStopListenerDelegate
) throws IOException {
ChannelFuture future = null;
long CLoverride = -2; // 0 and above are valid Content-Length values, -1 means omit
StringBuilder response = new StringBuilder();
DLNAResource dlna = null;
boolean xbox = mediaRenderer.isXBOX();
// Samsung 2012 TVs have a problematic preceding slash that needs to be removed.
if (argument.startsWith("/")) {
LOGGER.trace("Stripping preceding slash from: " + argument);
argument = argument.substring(1);
}
if ((method.equals("GET") || method.equals("HEAD")) && argument.startsWith("console/")) {
// Request to output a page to the HTML console.
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/html");
response.append(HTMLConsole.servePage(argument.substring(8)));
} else if ((method.equals("GET") || method.equals("HEAD")) && argument.startsWith("get/")) {
// Request to retrieve a file
// skip the leading "get/" and extract the
// resource ID from the first path element
// e.g. "get/0$1$5$3$4/Foo.mp4" -> "0$1$5$3$4"
String id = argument.substring(4, argument.lastIndexOf("/"));
// Some clients escape the separators in their request: unescape them.
id = id.replace("%24", "$");
// Retrieve the DLNAresource itself.
List<DLNAResource> files = PMS.get().getRootFolder(mediaRenderer).getDLNAResources(id, false, 0, 0, mediaRenderer);
if (transferMode != null) {
output.setHeader("TransferMode.DLNA.ORG", transferMode);
}
if (files.size() == 1) {
// DLNAresource was found.
dlna = files.get(0);
String fileName = argument.substring(argument.lastIndexOf("/") + 1);
if (fileName.startsWith("thumbnail0000")) {
// This is a request for a thumbnail file.
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, dlna.getThumbnailContentType());
output.setHeader(HttpHeaders.Names.ACCEPT_RANGES, "bytes");
output.setHeader(HttpHeaders.Names.EXPIRES, getFUTUREDATE() + " GMT");
output.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive");
if (mediaRenderer.isMediaParserV2()) {
dlna.checkThumbnail();
}
inputStream = dlna.getThumbnailInputStream();
} else if (fileName.indexOf("subtitle0000") > -1) {
// This is a request for a subtitle file
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
output.setHeader(HttpHeaders.Names.EXPIRES, getFUTUREDATE() + " GMT");
List<DLNAMediaSubtitle> subs = dlna.getMedia().getSubtitleTracksList();
if (subs != null && !subs.isEmpty()) {
// TODO: maybe loop subs to get the requested subtitle type instead of using the first one
DLNAMediaSubtitle sub = subs.get(0);
try {
// XXX external file is null if the first subtitle track is embedded:
// http://www.ps3mediaserver.org/forum/viewtopic.php?f=3&t=15805&p=75534#p75534
if (sub.isExternal()) {
inputStream = new java.io.FileInputStream(sub.getExternalFile());
}
} catch (NullPointerException npe) {
LOGGER.trace("Could not find external subtitles: " + sub);
}
}
} else {
// This is a request for a regular file.
// If range has not been initialized yet and the DLNAResource has its
// own start and end defined, initialize range with those values before
// requesting the input stream.
Range.Time splitRange = dlna.getSplitRange();
if (range.getStart() == null && splitRange.getStart() != null) {
range.setStart(splitRange.getStart());
}
if (range.getEnd() == null && splitRange.getEnd() != null) {
range.setEnd(splitRange.getEnd());
}
inputStream = dlna.getInputStream(Range.create(lowRange, highRange, range.getStart(), range.getEnd()), mediaRenderer);
// Some renderers (like Samsung devices) allow a custom header for a subtitle URL
String subtitleHttpHeader = mediaRenderer.getSubtitleHttpHeader();
if (subtitleHttpHeader != null && !"".equals(subtitleHttpHeader)) {
// Device allows a custom subtitle HTTP header; construct it
List<DLNAMediaSubtitle> subs = dlna.getMedia().getSubtitleTracksList();
if (subs != null && !subs.isEmpty()) {
DLNAMediaSubtitle sub = subs.get(0);
String subtitleUrl;
String subExtension = sub.getType().getExtension();
if (isNotBlank(subExtension)) {
subtitleUrl = "http://" + PMS.get().getServer().getHost() +
':' + PMS.get().getServer().getPort() + "/get/" +
id + "/subtitle0000." + subExtension;
} else {
subtitleUrl = "http://" + PMS.get().getServer().getHost() +
':' + PMS.get().getServer().getPort() + "/get/" +
id + "/subtitle0000";
}
output.setHeader(subtitleHttpHeader, subtitleUrl);
}
}
String name = dlna.getDisplayName(mediaRenderer);
if (dlna.isNoName()) {
name = dlna.getName() + " " + dlna.getDisplayName(mediaRenderer);
}
if (inputStream == null) {
// No inputStream indicates that transcoding / remuxing probably crashed.
LOGGER.error("There is no inputstream to return for " + name);
} else {
// Notify plugins that the DLNAresource is about to start playing
startStopListenerDelegate.start(dlna);
// Try to determine the content type of the file
String rendererMimeType = getRendererMimeType(dlna.mimeType(), mediaRenderer);
if (rendererMimeType != null && !"".equals(rendererMimeType)) {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, rendererMimeType);
}
PMS.get().getFrame().setStatusLine("Serving " + name);
// Response generation:
// We use -1 for arithmetic convenience but don't send it as a value.
// If Content-Length < 0 we omit it, for Content-Range we use '*' to signify unspecified.
boolean chunked = mediaRenderer.isChunkedTransfer();
// Determine the total size. Note: when transcoding the length is
// not known in advance, so DLNAMediaInfo.TRANS_SIZE will be returned instead.
long totalsize = dlna.length(mediaRenderer);
if (chunked && totalsize == DLNAMediaInfo.TRANS_SIZE) {
// In chunked mode we try to avoid arbitrary values.
totalsize = -1;
}
long remaining = totalsize - lowRange;
long requested = highRange - lowRange;
if (requested != 0) {
// Determine the range (i.e. smaller of known or requested bytes)
long bytes = remaining > -1 ? remaining : inputStream.available();
if (requested > 0 && bytes > requested) {
bytes = requested + 1;
}
// Calculate the corresponding highRange (this is usually redundant).
highRange = lowRange + bytes - (bytes > 0 ? 1 : 0);
LOGGER.trace((chunked ? "Using chunked response. " : "") + "Sending " + bytes + " bytes.");
output.setHeader(HttpHeaders.Names.CONTENT_RANGE, "bytes " + lowRange + "-" + (highRange > -1 ? highRange : "*") + "/" + (totalsize > -1 ? totalsize : "*"));
// Content-Length refers to the current chunk size here, though in chunked
// mode if the request is open-ended and totalsize is unknown we omit it.
if (chunked && requested < 0 && totalsize < 0) {
CLoverride = -1;
} else {
CLoverride = bytes;
}
} else {
// Content-Length refers to the total remaining size of the stream here.
CLoverride = remaining;
}
// Calculate the corresponding highRange (this is usually redundant).
highRange = lowRange + CLoverride - (CLoverride > 0 ? 1 : 0);
if (contentFeatures != null) {
output.setHeader("ContentFeatures.DLNA.ORG", dlna.getDlnaContentFeatures());
}
output.setHeader(HttpHeaders.Names.ACCEPT_RANGES, "bytes");
output.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive");
}
}
}
} else if ((method.equals("GET") || method.equals("HEAD")) && (argument.toLowerCase().endsWith(".png") || argument.toLowerCase().endsWith(".jpg") || argument.toLowerCase().endsWith(".jpeg"))) {
if (argument.toLowerCase().endsWith(".png")) {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "image/png");
} else {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "image/jpeg");
}
output.setHeader(HttpHeaders.Names.ACCEPT_RANGES, "bytes");
output.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive");
output.setHeader(HttpHeaders.Names.EXPIRES, getFUTUREDATE() + " GMT");
inputStream = getResourceInputStream(argument);
} else if ((method.equals("GET") || method.equals("HEAD")) && (argument.equals("description/fetch") || argument.endsWith("1.0.xml"))) {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml; charset=\"utf-8\"");
output.setHeader(HttpHeaders.Names.CACHE_CONTROL, "no-cache");
output.setHeader(HttpHeaders.Names.EXPIRES, "0");
output.setHeader(HttpHeaders.Names.ACCEPT_RANGES, "bytes");
output.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive");
inputStream = getResourceInputStream((argument.equals("description/fetch") ? "PMS.xml" : argument));
if (argument.equals("description/fetch")) {
byte b[] = new byte[inputStream.available()];
inputStream.read(b);
String s = new String(b);
s = s.replace("[uuid]", PMS.get().usn()); //.substring(0, PMS.get().usn().length()-2));
String profileName = configuration.getProfileName();
if (PMS.get().getServer().getHost() != null) {
s = s.replace("[host]", PMS.get().getServer().getHost());
s = s.replace("[port]", "" + PMS.get().getServer().getPort());
}
if (xbox) {
LOGGER.debug("DLNA changes for Xbox 360");
s = s.replace("Universal Media Server", "Universal Media Server [" + profileName + "] : Windows Media Connect");
s = s.replace("<modelName>UMS</modelName>", "<modelName>Windows Media Connect</modelName>");
s = s.replace("<serviceList>", "<serviceList>" + CRLF + "<service>" + CRLF +
"<serviceType>urn:microsoft.com:service:X_MS_MediaReceiverRegistrar:1</serviceType>" + CRLF +
"<serviceId>urn:microsoft.com:serviceId:X_MS_MediaReceiverRegistrar</serviceId>" + CRLF +
"<SCPDURL>/upnp/mrr/scpd</SCPDURL>" + CRLF +
"<controlURL>/upnp/mrr/control</controlURL>" + CRLF +
"</service>" + CRLF);
} else {
s = s.replace("Universal Media Server", "Universal Media Server [" + profileName + "]");
}
if (!mediaRenderer.isPS3()) {
// hacky stuff. replace the png icon by a jpeg one. Like mpeg2 remux,
// really need a proper format compatibility list by renderer
s = s.replace("<mimetype>image/png</mimetype>", "<mimetype>image/jpeg</mimetype>");
s = s.replace("/images/thumbnail-video-256.png", "/images/thumbnail-video-120.jpg");
s = s.replace(">256<", ">120<");
}
response.append(s);
inputStream = null;
}
} else if (method.equals("POST") && (argument.contains("MS_MediaReceiverRegistrar_control") || argument.contains("mrr/control"))) {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml; charset=\"utf-8\"");
response.append(HTTPXMLHelper.XML_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
response.append(CRLF);
if (soapaction != null && soapaction.contains("IsAuthorized")) {
response.append(HTTPXMLHelper.XBOX_2);
response.append(CRLF);
} else if (soapaction != null && soapaction.contains("IsValidated")) {
response.append(HTTPXMLHelper.XBOX_1);
response.append(CRLF);
}
response.append(HTTPXMLHelper.BROWSERESPONSE_FOOTER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
response.append(CRLF);
} else if (method.equals("POST") && argument.endsWith("upnp/control/connection_manager")) {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml; charset=\"utf-8\"");
if (soapaction != null && soapaction.indexOf("ConnectionManager:1#GetProtocolInfo") > -1) {
response.append(HTTPXMLHelper.XML_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.PROTOCOLINFO_RESPONSE);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
response.append(CRLF);
}
} else if (method.equals("POST") && argument.endsWith("upnp/control/content_directory")) {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml; charset=\"utf-8\"");
if (soapaction != null && soapaction.indexOf("ContentDirectory:1#GetSystemUpdateID") > -1) {
response.append(HTTPXMLHelper.XML_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.GETSYSTEMUPDATEID_HEADER);
response.append(CRLF);
response.append("<Id>").append(DLNAResource.getSystemUpdateId()).append("</Id>");
response.append(CRLF);
response.append(HTTPXMLHelper.GETSYSTEMUPDATEID_FOOTER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
response.append(CRLF);
} else if (soapaction != null && soapaction.indexOf("ContentDirectory:1#X_GetFeatureList") > -1) { // Added for Samsung 2012 TVs
response.append(HTTPXMLHelper.XML_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SAMSUNG_ERROR_RESPONSE);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
response.append(CRLF);
} else if (soapaction != null && soapaction.indexOf("ContentDirectory:1#GetSortCapabilities") > -1) {
response.append(HTTPXMLHelper.XML_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SORTCAPS_RESPONSE);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
response.append(CRLF);
} else if (soapaction != null && soapaction.indexOf("ContentDirectory:1#GetSearchCapabilities") > -1) {
response.append(HTTPXMLHelper.XML_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SEARCHCAPS_RESPONSE);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
response.append(CRLF);
} else if (soapaction != null && (soapaction.contains("ContentDirectory:1#Browse") || soapaction.contains("ContentDirectory:1#Search"))) {
objectID = getEnclosingValue(content, "<ObjectID>", "</ObjectID>");
String containerID = null;
if ((objectID == null || objectID.length() == 0)) {
containerID = getEnclosingValue(content, "<ContainerID>", "</ContainerID>");
- if (containerID == null && !containerID.contains("$")) {
+ if (containerID == null || !containerID.contains("$")) {
objectID = "0";
} else {
objectID = containerID;
containerID = null;
}
}
Object sI = getEnclosingValue(content, "<StartingIndex>", "</StartingIndex>");
Object rC = getEnclosingValue(content, "<RequestedCount>", "</RequestedCount>");
browseFlag = getEnclosingValue(content, "<BrowseFlag>", "</BrowseFlag>");
if (sI != null) {
startingIndex = Integer.parseInt(sI.toString());
}
if (rC != null) {
requestCount = Integer.parseInt(rC.toString());
}
response.append(HTTPXMLHelper.XML_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
response.append(CRLF);
if (soapaction != null && soapaction.contains("ContentDirectory:1#Search")) {
response.append(HTTPXMLHelper.SEARCHRESPONSE_HEADER);
} else {
response.append(HTTPXMLHelper.BROWSERESPONSE_HEADER);
}
response.append(CRLF);
response.append(HTTPXMLHelper.RESULT_HEADER);
response.append(HTTPXMLHelper.DIDL_HEADER);
if (soapaction != null && soapaction.contains("ContentDirectory:1#Search")) {
browseFlag = "BrowseDirectChildren";
}
// XBOX virtual containers ... d'oh!
String searchCriteria = null;
if (xbox && configuration.getUseCache() && PMS.get().getLibrary() != null && containerID != null) {
if (containerID.equals("7") && PMS.get().getLibrary().getAlbumFolder() != null) {
objectID = PMS.get().getLibrary().getAlbumFolder().getResourceId();
} else if (containerID.equals("6") && PMS.get().getLibrary().getArtistFolder() != null) {
objectID = PMS.get().getLibrary().getArtistFolder().getResourceId();
} else if (containerID.equals("5") && PMS.get().getLibrary().getGenreFolder() != null) {
objectID = PMS.get().getLibrary().getGenreFolder().getResourceId();
} else if (containerID.equals("F") && PMS.get().getLibrary().getPlaylistFolder() != null) {
objectID = PMS.get().getLibrary().getPlaylistFolder().getResourceId();
} else if (containerID.equals("4") && PMS.get().getLibrary().getAllFolder() != null) {
objectID = PMS.get().getLibrary().getAllFolder().getResourceId();
} else if (containerID.equals("1")) {
String artist = getEnclosingValue(content, "upnp:artist = "", "")");
if (artist != null) {
objectID = PMS.get().getLibrary().getArtistFolder().getResourceId();
searchCriteria = artist;
}
}
} else if (soapaction.contains("ContentDirectory:1#Search")) {
searchCriteria = getEnclosingValue(content,"<SearchCriteria>","</SearchCriteria>");
}
List<DLNAResource> files = PMS.get().getRootFolder(mediaRenderer).getDLNAResources(
objectID,
browseFlag != null && browseFlag.equals("BrowseDirectChildren"),
startingIndex,
requestCount,
mediaRenderer,
searchCriteria
);
if (searchCriteria != null && files != null) {
searchCriteria = searchCriteria.toLowerCase();
for(int i = files.size() - 1; i >= 0; i--) {
DLNAResource res = files.get(i);
if (res.isSearched()) {
continue;
}
boolean keep = res.getName().toLowerCase().indexOf(searchCriteria) != -1;
final DLNAMediaInfo media = res.getMedia();
if (media!=null) {
for (int j = 0;j < media.getAudioTracksList().size(); j++) {
DLNAMediaAudio audio = media.getAudioTracksList().get(j);
keep |= audio.getAlbum().toLowerCase().indexOf(searchCriteria) != -1;
keep |= audio.getArtist().toLowerCase().indexOf(searchCriteria) != -1;
keep |= audio.getSongname().toLowerCase().indexOf(searchCriteria) != -1;
}
}
if (!keep) { // dump it
files.remove(i);
}
}
if (xbox) {
if (files.size() > 0) {
files = files.get(0).getChildren();
}
}
}
int minus = 0;
if (files != null) {
for (DLNAResource uf : files) {
if (xbox && containerID != null) {
uf.setFakeParentId(containerID);
}
if (uf.isCompatible(mediaRenderer) && (uf.getPlayer() == null || uf.getPlayer().isPlayerCompatible(mediaRenderer))) {
response.append(uf.toString(mediaRenderer));
} else {
minus++;
}
}
}
response.append(HTTPXMLHelper.DIDL_FOOTER);
response.append(HTTPXMLHelper.RESULT_FOOTER);
response.append(CRLF);
int filessize = 0;
if (files != null) {
filessize = files.size();
}
response.append("<NumberReturned>").append(filessize - minus).append("</NumberReturned>");
response.append(CRLF);
DLNAResource parentFolder = null;
if (files != null && filessize > 0) {
parentFolder = files.get(0).getParent();
}
if (browseFlag != null && browseFlag.equals("BrowseDirectChildren") && mediaRenderer.isMediaParserV2() && mediaRenderer.isDLNATreeHack()) {
// with the new parser, files are parsed and analyzed *before* creating the DLNA tree,
// every 10 items (the ps3 asks 10 by 10),
// so we do not know exactly the total number of items in the DLNA folder to send
// (regular files, plus the #transcode folder, maybe the #imdb one, also files can be
// invalidated and hidden if format is broken or encrypted, etc.).
// let's send a fake total size to force the renderer to ask following items
int totalCount = startingIndex + requestCount + 1; // returns 11 when 10 asked
if (filessize - minus <= 0) // if no more elements, send the startingIndex
{
totalCount = startingIndex;
}
response.append("<TotalMatches>").append(totalCount).append("</TotalMatches>");
} else if (browseFlag != null && browseFlag.equals("BrowseDirectChildren")) {
response.append("<TotalMatches>").append(((parentFolder != null) ? parentFolder.childrenNumber() : filessize) - minus).append("</TotalMatches>");
} else { //from upnp spec: If BrowseMetadata is specified in the BrowseFlags then TotalMatches = 1
response.append("<TotalMatches>1</TotalMatches>");
}
response.append(CRLF);
response.append("<UpdateID>");
if (parentFolder != null) {
response.append(parentFolder.getUpdateId());
} else {
response.append("1");
}
response.append("</UpdateID>");
response.append(CRLF);
if (soapaction != null && soapaction.contains("ContentDirectory:1#Search")) {
response.append(HTTPXMLHelper.SEARCHRESPONSE_FOOTER);
} else {
response.append(HTTPXMLHelper.BROWSERESPONSE_FOOTER);
}
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
response.append(CRLF);
// LOGGER.trace(response.toString());
}
} else if (method.equals("SUBSCRIBE")) {
output.setHeader("SID", PMS.get().usn());
output.setHeader("TIMEOUT", "Second-1800");
if (soapaction != null) {
String cb = soapaction.replace("<", "").replace(">", "");
try {
URL soapActionUrl = new URL(cb);
String addr = soapActionUrl.getHost();
int port = soapActionUrl.getPort();
Socket sock = new Socket(addr,port);
OutputStream out = sock.getOutputStream();
out.write(("NOTIFY /" + argument + " HTTP/1.1").getBytes());
out.write(CRLF.getBytes());
out.write(("SID: " + PMS.get().usn()).getBytes());
out.write(CRLF.getBytes());
out.write(("SEQ: " + 0).getBytes());
out.write(CRLF.getBytes());
out.write(("NT: upnp:event").getBytes());
out.write(CRLF.getBytes());
out.write(("NTS: upnp:propchange").getBytes());
out.write(CRLF.getBytes());
out.write(("HOST: " + addr + ":" + port).getBytes());
out.write(CRLF.getBytes());
out.flush();
out.close();
} catch (MalformedURLException ex) {
LOGGER.debug("Cannot parse address and port from soap action \"" + soapaction + "\"", ex);
}
} else {
LOGGER.debug("Expected soap action in request");
}
if (argument.contains("connection_manager")) {
response.append(HTTPXMLHelper.eventHeader("urn:schemas-upnp-org:service:ConnectionManager:1"));
response.append(HTTPXMLHelper.eventProp("SinkProtocolInfo"));
response.append(HTTPXMLHelper.eventProp("SourceProtocolInfo"));
response.append(HTTPXMLHelper.eventProp("CurrentConnectionIDs"));
response.append(HTTPXMLHelper.EVENT_FOOTER);
} else if (argument.contains("content_directory")) {
response.append(HTTPXMLHelper.eventHeader("urn:schemas-upnp-org:service:ContentDirectory:1"));
response.append(HTTPXMLHelper.eventProp("TransferIDs"));
response.append(HTTPXMLHelper.eventProp("ContainerUpdateIDs"));
response.append(HTTPXMLHelper.eventProp("SystemUpdateID", "" + DLNAResource.getSystemUpdateId()));
response.append(HTTPXMLHelper.EVENT_FOOTER);
}
} else if (method.equals("NOTIFY")) {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml");
output.setHeader("NT", "upnp:event");
output.setHeader("NTS", "upnp:propchange");
output.setHeader("SID", PMS.get().usn());
output.setHeader("SEQ", "0");
response.append("<e:propertyset xmlns:e=\"urn:schemas-upnp-org:event-1-0\">");
response.append("<e:property>");
response.append("<TransferIDs></TransferIDs>");
response.append("</e:property>");
response.append("<e:property>");
response.append("<ContainerUpdateIDs></ContainerUpdateIDs>");
response.append("</e:property>");
response.append("<e:property>");
response.append("<SystemUpdateID>").append(DLNAResource.getSystemUpdateId()).append("</SystemUpdateID>");
response.append("</e:property>");
response.append("</e:propertyset>");
}
output.setHeader("Server", PMS.get().getServerName());
if (response.length() > 0) {
// A response message was constructed; convert it to data ready to be sent.
byte responseData[] = response.toString().getBytes("UTF-8");
output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "" + responseData.length);
// HEAD requests only require headers to be set, no need to set contents.
if (!method.equals("HEAD")) {
// Not a HEAD request, so set the contents of the response.
ChannelBuffer buf = ChannelBuffers.copiedBuffer(responseData);
output.setContent(buf);
}
// Send the response to the client.
future = e.getChannel().write(output);
if (close) {
// Close the channel after the response is sent.
future.addListener(ChannelFutureListener.CLOSE);
}
} else if (inputStream != null) {
// There is an input stream to send as a response.
if (CLoverride > -2) {
// Content-Length override has been set, send or omit as appropriate
if (CLoverride > -1 && CLoverride != DLNAMediaInfo.TRANS_SIZE) {
// Since PS3 firmware 2.50, it is wiser not to send an arbitrary Content-Length,
// as the PS3 will display a network error and request the last seconds of the
// transcoded video. Better to send no Content-Length at all.
output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "" + CLoverride);
}
} else {
int cl = inputStream.available();
LOGGER.trace("Available Content-Length: " + cl);
output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "" + cl);
}
if (range.isStartOffsetAvailable() && dlna != null) {
// Add timeseek information headers.
String timeseekValue = DLNAMediaInfo.getDurationString(range.getStartOrZero());
String timetotalValue = dlna.getMedia().getDurationString();
String timeEndValue = range.isEndLimitAvailable() ? DLNAMediaInfo.getDurationString(range.getEnd()) : timetotalValue;
output.setHeader("TimeSeekRange.dlna.org", "npt=" + timeseekValue + "-" + timeEndValue + "/" + timetotalValue);
output.setHeader("X-Seek-Range", "npt=" + timeseekValue + "-" + timeEndValue + "/" + timetotalValue);
}
// Send the response headers to the client.
future = e.getChannel().write(output);
if (lowRange != DLNAMediaInfo.ENDFILE_POS && !method.equals("HEAD")) {
// Send the response body to the client in chunks.
ChannelFuture chunkWriteFuture = e.getChannel().write(new ChunkedStream(inputStream, BUFFER_SIZE));
// Add a listener to clean up after sending the entire response body.
chunkWriteFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
try {
PMS.get().getRegistry().reenableGoToSleep();
inputStream.close();
} catch (IOException e) {
LOGGER.debug("Caught exception", e);
}
// Always close the channel after the response is sent because of
// a freeze at the end of video when the channel is not closed.
future.getChannel().close();
startStopListenerDelegate.stop();
}
});
} else {
// HEAD method is being used, so simply clean up after the response was sent.
try {
PMS.get().getRegistry().reenableGoToSleep();
inputStream.close();
} catch (IOException ioe) {
LOGGER.debug("Caught exception", ioe);
}
if (close) {
// Close the channel after the response is sent
future.addListener(ChannelFutureListener.CLOSE);
}
startStopListenerDelegate.stop();
}
} else {
// No response data and no input stream. Seems we are merely serving up headers.
if (lowRange > 0 && highRange > 0) {
// FIXME: There is no content, so why set a length?
output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "" + (highRange - lowRange + 1));
} else {
output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "0");
}
// Send the response headers to the client.
future = e.getChannel().write(output);
if (close) {
// Close the channel after the response is sent.
future.addListener(ChannelFutureListener.CLOSE);
}
}
// Log trace information
Iterator<String> it = output.getHeaderNames().iterator();
while (it.hasNext()) {
String headerName = it.next();
LOGGER.trace("Sent to socket: " + headerName + ": " + output.getHeader(headerName));
}
return future;
}
/**
* Returns a date somewhere in the far future.
* @return The {@link String} containing the date
*/
private String getFUTUREDATE() {
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
return sdf.format(new Date(10000000000L + System.currentTimeMillis()));
}
/**
* Returns the string value that is enclosed by the left and right tag in a content string.
* Only the first match of each tag is used to determine positions. If either of the tags
* cannot be found, null is returned.
* @param content The entire {@link String} that needs to be searched for the left and right tag.
* @param leftTag The {@link String} determining the match for the left tag.
* @param rightTag The {@link String} determining the match for the right tag.
* @return The {@link String} that was enclosed by the left and right tag.
*/
private String getEnclosingValue(String content, String leftTag, String rightTag) {
String result = null;
int leftTagPos = content.indexOf(leftTag);
int rightTagPos = content.indexOf(rightTag, leftTagPos + 1);
if (leftTagPos > -1 && rightTagPos > leftTagPos) {
result = content.substring(leftTagPos + leftTag.length(), rightTagPos);
}
return result;
}
/**
* Parse as double, or if it's not just one number, handles {hour}:{minute}:{seconds}
* @param time
* @return
*/
private double convertTime(String time) {
try {
return Double.parseDouble(time);
} catch (NumberFormatException e) {
String[] arrs = time.split(":");
double value, sum = 0;
for (int i = 0; i < arrs.length; i++) {
value = Double.parseDouble(arrs[arrs.length - i - 1]);
sum += value * MULTIPLIER[i];
}
return sum;
}
}
}
| true | true | public ChannelFuture answer(
HttpResponse output,
MessageEvent e,
final boolean close,
final StartStopListenerDelegate startStopListenerDelegate
) throws IOException {
ChannelFuture future = null;
long CLoverride = -2; // 0 and above are valid Content-Length values, -1 means omit
StringBuilder response = new StringBuilder();
DLNAResource dlna = null;
boolean xbox = mediaRenderer.isXBOX();
// Samsung 2012 TVs have a problematic preceding slash that needs to be removed.
if (argument.startsWith("/")) {
LOGGER.trace("Stripping preceding slash from: " + argument);
argument = argument.substring(1);
}
if ((method.equals("GET") || method.equals("HEAD")) && argument.startsWith("console/")) {
// Request to output a page to the HTML console.
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/html");
response.append(HTMLConsole.servePage(argument.substring(8)));
} else if ((method.equals("GET") || method.equals("HEAD")) && argument.startsWith("get/")) {
// Request to retrieve a file
// skip the leading "get/" and extract the
// resource ID from the first path element
// e.g. "get/0$1$5$3$4/Foo.mp4" -> "0$1$5$3$4"
String id = argument.substring(4, argument.lastIndexOf("/"));
// Some clients escape the separators in their request: unescape them.
id = id.replace("%24", "$");
// Retrieve the DLNAresource itself.
List<DLNAResource> files = PMS.get().getRootFolder(mediaRenderer).getDLNAResources(id, false, 0, 0, mediaRenderer);
if (transferMode != null) {
output.setHeader("TransferMode.DLNA.ORG", transferMode);
}
if (files.size() == 1) {
// DLNAresource was found.
dlna = files.get(0);
String fileName = argument.substring(argument.lastIndexOf("/") + 1);
if (fileName.startsWith("thumbnail0000")) {
// This is a request for a thumbnail file.
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, dlna.getThumbnailContentType());
output.setHeader(HttpHeaders.Names.ACCEPT_RANGES, "bytes");
output.setHeader(HttpHeaders.Names.EXPIRES, getFUTUREDATE() + " GMT");
output.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive");
if (mediaRenderer.isMediaParserV2()) {
dlna.checkThumbnail();
}
inputStream = dlna.getThumbnailInputStream();
} else if (fileName.indexOf("subtitle0000") > -1) {
// This is a request for a subtitle file
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
output.setHeader(HttpHeaders.Names.EXPIRES, getFUTUREDATE() + " GMT");
List<DLNAMediaSubtitle> subs = dlna.getMedia().getSubtitleTracksList();
if (subs != null && !subs.isEmpty()) {
// TODO: maybe loop subs to get the requested subtitle type instead of using the first one
DLNAMediaSubtitle sub = subs.get(0);
try {
// XXX external file is null if the first subtitle track is embedded:
// http://www.ps3mediaserver.org/forum/viewtopic.php?f=3&t=15805&p=75534#p75534
if (sub.isExternal()) {
inputStream = new java.io.FileInputStream(sub.getExternalFile());
}
} catch (NullPointerException npe) {
LOGGER.trace("Could not find external subtitles: " + sub);
}
}
} else {
// This is a request for a regular file.
// If range has not been initialized yet and the DLNAResource has its
// own start and end defined, initialize range with those values before
// requesting the input stream.
Range.Time splitRange = dlna.getSplitRange();
if (range.getStart() == null && splitRange.getStart() != null) {
range.setStart(splitRange.getStart());
}
if (range.getEnd() == null && splitRange.getEnd() != null) {
range.setEnd(splitRange.getEnd());
}
inputStream = dlna.getInputStream(Range.create(lowRange, highRange, range.getStart(), range.getEnd()), mediaRenderer);
// Some renderers (like Samsung devices) allow a custom header for a subtitle URL
String subtitleHttpHeader = mediaRenderer.getSubtitleHttpHeader();
if (subtitleHttpHeader != null && !"".equals(subtitleHttpHeader)) {
// Device allows a custom subtitle HTTP header; construct it
List<DLNAMediaSubtitle> subs = dlna.getMedia().getSubtitleTracksList();
if (subs != null && !subs.isEmpty()) {
DLNAMediaSubtitle sub = subs.get(0);
String subtitleUrl;
String subExtension = sub.getType().getExtension();
if (isNotBlank(subExtension)) {
subtitleUrl = "http://" + PMS.get().getServer().getHost() +
':' + PMS.get().getServer().getPort() + "/get/" +
id + "/subtitle0000." + subExtension;
} else {
subtitleUrl = "http://" + PMS.get().getServer().getHost() +
':' + PMS.get().getServer().getPort() + "/get/" +
id + "/subtitle0000";
}
output.setHeader(subtitleHttpHeader, subtitleUrl);
}
}
String name = dlna.getDisplayName(mediaRenderer);
if (dlna.isNoName()) {
name = dlna.getName() + " " + dlna.getDisplayName(mediaRenderer);
}
if (inputStream == null) {
// No inputStream indicates that transcoding / remuxing probably crashed.
LOGGER.error("There is no inputstream to return for " + name);
} else {
// Notify plugins that the DLNAresource is about to start playing
startStopListenerDelegate.start(dlna);
// Try to determine the content type of the file
String rendererMimeType = getRendererMimeType(dlna.mimeType(), mediaRenderer);
if (rendererMimeType != null && !"".equals(rendererMimeType)) {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, rendererMimeType);
}
PMS.get().getFrame().setStatusLine("Serving " + name);
// Response generation:
// We use -1 for arithmetic convenience but don't send it as a value.
// If Content-Length < 0 we omit it, for Content-Range we use '*' to signify unspecified.
boolean chunked = mediaRenderer.isChunkedTransfer();
// Determine the total size. Note: when transcoding the length is
// not known in advance, so DLNAMediaInfo.TRANS_SIZE will be returned instead.
long totalsize = dlna.length(mediaRenderer);
if (chunked && totalsize == DLNAMediaInfo.TRANS_SIZE) {
// In chunked mode we try to avoid arbitrary values.
totalsize = -1;
}
long remaining = totalsize - lowRange;
long requested = highRange - lowRange;
if (requested != 0) {
// Determine the range (i.e. smaller of known or requested bytes)
long bytes = remaining > -1 ? remaining : inputStream.available();
if (requested > 0 && bytes > requested) {
bytes = requested + 1;
}
// Calculate the corresponding highRange (this is usually redundant).
highRange = lowRange + bytes - (bytes > 0 ? 1 : 0);
LOGGER.trace((chunked ? "Using chunked response. " : "") + "Sending " + bytes + " bytes.");
output.setHeader(HttpHeaders.Names.CONTENT_RANGE, "bytes " + lowRange + "-" + (highRange > -1 ? highRange : "*") + "/" + (totalsize > -1 ? totalsize : "*"));
// Content-Length refers to the current chunk size here, though in chunked
// mode if the request is open-ended and totalsize is unknown we omit it.
if (chunked && requested < 0 && totalsize < 0) {
CLoverride = -1;
} else {
CLoverride = bytes;
}
} else {
// Content-Length refers to the total remaining size of the stream here.
CLoverride = remaining;
}
// Calculate the corresponding highRange (this is usually redundant).
highRange = lowRange + CLoverride - (CLoverride > 0 ? 1 : 0);
if (contentFeatures != null) {
output.setHeader("ContentFeatures.DLNA.ORG", dlna.getDlnaContentFeatures());
}
output.setHeader(HttpHeaders.Names.ACCEPT_RANGES, "bytes");
output.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive");
}
}
}
} else if ((method.equals("GET") || method.equals("HEAD")) && (argument.toLowerCase().endsWith(".png") || argument.toLowerCase().endsWith(".jpg") || argument.toLowerCase().endsWith(".jpeg"))) {
if (argument.toLowerCase().endsWith(".png")) {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "image/png");
} else {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "image/jpeg");
}
output.setHeader(HttpHeaders.Names.ACCEPT_RANGES, "bytes");
output.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive");
output.setHeader(HttpHeaders.Names.EXPIRES, getFUTUREDATE() + " GMT");
inputStream = getResourceInputStream(argument);
} else if ((method.equals("GET") || method.equals("HEAD")) && (argument.equals("description/fetch") || argument.endsWith("1.0.xml"))) {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml; charset=\"utf-8\"");
output.setHeader(HttpHeaders.Names.CACHE_CONTROL, "no-cache");
output.setHeader(HttpHeaders.Names.EXPIRES, "0");
output.setHeader(HttpHeaders.Names.ACCEPT_RANGES, "bytes");
output.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive");
inputStream = getResourceInputStream((argument.equals("description/fetch") ? "PMS.xml" : argument));
if (argument.equals("description/fetch")) {
byte b[] = new byte[inputStream.available()];
inputStream.read(b);
String s = new String(b);
s = s.replace("[uuid]", PMS.get().usn()); //.substring(0, PMS.get().usn().length()-2));
String profileName = configuration.getProfileName();
if (PMS.get().getServer().getHost() != null) {
s = s.replace("[host]", PMS.get().getServer().getHost());
s = s.replace("[port]", "" + PMS.get().getServer().getPort());
}
if (xbox) {
LOGGER.debug("DLNA changes for Xbox 360");
s = s.replace("Universal Media Server", "Universal Media Server [" + profileName + "] : Windows Media Connect");
s = s.replace("<modelName>UMS</modelName>", "<modelName>Windows Media Connect</modelName>");
s = s.replace("<serviceList>", "<serviceList>" + CRLF + "<service>" + CRLF +
"<serviceType>urn:microsoft.com:service:X_MS_MediaReceiverRegistrar:1</serviceType>" + CRLF +
"<serviceId>urn:microsoft.com:serviceId:X_MS_MediaReceiverRegistrar</serviceId>" + CRLF +
"<SCPDURL>/upnp/mrr/scpd</SCPDURL>" + CRLF +
"<controlURL>/upnp/mrr/control</controlURL>" + CRLF +
"</service>" + CRLF);
} else {
s = s.replace("Universal Media Server", "Universal Media Server [" + profileName + "]");
}
if (!mediaRenderer.isPS3()) {
// hacky stuff. replace the png icon by a jpeg one. Like mpeg2 remux,
// really need a proper format compatibility list by renderer
s = s.replace("<mimetype>image/png</mimetype>", "<mimetype>image/jpeg</mimetype>");
s = s.replace("/images/thumbnail-video-256.png", "/images/thumbnail-video-120.jpg");
s = s.replace(">256<", ">120<");
}
response.append(s);
inputStream = null;
}
} else if (method.equals("POST") && (argument.contains("MS_MediaReceiverRegistrar_control") || argument.contains("mrr/control"))) {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml; charset=\"utf-8\"");
response.append(HTTPXMLHelper.XML_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
response.append(CRLF);
if (soapaction != null && soapaction.contains("IsAuthorized")) {
response.append(HTTPXMLHelper.XBOX_2);
response.append(CRLF);
} else if (soapaction != null && soapaction.contains("IsValidated")) {
response.append(HTTPXMLHelper.XBOX_1);
response.append(CRLF);
}
response.append(HTTPXMLHelper.BROWSERESPONSE_FOOTER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
response.append(CRLF);
} else if (method.equals("POST") && argument.endsWith("upnp/control/connection_manager")) {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml; charset=\"utf-8\"");
if (soapaction != null && soapaction.indexOf("ConnectionManager:1#GetProtocolInfo") > -1) {
response.append(HTTPXMLHelper.XML_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.PROTOCOLINFO_RESPONSE);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
response.append(CRLF);
}
} else if (method.equals("POST") && argument.endsWith("upnp/control/content_directory")) {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml; charset=\"utf-8\"");
if (soapaction != null && soapaction.indexOf("ContentDirectory:1#GetSystemUpdateID") > -1) {
response.append(HTTPXMLHelper.XML_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.GETSYSTEMUPDATEID_HEADER);
response.append(CRLF);
response.append("<Id>").append(DLNAResource.getSystemUpdateId()).append("</Id>");
response.append(CRLF);
response.append(HTTPXMLHelper.GETSYSTEMUPDATEID_FOOTER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
response.append(CRLF);
} else if (soapaction != null && soapaction.indexOf("ContentDirectory:1#X_GetFeatureList") > -1) { // Added for Samsung 2012 TVs
response.append(HTTPXMLHelper.XML_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SAMSUNG_ERROR_RESPONSE);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
response.append(CRLF);
} else if (soapaction != null && soapaction.indexOf("ContentDirectory:1#GetSortCapabilities") > -1) {
response.append(HTTPXMLHelper.XML_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SORTCAPS_RESPONSE);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
response.append(CRLF);
} else if (soapaction != null && soapaction.indexOf("ContentDirectory:1#GetSearchCapabilities") > -1) {
response.append(HTTPXMLHelper.XML_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SEARCHCAPS_RESPONSE);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
response.append(CRLF);
} else if (soapaction != null && (soapaction.contains("ContentDirectory:1#Browse") || soapaction.contains("ContentDirectory:1#Search"))) {
objectID = getEnclosingValue(content, "<ObjectID>", "</ObjectID>");
String containerID = null;
if ((objectID == null || objectID.length() == 0)) {
containerID = getEnclosingValue(content, "<ContainerID>", "</ContainerID>");
if (containerID == null && !containerID.contains("$")) {
objectID = "0";
} else {
objectID = containerID;
containerID = null;
}
}
Object sI = getEnclosingValue(content, "<StartingIndex>", "</StartingIndex>");
Object rC = getEnclosingValue(content, "<RequestedCount>", "</RequestedCount>");
browseFlag = getEnclosingValue(content, "<BrowseFlag>", "</BrowseFlag>");
if (sI != null) {
startingIndex = Integer.parseInt(sI.toString());
}
if (rC != null) {
requestCount = Integer.parseInt(rC.toString());
}
response.append(HTTPXMLHelper.XML_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
response.append(CRLF);
if (soapaction != null && soapaction.contains("ContentDirectory:1#Search")) {
response.append(HTTPXMLHelper.SEARCHRESPONSE_HEADER);
} else {
response.append(HTTPXMLHelper.BROWSERESPONSE_HEADER);
}
response.append(CRLF);
response.append(HTTPXMLHelper.RESULT_HEADER);
response.append(HTTPXMLHelper.DIDL_HEADER);
if (soapaction != null && soapaction.contains("ContentDirectory:1#Search")) {
browseFlag = "BrowseDirectChildren";
}
// XBOX virtual containers ... d'oh!
String searchCriteria = null;
if (xbox && configuration.getUseCache() && PMS.get().getLibrary() != null && containerID != null) {
if (containerID.equals("7") && PMS.get().getLibrary().getAlbumFolder() != null) {
objectID = PMS.get().getLibrary().getAlbumFolder().getResourceId();
} else if (containerID.equals("6") && PMS.get().getLibrary().getArtistFolder() != null) {
objectID = PMS.get().getLibrary().getArtistFolder().getResourceId();
} else if (containerID.equals("5") && PMS.get().getLibrary().getGenreFolder() != null) {
objectID = PMS.get().getLibrary().getGenreFolder().getResourceId();
} else if (containerID.equals("F") && PMS.get().getLibrary().getPlaylistFolder() != null) {
objectID = PMS.get().getLibrary().getPlaylistFolder().getResourceId();
} else if (containerID.equals("4") && PMS.get().getLibrary().getAllFolder() != null) {
objectID = PMS.get().getLibrary().getAllFolder().getResourceId();
} else if (containerID.equals("1")) {
String artist = getEnclosingValue(content, "upnp:artist = "", "")");
if (artist != null) {
objectID = PMS.get().getLibrary().getArtistFolder().getResourceId();
searchCriteria = artist;
}
}
} else if (soapaction.contains("ContentDirectory:1#Search")) {
searchCriteria = getEnclosingValue(content,"<SearchCriteria>","</SearchCriteria>");
}
List<DLNAResource> files = PMS.get().getRootFolder(mediaRenderer).getDLNAResources(
objectID,
browseFlag != null && browseFlag.equals("BrowseDirectChildren"),
startingIndex,
requestCount,
mediaRenderer,
searchCriteria
);
if (searchCriteria != null && files != null) {
searchCriteria = searchCriteria.toLowerCase();
for(int i = files.size() - 1; i >= 0; i--) {
DLNAResource res = files.get(i);
if (res.isSearched()) {
continue;
}
boolean keep = res.getName().toLowerCase().indexOf(searchCriteria) != -1;
final DLNAMediaInfo media = res.getMedia();
if (media!=null) {
for (int j = 0;j < media.getAudioTracksList().size(); j++) {
DLNAMediaAudio audio = media.getAudioTracksList().get(j);
keep |= audio.getAlbum().toLowerCase().indexOf(searchCriteria) != -1;
keep |= audio.getArtist().toLowerCase().indexOf(searchCriteria) != -1;
keep |= audio.getSongname().toLowerCase().indexOf(searchCriteria) != -1;
}
}
if (!keep) { // dump it
files.remove(i);
}
}
if (xbox) {
if (files.size() > 0) {
files = files.get(0).getChildren();
}
}
}
int minus = 0;
if (files != null) {
for (DLNAResource uf : files) {
if (xbox && containerID != null) {
uf.setFakeParentId(containerID);
}
if (uf.isCompatible(mediaRenderer) && (uf.getPlayer() == null || uf.getPlayer().isPlayerCompatible(mediaRenderer))) {
response.append(uf.toString(mediaRenderer));
} else {
minus++;
}
}
}
response.append(HTTPXMLHelper.DIDL_FOOTER);
response.append(HTTPXMLHelper.RESULT_FOOTER);
response.append(CRLF);
int filessize = 0;
if (files != null) {
filessize = files.size();
}
response.append("<NumberReturned>").append(filessize - minus).append("</NumberReturned>");
response.append(CRLF);
DLNAResource parentFolder = null;
if (files != null && filessize > 0) {
parentFolder = files.get(0).getParent();
}
if (browseFlag != null && browseFlag.equals("BrowseDirectChildren") && mediaRenderer.isMediaParserV2() && mediaRenderer.isDLNATreeHack()) {
// with the new parser, files are parsed and analyzed *before* creating the DLNA tree,
// every 10 items (the ps3 asks 10 by 10),
// so we do not know exactly the total number of items in the DLNA folder to send
// (regular files, plus the #transcode folder, maybe the #imdb one, also files can be
// invalidated and hidden if format is broken or encrypted, etc.).
// let's send a fake total size to force the renderer to ask following items
int totalCount = startingIndex + requestCount + 1; // returns 11 when 10 asked
if (filessize - minus <= 0) // if no more elements, send the startingIndex
{
totalCount = startingIndex;
}
response.append("<TotalMatches>").append(totalCount).append("</TotalMatches>");
} else if (browseFlag != null && browseFlag.equals("BrowseDirectChildren")) {
response.append("<TotalMatches>").append(((parentFolder != null) ? parentFolder.childrenNumber() : filessize) - minus).append("</TotalMatches>");
} else { //from upnp spec: If BrowseMetadata is specified in the BrowseFlags then TotalMatches = 1
response.append("<TotalMatches>1</TotalMatches>");
}
response.append(CRLF);
response.append("<UpdateID>");
if (parentFolder != null) {
response.append(parentFolder.getUpdateId());
} else {
response.append("1");
}
response.append("</UpdateID>");
response.append(CRLF);
if (soapaction != null && soapaction.contains("ContentDirectory:1#Search")) {
response.append(HTTPXMLHelper.SEARCHRESPONSE_FOOTER);
} else {
response.append(HTTPXMLHelper.BROWSERESPONSE_FOOTER);
}
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
response.append(CRLF);
// LOGGER.trace(response.toString());
}
} else if (method.equals("SUBSCRIBE")) {
output.setHeader("SID", PMS.get().usn());
output.setHeader("TIMEOUT", "Second-1800");
if (soapaction != null) {
String cb = soapaction.replace("<", "").replace(">", "");
try {
URL soapActionUrl = new URL(cb);
String addr = soapActionUrl.getHost();
int port = soapActionUrl.getPort();
Socket sock = new Socket(addr,port);
OutputStream out = sock.getOutputStream();
out.write(("NOTIFY /" + argument + " HTTP/1.1").getBytes());
out.write(CRLF.getBytes());
out.write(("SID: " + PMS.get().usn()).getBytes());
out.write(CRLF.getBytes());
out.write(("SEQ: " + 0).getBytes());
out.write(CRLF.getBytes());
out.write(("NT: upnp:event").getBytes());
out.write(CRLF.getBytes());
out.write(("NTS: upnp:propchange").getBytes());
out.write(CRLF.getBytes());
out.write(("HOST: " + addr + ":" + port).getBytes());
out.write(CRLF.getBytes());
out.flush();
out.close();
} catch (MalformedURLException ex) {
LOGGER.debug("Cannot parse address and port from soap action \"" + soapaction + "\"", ex);
}
} else {
LOGGER.debug("Expected soap action in request");
}
if (argument.contains("connection_manager")) {
response.append(HTTPXMLHelper.eventHeader("urn:schemas-upnp-org:service:ConnectionManager:1"));
response.append(HTTPXMLHelper.eventProp("SinkProtocolInfo"));
response.append(HTTPXMLHelper.eventProp("SourceProtocolInfo"));
response.append(HTTPXMLHelper.eventProp("CurrentConnectionIDs"));
response.append(HTTPXMLHelper.EVENT_FOOTER);
} else if (argument.contains("content_directory")) {
response.append(HTTPXMLHelper.eventHeader("urn:schemas-upnp-org:service:ContentDirectory:1"));
response.append(HTTPXMLHelper.eventProp("TransferIDs"));
response.append(HTTPXMLHelper.eventProp("ContainerUpdateIDs"));
response.append(HTTPXMLHelper.eventProp("SystemUpdateID", "" + DLNAResource.getSystemUpdateId()));
response.append(HTTPXMLHelper.EVENT_FOOTER);
}
} else if (method.equals("NOTIFY")) {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml");
output.setHeader("NT", "upnp:event");
output.setHeader("NTS", "upnp:propchange");
output.setHeader("SID", PMS.get().usn());
output.setHeader("SEQ", "0");
response.append("<e:propertyset xmlns:e=\"urn:schemas-upnp-org:event-1-0\">");
response.append("<e:property>");
response.append("<TransferIDs></TransferIDs>");
response.append("</e:property>");
response.append("<e:property>");
response.append("<ContainerUpdateIDs></ContainerUpdateIDs>");
response.append("</e:property>");
response.append("<e:property>");
response.append("<SystemUpdateID>").append(DLNAResource.getSystemUpdateId()).append("</SystemUpdateID>");
response.append("</e:property>");
response.append("</e:propertyset>");
}
output.setHeader("Server", PMS.get().getServerName());
if (response.length() > 0) {
// A response message was constructed; convert it to data ready to be sent.
byte responseData[] = response.toString().getBytes("UTF-8");
output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "" + responseData.length);
// HEAD requests only require headers to be set, no need to set contents.
if (!method.equals("HEAD")) {
// Not a HEAD request, so set the contents of the response.
ChannelBuffer buf = ChannelBuffers.copiedBuffer(responseData);
output.setContent(buf);
}
// Send the response to the client.
future = e.getChannel().write(output);
if (close) {
// Close the channel after the response is sent.
future.addListener(ChannelFutureListener.CLOSE);
}
} else if (inputStream != null) {
// There is an input stream to send as a response.
if (CLoverride > -2) {
// Content-Length override has been set, send or omit as appropriate
if (CLoverride > -1 && CLoverride != DLNAMediaInfo.TRANS_SIZE) {
// Since PS3 firmware 2.50, it is wiser not to send an arbitrary Content-Length,
// as the PS3 will display a network error and request the last seconds of the
// transcoded video. Better to send no Content-Length at all.
output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "" + CLoverride);
}
} else {
int cl = inputStream.available();
LOGGER.trace("Available Content-Length: " + cl);
output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "" + cl);
}
if (range.isStartOffsetAvailable() && dlna != null) {
// Add timeseek information headers.
String timeseekValue = DLNAMediaInfo.getDurationString(range.getStartOrZero());
String timetotalValue = dlna.getMedia().getDurationString();
String timeEndValue = range.isEndLimitAvailable() ? DLNAMediaInfo.getDurationString(range.getEnd()) : timetotalValue;
output.setHeader("TimeSeekRange.dlna.org", "npt=" + timeseekValue + "-" + timeEndValue + "/" + timetotalValue);
output.setHeader("X-Seek-Range", "npt=" + timeseekValue + "-" + timeEndValue + "/" + timetotalValue);
}
// Send the response headers to the client.
future = e.getChannel().write(output);
if (lowRange != DLNAMediaInfo.ENDFILE_POS && !method.equals("HEAD")) {
// Send the response body to the client in chunks.
ChannelFuture chunkWriteFuture = e.getChannel().write(new ChunkedStream(inputStream, BUFFER_SIZE));
// Add a listener to clean up after sending the entire response body.
chunkWriteFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
try {
PMS.get().getRegistry().reenableGoToSleep();
inputStream.close();
} catch (IOException e) {
LOGGER.debug("Caught exception", e);
}
// Always close the channel after the response is sent because of
// a freeze at the end of video when the channel is not closed.
future.getChannel().close();
startStopListenerDelegate.stop();
}
});
} else {
// HEAD method is being used, so simply clean up after the response was sent.
try {
PMS.get().getRegistry().reenableGoToSleep();
inputStream.close();
} catch (IOException ioe) {
LOGGER.debug("Caught exception", ioe);
}
if (close) {
// Close the channel after the response is sent
future.addListener(ChannelFutureListener.CLOSE);
}
startStopListenerDelegate.stop();
}
} else {
// No response data and no input stream. Seems we are merely serving up headers.
if (lowRange > 0 && highRange > 0) {
// FIXME: There is no content, so why set a length?
output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "" + (highRange - lowRange + 1));
} else {
output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "0");
}
// Send the response headers to the client.
future = e.getChannel().write(output);
if (close) {
// Close the channel after the response is sent.
future.addListener(ChannelFutureListener.CLOSE);
}
}
// Log trace information
Iterator<String> it = output.getHeaderNames().iterator();
while (it.hasNext()) {
String headerName = it.next();
LOGGER.trace("Sent to socket: " + headerName + ": " + output.getHeader(headerName));
}
return future;
}
| public ChannelFuture answer(
HttpResponse output,
MessageEvent e,
final boolean close,
final StartStopListenerDelegate startStopListenerDelegate
) throws IOException {
ChannelFuture future = null;
long CLoverride = -2; // 0 and above are valid Content-Length values, -1 means omit
StringBuilder response = new StringBuilder();
DLNAResource dlna = null;
boolean xbox = mediaRenderer.isXBOX();
// Samsung 2012 TVs have a problematic preceding slash that needs to be removed.
if (argument.startsWith("/")) {
LOGGER.trace("Stripping preceding slash from: " + argument);
argument = argument.substring(1);
}
if ((method.equals("GET") || method.equals("HEAD")) && argument.startsWith("console/")) {
// Request to output a page to the HTML console.
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/html");
response.append(HTMLConsole.servePage(argument.substring(8)));
} else if ((method.equals("GET") || method.equals("HEAD")) && argument.startsWith("get/")) {
// Request to retrieve a file
// skip the leading "get/" and extract the
// resource ID from the first path element
// e.g. "get/0$1$5$3$4/Foo.mp4" -> "0$1$5$3$4"
String id = argument.substring(4, argument.lastIndexOf("/"));
// Some clients escape the separators in their request: unescape them.
id = id.replace("%24", "$");
// Retrieve the DLNAresource itself.
List<DLNAResource> files = PMS.get().getRootFolder(mediaRenderer).getDLNAResources(id, false, 0, 0, mediaRenderer);
if (transferMode != null) {
output.setHeader("TransferMode.DLNA.ORG", transferMode);
}
if (files.size() == 1) {
// DLNAresource was found.
dlna = files.get(0);
String fileName = argument.substring(argument.lastIndexOf("/") + 1);
if (fileName.startsWith("thumbnail0000")) {
// This is a request for a thumbnail file.
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, dlna.getThumbnailContentType());
output.setHeader(HttpHeaders.Names.ACCEPT_RANGES, "bytes");
output.setHeader(HttpHeaders.Names.EXPIRES, getFUTUREDATE() + " GMT");
output.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive");
if (mediaRenderer.isMediaParserV2()) {
dlna.checkThumbnail();
}
inputStream = dlna.getThumbnailInputStream();
} else if (fileName.indexOf("subtitle0000") > -1) {
// This is a request for a subtitle file
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
output.setHeader(HttpHeaders.Names.EXPIRES, getFUTUREDATE() + " GMT");
List<DLNAMediaSubtitle> subs = dlna.getMedia().getSubtitleTracksList();
if (subs != null && !subs.isEmpty()) {
// TODO: maybe loop subs to get the requested subtitle type instead of using the first one
DLNAMediaSubtitle sub = subs.get(0);
try {
// XXX external file is null if the first subtitle track is embedded:
// http://www.ps3mediaserver.org/forum/viewtopic.php?f=3&t=15805&p=75534#p75534
if (sub.isExternal()) {
inputStream = new java.io.FileInputStream(sub.getExternalFile());
}
} catch (NullPointerException npe) {
LOGGER.trace("Could not find external subtitles: " + sub);
}
}
} else {
// This is a request for a regular file.
// If range has not been initialized yet and the DLNAResource has its
// own start and end defined, initialize range with those values before
// requesting the input stream.
Range.Time splitRange = dlna.getSplitRange();
if (range.getStart() == null && splitRange.getStart() != null) {
range.setStart(splitRange.getStart());
}
if (range.getEnd() == null && splitRange.getEnd() != null) {
range.setEnd(splitRange.getEnd());
}
inputStream = dlna.getInputStream(Range.create(lowRange, highRange, range.getStart(), range.getEnd()), mediaRenderer);
// Some renderers (like Samsung devices) allow a custom header for a subtitle URL
String subtitleHttpHeader = mediaRenderer.getSubtitleHttpHeader();
if (subtitleHttpHeader != null && !"".equals(subtitleHttpHeader)) {
// Device allows a custom subtitle HTTP header; construct it
List<DLNAMediaSubtitle> subs = dlna.getMedia().getSubtitleTracksList();
if (subs != null && !subs.isEmpty()) {
DLNAMediaSubtitle sub = subs.get(0);
String subtitleUrl;
String subExtension = sub.getType().getExtension();
if (isNotBlank(subExtension)) {
subtitleUrl = "http://" + PMS.get().getServer().getHost() +
':' + PMS.get().getServer().getPort() + "/get/" +
id + "/subtitle0000." + subExtension;
} else {
subtitleUrl = "http://" + PMS.get().getServer().getHost() +
':' + PMS.get().getServer().getPort() + "/get/" +
id + "/subtitle0000";
}
output.setHeader(subtitleHttpHeader, subtitleUrl);
}
}
String name = dlna.getDisplayName(mediaRenderer);
if (dlna.isNoName()) {
name = dlna.getName() + " " + dlna.getDisplayName(mediaRenderer);
}
if (inputStream == null) {
// No inputStream indicates that transcoding / remuxing probably crashed.
LOGGER.error("There is no inputstream to return for " + name);
} else {
// Notify plugins that the DLNAresource is about to start playing
startStopListenerDelegate.start(dlna);
// Try to determine the content type of the file
String rendererMimeType = getRendererMimeType(dlna.mimeType(), mediaRenderer);
if (rendererMimeType != null && !"".equals(rendererMimeType)) {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, rendererMimeType);
}
PMS.get().getFrame().setStatusLine("Serving " + name);
// Response generation:
// We use -1 for arithmetic convenience but don't send it as a value.
// If Content-Length < 0 we omit it, for Content-Range we use '*' to signify unspecified.
boolean chunked = mediaRenderer.isChunkedTransfer();
// Determine the total size. Note: when transcoding the length is
// not known in advance, so DLNAMediaInfo.TRANS_SIZE will be returned instead.
long totalsize = dlna.length(mediaRenderer);
if (chunked && totalsize == DLNAMediaInfo.TRANS_SIZE) {
// In chunked mode we try to avoid arbitrary values.
totalsize = -1;
}
long remaining = totalsize - lowRange;
long requested = highRange - lowRange;
if (requested != 0) {
// Determine the range (i.e. smaller of known or requested bytes)
long bytes = remaining > -1 ? remaining : inputStream.available();
if (requested > 0 && bytes > requested) {
bytes = requested + 1;
}
// Calculate the corresponding highRange (this is usually redundant).
highRange = lowRange + bytes - (bytes > 0 ? 1 : 0);
LOGGER.trace((chunked ? "Using chunked response. " : "") + "Sending " + bytes + " bytes.");
output.setHeader(HttpHeaders.Names.CONTENT_RANGE, "bytes " + lowRange + "-" + (highRange > -1 ? highRange : "*") + "/" + (totalsize > -1 ? totalsize : "*"));
// Content-Length refers to the current chunk size here, though in chunked
// mode if the request is open-ended and totalsize is unknown we omit it.
if (chunked && requested < 0 && totalsize < 0) {
CLoverride = -1;
} else {
CLoverride = bytes;
}
} else {
// Content-Length refers to the total remaining size of the stream here.
CLoverride = remaining;
}
// Calculate the corresponding highRange (this is usually redundant).
highRange = lowRange + CLoverride - (CLoverride > 0 ? 1 : 0);
if (contentFeatures != null) {
output.setHeader("ContentFeatures.DLNA.ORG", dlna.getDlnaContentFeatures());
}
output.setHeader(HttpHeaders.Names.ACCEPT_RANGES, "bytes");
output.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive");
}
}
}
} else if ((method.equals("GET") || method.equals("HEAD")) && (argument.toLowerCase().endsWith(".png") || argument.toLowerCase().endsWith(".jpg") || argument.toLowerCase().endsWith(".jpeg"))) {
if (argument.toLowerCase().endsWith(".png")) {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "image/png");
} else {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "image/jpeg");
}
output.setHeader(HttpHeaders.Names.ACCEPT_RANGES, "bytes");
output.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive");
output.setHeader(HttpHeaders.Names.EXPIRES, getFUTUREDATE() + " GMT");
inputStream = getResourceInputStream(argument);
} else if ((method.equals("GET") || method.equals("HEAD")) && (argument.equals("description/fetch") || argument.endsWith("1.0.xml"))) {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml; charset=\"utf-8\"");
output.setHeader(HttpHeaders.Names.CACHE_CONTROL, "no-cache");
output.setHeader(HttpHeaders.Names.EXPIRES, "0");
output.setHeader(HttpHeaders.Names.ACCEPT_RANGES, "bytes");
output.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive");
inputStream = getResourceInputStream((argument.equals("description/fetch") ? "PMS.xml" : argument));
if (argument.equals("description/fetch")) {
byte b[] = new byte[inputStream.available()];
inputStream.read(b);
String s = new String(b);
s = s.replace("[uuid]", PMS.get().usn()); //.substring(0, PMS.get().usn().length()-2));
String profileName = configuration.getProfileName();
if (PMS.get().getServer().getHost() != null) {
s = s.replace("[host]", PMS.get().getServer().getHost());
s = s.replace("[port]", "" + PMS.get().getServer().getPort());
}
if (xbox) {
LOGGER.debug("DLNA changes for Xbox 360");
s = s.replace("Universal Media Server", "Universal Media Server [" + profileName + "] : Windows Media Connect");
s = s.replace("<modelName>UMS</modelName>", "<modelName>Windows Media Connect</modelName>");
s = s.replace("<serviceList>", "<serviceList>" + CRLF + "<service>" + CRLF +
"<serviceType>urn:microsoft.com:service:X_MS_MediaReceiverRegistrar:1</serviceType>" + CRLF +
"<serviceId>urn:microsoft.com:serviceId:X_MS_MediaReceiverRegistrar</serviceId>" + CRLF +
"<SCPDURL>/upnp/mrr/scpd</SCPDURL>" + CRLF +
"<controlURL>/upnp/mrr/control</controlURL>" + CRLF +
"</service>" + CRLF);
} else {
s = s.replace("Universal Media Server", "Universal Media Server [" + profileName + "]");
}
if (!mediaRenderer.isPS3()) {
// hacky stuff. replace the png icon by a jpeg one. Like mpeg2 remux,
// really need a proper format compatibility list by renderer
s = s.replace("<mimetype>image/png</mimetype>", "<mimetype>image/jpeg</mimetype>");
s = s.replace("/images/thumbnail-video-256.png", "/images/thumbnail-video-120.jpg");
s = s.replace(">256<", ">120<");
}
response.append(s);
inputStream = null;
}
} else if (method.equals("POST") && (argument.contains("MS_MediaReceiverRegistrar_control") || argument.contains("mrr/control"))) {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml; charset=\"utf-8\"");
response.append(HTTPXMLHelper.XML_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
response.append(CRLF);
if (soapaction != null && soapaction.contains("IsAuthorized")) {
response.append(HTTPXMLHelper.XBOX_2);
response.append(CRLF);
} else if (soapaction != null && soapaction.contains("IsValidated")) {
response.append(HTTPXMLHelper.XBOX_1);
response.append(CRLF);
}
response.append(HTTPXMLHelper.BROWSERESPONSE_FOOTER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
response.append(CRLF);
} else if (method.equals("POST") && argument.endsWith("upnp/control/connection_manager")) {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml; charset=\"utf-8\"");
if (soapaction != null && soapaction.indexOf("ConnectionManager:1#GetProtocolInfo") > -1) {
response.append(HTTPXMLHelper.XML_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.PROTOCOLINFO_RESPONSE);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
response.append(CRLF);
}
} else if (method.equals("POST") && argument.endsWith("upnp/control/content_directory")) {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml; charset=\"utf-8\"");
if (soapaction != null && soapaction.indexOf("ContentDirectory:1#GetSystemUpdateID") > -1) {
response.append(HTTPXMLHelper.XML_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.GETSYSTEMUPDATEID_HEADER);
response.append(CRLF);
response.append("<Id>").append(DLNAResource.getSystemUpdateId()).append("</Id>");
response.append(CRLF);
response.append(HTTPXMLHelper.GETSYSTEMUPDATEID_FOOTER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
response.append(CRLF);
} else if (soapaction != null && soapaction.indexOf("ContentDirectory:1#X_GetFeatureList") > -1) { // Added for Samsung 2012 TVs
response.append(HTTPXMLHelper.XML_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SAMSUNG_ERROR_RESPONSE);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
response.append(CRLF);
} else if (soapaction != null && soapaction.indexOf("ContentDirectory:1#GetSortCapabilities") > -1) {
response.append(HTTPXMLHelper.XML_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SORTCAPS_RESPONSE);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
response.append(CRLF);
} else if (soapaction != null && soapaction.indexOf("ContentDirectory:1#GetSearchCapabilities") > -1) {
response.append(HTTPXMLHelper.XML_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SEARCHCAPS_RESPONSE);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
response.append(CRLF);
} else if (soapaction != null && (soapaction.contains("ContentDirectory:1#Browse") || soapaction.contains("ContentDirectory:1#Search"))) {
objectID = getEnclosingValue(content, "<ObjectID>", "</ObjectID>");
String containerID = null;
if ((objectID == null || objectID.length() == 0)) {
containerID = getEnclosingValue(content, "<ContainerID>", "</ContainerID>");
if (containerID == null || !containerID.contains("$")) {
objectID = "0";
} else {
objectID = containerID;
containerID = null;
}
}
Object sI = getEnclosingValue(content, "<StartingIndex>", "</StartingIndex>");
Object rC = getEnclosingValue(content, "<RequestedCount>", "</RequestedCount>");
browseFlag = getEnclosingValue(content, "<BrowseFlag>", "</BrowseFlag>");
if (sI != null) {
startingIndex = Integer.parseInt(sI.toString());
}
if (rC != null) {
requestCount = Integer.parseInt(rC.toString());
}
response.append(HTTPXMLHelper.XML_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
response.append(CRLF);
if (soapaction != null && soapaction.contains("ContentDirectory:1#Search")) {
response.append(HTTPXMLHelper.SEARCHRESPONSE_HEADER);
} else {
response.append(HTTPXMLHelper.BROWSERESPONSE_HEADER);
}
response.append(CRLF);
response.append(HTTPXMLHelper.RESULT_HEADER);
response.append(HTTPXMLHelper.DIDL_HEADER);
if (soapaction != null && soapaction.contains("ContentDirectory:1#Search")) {
browseFlag = "BrowseDirectChildren";
}
// XBOX virtual containers ... d'oh!
String searchCriteria = null;
if (xbox && configuration.getUseCache() && PMS.get().getLibrary() != null && containerID != null) {
if (containerID.equals("7") && PMS.get().getLibrary().getAlbumFolder() != null) {
objectID = PMS.get().getLibrary().getAlbumFolder().getResourceId();
} else if (containerID.equals("6") && PMS.get().getLibrary().getArtistFolder() != null) {
objectID = PMS.get().getLibrary().getArtistFolder().getResourceId();
} else if (containerID.equals("5") && PMS.get().getLibrary().getGenreFolder() != null) {
objectID = PMS.get().getLibrary().getGenreFolder().getResourceId();
} else if (containerID.equals("F") && PMS.get().getLibrary().getPlaylistFolder() != null) {
objectID = PMS.get().getLibrary().getPlaylistFolder().getResourceId();
} else if (containerID.equals("4") && PMS.get().getLibrary().getAllFolder() != null) {
objectID = PMS.get().getLibrary().getAllFolder().getResourceId();
} else if (containerID.equals("1")) {
String artist = getEnclosingValue(content, "upnp:artist = "", "")");
if (artist != null) {
objectID = PMS.get().getLibrary().getArtistFolder().getResourceId();
searchCriteria = artist;
}
}
} else if (soapaction.contains("ContentDirectory:1#Search")) {
searchCriteria = getEnclosingValue(content,"<SearchCriteria>","</SearchCriteria>");
}
List<DLNAResource> files = PMS.get().getRootFolder(mediaRenderer).getDLNAResources(
objectID,
browseFlag != null && browseFlag.equals("BrowseDirectChildren"),
startingIndex,
requestCount,
mediaRenderer,
searchCriteria
);
if (searchCriteria != null && files != null) {
searchCriteria = searchCriteria.toLowerCase();
for(int i = files.size() - 1; i >= 0; i--) {
DLNAResource res = files.get(i);
if (res.isSearched()) {
continue;
}
boolean keep = res.getName().toLowerCase().indexOf(searchCriteria) != -1;
final DLNAMediaInfo media = res.getMedia();
if (media!=null) {
for (int j = 0;j < media.getAudioTracksList().size(); j++) {
DLNAMediaAudio audio = media.getAudioTracksList().get(j);
keep |= audio.getAlbum().toLowerCase().indexOf(searchCriteria) != -1;
keep |= audio.getArtist().toLowerCase().indexOf(searchCriteria) != -1;
keep |= audio.getSongname().toLowerCase().indexOf(searchCriteria) != -1;
}
}
if (!keep) { // dump it
files.remove(i);
}
}
if (xbox) {
if (files.size() > 0) {
files = files.get(0).getChildren();
}
}
}
int minus = 0;
if (files != null) {
for (DLNAResource uf : files) {
if (xbox && containerID != null) {
uf.setFakeParentId(containerID);
}
if (uf.isCompatible(mediaRenderer) && (uf.getPlayer() == null || uf.getPlayer().isPlayerCompatible(mediaRenderer))) {
response.append(uf.toString(mediaRenderer));
} else {
minus++;
}
}
}
response.append(HTTPXMLHelper.DIDL_FOOTER);
response.append(HTTPXMLHelper.RESULT_FOOTER);
response.append(CRLF);
int filessize = 0;
if (files != null) {
filessize = files.size();
}
response.append("<NumberReturned>").append(filessize - minus).append("</NumberReturned>");
response.append(CRLF);
DLNAResource parentFolder = null;
if (files != null && filessize > 0) {
parentFolder = files.get(0).getParent();
}
if (browseFlag != null && browseFlag.equals("BrowseDirectChildren") && mediaRenderer.isMediaParserV2() && mediaRenderer.isDLNATreeHack()) {
// with the new parser, files are parsed and analyzed *before* creating the DLNA tree,
// every 10 items (the ps3 asks 10 by 10),
// so we do not know exactly the total number of items in the DLNA folder to send
// (regular files, plus the #transcode folder, maybe the #imdb one, also files can be
// invalidated and hidden if format is broken or encrypted, etc.).
// let's send a fake total size to force the renderer to ask following items
int totalCount = startingIndex + requestCount + 1; // returns 11 when 10 asked
if (filessize - minus <= 0) // if no more elements, send the startingIndex
{
totalCount = startingIndex;
}
response.append("<TotalMatches>").append(totalCount).append("</TotalMatches>");
} else if (browseFlag != null && browseFlag.equals("BrowseDirectChildren")) {
response.append("<TotalMatches>").append(((parentFolder != null) ? parentFolder.childrenNumber() : filessize) - minus).append("</TotalMatches>");
} else { //from upnp spec: If BrowseMetadata is specified in the BrowseFlags then TotalMatches = 1
response.append("<TotalMatches>1</TotalMatches>");
}
response.append(CRLF);
response.append("<UpdateID>");
if (parentFolder != null) {
response.append(parentFolder.getUpdateId());
} else {
response.append("1");
}
response.append("</UpdateID>");
response.append(CRLF);
if (soapaction != null && soapaction.contains("ContentDirectory:1#Search")) {
response.append(HTTPXMLHelper.SEARCHRESPONSE_FOOTER);
} else {
response.append(HTTPXMLHelper.BROWSERESPONSE_FOOTER);
}
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
response.append(CRLF);
// LOGGER.trace(response.toString());
}
} else if (method.equals("SUBSCRIBE")) {
output.setHeader("SID", PMS.get().usn());
output.setHeader("TIMEOUT", "Second-1800");
if (soapaction != null) {
String cb = soapaction.replace("<", "").replace(">", "");
try {
URL soapActionUrl = new URL(cb);
String addr = soapActionUrl.getHost();
int port = soapActionUrl.getPort();
Socket sock = new Socket(addr,port);
OutputStream out = sock.getOutputStream();
out.write(("NOTIFY /" + argument + " HTTP/1.1").getBytes());
out.write(CRLF.getBytes());
out.write(("SID: " + PMS.get().usn()).getBytes());
out.write(CRLF.getBytes());
out.write(("SEQ: " + 0).getBytes());
out.write(CRLF.getBytes());
out.write(("NT: upnp:event").getBytes());
out.write(CRLF.getBytes());
out.write(("NTS: upnp:propchange").getBytes());
out.write(CRLF.getBytes());
out.write(("HOST: " + addr + ":" + port).getBytes());
out.write(CRLF.getBytes());
out.flush();
out.close();
} catch (MalformedURLException ex) {
LOGGER.debug("Cannot parse address and port from soap action \"" + soapaction + "\"", ex);
}
} else {
LOGGER.debug("Expected soap action in request");
}
if (argument.contains("connection_manager")) {
response.append(HTTPXMLHelper.eventHeader("urn:schemas-upnp-org:service:ConnectionManager:1"));
response.append(HTTPXMLHelper.eventProp("SinkProtocolInfo"));
response.append(HTTPXMLHelper.eventProp("SourceProtocolInfo"));
response.append(HTTPXMLHelper.eventProp("CurrentConnectionIDs"));
response.append(HTTPXMLHelper.EVENT_FOOTER);
} else if (argument.contains("content_directory")) {
response.append(HTTPXMLHelper.eventHeader("urn:schemas-upnp-org:service:ContentDirectory:1"));
response.append(HTTPXMLHelper.eventProp("TransferIDs"));
response.append(HTTPXMLHelper.eventProp("ContainerUpdateIDs"));
response.append(HTTPXMLHelper.eventProp("SystemUpdateID", "" + DLNAResource.getSystemUpdateId()));
response.append(HTTPXMLHelper.EVENT_FOOTER);
}
} else if (method.equals("NOTIFY")) {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml");
output.setHeader("NT", "upnp:event");
output.setHeader("NTS", "upnp:propchange");
output.setHeader("SID", PMS.get().usn());
output.setHeader("SEQ", "0");
response.append("<e:propertyset xmlns:e=\"urn:schemas-upnp-org:event-1-0\">");
response.append("<e:property>");
response.append("<TransferIDs></TransferIDs>");
response.append("</e:property>");
response.append("<e:property>");
response.append("<ContainerUpdateIDs></ContainerUpdateIDs>");
response.append("</e:property>");
response.append("<e:property>");
response.append("<SystemUpdateID>").append(DLNAResource.getSystemUpdateId()).append("</SystemUpdateID>");
response.append("</e:property>");
response.append("</e:propertyset>");
}
output.setHeader("Server", PMS.get().getServerName());
if (response.length() > 0) {
// A response message was constructed; convert it to data ready to be sent.
byte responseData[] = response.toString().getBytes("UTF-8");
output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "" + responseData.length);
// HEAD requests only require headers to be set, no need to set contents.
if (!method.equals("HEAD")) {
// Not a HEAD request, so set the contents of the response.
ChannelBuffer buf = ChannelBuffers.copiedBuffer(responseData);
output.setContent(buf);
}
// Send the response to the client.
future = e.getChannel().write(output);
if (close) {
// Close the channel after the response is sent.
future.addListener(ChannelFutureListener.CLOSE);
}
} else if (inputStream != null) {
// There is an input stream to send as a response.
if (CLoverride > -2) {
// Content-Length override has been set, send or omit as appropriate
if (CLoverride > -1 && CLoverride != DLNAMediaInfo.TRANS_SIZE) {
// Since PS3 firmware 2.50, it is wiser not to send an arbitrary Content-Length,
// as the PS3 will display a network error and request the last seconds of the
// transcoded video. Better to send no Content-Length at all.
output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "" + CLoverride);
}
} else {
int cl = inputStream.available();
LOGGER.trace("Available Content-Length: " + cl);
output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "" + cl);
}
if (range.isStartOffsetAvailable() && dlna != null) {
// Add timeseek information headers.
String timeseekValue = DLNAMediaInfo.getDurationString(range.getStartOrZero());
String timetotalValue = dlna.getMedia().getDurationString();
String timeEndValue = range.isEndLimitAvailable() ? DLNAMediaInfo.getDurationString(range.getEnd()) : timetotalValue;
output.setHeader("TimeSeekRange.dlna.org", "npt=" + timeseekValue + "-" + timeEndValue + "/" + timetotalValue);
output.setHeader("X-Seek-Range", "npt=" + timeseekValue + "-" + timeEndValue + "/" + timetotalValue);
}
// Send the response headers to the client.
future = e.getChannel().write(output);
if (lowRange != DLNAMediaInfo.ENDFILE_POS && !method.equals("HEAD")) {
// Send the response body to the client in chunks.
ChannelFuture chunkWriteFuture = e.getChannel().write(new ChunkedStream(inputStream, BUFFER_SIZE));
// Add a listener to clean up after sending the entire response body.
chunkWriteFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
try {
PMS.get().getRegistry().reenableGoToSleep();
inputStream.close();
} catch (IOException e) {
LOGGER.debug("Caught exception", e);
}
// Always close the channel after the response is sent because of
// a freeze at the end of video when the channel is not closed.
future.getChannel().close();
startStopListenerDelegate.stop();
}
});
} else {
// HEAD method is being used, so simply clean up after the response was sent.
try {
PMS.get().getRegistry().reenableGoToSleep();
inputStream.close();
} catch (IOException ioe) {
LOGGER.debug("Caught exception", ioe);
}
if (close) {
// Close the channel after the response is sent
future.addListener(ChannelFutureListener.CLOSE);
}
startStopListenerDelegate.stop();
}
} else {
// No response data and no input stream. Seems we are merely serving up headers.
if (lowRange > 0 && highRange > 0) {
// FIXME: There is no content, so why set a length?
output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "" + (highRange - lowRange + 1));
} else {
output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "0");
}
// Send the response headers to the client.
future = e.getChannel().write(output);
if (close) {
// Close the channel after the response is sent.
future.addListener(ChannelFutureListener.CLOSE);
}
}
// Log trace information
Iterator<String> it = output.getHeaderNames().iterator();
while (it.hasNext()) {
String headerName = it.next();
LOGGER.trace("Sent to socket: " + headerName + ": " + output.getHeader(headerName));
}
return future;
}
|
diff --git a/server/src/main/java/org/uiautomation/ios/wkrdp/model/RemoteWebNativeBackedElement.java b/server/src/main/java/org/uiautomation/ios/wkrdp/model/RemoteWebNativeBackedElement.java
index 30894798..0c87938f 100644
--- a/server/src/main/java/org/uiautomation/ios/wkrdp/model/RemoteWebNativeBackedElement.java
+++ b/server/src/main/java/org/uiautomation/ios/wkrdp/model/RemoteWebNativeBackedElement.java
@@ -1,307 +1,308 @@
/*
* Copyright 2012-2013 eBay Software Foundation and ios-driver committers
*
* 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.uiautomation.ios.wkrdp.model;
import com.google.common.collect.ImmutableList;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebDriverException;
import org.uiautomation.ios.IOSCapabilities;
import org.uiautomation.ios.UIAModels.UIAElement;
import org.uiautomation.ios.UIAModels.UIAScrollView;
import org.uiautomation.ios.UIAModels.UIAWebView;
import org.uiautomation.ios.UIAModels.predicate.AndCriteria;
import org.uiautomation.ios.UIAModels.predicate.Criteria;
import org.uiautomation.ios.UIAModels.predicate.LabelCriteria;
import org.uiautomation.ios.UIAModels.predicate.NameCriteria;
import org.uiautomation.ios.UIAModels.predicate.OrCriteria;
import org.uiautomation.ios.UIAModels.predicate.TypeCriteria;
import org.uiautomation.ios.client.uiamodels.impl.RemoteIOSDriver;
import org.uiautomation.ios.communication.device.DeviceType;
import org.uiautomation.ios.context.BaseWebInspector;
import org.uiautomation.ios.server.ServerSideSession;
import org.uiautomation.ios.server.application.ContentResult;
import org.uiautomation.ios.utils.IOSVersion;
import org.uiautomation.ios.utils.XPath2Engine;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
public class RemoteWebNativeBackedElement extends RemoteWebElement {
private static final Logger log = Logger.getLogger(RemoteWebNativeBackedElement.class.getName());
private final ServerSideSession session;
private final RemoteIOSDriver nativeDriver;
private final List<Character> specialKeys = new ArrayList<Character>() {{
this.add(Keys.DELETE.toString().charAt(0));
this.add(Keys.ENTER.toString().charAt(0));
this.add(Keys.RETURN.toString().charAt(0));
this.add(Keys.SHIFT.toString().charAt(0));
}};
public RemoteWebNativeBackedElement(NodeId id, BaseWebInspector inspector,
ServerSideSession session) {
super(id, inspector);
this.session = session;
this.nativeDriver = session.getDualDriver().getNativeDriver();
}
private static String normalizeDateValue(String value) {
// convert MM/DD/YYYY to YYYY-MM-DD
int sep1 = value.indexOf('/');
int sep2 = value.lastIndexOf('/');
if (sep1 == -1 || sep2 == -1)
return value;
String mm = value.substring(0, sep1);
String dd = value.substring(sep1 + 1, sep2);
String yyyy = value.substring(sep2 + 1);
return yyyy + '-' + to2CharDateDigit(mm) + '-' + to2CharDateDigit(dd);
}
private static String to2CharDateDigit(String text) {
return (text.length() == 1) ? '0' + text : text;
}
private boolean isSafari() {
return session.getApplication().isSafari();
}
public void nativeClick() {
if ("option".equalsIgnoreCase(getTagName())) {
click();
} else {
try {
((JavascriptExecutor) nativeDriver).executeScript(getNativeElementClickOnIt());
getInspector().checkForPageLoad();
} catch (Exception e) {
throw new WebDriverException(e);
}
}
}
@Override
public Point getLocation()
throws Exception {
// web stuff.
//scrollIntoViewIfNeeded();
Point po = findPosition();
Dimension dim = getInspector().getSize();
int webPageWidth = getInspector().getInnerWidth();
if (dim.getWidth() != webPageWidth) {
log.fine("BUG : dim.getWidth()!=webPageWidth");
}
Criteria c = new TypeCriteria(UIAWebView.class);
String json = c.stringify().toString();
StringBuilder script = new StringBuilder();
script.append("var root = UIAutomation.cache.get('1');");
script.append("var webview = root.element(-1," + json + ");");
script.append("var webviewSize = webview.rect();");
script.append("var ratio = webviewSize.size.width / " + dim.getWidth() + ";");
int top = po.getY();
int left = po.getX();
// switch +1 to +2 in next, with +1 some clicks in text fields didn't bring up the
// keyboard, the text field would get focus, but the keyboard would not launch
// also with this change 17 miscellaneous selenium tests got fixed
script.append("var top = (" + top + "*ratio)+2;");
script.append("var left = (" + left + "*ratio)+2;");
script.append("var x = left;");
boolean ipad = session.getCapabilities().getDevice() == DeviceType.ipad;
boolean ios7 = new IOSVersion(session.getCapabilities().getSDKVersion()).isGreaterOrEqualTo("7.0");
if (isSafari()) {
if (ios7) {
script.append("var orientation = UIATarget.localTarget().deviceOrientation();");
- script.append("var landscape = orientation == UIA_DEVICE_ORIENTATION_LANDSCAPELEFT || orientation == UIA_DEVICE_ORIENTATION_LANDSCAPERIGHT;");
+ script.append("var plus = orientation == UIA_DEVICE_ORIENTATION_LANDSCAPELEFT || orientation == UIA_DEVICE_ORIENTATION_PORTRAIT_UPSIDEDOWN;");
// TODO: why is the webView shifted by 20
- script.append("var y = webviewSize.origin.y + (landscape? 20 : -20) + top;");
+ script.append("var y = webviewSize.origin.y + (plus? 20 : -20) + top;");
} else {
if (ipad) {
// for ipad, the adress bar h is fixed @ 96px.
script.append("var y = top+96;");
} else {
ImmutableList<ContentResult> results =
session.getApplication().getCurrentDictionary().getPotentialMatches("Address");
if (results.size() != 1) {
log.warning("translation returned " + results.size());
}
ContentResult result = results.get(0);
String addressL10ned = result.getL10nFormatted();
Criteria
c2 =
new AndCriteria(new TypeCriteria(UIAElement.class), new NameCriteria(addressL10ned),
new LabelCriteria(addressL10ned));
script.append("var addressBar = root.element(-1," + c2.stringify().toString() + ");");
script.append("var addressBarSize = addressBar.rect();");
script.append("var delta = addressBarSize.origin.y +39;");
script.append("if (delta<20){delta=20;};");
script.append("var y = top+delta;");
}
}
} else {
Criteria wv = new TypeCriteria(UIAScrollView.class);
script.append("var webview = root.element(-1," + wv.stringify().toString() + ");");
script.append("var size = webview.rect();");
script.append("var offsetY = size.origin.y;");
// UIAWebView.y
script.append("var y = top+offsetY;");
//script.append("var y = top+64;");
}
- script.append("return new Array(parseInt(x), parseInt(y));");
+ script.append("return new Array(parseInt(x), parseInt(y), parseInt(top));");
Object response = ((JavascriptExecutor) nativeDriver).executeScript(String.valueOf(script));
int x = ((ArrayList<Long>) response).get(0).intValue();
int y = ((ArrayList<Long>) response).get(1).intValue();
+ top = ((ArrayList<Long>) response).get(2).intValue();
return new Point(x, y);
}
private String getNativeElementClickOnIt() throws Exception {
// web stuff.
scrollIntoViewIfNeeded();
Point location = getLocation();
return "UIATarget.localTarget().tap({'x':" + location.getX() + ",'y':" + location.getY() + "});";
}
private String getKeyboardTypeStringSegement(String value) {
StringBuilder script = new StringBuilder();
script.append("keyboard.typeString('");
// got to love java...
// first replacing a \ (backslash) with \\ (double backslash)
// and then ' (single quote) with \' (backslash, single quote)
script.append(value.replaceAll("\\\\", "\\\\\\\\").replaceAll("'", "\\\\'"));
script.append("');");
return script.toString();
}
private String getReferenceToTapByXpath(XPath2Engine xPath2Engine, String xpath) {
StringBuilder script = new StringBuilder();
script.append("UIAutomation.cache.get(");
script.append(xPath2Engine.findElementByXpath(xpath).get("ELEMENT"));
script.append(", false).tap();");
return script.toString();
}
// TODO freynaud use keyboard.js bot.Keyboard.prototype.moveCursor = function(element)
private String getNativeElementClickOnItAndTypeUsingKeyboardScript(String value)
throws Exception {
StringBuilder script = new StringBuilder();
script.append("var keyboard = UIAutomation.cache.get('1').keyboard();");
Boolean keyboardResigned = false;
boolean ios7 = new IOSVersion(session.getCapabilities().getSDKVersion()).isGreaterOrEqualTo("7.0");
StringBuilder current = new StringBuilder();
XPath2Engine xpathEngine = null;
for (int i = 0; i < value.length(); i++) {
int idx = specialKeys.indexOf(value.charAt(i));
if (idx >= 0) {
if (xpathEngine == null) {
xpathEngine = XPath2Engine.getXpath2Engine(nativeDriver);
}
if (current.length() > 0) {
script.append(getKeyboardTypeStringSegement(current.toString()));
current = new StringBuilder();
}
switch (idx) {
case 0:
// DELETE
// TODO, i don't like this xpath... should find the key in a better way
// (like keyboard.shift)
script.append(getReferenceToTapByXpath(xpathEngine, "//UIAKeyboard/UIAKey[" +
( nativeDriver.getCapabilities().getDevice() == DeviceType.ipad ?
(ios7? "13" : "11") : (ios7? "last()-2" : "last()-3")) + ']'
));
break;
case 1:
case 2:
// ENTER / RETURN
// TODO another smelly xpath.
script.append(getReferenceToTapByXpath(xpathEngine, "//UIAKeyboard/UIAButton[" +
( nativeDriver.getCapabilities().getDevice() == DeviceType.ipad ?
"1" : (ios7? "4" : "2")) + ']'
));
keyboardResigned = true;
break;
case 3:
// SHIFT
script.append("keyboard.shift();");
break;
default:
throw new RuntimeException("Special key found in the list but not taken care of??");
}
} else {
current.append(value.charAt(i));
}
}
if (current.length() > 0) {
script.append(getKeyboardTypeStringSegement(current.toString()));
}
if (!keyboardResigned) {
script.append("keyboard.hide();");
}
return script.toString();
}
public void setValueNative(String value) throws Exception {
String type = getAttribute("type");
if ("date".equalsIgnoreCase(type)) {
value = normalizeDateValue(value);
setValueAtoms(value);
return;
}
// iphone on telephone inputs only shows the keypad keyboard.
if ("tel".equalsIgnoreCase(type) && nativeDriver.getCapabilities().getDevice() == DeviceType.iphone) {
value = replaceLettersWithNumbersKeypad(value,
(String) nativeDriver.getCapabilities()
.getCapability(IOSCapabilities.LOCALE));
}
((JavascriptExecutor) nativeDriver)
.executeScript(getNativeElementClickOnIt());
Thread.sleep(750);
setCursorAtTheEnd();
((JavascriptExecutor) nativeDriver)
.executeScript(getNativeElementClickOnItAndTypeUsingKeyboardScript(value));
}
// TODO actually handle more locales
private static String replaceLettersWithNumbersKeypad(String str, String locale) {
if (locale.toLowerCase().startsWith("en")) {
return str.replaceAll("[AaBbCc]", "2").replaceAll("[DdEeFf]", "3").replaceAll("[GgHhIi]", "4")
.replaceAll("[JjKkLl]", "5").replaceAll("[MmNnOo]", "6").replaceAll("[PpQqRrSs]", "7")
.replaceAll("[TtUuVv]", "8").replaceAll("[WwXxYyZz]", "9").replaceAll("-", "");
}
return str.replaceAll("-", "");
}
}
| false | true | public Point getLocation()
throws Exception {
// web stuff.
//scrollIntoViewIfNeeded();
Point po = findPosition();
Dimension dim = getInspector().getSize();
int webPageWidth = getInspector().getInnerWidth();
if (dim.getWidth() != webPageWidth) {
log.fine("BUG : dim.getWidth()!=webPageWidth");
}
Criteria c = new TypeCriteria(UIAWebView.class);
String json = c.stringify().toString();
StringBuilder script = new StringBuilder();
script.append("var root = UIAutomation.cache.get('1');");
script.append("var webview = root.element(-1," + json + ");");
script.append("var webviewSize = webview.rect();");
script.append("var ratio = webviewSize.size.width / " + dim.getWidth() + ";");
int top = po.getY();
int left = po.getX();
// switch +1 to +2 in next, with +1 some clicks in text fields didn't bring up the
// keyboard, the text field would get focus, but the keyboard would not launch
// also with this change 17 miscellaneous selenium tests got fixed
script.append("var top = (" + top + "*ratio)+2;");
script.append("var left = (" + left + "*ratio)+2;");
script.append("var x = left;");
boolean ipad = session.getCapabilities().getDevice() == DeviceType.ipad;
boolean ios7 = new IOSVersion(session.getCapabilities().getSDKVersion()).isGreaterOrEqualTo("7.0");
if (isSafari()) {
if (ios7) {
script.append("var orientation = UIATarget.localTarget().deviceOrientation();");
script.append("var landscape = orientation == UIA_DEVICE_ORIENTATION_LANDSCAPELEFT || orientation == UIA_DEVICE_ORIENTATION_LANDSCAPERIGHT;");
// TODO: why is the webView shifted by 20
script.append("var y = webviewSize.origin.y + (landscape? 20 : -20) + top;");
} else {
if (ipad) {
// for ipad, the adress bar h is fixed @ 96px.
script.append("var y = top+96;");
} else {
ImmutableList<ContentResult> results =
session.getApplication().getCurrentDictionary().getPotentialMatches("Address");
if (results.size() != 1) {
log.warning("translation returned " + results.size());
}
ContentResult result = results.get(0);
String addressL10ned = result.getL10nFormatted();
Criteria
c2 =
new AndCriteria(new TypeCriteria(UIAElement.class), new NameCriteria(addressL10ned),
new LabelCriteria(addressL10ned));
script.append("var addressBar = root.element(-1," + c2.stringify().toString() + ");");
script.append("var addressBarSize = addressBar.rect();");
script.append("var delta = addressBarSize.origin.y +39;");
script.append("if (delta<20){delta=20;};");
script.append("var y = top+delta;");
}
}
} else {
Criteria wv = new TypeCriteria(UIAScrollView.class);
script.append("var webview = root.element(-1," + wv.stringify().toString() + ");");
script.append("var size = webview.rect();");
script.append("var offsetY = size.origin.y;");
// UIAWebView.y
script.append("var y = top+offsetY;");
//script.append("var y = top+64;");
}
script.append("return new Array(parseInt(x), parseInt(y));");
Object response = ((JavascriptExecutor) nativeDriver).executeScript(String.valueOf(script));
int x = ((ArrayList<Long>) response).get(0).intValue();
int y = ((ArrayList<Long>) response).get(1).intValue();
return new Point(x, y);
}
| public Point getLocation()
throws Exception {
// web stuff.
//scrollIntoViewIfNeeded();
Point po = findPosition();
Dimension dim = getInspector().getSize();
int webPageWidth = getInspector().getInnerWidth();
if (dim.getWidth() != webPageWidth) {
log.fine("BUG : dim.getWidth()!=webPageWidth");
}
Criteria c = new TypeCriteria(UIAWebView.class);
String json = c.stringify().toString();
StringBuilder script = new StringBuilder();
script.append("var root = UIAutomation.cache.get('1');");
script.append("var webview = root.element(-1," + json + ");");
script.append("var webviewSize = webview.rect();");
script.append("var ratio = webviewSize.size.width / " + dim.getWidth() + ";");
int top = po.getY();
int left = po.getX();
// switch +1 to +2 in next, with +1 some clicks in text fields didn't bring up the
// keyboard, the text field would get focus, but the keyboard would not launch
// also with this change 17 miscellaneous selenium tests got fixed
script.append("var top = (" + top + "*ratio)+2;");
script.append("var left = (" + left + "*ratio)+2;");
script.append("var x = left;");
boolean ipad = session.getCapabilities().getDevice() == DeviceType.ipad;
boolean ios7 = new IOSVersion(session.getCapabilities().getSDKVersion()).isGreaterOrEqualTo("7.0");
if (isSafari()) {
if (ios7) {
script.append("var orientation = UIATarget.localTarget().deviceOrientation();");
script.append("var plus = orientation == UIA_DEVICE_ORIENTATION_LANDSCAPELEFT || orientation == UIA_DEVICE_ORIENTATION_PORTRAIT_UPSIDEDOWN;");
// TODO: why is the webView shifted by 20
script.append("var y = webviewSize.origin.y + (plus? 20 : -20) + top;");
} else {
if (ipad) {
// for ipad, the adress bar h is fixed @ 96px.
script.append("var y = top+96;");
} else {
ImmutableList<ContentResult> results =
session.getApplication().getCurrentDictionary().getPotentialMatches("Address");
if (results.size() != 1) {
log.warning("translation returned " + results.size());
}
ContentResult result = results.get(0);
String addressL10ned = result.getL10nFormatted();
Criteria
c2 =
new AndCriteria(new TypeCriteria(UIAElement.class), new NameCriteria(addressL10ned),
new LabelCriteria(addressL10ned));
script.append("var addressBar = root.element(-1," + c2.stringify().toString() + ");");
script.append("var addressBarSize = addressBar.rect();");
script.append("var delta = addressBarSize.origin.y +39;");
script.append("if (delta<20){delta=20;};");
script.append("var y = top+delta;");
}
}
} else {
Criteria wv = new TypeCriteria(UIAScrollView.class);
script.append("var webview = root.element(-1," + wv.stringify().toString() + ");");
script.append("var size = webview.rect();");
script.append("var offsetY = size.origin.y;");
// UIAWebView.y
script.append("var y = top+offsetY;");
//script.append("var y = top+64;");
}
script.append("return new Array(parseInt(x), parseInt(y), parseInt(top));");
Object response = ((JavascriptExecutor) nativeDriver).executeScript(String.valueOf(script));
int x = ((ArrayList<Long>) response).get(0).intValue();
int y = ((ArrayList<Long>) response).get(1).intValue();
top = ((ArrayList<Long>) response).get(2).intValue();
return new Point(x, y);
}
|
diff --git a/core/src/processing/core/PApplet.java b/core/src/processing/core/PApplet.java
index bbde1fcef..5b0107c2c 100755
--- a/core/src/processing/core/PApplet.java
+++ b/core/src/processing/core/PApplet.java
@@ -1,15710 +1,15710 @@
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2012-13 The Processing Foundation
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.JFrame;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileSystemView;
/**
* 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 & 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 (checkRetina()) {
// 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();
}
private boolean checkRetina() {
if (platform == MACOSX) {
// This should probably be reset each time there's a display change.
// A 5-minute search didn't turn up any such event in the Java API.
// Also, should we use the Toolkit associated with the editor window?
final String javaVendor = System.getProperty("java.vendor");
if (javaVendor.contains("Apple")) {
Float prop = (Float)
getToolkit().getDesktopProperty("apple.awt.contentScaleFactor");
if (prop != null) {
return prop == 2;
}
} else if (javaVendor.contains("Oracle")) {
String version = System.getProperty("java.version"); // 1.7.0_40
String[] m = match(version, "1.(\\d).*_(\\d+)");
// Make sure this is Oracle Java 7u40 or later
if (m != null &&
PApplet.parseInt(m[1]) >= 7 &&
PApplet.parseInt(m[1]) >= 40) {
GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice device = env.getDefaultScreenDevice();
try {
Field field = device.getClass().getDeclaredField("scale");
if (field != null) {
field.setAccessible(true);
Object scale = field.get(device);
if (scale instanceof Integer && ((Integer)scale).intValue() == 2) {
return true;
}
}
} catch (Exception ignore) { }
}
}
}
return false;
}
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 → 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();
// For 2.0, pass this to the renderer, to lend a hand to OpenGL
g.requestFocus();
}
});
}
// 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 data to print to console
* @see PApplet#println()
* @see PApplet#printArray(Object)
* @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();
}
/**
* @param variables list of data, separated by commas
*/
static public void print(Object... variables) {
StringBuilder sb = new StringBuilder();
for (Object o : variables) {
if (sb.length() != 0) {
sb.append(" ");
}
if (o == null) {
sb.append("null");
} else {
sb.append(o.toString());
}
}
System.out.print(sb.toString());
}
/*
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)
* @see PApplet#printArray(Object)
*/
static public void println() {
System.out.println();
}
/**
* @param what data to print to console
*/
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();
}
/**
* @param variables list of data, separated by commas
*/
static public void println(Object... variables) {
// System.out.println("got " + variables.length + " variables");
print(variables);
println();
}
/*
// Breaking this out since the compiler doesn't know the difference between
// Object... and just Object (with an array passed in). This should take care
// of the confusion for at least the most common case (a String array).
// On second thought, we're going the printArray() route, since the other
// object types are also used frequently.
static public void println(String[] array) {
for (int i = 0; i < array.length; i++) {
System.out.println("[" + i + "] \"" + array[i] + "\"");
}
System.out.flush();
}
*/
/**
* For arrays, use printArray() instead. This function causes a warning
* because the new print(Object...) and println(Object...) functions can't
* be reliably bound by the compiler.
*/
static public void println(Object what) {
if (what != null && what.getClass().isArray()) {
printArray(what);
} else {
System.out.println(what.toString());
System.out.flush();
}
}
/**
* ( begin auto-generated from printArray.xml )
*
* To come...
*
* ( end auto-generated )
* @webref output:text_area
* @param what one-dimensional array
* @usage IDE
* @see PApplet#print(byte)
* @see PApplet#println()
*/
static public void printArray(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° = 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° = 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).
* <p>
* A version of this function is in MovieMaker.java. Any fixes here
* should be applied over in MovieMaker as well.
* <p>
* Known issue with RLE encoding and odd behavior in some apps:
* https://github.com/processing/processing/issues/2096
* Please help!
*/
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) - Run-length 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);
// return new XML(createInput(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 input: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));
}
static public JSONObject loadJSONObject(File file) {
return new JSONObject(createReader(file));
}
/**
* @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 input: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));
}
static public JSONArray loadJSONArray(File file) {
return new JSONArray(createReader(file));
}
/**
* @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);
}
/**
* Options may contain "header", "tsv", "csv", or "bin" separated by commas.
*
* Another option is "dictionary=filename.tsv", which allows users to
* specify a "dictionary" file that contains a mapping of the column titles
* and the data types used in the table file. This can be far more efficient
* (in terms of speed and memory usage) for loading and parsing tables. The
* dictionary file can only be tab separated values (.tsv) and its extension
* will be ignored. This option was added in Processing 2.0.2.
*/
public Table loadTable(String filename, String options) {
try {
String optionStr = Table.extensionOptions(true, filename, options);
String[] optionList = trim(split(optionStr, ','));
Table dictionary = null;
for (String opt : optionList) {
if (opt.startsWith("dictionary=")) {
dictionary = loadTable(opt.substring(opt.indexOf('=') + 1), "tsv");
return dictionary.typedParse(createInput(filename), optionStr);
}
}
return new Table(createInput(filename), optionStr);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
- * @webref input:files
+ * @webref output: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));
}
static File desktopFolder;
/** Not a supported function. For testing use only. */
static public File desktopFile(String what) {
if (desktopFolder == null) {
// Should work on Linux and OS X (on OS X, even with the localized version).
desktopFolder = new File(System.getProperty("user.home"), "Desktop");
if (!desktopFolder.exists()) {
if (platform == WINDOWS) {
FileSystemView filesys = FileSystemView.getFileSystemView();
desktopFolder = filesys.getHomeDirectory();
} else {
throw new UnsupportedOperationException("Could not find a suitable desktop foldder");
}
}
}
return new File(desktopFolder, what);
}
/** Not a supported function. For testing use only. */
static public String desktopPath(String what) {
return desktopFile(what).getAbsolutePath();
}
/**
* 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/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/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");
System.out.println(dataFolder);
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/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();
// JFrame (unlike java.awt.Frame) doesn't include the left/top
// insets for placement (though it does seem to need them for
// overall size of the window. Perhaps JFrame sets its coord
// system so that (0, 0) is always the upper-left of the content
// area. Which seems nice, but breaks any f*ing AWT-based code.
Rectangle newBounds =
new Rectangle(0, 0, //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);
revalidate(); // let the layout manager do its work
}
}
}
}
});
}
// /**
// * 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();
}
// Using a JFrame fixes a Windows problem with Present mode. This might
// be our error, but usually this is the sort of crap we usually get from
// OS X. It's time for a turnaround: Redmond is thinking different too!
// https://github.com/processing/processing/issues/1955
Frame frame = new JFrame(displayDevice.getDefaultConfiguration());
// Default Processing gray, which will be replaced below if another
// color is specified on the command line (i.e. in the prefs).
final Color defaultGray = new Color(0xCC, 0xCC, 0xCC);
((JFrame) frame).getContentPane().setBackground(defaultGray);
// Cannot call setResizable(false) until later due to OS X (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();
// }
// Tried to use this to fix the 'present' mode issue.
// Did not help, and the screenRect setup seems to work fine.
//frame.setExtendedState(Frame.MAXIMIZED_BOTH);
frame.setUndecorated(true);
if (backgroundColor != null) {
((JFrame) frame).getContentPane().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;
int contentW = Math.max(applet.width, MIN_WINDOW_WIDTH);
int contentH = Math.max(applet.height, MIN_WINDOW_HEIGHT);
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;
// }
((JFrame) frame).getContentPane().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);
applet.setBounds((contentW - applet.width)/2,
(contentH - 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);
// Linux doesn't deal with insets the same way. We get fake insets
// earlier, and then the window manager will slap its own insets
// onto things once the frame is realized on the screen. Awzm.
if (platform == LINUX) {
Insets irlInsets = frame.getInsets();
if (!irlInsets.equals(insets)) {
insets = irlInsets;
windowW = Math.max(applet.width, MIN_WINDOW_WIDTH) +
insets.left + insets.right;
windowH = Math.max(applet.height, MIN_WINDOW_HEIGHT) +
insets.top + insets.bottom;
frame.setSize(windowW, windowH);
}
}
}
}
// 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 >> (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 >> 16
* & 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 >> (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 >> 8 & 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
* & 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).
* <p>
* A version of this function is in MovieMaker.java. Any fixes here
* should be applied over in MovieMaker as well.
* <p>
* Known issue with RLE encoding and odd behavior in some apps:
* https://github.com/processing/processing/issues/2096
* Please help!
*/
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) - Run-length 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);
// return new XML(createInput(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 input: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));
}
static public JSONObject loadJSONObject(File file) {
return new JSONObject(createReader(file));
}
/**
* @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 input: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));
}
static public JSONArray loadJSONArray(File file) {
return new JSONArray(createReader(file));
}
/**
* @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);
}
/**
* Options may contain "header", "tsv", "csv", or "bin" separated by commas.
*
* Another option is "dictionary=filename.tsv", which allows users to
* specify a "dictionary" file that contains a mapping of the column titles
* and the data types used in the table file. This can be far more efficient
* (in terms of speed and memory usage) for loading and parsing tables. The
* dictionary file can only be tab separated values (.tsv) and its extension
* will be ignored. This option was added in Processing 2.0.2.
*/
public Table loadTable(String filename, String options) {
try {
String optionStr = Table.extensionOptions(true, filename, options);
String[] optionList = trim(split(optionStr, ','));
Table dictionary = null;
for (String opt : optionList) {
if (opt.startsWith("dictionary=")) {
dictionary = loadTable(opt.substring(opt.indexOf('=') + 1), "tsv");
return dictionary.typedParse(createInput(filename), optionStr);
}
}
return new Table(createInput(filename), optionStr);
} 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));
}
static File desktopFolder;
/** Not a supported function. For testing use only. */
static public File desktopFile(String what) {
if (desktopFolder == null) {
// Should work on Linux and OS X (on OS X, even with the localized version).
desktopFolder = new File(System.getProperty("user.home"), "Desktop");
if (!desktopFolder.exists()) {
if (platform == WINDOWS) {
FileSystemView filesys = FileSystemView.getFileSystemView();
desktopFolder = filesys.getHomeDirectory();
} else {
throw new UnsupportedOperationException("Could not find a suitable desktop foldder");
}
}
}
return new File(desktopFolder, what);
}
/** Not a supported function. For testing use only. */
static public String desktopPath(String what) {
return desktopFile(what).getAbsolutePath();
}
/**
* 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/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/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");
System.out.println(dataFolder);
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/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();
// JFrame (unlike java.awt.Frame) doesn't include the left/top
// insets for placement (though it does seem to need them for
// overall size of the window. Perhaps JFrame sets its coord
// system so that (0, 0) is always the upper-left of the content
// area. Which seems nice, but breaks any f*ing AWT-based code.
Rectangle newBounds =
new Rectangle(0, 0, //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);
revalidate(); // let the layout manager do its work
}
}
}
}
});
}
// /**
// * 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();
}
// Using a JFrame fixes a Windows problem with Present mode. This might
// be our error, but usually this is the sort of crap we usually get from
// OS X. It's time for a turnaround: Redmond is thinking different too!
// https://github.com/processing/processing/issues/1955
Frame frame = new JFrame(displayDevice.getDefaultConfiguration());
// Default Processing gray, which will be replaced below if another
// color is specified on the command line (i.e. in the prefs).
final Color defaultGray = new Color(0xCC, 0xCC, 0xCC);
((JFrame) frame).getContentPane().setBackground(defaultGray);
// Cannot call setResizable(false) until later due to OS X (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();
// }
// Tried to use this to fix the 'present' mode issue.
// Did not help, and the screenRect setup seems to work fine.
//frame.setExtendedState(Frame.MAXIMIZED_BOTH);
frame.setUndecorated(true);
if (backgroundColor != null) {
((JFrame) frame).getContentPane().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;
int contentW = Math.max(applet.width, MIN_WINDOW_WIDTH);
int contentH = Math.max(applet.height, MIN_WINDOW_HEIGHT);
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;
// }
((JFrame) frame).getContentPane().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);
applet.setBounds((contentW - applet.width)/2,
(contentH - 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);
// Linux doesn't deal with insets the same way. We get fake insets
// earlier, and then the window manager will slap its own insets
// onto things once the frame is realized on the screen. Awzm.
if (platform == LINUX) {
Insets irlInsets = frame.getInsets();
if (!irlInsets.equals(insets)) {
insets = irlInsets;
windowW = Math.max(applet.width, MIN_WINDOW_WIDTH) +
insets.left + insets.right;
windowH = Math.max(applet.height, MIN_WINDOW_HEIGHT) +
insets.top + insets.bottom;
frame.setSize(windowW, windowH);
}
}
}
}
// 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 >> (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 >> 16
* & 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 >> (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 >> 8 & 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
* & 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).
* <p>
* A version of this function is in MovieMaker.java. Any fixes here
* should be applied over in MovieMaker as well.
* <p>
* Known issue with RLE encoding and odd behavior in some apps:
* https://github.com/processing/processing/issues/2096
* Please help!
*/
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) - Run-length 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);
// return new XML(createInput(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 input: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));
}
static public JSONObject loadJSONObject(File file) {
return new JSONObject(createReader(file));
}
/**
* @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 input: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));
}
static public JSONArray loadJSONArray(File file) {
return new JSONArray(createReader(file));
}
/**
* @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);
}
/**
* Options may contain "header", "tsv", "csv", or "bin" separated by commas.
*
* Another option is "dictionary=filename.tsv", which allows users to
* specify a "dictionary" file that contains a mapping of the column titles
* and the data types used in the table file. This can be far more efficient
* (in terms of speed and memory usage) for loading and parsing tables. The
* dictionary file can only be tab separated values (.tsv) and its extension
* will be ignored. This option was added in Processing 2.0.2.
*/
public Table loadTable(String filename, String options) {
try {
String optionStr = Table.extensionOptions(true, filename, options);
String[] optionList = trim(split(optionStr, ','));
Table dictionary = null;
for (String opt : optionList) {
if (opt.startsWith("dictionary=")) {
dictionary = loadTable(opt.substring(opt.indexOf('=') + 1), "tsv");
return dictionary.typedParse(createInput(filename), optionStr);
}
}
return new Table(createInput(filename), optionStr);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* @webref output: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));
}
static File desktopFolder;
/** Not a supported function. For testing use only. */
static public File desktopFile(String what) {
if (desktopFolder == null) {
// Should work on Linux and OS X (on OS X, even with the localized version).
desktopFolder = new File(System.getProperty("user.home"), "Desktop");
if (!desktopFolder.exists()) {
if (platform == WINDOWS) {
FileSystemView filesys = FileSystemView.getFileSystemView();
desktopFolder = filesys.getHomeDirectory();
} else {
throw new UnsupportedOperationException("Could not find a suitable desktop foldder");
}
}
}
return new File(desktopFolder, what);
}
/** Not a supported function. For testing use only. */
static public String desktopPath(String what) {
return desktopFile(what).getAbsolutePath();
}
/**
* 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/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/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");
System.out.println(dataFolder);
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/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();
// JFrame (unlike java.awt.Frame) doesn't include the left/top
// insets for placement (though it does seem to need them for
// overall size of the window. Perhaps JFrame sets its coord
// system so that (0, 0) is always the upper-left of the content
// area. Which seems nice, but breaks any f*ing AWT-based code.
Rectangle newBounds =
new Rectangle(0, 0, //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);
revalidate(); // let the layout manager do its work
}
}
}
}
});
}
// /**
// * 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();
}
// Using a JFrame fixes a Windows problem with Present mode. This might
// be our error, but usually this is the sort of crap we usually get from
// OS X. It's time for a turnaround: Redmond is thinking different too!
// https://github.com/processing/processing/issues/1955
Frame frame = new JFrame(displayDevice.getDefaultConfiguration());
// Default Processing gray, which will be replaced below if another
// color is specified on the command line (i.e. in the prefs).
final Color defaultGray = new Color(0xCC, 0xCC, 0xCC);
((JFrame) frame).getContentPane().setBackground(defaultGray);
// Cannot call setResizable(false) until later due to OS X (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();
// }
// Tried to use this to fix the 'present' mode issue.
// Did not help, and the screenRect setup seems to work fine.
//frame.setExtendedState(Frame.MAXIMIZED_BOTH);
frame.setUndecorated(true);
if (backgroundColor != null) {
((JFrame) frame).getContentPane().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;
int contentW = Math.max(applet.width, MIN_WINDOW_WIDTH);
int contentH = Math.max(applet.height, MIN_WINDOW_HEIGHT);
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;
// }
((JFrame) frame).getContentPane().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);
applet.setBounds((contentW - applet.width)/2,
(contentH - 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);
// Linux doesn't deal with insets the same way. We get fake insets
// earlier, and then the window manager will slap its own insets
// onto things once the frame is realized on the screen. Awzm.
if (platform == LINUX) {
Insets irlInsets = frame.getInsets();
if (!irlInsets.equals(insets)) {
insets = irlInsets;
windowW = Math.max(applet.width, MIN_WINDOW_WIDTH) +
insets.left + insets.right;
windowH = Math.max(applet.height, MIN_WINDOW_HEIGHT) +
insets.top + insets.bottom;
frame.setSize(windowW, windowH);
}
}
}
}
// 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 >> (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 >> 16
* & 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 >> (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 >> 8 & 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
* & 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/src/main/java/org/jvnet/hudson/plugins/m2release/M2ReleaseAction.java b/src/main/java/org/jvnet/hudson/plugins/m2release/M2ReleaseAction.java
index 4b40697..c5dbc0d 100644
--- a/src/main/java/org/jvnet/hudson/plugins/m2release/M2ReleaseAction.java
+++ b/src/main/java/org/jvnet/hudson/plugins/m2release/M2ReleaseAction.java
@@ -1,237 +1,239 @@
/*
* The MIT License
*
* Copyright (c) 2009, NDS Group Ltd., James Nord
*
* 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 org.jvnet.hudson.plugins.m2release;
import hudson.maven.MavenModule;
import hudson.maven.MavenModuleSet;
import hudson.model.Action;
import hudson.model.Hudson;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import org.jvnet.hudson.plugins.m2release.M2ReleaseBuildWrapper.DescriptorImpl;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
/**
* The action appears as the link in the side bar that users will click on in order to start the release
* process.
*
* @author James Nord
* @version 0.3
*/
public class M2ReleaseAction implements Action {
private MavenModuleSet project;
private String versioningMode;
private boolean selectCustomScmCommentPrefix;
private boolean selectAppendHudsonUsername;
public M2ReleaseAction(MavenModuleSet project, String versioningMode, boolean selectCustomScmCommentPrefix, boolean selectAppendHudsonUsername) {
this.project = project;
this.versioningMode = versioningMode;
this.selectCustomScmCommentPrefix = selectCustomScmCommentPrefix;
this.selectAppendHudsonUsername = selectAppendHudsonUsername;
}
public String getDisplayName() {
return Messages.ReleaseAction_perform_release_name();
}
public String getIconFileName() {
if (M2ReleaseBuildWrapper.hasReleasePermission(project)) {
return "installer.gif"; //$NON-NLS-1$
}
// by returning null the link will not be shown.
return null;
}
public String getUrlName() {
return "m2release"; //$NON-NLS-1$
}
public String getVersioningMode() {
return versioningMode;
}
public void setVersioningMode(String versioningMode) {
this.versioningMode = versioningMode;
}
public boolean isSelectCustomScmCommentPrefix() {
return selectCustomScmCommentPrefix;
}
public void setSelectCustomScmCommentPrefix(boolean selectCustomScmCommentPrefix) {
this.selectCustomScmCommentPrefix = selectCustomScmCommentPrefix;
}
public boolean isSelectAppendHudsonUsername() {
return selectAppendHudsonUsername;
}
public void setSelectAppendHudsonUsername(boolean selectAppendHudsonUsername) {
this.selectAppendHudsonUsername = selectAppendHudsonUsername;
}
public Collection<MavenModule> getModules() {
return project.getModules();
}
public MavenModule getRootModule() {
return project.getRootModule();
}
public String computeReleaseVersion(String version) {
return version.replace("-SNAPSHOT", ""); //$NON-NLS-1$ //$NON-NLS-2$
}
public String computeRepoDescription() {
return "Release " + computeReleaseVersion(project.getRootModule().getVersion()) + " of " + project.getRootModule().getName();
}
public String computeNextVersion(String version) {
/// XXX would be nice to use maven to do this...
/// tip: see DefaultVersionInfo.getNextVersion() in org.apache.maven.release:maven-release-manager
String retVal = computeReleaseVersion(version);
// get the integer after the last "."
int dotIdx = retVal.lastIndexOf('.');
if (dotIdx != -1) {
dotIdx++;
String ver = retVal.substring(dotIdx);
int intVer = Integer.parseInt(ver);
intVer += 1;
retVal = retVal.substring(0, dotIdx);
retVal = retVal + intVer;
}
else {
//just a major version...
try {
int intVer = Integer.parseInt(retVal);
intVer += 1;
retVal = Integer.toString(intVer);
}
catch (NumberFormatException nfEx) {
// not a major version - just a qualifier!
Logger logger = Logger.getLogger(this.getClass().getName());
logger.log(Level.WARNING, "{0} is not a number, so I can't work out the next version.",
new Object[] {retVal});
retVal = "NaN";
}
}
return retVal + "-SNAPSHOT"; //$NON-NLS-1$
}
public boolean isNexusSupportEnabled() {
return project.getBuildWrappersList().get(M2ReleaseBuildWrapper.class).getDescriptor().isNexusSupport();
}
public void doSubmit(StaplerRequest req, StaplerResponse resp) throws IOException, ServletException {
M2ReleaseBuildWrapper.checkReleasePermission(project);
M2ReleaseBuildWrapper m2Wrapper = project.getBuildWrappersList().get(M2ReleaseBuildWrapper.class);
// JSON collapses everything in the dynamic specifyVersions section so we need to fall back to
// good old http...
Map<?,?> httpParams = req.getParameterMap();
Map<String,String> versions = null;
final boolean appendHudsonBuildNumber = httpParams.containsKey("appendHudsonBuildNumber"); //$NON-NLS-1$
final boolean closeNexusStage = httpParams.containsKey("closeNexusStage"); //$NON-NLS-1$
final String repoDescription = closeNexusStage ? getString("repoDescription", httpParams) : ""; //$NON-NLS-1$
final boolean specifyScmCredentials = httpParams.containsKey("specifyScmCredentials"); //$NON-NLS-1$
final String scmUsername = specifyScmCredentials ? getString("scmUsername", httpParams) : null; //$NON-NLS-1$
final String scmPassword = specifyScmCredentials ? getString("scmPassword", httpParams) : null; //$NON-NLS-1$
final boolean specifyScmCommentPrefix = httpParams.containsKey("specifyScmCommentPrefix"); //$NON-NLS-1$
final String scmCommentPrefix = specifyScmCommentPrefix ? getString("scmCommentPrefix", httpParams) : null; //$NON-NLS-1$
final boolean appendHusonUserName = specifyScmCommentPrefix && httpParams.containsKey("appendHudsonUserName"); //$NON-NLS-1$
final String versioningMode = getString("versioningMode", httpParams);
if (DescriptorImpl.VERSIONING_SPECIFY_VERSIONS.equals(versioningMode)) {
versions = new HashMap<String,String>();
for (Object key : httpParams.keySet()) {
String keyStr = (String)key;
if (keyStr.startsWith("-Dproject.")) {
versions.put(keyStr, getString(keyStr, httpParams));
}
}
}
else if (DescriptorImpl.VERSIONING_SPECIFY_VERSION.equals(versioningMode)) {
versions = new HashMap<String, String>();
final String releaseVersion = getString("releaseVersion", httpParams); //$NON-NLS-1$
final String developmentVersion = getString("developmentVersion", httpParams); //$NON-NLS-1$
for(MavenModule mavenModule : getModules()) {
final String name = mavenModule.getModuleName().toString();
versions.put(String.format("-Dproject.dev.%s", name), developmentVersion); //$NON-NLS-1$
versions.put(String.format("-Dproject.rel.%s", name), releaseVersion); //$NON-NLS-1$
}
}
// schedule release build
synchronized (project) {
if (project.scheduleBuild(0, new ReleaseCause())) {
m2Wrapper.enableRelease();
m2Wrapper.setVersions(versions);
m2Wrapper.setAppendHudsonBuildNumber(appendHudsonBuildNumber);
m2Wrapper.setCloseNexusStage(closeNexusStage);
m2Wrapper.setRepoDescription(repoDescription);
m2Wrapper.setScmUsername(scmUsername);
m2Wrapper.setScmPassword(scmPassword);
m2Wrapper.setScmCommentPrefix(scmCommentPrefix);
m2Wrapper.setAppendHusonUserName(appendHusonUserName);
m2Wrapper.setHudsonUserName(Hudson.getAuthentication().getName());
+ // redirect to project page
+ resp.sendRedirect(req.getContextPath()+ '/' + project.getUrl());
}
else {
+ // redirect to error page.
+ // TODO try and get this to go back to the form page with an error at the top.
resp.sendRedirect(req.getContextPath()+ '/' + project.getUrl() + '/' + getUrlName() + "/failed");
}
}
- // redirect to status page
- resp.sendRedirect(req.getContextPath()+ '/' + project.getUrl());
}
/**
* returns the value of the key as a String. if multiple values
* have been submitted, the first one will be returned.
* @param key
* @param httpParams
* @return
*/
private String getString(String key, Map<?,?> httpParams) {
return (String)(((Object[])httpParams.get(key))[0]);
}
}
| false | true | public void doSubmit(StaplerRequest req, StaplerResponse resp) throws IOException, ServletException {
M2ReleaseBuildWrapper.checkReleasePermission(project);
M2ReleaseBuildWrapper m2Wrapper = project.getBuildWrappersList().get(M2ReleaseBuildWrapper.class);
// JSON collapses everything in the dynamic specifyVersions section so we need to fall back to
// good old http...
Map<?,?> httpParams = req.getParameterMap();
Map<String,String> versions = null;
final boolean appendHudsonBuildNumber = httpParams.containsKey("appendHudsonBuildNumber"); //$NON-NLS-1$
final boolean closeNexusStage = httpParams.containsKey("closeNexusStage"); //$NON-NLS-1$
final String repoDescription = closeNexusStage ? getString("repoDescription", httpParams) : ""; //$NON-NLS-1$
final boolean specifyScmCredentials = httpParams.containsKey("specifyScmCredentials"); //$NON-NLS-1$
final String scmUsername = specifyScmCredentials ? getString("scmUsername", httpParams) : null; //$NON-NLS-1$
final String scmPassword = specifyScmCredentials ? getString("scmPassword", httpParams) : null; //$NON-NLS-1$
final boolean specifyScmCommentPrefix = httpParams.containsKey("specifyScmCommentPrefix"); //$NON-NLS-1$
final String scmCommentPrefix = specifyScmCommentPrefix ? getString("scmCommentPrefix", httpParams) : null; //$NON-NLS-1$
final boolean appendHusonUserName = specifyScmCommentPrefix && httpParams.containsKey("appendHudsonUserName"); //$NON-NLS-1$
final String versioningMode = getString("versioningMode", httpParams);
if (DescriptorImpl.VERSIONING_SPECIFY_VERSIONS.equals(versioningMode)) {
versions = new HashMap<String,String>();
for (Object key : httpParams.keySet()) {
String keyStr = (String)key;
if (keyStr.startsWith("-Dproject.")) {
versions.put(keyStr, getString(keyStr, httpParams));
}
}
}
else if (DescriptorImpl.VERSIONING_SPECIFY_VERSION.equals(versioningMode)) {
versions = new HashMap<String, String>();
final String releaseVersion = getString("releaseVersion", httpParams); //$NON-NLS-1$
final String developmentVersion = getString("developmentVersion", httpParams); //$NON-NLS-1$
for(MavenModule mavenModule : getModules()) {
final String name = mavenModule.getModuleName().toString();
versions.put(String.format("-Dproject.dev.%s", name), developmentVersion); //$NON-NLS-1$
versions.put(String.format("-Dproject.rel.%s", name), releaseVersion); //$NON-NLS-1$
}
}
// schedule release build
synchronized (project) {
if (project.scheduleBuild(0, new ReleaseCause())) {
m2Wrapper.enableRelease();
m2Wrapper.setVersions(versions);
m2Wrapper.setAppendHudsonBuildNumber(appendHudsonBuildNumber);
m2Wrapper.setCloseNexusStage(closeNexusStage);
m2Wrapper.setRepoDescription(repoDescription);
m2Wrapper.setScmUsername(scmUsername);
m2Wrapper.setScmPassword(scmPassword);
m2Wrapper.setScmCommentPrefix(scmCommentPrefix);
m2Wrapper.setAppendHusonUserName(appendHusonUserName);
m2Wrapper.setHudsonUserName(Hudson.getAuthentication().getName());
}
else {
resp.sendRedirect(req.getContextPath()+ '/' + project.getUrl() + '/' + getUrlName() + "/failed");
}
}
// redirect to status page
resp.sendRedirect(req.getContextPath()+ '/' + project.getUrl());
}
| public void doSubmit(StaplerRequest req, StaplerResponse resp) throws IOException, ServletException {
M2ReleaseBuildWrapper.checkReleasePermission(project);
M2ReleaseBuildWrapper m2Wrapper = project.getBuildWrappersList().get(M2ReleaseBuildWrapper.class);
// JSON collapses everything in the dynamic specifyVersions section so we need to fall back to
// good old http...
Map<?,?> httpParams = req.getParameterMap();
Map<String,String> versions = null;
final boolean appendHudsonBuildNumber = httpParams.containsKey("appendHudsonBuildNumber"); //$NON-NLS-1$
final boolean closeNexusStage = httpParams.containsKey("closeNexusStage"); //$NON-NLS-1$
final String repoDescription = closeNexusStage ? getString("repoDescription", httpParams) : ""; //$NON-NLS-1$
final boolean specifyScmCredentials = httpParams.containsKey("specifyScmCredentials"); //$NON-NLS-1$
final String scmUsername = specifyScmCredentials ? getString("scmUsername", httpParams) : null; //$NON-NLS-1$
final String scmPassword = specifyScmCredentials ? getString("scmPassword", httpParams) : null; //$NON-NLS-1$
final boolean specifyScmCommentPrefix = httpParams.containsKey("specifyScmCommentPrefix"); //$NON-NLS-1$
final String scmCommentPrefix = specifyScmCommentPrefix ? getString("scmCommentPrefix", httpParams) : null; //$NON-NLS-1$
final boolean appendHusonUserName = specifyScmCommentPrefix && httpParams.containsKey("appendHudsonUserName"); //$NON-NLS-1$
final String versioningMode = getString("versioningMode", httpParams);
if (DescriptorImpl.VERSIONING_SPECIFY_VERSIONS.equals(versioningMode)) {
versions = new HashMap<String,String>();
for (Object key : httpParams.keySet()) {
String keyStr = (String)key;
if (keyStr.startsWith("-Dproject.")) {
versions.put(keyStr, getString(keyStr, httpParams));
}
}
}
else if (DescriptorImpl.VERSIONING_SPECIFY_VERSION.equals(versioningMode)) {
versions = new HashMap<String, String>();
final String releaseVersion = getString("releaseVersion", httpParams); //$NON-NLS-1$
final String developmentVersion = getString("developmentVersion", httpParams); //$NON-NLS-1$
for(MavenModule mavenModule : getModules()) {
final String name = mavenModule.getModuleName().toString();
versions.put(String.format("-Dproject.dev.%s", name), developmentVersion); //$NON-NLS-1$
versions.put(String.format("-Dproject.rel.%s", name), releaseVersion); //$NON-NLS-1$
}
}
// schedule release build
synchronized (project) {
if (project.scheduleBuild(0, new ReleaseCause())) {
m2Wrapper.enableRelease();
m2Wrapper.setVersions(versions);
m2Wrapper.setAppendHudsonBuildNumber(appendHudsonBuildNumber);
m2Wrapper.setCloseNexusStage(closeNexusStage);
m2Wrapper.setRepoDescription(repoDescription);
m2Wrapper.setScmUsername(scmUsername);
m2Wrapper.setScmPassword(scmPassword);
m2Wrapper.setScmCommentPrefix(scmCommentPrefix);
m2Wrapper.setAppendHusonUserName(appendHusonUserName);
m2Wrapper.setHudsonUserName(Hudson.getAuthentication().getName());
// redirect to project page
resp.sendRedirect(req.getContextPath()+ '/' + project.getUrl());
}
else {
// redirect to error page.
// TODO try and get this to go back to the form page with an error at the top.
resp.sendRedirect(req.getContextPath()+ '/' + project.getUrl() + '/' + getUrlName() + "/failed");
}
}
}
|
diff --git a/samigo-app/src/java/org/sakaiproject/tool/assessment/ui/bean/author/AssessmentSettingsBean.java b/samigo-app/src/java/org/sakaiproject/tool/assessment/ui/bean/author/AssessmentSettingsBean.java
index c18d53d6f..38c1b55c6 100644
--- a/samigo-app/src/java/org/sakaiproject/tool/assessment/ui/bean/author/AssessmentSettingsBean.java
+++ b/samigo-app/src/java/org/sakaiproject/tool/assessment/ui/bean/author/AssessmentSettingsBean.java
@@ -1,1269 +1,1272 @@
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2004, 2005, 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.tool.assessment.ui.bean.author;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ResourceBundle;
import java.util.Set;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.context.ExternalContext;
import javax.faces.model.SelectItem;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.service.gradebook.shared.GradebookService;
import org.sakaiproject.spring.SpringBeanLocator;
import org.sakaiproject.tool.assessment.data.ifc.assessment.AssessmentAccessControlIfc;
import org.sakaiproject.tool.assessment.data.ifc.assessment.AssessmentFeedbackIfc;
import org.sakaiproject.tool.assessment.data.ifc.assessment.AssessmentMetaDataIfc;
import org.sakaiproject.tool.assessment.data.ifc.assessment.AssessmentTemplateIfc;
import org.sakaiproject.tool.assessment.data.ifc.assessment.AttachmentIfc;
import org.sakaiproject.tool.assessment.data.ifc.assessment.EvaluationModelIfc;
import org.sakaiproject.tool.assessment.data.ifc.assessment.SecuredIPAddressIfc;
import org.sakaiproject.tool.assessment.facade.AgentFacade;
import org.sakaiproject.tool.assessment.facade.AssessmentFacade;
import org.sakaiproject.tool.assessment.facade.AssessmentTemplateFacade;
import org.sakaiproject.tool.assessment.facade.GradebookFacade;
import org.sakaiproject.tool.assessment.integration.context.IntegrationContextFactory;
import org.sakaiproject.tool.assessment.integration.helper.ifc.GradebookServiceHelper;
import org.sakaiproject.tool.assessment.integration.helper.ifc.PublishingTargetHelper;
import org.sakaiproject.tool.assessment.services.assessment.AssessmentService;
import org.sakaiproject.tool.assessment.ui.listener.author.SaveAssessmentAttachmentListener;
import org.sakaiproject.tool.assessment.ui.listener.author.SaveAssessmentSettings;
import org.sakaiproject.tool.assessment.ui.listener.util.TimeUtil;
import org.sakaiproject.tool.assessment.ui.listener.util.ContextUtil;
import org.sakaiproject.tool.api.ToolSession;
import org.sakaiproject.entity.impl.ReferenceComponent;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.exception.PermissionException;
import org.sakaiproject.exception.TypeException;
import org.sakaiproject.content.api.ContentResource;
import org.sakaiproject.content.api.FilePickerHelper;
import org.sakaiproject.content.cover.ContentHostingService;
import org.sakaiproject.tool.cover.SessionManager;
/**
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*
* Used to be org.navigoproject.ui.web.asi.author.assessment.AssessmentActionForm.java
*/
public class AssessmentSettingsBean
implements Serializable {
private static Log log = LogFactory.getLog(AssessmentSettingsBean.class);
private static final IntegrationContextFactory integrationContextFactory =
IntegrationContextFactory.getInstance();
private static final GradebookServiceHelper gbsHelper =
integrationContextFactory.getGradebookServiceHelper();
private static final PublishingTargetHelper ptHelper =
integrationContextFactory.getPublishingTargetHelper();
private static final boolean integrated =
integrationContextFactory.isIntegrated();
/** Use serialVersionUID for interoperability. */
private final static long serialVersionUID = -630950053380808339L;
private String outcomeSave;
private String outcomePublish;
private AssessmentFacade assessment;
private AssessmentTemplateFacade template;
private Long assessmentId;
private String title;
private String creator;
private String description;
private boolean hasQuestions;
private String templateTitle;
private String templateDescription;
// meta data
private String objectives;
private String keywords;
private String rubrics;
private String authors;
private String templateAuthors;
// these are properties in AssessmentAccessControl
private Date startDate;
private Date dueDate;
private Date retractDate;
private Date feedbackDate;
private Integer timeLimit = new Integer(0); // in seconds, calculated from timedHours & timedMinutes
private Integer timedHours = new Integer(0);
private Integer timedMinutes = new Integer(0);
private Integer timedSeconds = new Integer(0);
private boolean timedAssessment = false;
private boolean autoSubmit = false;
private String assessmentFormat; // question (1)/part(2)/assessment(3) on separate page
private String itemNavigation; // linear (1)or random (2)
private String itemNumbering; // continuous between parts(1), restart between parts(2)
private String unlimitedSubmissions;
private String submissionsAllowed;
private String submissionsSaved; // bad name, this is autoSaved
private String lateHandling;
private String submissionMessage;
private String releaseTo;
private SelectItem[] publishingTargets;
private String[] targetSelected;
private String firstTargetSelected;
private String username;
private String password;
private String finalPageUrl;
private String ipAddresses;
// properties of AssesmentFeedback
private String feedbackDelivery; // immediate, on specific date , no feedback
//private String editComponents; // 0 = cannot
private boolean showQuestionText = true;
private boolean showStudentResponse = false;
private boolean showCorrectResponse = false;
private boolean showStudentScore = false;
private boolean showStudentQuestionScore = false;
private boolean showQuestionLevelFeedback = false;
private boolean showSelectionLevelFeedback = false; // must be MC
private boolean showGraderComments = false;
private boolean showStatistics = false;
// properties of EvaluationModel
private String anonymousGrading;
private boolean gradebookExists;
private String toDefaultGradebook;
private String scoringType;
private String bgColor;
private String bgImage;
private HashMap values = new HashMap(); // contains only "can edit" element
private String bgColorSelect;
private String bgImageSelect;
// extra properties
private boolean noTemplate;
private String publishedUrl;
private String alias;
private static boolean error;
private List attachmentList;
/**
* we use the calendar widget which uses 'MM/dd/yyyy hh:mm:ss a'
* used to take the internal format from calendar picker and move it
* transparently in and out of the date properties
*
*/
//private static final String DISPLAY_DATEFORMAT = "MM/dd/yyyy hh:mm:ss a";
private String display_dateFormat= ContextUtil.getLocalizedString("org.sakaiproject.tool.assessment.bundle.GeneralMessages","output_data_picker_w_sec");
private SimpleDateFormat displayFormat = new SimpleDateFormat(display_dateFormat);
/*
* Creates a new AssessmentBean object.
*/
public AssessmentSettingsBean() {
}
public AssessmentFacade getAssessment() {
return assessment;
}
public void setAssessment(AssessmentFacade assessment) {
try {
//1. set the template info
AssessmentService service = new AssessmentService();
- AssessmentTemplateIfc template = service.getAssessmentTemplate(
+ AssessmentTemplateIfc template = null;
+ if (assessment.getAssessmentTemplateId()!=null){
+ template = service.getAssessmentTemplate(
assessment.getAssessmentTemplateId().toString());
+ }
if (template != null){
setNoTemplate(false);
this.templateTitle = template.getTitle();
this.templateDescription = template.getDescription();
this.templateAuthors = template.getAssessmentMetaDataByLabel(
"author"); // see TemplateUploadListener line 142
}
else{
setNoTemplate(true);
}
//2. set the assessment info
this.assessment = assessment;
// set the valueMap
setValueMap(assessment.getAssessmentMetaDataMap());
this.assessmentId = assessment.getAssessmentId();
this.title = assessment.getTitle();
this.creator = AgentFacade.getDisplayName(assessment.getCreatedBy());
this.description = assessment.getDescription();
// assessment meta data
this.authors = assessment.getAssessmentMetaDataByLabel(AssessmentMetaDataIfc.
AUTHORS);
this.objectives = assessment.getAssessmentMetaDataByLabel(
AssessmentMetaDataIfc.OBJECTIVES);
this.keywords = assessment.getAssessmentMetaDataByLabel(AssessmentMetaDataIfc.
KEYWORDS);
this.rubrics = assessment.getAssessmentMetaDataByLabel(AssessmentMetaDataIfc.
RUBRICS);
this.bgColor = assessment.getAssessmentMetaDataByLabel(AssessmentMetaDataIfc.
BGCOLOR);
this.bgImage = assessment.getAssessmentMetaDataByLabel(AssessmentMetaDataIfc.
BGIMAGE);
if((assessment.getAssessmentMetaDataByLabel(AssessmentMetaDataIfc.
BGIMAGE)!=null )&&(!assessment.getAssessmentMetaDataByLabel(AssessmentMetaDataIfc.
BGIMAGE).equals(""))){
this.bgImageSelect="1";
this.bgColorSelect=null;
}
else{
this.bgImageSelect=null;
this.bgColorSelect="1";
}
// these are properties in AssessmentAccessControl
AssessmentAccessControlIfc accessControl = null;
accessControl = assessment.getAssessmentAccessControl();
if (accessControl != null) {
this.startDate = accessControl.getStartDate();
this.dueDate = accessControl.getDueDate();
this.retractDate = accessControl.getRetractDate();
this.feedbackDate = accessControl.getFeedbackDate();
// deal with releaseTo
this.releaseTo = accessControl.getReleaseTo(); // list of String
this.publishingTargets = getPublishingTargets();
this.targetSelected = getTargetSelected(releaseTo);
this.firstTargetSelected = getFirstTargetSelected(releaseTo);
// SAK-1850 - when importing assessment forget to set releaseTo, we will catch it
// and set it to host site
if (!validateTarget(firstTargetSelected)){
releaseTo = AgentFacade.getCurrentSiteName();
firstTargetSelected = AgentFacade.getCurrentSiteName();
targetSelected = getTargetSelected(releaseTo);
}
this.timeLimit = accessControl.getTimeLimit(); // in seconds
if (timeLimit !=null && timeLimit.intValue()>0)
setTimeLimitDisplay(timeLimit.intValue());
else
resetTimeLimitDisplay();
if ((new Integer(1)).equals(accessControl.getTimedAssessment()))
this.timedAssessment = true;
if ((new Integer(1)).equals(accessControl.getAutoSubmit()))
this.autoSubmit = true;
if (accessControl.getAssessmentFormat()!=null)
this.assessmentFormat = accessControl.getAssessmentFormat().toString(); // question/part/assessment on separate page
if (accessControl.getItemNavigation()!=null)
this.itemNavigation = accessControl.getItemNavigation().toString(); // linear or random
if (accessControl.getItemNumbering()!=null)
this.itemNumbering = accessControl.getItemNumbering().toString();
if (accessControl.getSubmissionsSaved()!=null) // bad name, this is autoSaved
this.submissionsSaved = accessControl.getSubmissionsSaved().toString();
// default to unlimited if control value is null
if (accessControl.getUnlimitedSubmissions()!=null && !accessControl.getUnlimitedSubmissions().booleanValue()){
this.unlimitedSubmissions=AssessmentAccessControlIfc.LIMITED_SUBMISSIONS.toString();
this.submissionsAllowed = accessControl.getSubmissionsAllowed().toString();
}
else{
this.unlimitedSubmissions=AssessmentAccessControlIfc.UNLIMITED_SUBMISSIONS.toString();
this.submissionsAllowed="";
}
if (accessControl.getLateHandling() !=null)
this.lateHandling = accessControl.getLateHandling().toString();
if (accessControl.getSubmissionsSaved()!=null)
this.submissionsSaved = accessControl.getSubmissionsSaved().toString();
this.submissionMessage = accessControl.getSubmissionMessage();
this.username = accessControl.getUsername();
this.password = accessControl.getPassword();
this.finalPageUrl = accessControl.getFinalPageUrl();
}
// properties of AssesmentFeedback
AssessmentFeedbackIfc feedback = assessment.getAssessmentFeedback();
if (feedback != null) {
if (feedback.getFeedbackDelivery()!=null)
this.feedbackDelivery = feedback.getFeedbackDelivery().toString();
if (feedback.getFeedbackAuthoring()!=null)
this.feedbackAuthoring = feedback.getFeedbackAuthoring().toString();
if ((Boolean.TRUE).equals(feedback.getShowQuestionText()))
this.showQuestionText = true;
if ((Boolean.TRUE).equals(feedback.getShowStudentResponse()))
this.showStudentResponse = true;
if ((Boolean.TRUE).equals(feedback.getShowCorrectResponse()))
this.showCorrectResponse = true;
if ((Boolean.TRUE).equals(feedback.getShowStudentScore()))
this.showStudentScore = true;
if ((Boolean.TRUE).equals(feedback.getShowStudentQuestionScore()))
this.showStudentQuestionScore = true;
if ((Boolean.TRUE).equals(feedback.getShowQuestionLevelFeedback()))
this.showQuestionLevelFeedback = true;
if ((Boolean.TRUE).equals(feedback.getShowSelectionLevelFeedback()))
this.showSelectionLevelFeedback = true;// must be MC
if ((Boolean.TRUE).equals(feedback.getShowGraderComments()))
this.showGraderComments = true;
if ((Boolean.TRUE).equals(feedback.getShowStatistics()))
this.showStatistics = true;
}
// properties of EvaluationModel
EvaluationModelIfc evaluation = assessment.getEvaluationModel();
if (evaluation != null) {
if (evaluation.getAnonymousGrading()!=null)
this.anonymousGrading = evaluation.getAnonymousGrading().toString();
if (evaluation.getToGradeBook()!=null )
this.toDefaultGradebook = evaluation.getToGradeBook();
if (evaluation.getScoringType()!=null)
this.scoringType = evaluation.getScoringType().toString();
GradebookService g = null;
if (integrated)
{
g = (GradebookService) SpringBeanLocator.getInstance().
getBean("org.sakaiproject.service.gradebook.GradebookService");
}
this.gradebookExists = gbsHelper.gradebookExists(
GradebookFacade.getGradebookUId(), g);
}
// ip addresses
this.ipAddresses = "";
Set ipAddressSet = assessment.getSecuredIPAddressSet();
if (ipAddressSet != null){
Iterator iter = ipAddressSet.iterator();
while (iter.hasNext()) {
SecuredIPAddressIfc ip = (SecuredIPAddressIfc) iter.next();
if (ip.getIpAddress()!=null)
this.ipAddresses = ip.getIpAddress()+"\n"+this.ipAddresses;
}
}
// attachment
this.attachmentList = assessment.getAssessmentAttachmentList();
}
catch (RuntimeException ex) {
ex.printStackTrace();
}
}
public String getBgColorSelect()
{
return this.bgColorSelect;
}
public void setBgColorSelect(String bgColorSelect)
{
this.bgColorSelect=bgColorSelect;
}
public String getBgImageSelect()
{
return this.bgImageSelect;
}
public void setBgImageSelect(String bgImageSelect)
{
this.bgImageSelect=bgImageSelect;
}
//Huong adding for outcome error
public String getOutcomeSave()
{
return this.outcomeSave;
}
public void setOutcomeSave(String outcomeSave)
{
this.outcomeSave=outcomeSave;
}
public String getOutcomePublish()
{
return this.outcomePublish;
}
public void setOutcomePublish(String outcomePublish)
{
this.outcomePublish=outcomePublish;
}
// properties from Assessment
public Long getAssessmentId() {
return this.assessmentId;
}
public void setAssessmentId(Long assessmentId) {
this.assessmentId = assessmentId;
}
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
public String getCreator() {
return this.creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
// properties form AssessmentMetaData
public String getObjectives() {
return this.objectives;
}
public void setObjectives(String objectives) {
this.objectives = objectives;
}
public String getKeywords() {
return this.keywords;
}
public void setKeywords(String keywords) {
this.keywords = keywords;
}
public String getRubrics() {
return this.rubrics;
}
public void setRubrics(String rubrics) {
this.rubrics = rubrics;
}
public String getAuthors() {
return this.authors;
}
public void setAuthors(String authors) {
this.authors = authors;
}
public String getBgColor() {
if((this.getBgColorSelect()!=null) && (this.getBgColorSelect().equals("1")))
return this.bgColor;
else
return "";
}
public void setBgColor(String bgColor) {
if((this.getBgColorSelect()!=null) && (this.getBgColorSelect().equals("1")))
this.bgColor = bgColor;
else
this.bgColor="";
}
public String getBgImage() {
if((this.getBgImageSelect()!=null) && (this.getBgImageSelect().equals("1")))
return this.bgImage;
else return "";
}
public void setBgImage(String bgImage) {
if((this.getBgImageSelect()!=null) && (this.getBgImageSelect().equals("1")))
this.bgImage = bgImage;
else this.bgImage="";
}
public boolean getHasQuestions() {
return this.hasQuestions;
}
public void setHasQuestions(boolean hasQuestions) {
this.hasQuestions = hasQuestions;
}
// copied from AssessmentAccessControl ;-)
public Date getStartDate() {
return this.startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getDueDate() {
return this.dueDate;
}
public void setDueDate(Date dueDate) {
this.dueDate = dueDate;
}
public Date getFeedbackDate() {
return this.feedbackDate;
}
public void setFeedbackDate(Date feedbackDate) {
this.feedbackDate = feedbackDate;
}
public Date getRetractDate() {
return this.retractDate;
}
public void setRetractDate(Date retractDate) {
this.retractDate = retractDate;
}
public String getReleaseTo() {
this.releaseTo="";
if (targetSelected != null){
for (int i = 0; i < targetSelected.length; i++) {
String user = targetSelected[i];
if (!releaseTo.equals(""))
releaseTo = releaseTo + ", " + user;
else
releaseTo = user;
}
}
return this.releaseTo;
}
public void setReleaseTo(String releaseTo) {
this.releaseTo = releaseTo;
}
public Integer getTimeLimit() {
return new Integer(timedHours.intValue()*3600
+ timedMinutes.intValue()*60
+ timedSeconds.intValue());
}
public void setTimeLimit(Integer timeLimit) {
this.timeLimit = timeLimit;
}
public void setTimedHours(Integer timedHours) {
this.timedHours = timedHours;
}
public Integer getTimedHours() {
return timedHours;
}
public void setTimedMinutes(Integer timedMinutes) {
this.timedMinutes = timedMinutes;
}
public Integer getTimedMinutes() {
return timedMinutes;
}
public void setTimedSeconds(Integer timedSeconds) {
this.timedSeconds = timedSeconds;
}
public Integer getTimedSeconds() {
return timedSeconds;
}
public boolean getTimedAssessment() {
return timedAssessment;
}
public void setTimedAssessment(boolean timedAssessment) {
this.timedAssessment = timedAssessment;
}
public boolean getAutoSubmit() {
return autoSubmit;
}
public void setAutoSubmit(boolean autoSubmit) {
this.autoSubmit = autoSubmit;
}
public String getAssessmentFormat() {
return assessmentFormat;
}
public void setAssessmentFormat(String assessmentFormat) {
this.assessmentFormat = assessmentFormat;
}
public String getItemNavigation() {
return itemNavigation;
}
public void setItemNavigation(String itemNavigation) {
this.itemNavigation = itemNavigation;
}
public String getItemNumbering() {
return itemNumbering;
}
public void setItemNumbering(String itemNumbering) {
this.itemNumbering = itemNumbering;
}
public String getUnlimitedSubmissions() {
return unlimitedSubmissions;
}
public void setUnlimitedSubmissions(String unlimitedSubmissions) {
this.unlimitedSubmissions = unlimitedSubmissions;
}
public String getSubmissionsAllowed() {
return submissionsAllowed;
}
public void setSubmissionsAllowed(String submissionsAllowed) {
this.submissionsAllowed = submissionsAllowed;
}
public void setLateHandling(String lateHandling) {
this.lateHandling = lateHandling;
}
public String getLateHandling() {
return lateHandling;
}
// bad name - this is autoSaved
public void setSubmissionsSaved(String submissionSaved) {
this.submissionsSaved = submissionSaved;
}
public String getSubmissionsSaved() {
return submissionsSaved;
}
public void setSubmissionMessage(String submissionMessage) {
this.submissionMessage = submissionMessage;
}
public String getSubmissionMessage() {
return submissionMessage;
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public void setFinalPageUrl(String finalPageUrl) {
this.finalPageUrl = finalPageUrl;
}
public String getFinalPageUrl() {
return finalPageUrl;
}
public String getFeedbackDelivery() {
return feedbackDelivery;
}
public void setFeedbackDelivery(String feedbackDelivery) {
this.feedbackDelivery = feedbackDelivery;
}
public boolean getShowQuestionText() {
return showQuestionText;
}
public void setShowQuestionText(boolean showQuestionText) {
this.showQuestionText = showQuestionText;
}
public boolean getShowStudentResponse() {
return showStudentResponse;
}
public void setShowStudentResponse(boolean showStudentResponse) {
this.showStudentResponse = showStudentResponse;
}
public boolean getShowCorrectResponse() {
return showCorrectResponse;
}
public void setShowCorrectResponse(boolean showCorrectResponse) {
this.showCorrectResponse = showCorrectResponse;
}
public boolean getShowStudentScore() {
return showStudentScore;
}
public void setShowStudentScore(boolean showStudentScore) {
this.showStudentScore = showStudentScore;
}
public boolean getShowStudentQuestionScore() {
return showStudentQuestionScore;
}
public void setShowStudentQuestionScore(boolean showStudentQuestionScore) {
this.showStudentQuestionScore = showStudentQuestionScore;
}
public boolean getShowQuestionLevelFeedback() {
return showQuestionLevelFeedback;
}
public void setShowQuestionLevelFeedback(boolean showQuestionLevelFeedback) {
this.showQuestionLevelFeedback = showQuestionLevelFeedback;
}
public boolean getShowSelectionLevelFeedback() {
return showSelectionLevelFeedback;
}
public void setShowSelectionLevelFeedback(boolean showSelectionLevelFeedback) {
this.showSelectionLevelFeedback = showSelectionLevelFeedback;
}
public boolean getShowGraderComments() {
return showGraderComments;
}
public void setShowGraderComments(boolean showGraderComments) {
this.showGraderComments = showGraderComments;
}
public boolean getShowStatistics() {
return showStatistics;
}
public void setShowStatistics(boolean showStatistics) {
this.showStatistics = showStatistics;
}
public String getAnonymousGrading() {
return this.anonymousGrading;
}
public void setAnonymousGrading(String anonymousGrading) {
this.anonymousGrading = anonymousGrading;
}
public String getToDefaultGradebook() {
return this.toDefaultGradebook;
}
public void setToDefaultGradebook(String toDefaultGradebook) {
this.toDefaultGradebook = toDefaultGradebook;
}
public boolean getGradebookExists() {
return this.gradebookExists;
}
public void setGradebookExists(boolean gradebookExists) {
this.gradebookExists = gradebookExists;
}
public String getScoringType() {
return this.scoringType;
}
public void setScoringType(String scoringType) {
this.scoringType = scoringType;
}
public void setValue(String key, Object value){
this.values.put(key, value);
}
// retrieve value in valueMap
public Boolean getValue(String key)
{
Boolean returnValue = Boolean.FALSE;
Object o = this.values.get(key);
if (("true").equals((String)o))
returnValue = Boolean.TRUE;
return returnValue;
}
// newMap contains both the regular metadata such as "objectives" as well as
// "can edit" element. However, we only want to have "can edit" elements inside
// our valueMap, so we need to weed out the metadata
public void setValueMap(HashMap newMap){
HashMap h = new HashMap();
Iterator iter = newMap.keySet().iterator();
while( iter.hasNext()){
String key = (String)iter.next();
Object o = newMap.get(key);
if ((key.equals("ASSESSMENT_AUTHORS")) ||
(key.equals("ASSESSMENT_KEYWORDS")) ||
(key.equals("ASSESSMENT_OBJECTIVES")) ||
(key.equals("ASSESSMENT_RUBRICS")) ||
(key.equals("ASSESSMENT_BGCOLOR")) ||
(key.equals("ASSESSMENT_BGIMAGE")));
else{
h.put(key, o);
}
}
this.values = h ;
}
public HashMap getValueMap(){
return values;
}
public String getDateString(Date date) {
if (date!=null){
Calendar c = Calendar.getInstance();
c.setTime(date);
int mon = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
int year = c.get(Calendar.YEAR);
String dateString = mon + "/" + day + "/" + year;
return dateString;
}
else
return "";
}
public void setTimeLimitDisplay(int time){
this.timedHours=new Integer(time/60/60);
this.timedMinutes = new Integer((time/60)%60);
this.timedSeconds = new Integer(time % 60);
}
public void resetTimeLimitDisplay(){
this.timedHours=new Integer(0);
this.timedMinutes = new Integer(0);
this.timedSeconds = new Integer(0);
}
// followings are set of SelectItem[] used in authorSettings.jsp
public SelectItem[] getHours() {
return hours;
}
public static void setHours(SelectItem[] hours) {
AssessmentSettingsBean.hours = hours;
}
public SelectItem[] getMins() {
return mins;
}
public static void setMins(SelectItem[] mins) {
AssessmentSettingsBean.mins = mins;
}
private static List months;
private static List days;
private static SelectItem[] mins;
private static SelectItem[] hours;
// don't know what this is for, had to add it --esmiley
private String feedbackAuthoring;// this was left out, but referenced in UI
static{
months = new ArrayList();
for (int i=1; i<=12; i++){
months.add(new SelectItem(new Integer(i)));
}
days = new ArrayList();
for (int i=1; i<32; i++){
days.add(new SelectItem(new Integer(i)));
}
hours = new SelectItem[24];
for (int i=0; i<24; i++){
if (i < 10)
hours[i] = new SelectItem(new Integer(i),"0"+i);
else
hours[i] = new SelectItem(new Integer(i),i+"");
}
mins = new SelectItem[60];
for (int i=0; i<60; i++){
if (i < 10)
mins[i] = new SelectItem(new Integer(i),"0"+i);
else
mins[i] = new SelectItem(new Integer(i),i+"");
}
}
public String getIpAddresses() {
return ipAddresses;
}
public void setIpAddresses(String ipAddresses) {
this.ipAddresses = ipAddresses;
}
// the following methods are used to take the internal format from
// calendar picker and move it transparently in and out of the date
// properties
/**
* date from internal string of calendar widget
* @param date Date object
* @return date String "MM-dd-yyyy hh:mm:ss a"
*/
private String getDisplayFormatFromDate(Date date) {
String dateString = "";
if (date == null) {
return dateString;
}
try {
//dateString = displayFormat.format(date);
TimeUtil tu = new TimeUtil();
dateString = tu.getDisplayDateTime(displayFormat, date);
}
catch (Exception ex) {
// we will leave it as an empty string
log.warn("Unable to format date.");
ex.printStackTrace();
}
return dateString;
}
/**
* format according to internal requirements of calendar widget
* @param dateString "MM-dd-yyyy hh:mm:ss a"
* @return Date object
*/
private Date getDateFromDisplayFormat(String dateString) {
Date date = null;
if (dateString == null || dateString.trim().equals("")) {
return date;
}
try {
//Date date= (Date) displayFormat.parse(dateString);
// dateString is in client timezone, change it to server time zone
TimeUtil tu = new TimeUtil();
date = tu.getServerDateTime(displayFormat, dateString);
}
catch (Exception ex) {
// we will leave it as a null date
log.warn("Unable to format date.");
error=true;
ex.printStackTrace();
}
return date;
}
public String getStartDateString()
{
return getDisplayFormatFromDate(startDate);
}
public void setStartDateString(String startDateString)
{
this.startDate= getDateFromDisplayFormat(startDateString);
}
public String getDueDateString()
{
return getDisplayFormatFromDate(dueDate);
}
public void setDueDateString(String dueDateString)
{
this.dueDate = getDateFromDisplayFormat(dueDateString);
}
public String getRetractDateString()
{
return getDisplayFormatFromDate(retractDate);
}
public void setRetractDateString(String retractDateString)
{
this.retractDate = getDateFromDisplayFormat(retractDateString);
}
public String getFeedbackDateString()
{
return getDisplayFormatFromDate(feedbackDate);
}
public void setFeedbackDateString(String feedbackDateString)
{
this.feedbackDate = getDateFromDisplayFormat(feedbackDateString);
}
public String getTemplateTitle() {
return this.templateTitle;
}
public void setTemplateTitle(String title) {
this.templateTitle = title;
}
public String getTemplateAuthors() {
return this.templateAuthors;
}
public void setTemplateAuthors(String templateAuthors) {
this.templateAuthors = templateAuthors;
}
public String getTemplateDescription() {
return this.templateDescription;
}
public void setTemplateDescription(String templateDescription) {
this.templateDescription = templateDescription;
}
public boolean getNoTemplate() {
return this.noTemplate;
}
public void setNoTemplate(boolean noTemplate) {
this.noTemplate = noTemplate;
}
public boolean validateTarget(String firstTarget){
HashMap targets = ptHelper.getTargets();
if (targets.get(firstTarget) != null)
return true;
else
return false;
}
public SelectItem[] getPublishingTargets(){
HashMap targets = ptHelper.getTargets();
Set e = targets.keySet();
Iterator iter = e.iterator();
// sort the targets
String[] titles = new String[targets.size()];
while (iter.hasNext()){
for (int m = 0; m < e.size(); m++) {
String t = (String)iter.next();
titles[m] = t;
}
}
Arrays.sort(titles);
SelectItem[] target = new SelectItem[targets.size()];
for (int i=0; i<titles.length; i++){
target[i] = new SelectItem(titles[i]);
}
/**
SelectItem[] target = new SelectItem[targets.size()];
while (iter.hasNext()){
for (int i = 0; i < e.size(); i++) {
target[i] = new SelectItem((String)iter.next());
}
}
*/
return target;
}
public void setTargetSelected(String[] targetSelected){
this.targetSelected = targetSelected;
}
public String[] getTargetSelected(){
return targetSelected;
}
public String[] getTargetSelected(String releaseTo){
if (releaseTo != null){
this.targetSelected = releaseTo.split(",");
for (int i = 0; i < targetSelected.length; i++) {
targetSelected[i] = targetSelected[i].trim();
}
}
return this.targetSelected;
}
public void setFirstTargetSelected(String firstTargetSelected){
this.firstTargetSelected = firstTargetSelected.trim();
this.targetSelected[0] = firstTargetSelected.trim();
}
public String getFirstTargetSelected(){
return firstTargetSelected;
}
public String getFirstTargetSelected(String releaseTo){
if (releaseTo != null){
this.targetSelected = releaseTo.split(",");
this.firstTargetSelected = targetSelected[0].trim();
}
return this.firstTargetSelected;
}
public String getPublishedUrl() {
return this.publishedUrl;
}
public void setPublishedUrl(String publishedUrl) {
this.publishedUrl = publishedUrl;
}
public String getAlias() {
return this.alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
public String checkDate(){
FacesContext context=FacesContext.getCurrentInstance();
ResourceBundle rb=ResourceBundle.getBundle("org.sakaiproject.tool.assessment.bundle.AuthorMessages", context.getViewRoot().getLocale());
String err;
if(this.error)
{
err=(String)rb.getObject("deliveryDate_error");
context.addMessage(null,new FacesMessage(err));
log.error("START DATE ADD MESSAGE");
return "deliveryDate_error";
}
else
{
return "saveSettings";
}
}
public String getFeedbackAuthoring()
{
return feedbackAuthoring;
}
public void setFeedbackAuthoring(String feedbackAuthoring)
{
this.feedbackAuthoring = feedbackAuthoring;
}
public List getAttachmentList() {
return attachmentList;
}
public void setAttachmentList(List attachmentList)
{
this.attachmentList = attachmentList;
}
private boolean hasAttachment = false;
public boolean getHasAttachment(){
if (attachmentList!=null && attachmentList.size() >0)
this.hasAttachment = true;
return this.hasAttachment;
}
public String addAttachmentsRedirect() {
// 1. redirect to add attachment
try {
List filePickerList = new ArrayList();
if (attachmentList != null){
filePickerList = prepareReferenceList(attachmentList);
}
ToolSession currentToolSession = SessionManager.getCurrentToolSession();
currentToolSession.setAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS, filePickerList);
ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
context.redirect("sakai.filepicker.helper/tool");
}
catch(Exception e){
log.error("fail to redirect to attachment page: " + e.getMessage());
}
return "editAssessmentSettings";
}
public void setAssessmentAttachment(){
SaveAssessmentAttachmentListener lis = new SaveAssessmentAttachmentListener();
lis.processAction(null);
}
private List prepareReferenceList(List attachmentList){
List list = new ArrayList();
for (int i=0; i<attachmentList.size(); i++){
ContentResource cr = null;
AttachmentIfc attach = (AttachmentIfc) attachmentList.get(i);
try{
cr = ContentHostingService.getResource(attach.getResourceId());
}
catch (PermissionException e) {
log.warn("PermissionException from ContentHostingService:"+e.getMessage());
}
catch (IdUnusedException e) {
log.warn("IdUnusedException from ContentHostingService:"+e.getMessage());
// <-- bad sign, some left over association of assessment and resource,
// use case: user remove resource in file picker, then exit modification without
// proper cancellation by clicking at the left nav instead of "cancel".
// Also in this use case, any added resource would be left orphan.
AssessmentService assessmentService = new AssessmentService();
assessmentService.removeAssessmentAttachment(attach.getAttachmentId().toString());
}
catch (TypeException e) {
log.warn("TypeException from ContentHostingService:"+e.getMessage());
}
if (cr!=null){
ReferenceComponent ref = new ReferenceComponent(cr.getReference());
if (ref !=null ) list.add(ref);
}
}
return list;
}
private HashMap resourceHash = new HashMap();
public HashMap getResourceHash() {
return resourceHash;
}
public void setResourceHash(HashMap resourceHash)
{
this.resourceHash = resourceHash;
}
}
| false | true | public void setAssessment(AssessmentFacade assessment) {
try {
//1. set the template info
AssessmentService service = new AssessmentService();
AssessmentTemplateIfc template = service.getAssessmentTemplate(
assessment.getAssessmentTemplateId().toString());
if (template != null){
setNoTemplate(false);
this.templateTitle = template.getTitle();
this.templateDescription = template.getDescription();
this.templateAuthors = template.getAssessmentMetaDataByLabel(
"author"); // see TemplateUploadListener line 142
}
else{
setNoTemplate(true);
}
//2. set the assessment info
this.assessment = assessment;
// set the valueMap
setValueMap(assessment.getAssessmentMetaDataMap());
this.assessmentId = assessment.getAssessmentId();
this.title = assessment.getTitle();
this.creator = AgentFacade.getDisplayName(assessment.getCreatedBy());
this.description = assessment.getDescription();
// assessment meta data
this.authors = assessment.getAssessmentMetaDataByLabel(AssessmentMetaDataIfc.
AUTHORS);
this.objectives = assessment.getAssessmentMetaDataByLabel(
AssessmentMetaDataIfc.OBJECTIVES);
this.keywords = assessment.getAssessmentMetaDataByLabel(AssessmentMetaDataIfc.
KEYWORDS);
this.rubrics = assessment.getAssessmentMetaDataByLabel(AssessmentMetaDataIfc.
RUBRICS);
this.bgColor = assessment.getAssessmentMetaDataByLabel(AssessmentMetaDataIfc.
BGCOLOR);
this.bgImage = assessment.getAssessmentMetaDataByLabel(AssessmentMetaDataIfc.
BGIMAGE);
if((assessment.getAssessmentMetaDataByLabel(AssessmentMetaDataIfc.
BGIMAGE)!=null )&&(!assessment.getAssessmentMetaDataByLabel(AssessmentMetaDataIfc.
BGIMAGE).equals(""))){
this.bgImageSelect="1";
this.bgColorSelect=null;
}
else{
this.bgImageSelect=null;
this.bgColorSelect="1";
}
// these are properties in AssessmentAccessControl
AssessmentAccessControlIfc accessControl = null;
accessControl = assessment.getAssessmentAccessControl();
if (accessControl != null) {
this.startDate = accessControl.getStartDate();
this.dueDate = accessControl.getDueDate();
this.retractDate = accessControl.getRetractDate();
this.feedbackDate = accessControl.getFeedbackDate();
// deal with releaseTo
this.releaseTo = accessControl.getReleaseTo(); // list of String
this.publishingTargets = getPublishingTargets();
this.targetSelected = getTargetSelected(releaseTo);
this.firstTargetSelected = getFirstTargetSelected(releaseTo);
// SAK-1850 - when importing assessment forget to set releaseTo, we will catch it
// and set it to host site
if (!validateTarget(firstTargetSelected)){
releaseTo = AgentFacade.getCurrentSiteName();
firstTargetSelected = AgentFacade.getCurrentSiteName();
targetSelected = getTargetSelected(releaseTo);
}
this.timeLimit = accessControl.getTimeLimit(); // in seconds
if (timeLimit !=null && timeLimit.intValue()>0)
setTimeLimitDisplay(timeLimit.intValue());
else
resetTimeLimitDisplay();
if ((new Integer(1)).equals(accessControl.getTimedAssessment()))
this.timedAssessment = true;
if ((new Integer(1)).equals(accessControl.getAutoSubmit()))
this.autoSubmit = true;
if (accessControl.getAssessmentFormat()!=null)
this.assessmentFormat = accessControl.getAssessmentFormat().toString(); // question/part/assessment on separate page
if (accessControl.getItemNavigation()!=null)
this.itemNavigation = accessControl.getItemNavigation().toString(); // linear or random
if (accessControl.getItemNumbering()!=null)
this.itemNumbering = accessControl.getItemNumbering().toString();
if (accessControl.getSubmissionsSaved()!=null) // bad name, this is autoSaved
this.submissionsSaved = accessControl.getSubmissionsSaved().toString();
// default to unlimited if control value is null
if (accessControl.getUnlimitedSubmissions()!=null && !accessControl.getUnlimitedSubmissions().booleanValue()){
this.unlimitedSubmissions=AssessmentAccessControlIfc.LIMITED_SUBMISSIONS.toString();
this.submissionsAllowed = accessControl.getSubmissionsAllowed().toString();
}
else{
this.unlimitedSubmissions=AssessmentAccessControlIfc.UNLIMITED_SUBMISSIONS.toString();
this.submissionsAllowed="";
}
if (accessControl.getLateHandling() !=null)
this.lateHandling = accessControl.getLateHandling().toString();
if (accessControl.getSubmissionsSaved()!=null)
this.submissionsSaved = accessControl.getSubmissionsSaved().toString();
this.submissionMessage = accessControl.getSubmissionMessage();
this.username = accessControl.getUsername();
this.password = accessControl.getPassword();
this.finalPageUrl = accessControl.getFinalPageUrl();
}
// properties of AssesmentFeedback
AssessmentFeedbackIfc feedback = assessment.getAssessmentFeedback();
if (feedback != null) {
if (feedback.getFeedbackDelivery()!=null)
this.feedbackDelivery = feedback.getFeedbackDelivery().toString();
if (feedback.getFeedbackAuthoring()!=null)
this.feedbackAuthoring = feedback.getFeedbackAuthoring().toString();
if ((Boolean.TRUE).equals(feedback.getShowQuestionText()))
this.showQuestionText = true;
if ((Boolean.TRUE).equals(feedback.getShowStudentResponse()))
this.showStudentResponse = true;
if ((Boolean.TRUE).equals(feedback.getShowCorrectResponse()))
this.showCorrectResponse = true;
if ((Boolean.TRUE).equals(feedback.getShowStudentScore()))
this.showStudentScore = true;
if ((Boolean.TRUE).equals(feedback.getShowStudentQuestionScore()))
this.showStudentQuestionScore = true;
if ((Boolean.TRUE).equals(feedback.getShowQuestionLevelFeedback()))
this.showQuestionLevelFeedback = true;
if ((Boolean.TRUE).equals(feedback.getShowSelectionLevelFeedback()))
this.showSelectionLevelFeedback = true;// must be MC
if ((Boolean.TRUE).equals(feedback.getShowGraderComments()))
this.showGraderComments = true;
if ((Boolean.TRUE).equals(feedback.getShowStatistics()))
this.showStatistics = true;
}
// properties of EvaluationModel
EvaluationModelIfc evaluation = assessment.getEvaluationModel();
if (evaluation != null) {
if (evaluation.getAnonymousGrading()!=null)
this.anonymousGrading = evaluation.getAnonymousGrading().toString();
if (evaluation.getToGradeBook()!=null )
this.toDefaultGradebook = evaluation.getToGradeBook();
if (evaluation.getScoringType()!=null)
this.scoringType = evaluation.getScoringType().toString();
GradebookService g = null;
if (integrated)
{
g = (GradebookService) SpringBeanLocator.getInstance().
getBean("org.sakaiproject.service.gradebook.GradebookService");
}
this.gradebookExists = gbsHelper.gradebookExists(
GradebookFacade.getGradebookUId(), g);
}
// ip addresses
this.ipAddresses = "";
Set ipAddressSet = assessment.getSecuredIPAddressSet();
if (ipAddressSet != null){
Iterator iter = ipAddressSet.iterator();
while (iter.hasNext()) {
SecuredIPAddressIfc ip = (SecuredIPAddressIfc) iter.next();
if (ip.getIpAddress()!=null)
this.ipAddresses = ip.getIpAddress()+"\n"+this.ipAddresses;
}
}
// attachment
this.attachmentList = assessment.getAssessmentAttachmentList();
}
catch (RuntimeException ex) {
ex.printStackTrace();
}
}
| public void setAssessment(AssessmentFacade assessment) {
try {
//1. set the template info
AssessmentService service = new AssessmentService();
AssessmentTemplateIfc template = null;
if (assessment.getAssessmentTemplateId()!=null){
template = service.getAssessmentTemplate(
assessment.getAssessmentTemplateId().toString());
}
if (template != null){
setNoTemplate(false);
this.templateTitle = template.getTitle();
this.templateDescription = template.getDescription();
this.templateAuthors = template.getAssessmentMetaDataByLabel(
"author"); // see TemplateUploadListener line 142
}
else{
setNoTemplate(true);
}
//2. set the assessment info
this.assessment = assessment;
// set the valueMap
setValueMap(assessment.getAssessmentMetaDataMap());
this.assessmentId = assessment.getAssessmentId();
this.title = assessment.getTitle();
this.creator = AgentFacade.getDisplayName(assessment.getCreatedBy());
this.description = assessment.getDescription();
// assessment meta data
this.authors = assessment.getAssessmentMetaDataByLabel(AssessmentMetaDataIfc.
AUTHORS);
this.objectives = assessment.getAssessmentMetaDataByLabel(
AssessmentMetaDataIfc.OBJECTIVES);
this.keywords = assessment.getAssessmentMetaDataByLabel(AssessmentMetaDataIfc.
KEYWORDS);
this.rubrics = assessment.getAssessmentMetaDataByLabel(AssessmentMetaDataIfc.
RUBRICS);
this.bgColor = assessment.getAssessmentMetaDataByLabel(AssessmentMetaDataIfc.
BGCOLOR);
this.bgImage = assessment.getAssessmentMetaDataByLabel(AssessmentMetaDataIfc.
BGIMAGE);
if((assessment.getAssessmentMetaDataByLabel(AssessmentMetaDataIfc.
BGIMAGE)!=null )&&(!assessment.getAssessmentMetaDataByLabel(AssessmentMetaDataIfc.
BGIMAGE).equals(""))){
this.bgImageSelect="1";
this.bgColorSelect=null;
}
else{
this.bgImageSelect=null;
this.bgColorSelect="1";
}
// these are properties in AssessmentAccessControl
AssessmentAccessControlIfc accessControl = null;
accessControl = assessment.getAssessmentAccessControl();
if (accessControl != null) {
this.startDate = accessControl.getStartDate();
this.dueDate = accessControl.getDueDate();
this.retractDate = accessControl.getRetractDate();
this.feedbackDate = accessControl.getFeedbackDate();
// deal with releaseTo
this.releaseTo = accessControl.getReleaseTo(); // list of String
this.publishingTargets = getPublishingTargets();
this.targetSelected = getTargetSelected(releaseTo);
this.firstTargetSelected = getFirstTargetSelected(releaseTo);
// SAK-1850 - when importing assessment forget to set releaseTo, we will catch it
// and set it to host site
if (!validateTarget(firstTargetSelected)){
releaseTo = AgentFacade.getCurrentSiteName();
firstTargetSelected = AgentFacade.getCurrentSiteName();
targetSelected = getTargetSelected(releaseTo);
}
this.timeLimit = accessControl.getTimeLimit(); // in seconds
if (timeLimit !=null && timeLimit.intValue()>0)
setTimeLimitDisplay(timeLimit.intValue());
else
resetTimeLimitDisplay();
if ((new Integer(1)).equals(accessControl.getTimedAssessment()))
this.timedAssessment = true;
if ((new Integer(1)).equals(accessControl.getAutoSubmit()))
this.autoSubmit = true;
if (accessControl.getAssessmentFormat()!=null)
this.assessmentFormat = accessControl.getAssessmentFormat().toString(); // question/part/assessment on separate page
if (accessControl.getItemNavigation()!=null)
this.itemNavigation = accessControl.getItemNavigation().toString(); // linear or random
if (accessControl.getItemNumbering()!=null)
this.itemNumbering = accessControl.getItemNumbering().toString();
if (accessControl.getSubmissionsSaved()!=null) // bad name, this is autoSaved
this.submissionsSaved = accessControl.getSubmissionsSaved().toString();
// default to unlimited if control value is null
if (accessControl.getUnlimitedSubmissions()!=null && !accessControl.getUnlimitedSubmissions().booleanValue()){
this.unlimitedSubmissions=AssessmentAccessControlIfc.LIMITED_SUBMISSIONS.toString();
this.submissionsAllowed = accessControl.getSubmissionsAllowed().toString();
}
else{
this.unlimitedSubmissions=AssessmentAccessControlIfc.UNLIMITED_SUBMISSIONS.toString();
this.submissionsAllowed="";
}
if (accessControl.getLateHandling() !=null)
this.lateHandling = accessControl.getLateHandling().toString();
if (accessControl.getSubmissionsSaved()!=null)
this.submissionsSaved = accessControl.getSubmissionsSaved().toString();
this.submissionMessage = accessControl.getSubmissionMessage();
this.username = accessControl.getUsername();
this.password = accessControl.getPassword();
this.finalPageUrl = accessControl.getFinalPageUrl();
}
// properties of AssesmentFeedback
AssessmentFeedbackIfc feedback = assessment.getAssessmentFeedback();
if (feedback != null) {
if (feedback.getFeedbackDelivery()!=null)
this.feedbackDelivery = feedback.getFeedbackDelivery().toString();
if (feedback.getFeedbackAuthoring()!=null)
this.feedbackAuthoring = feedback.getFeedbackAuthoring().toString();
if ((Boolean.TRUE).equals(feedback.getShowQuestionText()))
this.showQuestionText = true;
if ((Boolean.TRUE).equals(feedback.getShowStudentResponse()))
this.showStudentResponse = true;
if ((Boolean.TRUE).equals(feedback.getShowCorrectResponse()))
this.showCorrectResponse = true;
if ((Boolean.TRUE).equals(feedback.getShowStudentScore()))
this.showStudentScore = true;
if ((Boolean.TRUE).equals(feedback.getShowStudentQuestionScore()))
this.showStudentQuestionScore = true;
if ((Boolean.TRUE).equals(feedback.getShowQuestionLevelFeedback()))
this.showQuestionLevelFeedback = true;
if ((Boolean.TRUE).equals(feedback.getShowSelectionLevelFeedback()))
this.showSelectionLevelFeedback = true;// must be MC
if ((Boolean.TRUE).equals(feedback.getShowGraderComments()))
this.showGraderComments = true;
if ((Boolean.TRUE).equals(feedback.getShowStatistics()))
this.showStatistics = true;
}
// properties of EvaluationModel
EvaluationModelIfc evaluation = assessment.getEvaluationModel();
if (evaluation != null) {
if (evaluation.getAnonymousGrading()!=null)
this.anonymousGrading = evaluation.getAnonymousGrading().toString();
if (evaluation.getToGradeBook()!=null )
this.toDefaultGradebook = evaluation.getToGradeBook();
if (evaluation.getScoringType()!=null)
this.scoringType = evaluation.getScoringType().toString();
GradebookService g = null;
if (integrated)
{
g = (GradebookService) SpringBeanLocator.getInstance().
getBean("org.sakaiproject.service.gradebook.GradebookService");
}
this.gradebookExists = gbsHelper.gradebookExists(
GradebookFacade.getGradebookUId(), g);
}
// ip addresses
this.ipAddresses = "";
Set ipAddressSet = assessment.getSecuredIPAddressSet();
if (ipAddressSet != null){
Iterator iter = ipAddressSet.iterator();
while (iter.hasNext()) {
SecuredIPAddressIfc ip = (SecuredIPAddressIfc) iter.next();
if (ip.getIpAddress()!=null)
this.ipAddresses = ip.getIpAddress()+"\n"+this.ipAddresses;
}
}
// attachment
this.attachmentList = assessment.getAssessmentAttachmentList();
}
catch (RuntimeException ex) {
ex.printStackTrace();
}
}
|
diff --git a/server/src/main/java/org/apache/accumulo/server/tabletserver/TabletStatsKeeper.java b/server/src/main/java/org/apache/accumulo/server/tabletserver/TabletStatsKeeper.java
index 67e3aa540..81a6c64b5 100644
--- a/server/src/main/java/org/apache/accumulo/server/tabletserver/TabletStatsKeeper.java
+++ b/server/src/main/java/org/apache/accumulo/server/tabletserver/TabletStatsKeeper.java
@@ -1,123 +1,123 @@
/*
* 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.accumulo.server.tabletserver;
import org.apache.accumulo.core.tabletserver.thrift.ActionStats;
import org.apache.accumulo.core.tabletserver.thrift.TabletStats;
public class TabletStatsKeeper {
public static void update(ActionStats summary, ActionStats td) {
summary.status += td.status;
summary.elapsed += td.elapsed;
summary.num += td.num;
summary.count += td.count;
summary.sumDev += td.sumDev;
summary.queueTime += td.queueTime;
summary.queueSumDev += td.queueSumDev;
summary.fail += td.fail;
}
private ActionStats major = new ActionStats();
private ActionStats minor = new ActionStats();
private ActionStats split = new ActionStats();
public enum Operation {
MAJOR, SPLIT, MINOR
}
private ActionStats[] map = new ActionStats[] {major, split, minor};
public void updateTime(Operation operation, long queued, long start, long count, boolean failed) {
try {
ActionStats data = map[operation.ordinal()];
if (failed) {
data.fail++;
data.status--;
} else {
double t = (System.currentTimeMillis() - start) / 1000.0;
double q = (start - queued) / 1000.0;
data.status--;
data.count += count;
data.num++;
data.elapsed += t;
- data.queueTime += t;
+ data.queueTime += q;
data.sumDev += t * t;
data.queueSumDev += q * q;
if (data.elapsed < 0 || data.sumDev < 0 || data.queueSumDev < 0 || data.queueTime < 0)
resetTimes();
}
} catch (Exception E) {
resetTimes();
}
}
public void updateTime(Operation operation, long start, long count, boolean failed) {
try {
ActionStats data = map[operation.ordinal()];
if (failed) {
data.fail++;
data.status--;
} else {
double t = (System.currentTimeMillis() - start) / 1000.0;
data.status--;
data.num++;
data.elapsed += t;
data.sumDev += t * t;
if (data.elapsed < 0 || data.sumDev < 0 || data.queueSumDev < 0 || data.queueTime < 0)
resetTimes();
}
} catch (Exception E) {
resetTimes();
}
}
public void saveMinorTimes(TabletStatsKeeper t) {
update(minor, t.minor);
}
public void saveMajorTimes(TabletStatsKeeper t) {
update(major, t.major);
}
public void resetTimes() {
major = new ActionStats();
split = new ActionStats();
minor = new ActionStats();
}
public void incrementStatusMinor() {
minor.status++;
}
public void incrementStatusMajor() {
major.status++;
}
public void incrementStatusSplit() {
split.status++;
}
public TabletStats getTabletStats() {
return new TabletStats(null, major, minor, split, 0, 0, 0, 0);
}
}
| true | true | public void updateTime(Operation operation, long queued, long start, long count, boolean failed) {
try {
ActionStats data = map[operation.ordinal()];
if (failed) {
data.fail++;
data.status--;
} else {
double t = (System.currentTimeMillis() - start) / 1000.0;
double q = (start - queued) / 1000.0;
data.status--;
data.count += count;
data.num++;
data.elapsed += t;
data.queueTime += t;
data.sumDev += t * t;
data.queueSumDev += q * q;
if (data.elapsed < 0 || data.sumDev < 0 || data.queueSumDev < 0 || data.queueTime < 0)
resetTimes();
}
} catch (Exception E) {
resetTimes();
}
}
| public void updateTime(Operation operation, long queued, long start, long count, boolean failed) {
try {
ActionStats data = map[operation.ordinal()];
if (failed) {
data.fail++;
data.status--;
} else {
double t = (System.currentTimeMillis() - start) / 1000.0;
double q = (start - queued) / 1000.0;
data.status--;
data.count += count;
data.num++;
data.elapsed += t;
data.queueTime += q;
data.sumDev += t * t;
data.queueSumDev += q * q;
if (data.elapsed < 0 || data.sumDev < 0 || data.queueSumDev < 0 || data.queueTime < 0)
resetTimes();
}
} catch (Exception E) {
resetTimes();
}
}
|
diff --git a/src/main/java/mcgill/fiveCardStud/FiveCardStud.java b/src/main/java/mcgill/fiveCardStud/FiveCardStud.java
index e68b227..3323d50 100644
--- a/src/main/java/mcgill/fiveCardStud/FiveCardStud.java
+++ b/src/main/java/mcgill/fiveCardStud/FiveCardStud.java
@@ -1,413 +1,413 @@
package mcgill.fiveCardStud;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import mcgill.game.ClientNotification;
import mcgill.game.Config;
import mcgill.game.Database;
import mcgill.game.Server;
import mcgill.game.User;
import mcgill.poker.Deck;
import mcgill.poker.Hand;
import mcgill.poker.HandRank;
import mcgill.poker.Player;
import mcgill.poker.Pot;
import mcgill.poker.OutOfMoneyException;
import mcgill.poker.TooFewCardsException;
import mcgill.poker.TooManyCardsException;
public class FiveCardStud implements Runnable {
public static final int FOLDED = -1;
public static final int BETTING = 0;
public static final int ALL_IN = 1;
private int maxRaises;
private int street;
private int raises;
private int lowBet;
private int bringIn;
private Deck deck;
private List<Player> players;
private List<Pot> pots;
private int startingPlayer;
public FiveCardStud(List<Player> players, int lowBet, int maxRaises, int bringIn) {
this.raises = 0;
this.players = players;
this.pots= new ArrayList<Pot>();
this.deck = new Deck();
this.street = 2;
this.lowBet = lowBet;
this.maxRaises = maxRaises;
this.bringIn = bringIn;
this.startingPlayer = 0;
}
public void run() {
try {
this.playRound();
System.out.println("Round is done");
} catch (Exception e) {
System.out.println("*** PLAY ROUND EXCEPTION ***");
e.printStackTrace();
}
}
public void playRound() throws TooFewCardsException, TooManyCardsException, OutOfMoneyException {
while (this.street < 6) {
if (this.street == 2) {
initialize();
}
if (onlyOneBetting()) break;
for(Player player : this.players) {
player.addCard(this.deck.getTop());
emitHands();
}
betting();
}
makePots();
dividePots();
Database db = new Database(Config.REDIS_HOST, Config.REDIS_PORT);
String winner = null;
Map<String, Integer> credit_map = new HashMap<String, Integer>();
for (Player player : this.players) {
User user = db.getUser(player.getUsername(), false);
user.setCredits(player.getTotalMoney());
db.setUser(user);
credit_map.put(player.getUsername(), player.getTotalMoney());
if (player.isWinner()) {
winner = player.getUsername();
}
}
emitEndOfRound(winner, credit_map);
}
private void emitEndOfRound(String winner, Map<String, Integer> credit_map) {
EndOfRound end = new EndOfRound(winner, credit_map);
for (Player player : this.players) {
String session_str = Server.getUserSession(player.getUsername());
ClientNotification notification = new ClientNotification(session_str);
notification.sendEndOfRound(end);
}
}
private void potAndStatusNotification(Player player) {
int[] current = new int[2];
current[0] = player.getAmountInPots();
current[1] = player.getStatus();
String session_str = Server.getUserSession(player.getUsername());
ClientNotification notification = new ClientNotification(session_str);
notification.potAndStatus(current);
}
private int getAction(String username, int[] limits) {
String session_str = Server.getUserSession(username);
ClientNotification notification = new ClientNotification(session_str);
String command = notification.getCommand(limits);
return Integer.parseInt(command);
}
private void emitHands() {
Map<String, Hand> hands = new HashMap<String, Hand>();
for (Player player : this.players) {
hands.put(player.getUsername(), player.getHand());
}
for (Player player : this.players) {
String session_str = Server.getUserSession(player.getUsername());
ClientNotification notification = new ClientNotification(session_str);
notification.sendHand(hands);
}
}
private void initialize() throws TooFewCardsException, TooManyCardsException, OutOfMoneyException {
for(Player player : this.players) {
try {
player.bet(this.lowBet/4);
player.addCard(this.deck.getTop()); //face down
emitHands();
} catch (OutOfMoneyException e) {
this.players.remove(player);
} catch (TooManyCardsException e) {
throw new RuntimeException(e.getMessage());
}
}
}
private void betting() throws OutOfMoneyException, TooFewCardsException, TooManyCardsException {
int i = 1;
boolean continueStreet = true;
findStartingPlayer();
while (continueStreet) {
for (int j = startingPlayer; j < (startingPlayer + this.players.size()); j++){
if ((noMoreCalls() || onlyOneBetting()) && i != 1) {
continueStreet = false;
this.startingPlayer = 0;
this.raises = 0;
this.street++;
break;
}
int index = j;
int betLimit;
//Betting limits based on which street the round is in
if (this.street == 2) {
if (index == this.startingPlayer && i == 1) {
betLimit = this.bringIn;
} else if (index == (this.startingPlayer + 1) && i == 1) {
betLimit = this.lowBet - this.bringIn;
} else {
betLimit = this.lowBet;
}
} else if (this.street == 3) {
betLimit = this.lowBet;
} else {
betLimit = 2*(this.lowBet);
}
//Wraps around
if (index >= this.players.size()) {
index = j - this.players.size();
}
Player currentPlayer = players.get(index);
if (currentPlayer.isBetting()) {
potAndStatusNotification(players.get(index));
int callAmount = getCallAmount() - currentPlayer.getAmountInPots();
if (this.street == 2 && this.startingPlayer == index && i == 1) {
callAmount = this.bringIn;
} else if (raises >= maxRaises) {
- betLimit = callAmount;
+ betLimit = 0;
}
int limitAmount = callAmount + betLimit;
int[] limits = {callAmount, limitAmount};
int action = getAction(players.get(index).getUsername(), limits);
System.out.println("Action for " + players.get(index).getUsername() + " is: " + action);
if (action == 0);
else if (action == -1) {
currentPlayer.setStatus(FOLDED);
} else {
if (action > callAmount) {this.raises++;}
if (action >= currentPlayer.getTotalMoney()) {
currentPlayer.bet(currentPlayer.getTotalMoney());
currentPlayer.setStatus(ALL_IN);
} else {
currentPlayer.bet(action);
}
}
//GameTest.printAmountInPots(players.get(index));
System.out.println("\n ---------------------------------------- \n");
}
}
i++;
}
}
//Fix 2,3,4 cards (it for some reason does not just look for pairs, three of a kind, four of a kind, 2 pairs)
private void findStartingPlayer() throws TooFewCardsException, TooManyCardsException {
int i = 0;
if (street == 2) {
for (Player player : this.players) {
if (HandRank.compareHands(players.get(startingPlayer).getHand(), player.getHand(), 1) == 0) {
startingPlayer = i;
}
i++;
}
} else {
for (Player player : this.players) {
if (player.isBetting() && (HandRank.compareHands(players.get(startingPlayer).getHand(), player.getHand(), street - 1) == 1)) {
startingPlayer = i;
}
i++;
}
}
}
private void makePots() {
Player[] playerArray = new Player[this.players.size()];
this.players.toArray(playerArray);
Arrays.sort(playerArray);
int[] amountInPots = new int[playerArray.length];
for (int i = 0; i < playerArray.length; i++) {
amountInPots[i] = playerArray[i].getAmountInPots();
}
for (int i = 0; i < playerArray.length; i++) {
Player player = playerArray[i];
if (player.isAllIn() && (amountInPots[i] != 0)) {
Pot pot = new Pot();
pot.setLimit(amountInPots[i]);
for (int j = 0; j < playerArray.length; j++) {
if (amountInPots[j] != 0) {
if (playerArray[j].isFolded()) {
if (amountInPots[j] > pot.getLimit()) {
pot.addToPot(pot.getLimit());
amountInPots[j] -= pot.getLimit();
} else {
pot.addToPot(amountInPots[j]);
amountInPots[j] = 0;
}
} else {
if (amountInPots[j] > pot.getLimit()) {
if (pot.containsPlayer(playerArray[j])) {
pot.addToPot(pot.getLimit());
} else {
pot.addPlayer(playerArray[j], pot.getLimit());
}
amountInPots[j] -= pot.getLimit();
} else {
if (pot.containsPlayer(playerArray[j])) {
pot.addToPot(amountInPots[j]);
} else {
pot.addPlayer(playerArray[j], amountInPots[j]);
}
amountInPots[j] = 0;
}
}
}
}
this.pots.add(pot);
}
}
Pot pot = new Pot();
for (int j = 0; j < playerArray.length; j++) {
if (amountInPots[j] != 0) {
if (playerArray[j].isFolded()) {
pot.addToPot(amountInPots[j]);
amountInPots[j] = 0;
} else {
if (pot.containsPlayer(playerArray[j])) {
pot.addToPot(amountInPots[j]);
} else {
pot.addPlayer(playerArray[j], amountInPots[j]);
}
amountInPots[j] = 0;
}
}
}
this.pots.add(pot);
}
private boolean onlyOneBetting() {
int playersBetting = 0;
for (Player player : this.players) {
if (player.isBetting()) {
playersBetting++;
}
}
if (playersBetting <= 1) {
return true;
} else {
return false;
}
}
private boolean noMoreCalls() {
for (Player player : this.players) {
if (player.isBetting()) {
int moneyToMatch = player.getAmountInPots();
for (Player tmpPlayer : this.players) {
if (tmpPlayer.isBetting()) {
if (tmpPlayer.getAmountInPots() != moneyToMatch) {
return false;
}
}
}
}
}
return true;
}
private int getCallAmount() {
int callAmount = 0;
for (Player player : this.players) {
if ((!player.isFolded()) && (player.getAmountInPots() > callAmount)) {
callAmount = player.getAmountInPots();
}
}
return callAmount;
}
private void dividePots() throws TooFewCardsException, TooManyCardsException {
//need to account for ties
for (Pot pot : this.pots) {
int winningPlayer = 0;
int winners = 0;
int i = 0;
ArrayList<Player> potPlayers = pot.getPlayers();
for (Player player : potPlayers) {
if ((!player.isFolded()) && (HandRank.compareHands(potPlayers.get(winningPlayer).getHand(), player.getHand(), 5) == 1)) {
winningPlayer = i;
}
i++;
}
Player winner = potPlayers.get(winningPlayer);
for (Player player : this.players) {
if ((!player.isFolded()) && (HandRank.compareHands(winner.getHand(), player.getHand(), 5) == -1)) {
player.setWinner(true);
winners++;
}
}
for (Player player : this.players) {
if (player.isWinner()) {
player.addMoney(pot.getTotalAmount()/winners);
player.setWinner(false);
}
}
}
}
}
| true | true | private void betting() throws OutOfMoneyException, TooFewCardsException, TooManyCardsException {
int i = 1;
boolean continueStreet = true;
findStartingPlayer();
while (continueStreet) {
for (int j = startingPlayer; j < (startingPlayer + this.players.size()); j++){
if ((noMoreCalls() || onlyOneBetting()) && i != 1) {
continueStreet = false;
this.startingPlayer = 0;
this.raises = 0;
this.street++;
break;
}
int index = j;
int betLimit;
//Betting limits based on which street the round is in
if (this.street == 2) {
if (index == this.startingPlayer && i == 1) {
betLimit = this.bringIn;
} else if (index == (this.startingPlayer + 1) && i == 1) {
betLimit = this.lowBet - this.bringIn;
} else {
betLimit = this.lowBet;
}
} else if (this.street == 3) {
betLimit = this.lowBet;
} else {
betLimit = 2*(this.lowBet);
}
//Wraps around
if (index >= this.players.size()) {
index = j - this.players.size();
}
Player currentPlayer = players.get(index);
if (currentPlayer.isBetting()) {
potAndStatusNotification(players.get(index));
int callAmount = getCallAmount() - currentPlayer.getAmountInPots();
if (this.street == 2 && this.startingPlayer == index && i == 1) {
callAmount = this.bringIn;
} else if (raises >= maxRaises) {
betLimit = callAmount;
}
int limitAmount = callAmount + betLimit;
int[] limits = {callAmount, limitAmount};
int action = getAction(players.get(index).getUsername(), limits);
System.out.println("Action for " + players.get(index).getUsername() + " is: " + action);
if (action == 0);
else if (action == -1) {
currentPlayer.setStatus(FOLDED);
} else {
if (action > callAmount) {this.raises++;}
if (action >= currentPlayer.getTotalMoney()) {
currentPlayer.bet(currentPlayer.getTotalMoney());
currentPlayer.setStatus(ALL_IN);
} else {
currentPlayer.bet(action);
}
}
//GameTest.printAmountInPots(players.get(index));
System.out.println("\n ---------------------------------------- \n");
}
}
i++;
}
}
| private void betting() throws OutOfMoneyException, TooFewCardsException, TooManyCardsException {
int i = 1;
boolean continueStreet = true;
findStartingPlayer();
while (continueStreet) {
for (int j = startingPlayer; j < (startingPlayer + this.players.size()); j++){
if ((noMoreCalls() || onlyOneBetting()) && i != 1) {
continueStreet = false;
this.startingPlayer = 0;
this.raises = 0;
this.street++;
break;
}
int index = j;
int betLimit;
//Betting limits based on which street the round is in
if (this.street == 2) {
if (index == this.startingPlayer && i == 1) {
betLimit = this.bringIn;
} else if (index == (this.startingPlayer + 1) && i == 1) {
betLimit = this.lowBet - this.bringIn;
} else {
betLimit = this.lowBet;
}
} else if (this.street == 3) {
betLimit = this.lowBet;
} else {
betLimit = 2*(this.lowBet);
}
//Wraps around
if (index >= this.players.size()) {
index = j - this.players.size();
}
Player currentPlayer = players.get(index);
if (currentPlayer.isBetting()) {
potAndStatusNotification(players.get(index));
int callAmount = getCallAmount() - currentPlayer.getAmountInPots();
if (this.street == 2 && this.startingPlayer == index && i == 1) {
callAmount = this.bringIn;
} else if (raises >= maxRaises) {
betLimit = 0;
}
int limitAmount = callAmount + betLimit;
int[] limits = {callAmount, limitAmount};
int action = getAction(players.get(index).getUsername(), limits);
System.out.println("Action for " + players.get(index).getUsername() + " is: " + action);
if (action == 0);
else if (action == -1) {
currentPlayer.setStatus(FOLDED);
} else {
if (action > callAmount) {this.raises++;}
if (action >= currentPlayer.getTotalMoney()) {
currentPlayer.bet(currentPlayer.getTotalMoney());
currentPlayer.setStatus(ALL_IN);
} else {
currentPlayer.bet(action);
}
}
//GameTest.printAmountInPots(players.get(index));
System.out.println("\n ---------------------------------------- \n");
}
}
i++;
}
}
|
diff --git a/MonTransit/src/org/montrealtransit/android/LocationUtils.java b/MonTransit/src/org/montrealtransit/android/LocationUtils.java
index fab93747..18256a68 100755
--- a/MonTransit/src/org/montrealtransit/android/LocationUtils.java
+++ b/MonTransit/src/org/montrealtransit/android/LocationUtils.java
@@ -1,140 +1,143 @@
package org.montrealtransit.android;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
/**
* Location useful methods.
* @author Mathieu Méa
*/
public class LocationUtils {
/**
* The log tag.
*/
private static final String TAG = LocationUtils.class.getSimpleName();
/**
* The minimum time between 2 locations updates (in milliseconds)
*/
public static final long MIN_TIME = 2000; // 2 second
/**
* The minimum distance between 2 updates
*/
public static final float MIN_DISTANCE = 5; // 5 meter
/**
* The validity of a last know location (in milliseconds)
*/
private static final long MAX_LAST_KNOW_LOCATION_TIME = 600000; // 10 minutes
/**
* Utility class.
*/
private LocationUtils() {
};
/**
* @param activity the activity
* @return the providers matching the application requirement
*/
private static List<String> getBestProviders(Activity activity) {
Criteria criteria = new Criteria();
// criteria.setAccuracy(Criteria.ACCURACY_FINE); any accuracy
criteria.setAltitudeRequired(false); // no altitude
criteria.setBearingRequired(false); // no compass... for now ;)
criteria.setSpeedRequired(false); // no speed required
boolean enabledOnly = true; // only enabled location providers
List<String> providers = getLocationManager(activity).getProviders(criteria, enabledOnly);
MyLog.v(TAG, "nb location providers: " + providers.size());
return providers;
}
/**
* @param activity the activity
* @return the location manager service
*/
public static LocationManager getLocationManager(Activity activity) {
return (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
}
/**
* @param activity the activity
* @return the best valid last know location or <b>NULL</b>
*/
public static Location getBestLastKnownLocation(Activity activity) {
Location result = null;
for (String provider : getBestProviders(activity)) {
Location lastLocation = getLocationManager(activity).getLastKnownLocation(provider);
- // IF no last location candidate DO
- if (result == null) {
- // IF this location candidate is not too old DO
- if (isNotTooOld(lastLocation)) {
- result = lastLocation;
+ // IF the last location is NOT NULL (= location provider disabled) DO
+ if (lastLocation != null) {
+ // IF no last location candidate DO
+ if (result == null) {
+ // IF this location candidate is not too old DO
+ if (isNotTooOld(lastLocation)) {
+ result = lastLocation;
+ }
+ } else {
+ // IF the new location candidate is more recent DO
+ if (lastLocation.getTime() > result.getTime()) {
+ result = lastLocation;
+ }
+ // TODO compare accuracy?
}
- } else {
- // IF the new location candidate is more recent DO
- if (lastLocation.getTime() > result.getTime()) {
- result = lastLocation;
- }
- // TODO compare accuracy?
}
}
if (result != null) {
MyLog.v(TAG, "last know location:" + result.getProvider() + " > " + result.getLatitude() + ", "
+ result.getLongitude() + "(" + result.getAccuracy() + ") "
+ ((System.currentTimeMillis() - result.getTime()) / 1000) + " seconds ago.");
} else {
MyLog.v(TAG, "no valid last location found!");
}
return result;
}
/**
* @param location the location
* @return true if the location is not too "old"
*/
private static boolean isNotTooOld(Location location) {
return System.currentTimeMillis() - location.getTime() < MAX_LAST_KNOW_LOCATION_TIME;
}
/**
* Enable updates for an activity and a listener
* @param activity the activity
* @param listener the listener
*/
public static void enableLocationUpdates(Activity activity, LocationListener listener) {
MyLog.v(TAG, "enableLocationUpdates()");
// enable location updates
for (String provider : getBestProviders(activity)) {
getLocationManager(activity).requestLocationUpdates(provider, MIN_TIME, MIN_DISTANCE, listener);
}
}
/**
* Disable updates for an activity and a listener
* @param activity the activity
* @param listener the listener
*/
public static void disableLocationUpdates(Activity activity, LocationListener listener) {
MyLog.v(TAG, "disableLocationUpdates()");
getLocationManager(activity).removeUpdates(listener);
}
/**
* @param lat the latitude
* @param lng the longitude
* @return the new location object
*/
public static Location getNewLocation(double lat, double lng) {
Location newLocation = new Location("MonTransit");
newLocation.setLatitude(lat);
newLocation.setLongitude(lng);
return newLocation;
}
}
| false | true | public static Location getBestLastKnownLocation(Activity activity) {
Location result = null;
for (String provider : getBestProviders(activity)) {
Location lastLocation = getLocationManager(activity).getLastKnownLocation(provider);
// IF no last location candidate DO
if (result == null) {
// IF this location candidate is not too old DO
if (isNotTooOld(lastLocation)) {
result = lastLocation;
}
} else {
// IF the new location candidate is more recent DO
if (lastLocation.getTime() > result.getTime()) {
result = lastLocation;
}
// TODO compare accuracy?
}
}
if (result != null) {
MyLog.v(TAG, "last know location:" + result.getProvider() + " > " + result.getLatitude() + ", "
+ result.getLongitude() + "(" + result.getAccuracy() + ") "
+ ((System.currentTimeMillis() - result.getTime()) / 1000) + " seconds ago.");
} else {
MyLog.v(TAG, "no valid last location found!");
}
return result;
}
| public static Location getBestLastKnownLocation(Activity activity) {
Location result = null;
for (String provider : getBestProviders(activity)) {
Location lastLocation = getLocationManager(activity).getLastKnownLocation(provider);
// IF the last location is NOT NULL (= location provider disabled) DO
if (lastLocation != null) {
// IF no last location candidate DO
if (result == null) {
// IF this location candidate is not too old DO
if (isNotTooOld(lastLocation)) {
result = lastLocation;
}
} else {
// IF the new location candidate is more recent DO
if (lastLocation.getTime() > result.getTime()) {
result = lastLocation;
}
// TODO compare accuracy?
}
}
}
if (result != null) {
MyLog.v(TAG, "last know location:" + result.getProvider() + " > " + result.getLatitude() + ", "
+ result.getLongitude() + "(" + result.getAccuracy() + ") "
+ ((System.currentTimeMillis() - result.getTime()) / 1000) + " seconds ago.");
} else {
MyLog.v(TAG, "no valid last location found!");
}
return result;
}
|
diff --git a/Android/YDP/src/com/example/ydp/HOMESCREEN.java b/Android/YDP/src/com/example/ydp/HOMESCREEN.java
index 1e142a4..9229626 100644
--- a/Android/YDP/src/com/example/ydp/HOMESCREEN.java
+++ b/Android/YDP/src/com/example/ydp/HOMESCREEN.java
@@ -1,41 +1,41 @@
package com.example.ydp;
import android.app.TabActivity;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.TabHost;
public class HOMESCREEN extends TabActivity{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.homescreen);
Resources res = getResources(); // Resource object to get Drawables
TabHost tabHost = getTabHost(); // The activity TabHost
TabHost.TabSpec spec; // Resusable TabSpec for each tab
// Initialize a TabSpec for each tab and add it to the TabHost
//for Tab1
- spec = tabHost.newTabSpec("Tab1").setIndicator("YDP CARE PLAN",res.getDrawable(R.drawable.all))
+ spec = tabHost.newTabSpec("Tab1").setIndicator("YDP Care Plan",res.getDrawable(R.drawable.faves))
.setContent(new Intent(this,YDPCAREPLAN.class));
tabHost.addTab(spec);
// for Tab2
- spec = tabHost.newTabSpec("Tab2").setIndicator("NOTIFY YDP",res.getDrawable(R.drawable.faves))
+ spec = tabHost.newTabSpec("Tab2").setIndicator("Notify YDP",res.getDrawable(R.drawable.all))
.setContent(new Intent(this,NOTIFYYDP.class));
tabHost.addTab(spec);
}
private Drawable getDrawable(int all) {
// TODO Auto-generated method stub
return null;
}
}
| false | true | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.homescreen);
Resources res = getResources(); // Resource object to get Drawables
TabHost tabHost = getTabHost(); // The activity TabHost
TabHost.TabSpec spec; // Resusable TabSpec for each tab
// Initialize a TabSpec for each tab and add it to the TabHost
//for Tab1
spec = tabHost.newTabSpec("Tab1").setIndicator("YDP CARE PLAN",res.getDrawable(R.drawable.all))
.setContent(new Intent(this,YDPCAREPLAN.class));
tabHost.addTab(spec);
// for Tab2
spec = tabHost.newTabSpec("Tab2").setIndicator("NOTIFY YDP",res.getDrawable(R.drawable.faves))
.setContent(new Intent(this,NOTIFYYDP.class));
tabHost.addTab(spec);
}
| protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.homescreen);
Resources res = getResources(); // Resource object to get Drawables
TabHost tabHost = getTabHost(); // The activity TabHost
TabHost.TabSpec spec; // Resusable TabSpec for each tab
// Initialize a TabSpec for each tab and add it to the TabHost
//for Tab1
spec = tabHost.newTabSpec("Tab1").setIndicator("YDP Care Plan",res.getDrawable(R.drawable.faves))
.setContent(new Intent(this,YDPCAREPLAN.class));
tabHost.addTab(spec);
// for Tab2
spec = tabHost.newTabSpec("Tab2").setIndicator("Notify YDP",res.getDrawable(R.drawable.all))
.setContent(new Intent(this,NOTIFYYDP.class));
tabHost.addTab(spec);
}
|
diff --git a/com.piece_framework.makegood.core/src/com/piece_framework/makegood/core/TestClass.java b/com.piece_framework.makegood.core/src/com/piece_framework/makegood/core/TestClass.java
index 5076186f..4a69dcbd 100644
--- a/com.piece_framework.makegood.core/src/com/piece_framework/makegood/core/TestClass.java
+++ b/com.piece_framework.makegood.core/src/com/piece_framework/makegood/core/TestClass.java
@@ -1,449 +1,449 @@
/**
* Copyright (c) 2012 MATSUFUJI Hideharu <[email protected]>,
*
* All rights reserved.
*
* This file is part of MakeGood.
*
* 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
*/
package com.piece_framework.makegood.core;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.dltk.ast.Modifiers;
import org.eclipse.dltk.core.CompletionRequestor;
import org.eclipse.dltk.core.IField;
import org.eclipse.dltk.core.IMethod;
import org.eclipse.dltk.core.IModelElement;
import org.eclipse.dltk.core.IModelElementVisitor;
import org.eclipse.dltk.core.IModelElementVisitorExtension;
import org.eclipse.dltk.core.INamespace;
import org.eclipse.dltk.core.IOpenable;
import org.eclipse.dltk.core.IScriptFolder;
import org.eclipse.dltk.core.IScriptModel;
import org.eclipse.dltk.core.IScriptProject;
import org.eclipse.dltk.core.ISourceModule;
import org.eclipse.dltk.core.ISourceRange;
import org.eclipse.dltk.core.IType;
import org.eclipse.dltk.core.ITypeHierarchy;
import org.eclipse.dltk.core.ModelException;
import org.eclipse.dltk.core.WorkingCopyOwner;
/**
* @since 1.x.0
*/
public class TestClass implements IType {
private IType origin;
private IType baseType;
private IModelElement[] children;
private TestingFramework testingFramework;
public TestClass(IType type, TestingFramework testingFramework) {
this.origin = type;
while (this.origin instanceof TestClass) {
this.origin = ((TestClass) this.origin).origin;
}
this.testingFramework = testingFramework;
}
@Override
public IPath getPath() {
return origin.getPath();
}
@Override
public ISourceRange getNameRange() throws ModelException {
return origin.getNameRange();
}
@Override
public int getFlags() throws ModelException {
return origin.getFlags();
}
@Override
public IType getDeclaringType() {
return createTestClass(origin.getDeclaringType());
}
@Override
public ISourceModule getSourceModule() {
return origin.getSourceModule();
}
@Override
public IType getType(String name, int occurrenceCount) {
return createTestClass(origin.getType(name, occurrenceCount));
}
@Override
public int getElementType() {
return origin.getElementType();
}
@Override
public String getElementName() {
return origin.getElementName();
}
@Override
public IModelElement getParent() {
return origin.getParent();
}
@Override
public boolean isReadOnly() {
return origin.isReadOnly();
}
@Override
public IResource getResource() {
return origin.getResource();
}
@Override
public boolean exists() {
return origin.exists();
}
@Override
public IModelElement getAncestor(int ancestorType) {
return origin.getAncestor(ancestorType);
}
@Override
public IOpenable getOpenable() {
return origin.getOpenable();
}
@Override
public IScriptModel getModel() {
return origin.getModel();
}
@Override
public IScriptProject getScriptProject() {
return origin.getScriptProject();
}
@Override
public IResource getUnderlyingResource() throws ModelException {
return origin.getUnderlyingResource();
}
@Override
public IResource getCorrespondingResource() throws ModelException {
return origin.getCorrespondingResource();
}
@Override
public IModelElement getPrimaryElement() {
return origin.getPrimaryElement();
}
@Override
public String getHandleIdentifier() {
return origin.getHandleIdentifier();
}
@Override
public boolean isStructureKnown() throws ModelException {
return origin.isStructureKnown();
}
@Override
public void accept(IModelElementVisitor visitor) throws ModelException {
if (visitor.visit(this)) {
IModelElement[] elements = getChildren();
for (int i = 0; i < elements.length; ++i) {
elements[i].accept(visitor);
}
if (visitor instanceof IModelElementVisitorExtension) {
((IModelElementVisitorExtension) visitor).endVisit(this);
}
}
}
@Override
@SuppressWarnings("rawtypes")
public Object getAdapter(Class adapter) {
return origin.getAdapter(adapter);
}
@Override
public ISourceRange getSourceRange() throws ModelException {
return origin.getSourceRange();
}
@Override
public String getSource() throws ModelException {
return origin.getSource();
}
@Override
public IModelElement[] getChildren() throws ModelException {
if (this.children != null) return this.children;
List<IModelElement> children = new ArrayList<IModelElement>();
- if (getFlags() != Modifiers.AccNameSpace) {
+ if ((getFlags() & Modifiers.AccNameSpace) == 0) {
children.addAll(Arrays.asList(getMethods()));
ITypeHierarchy hierarchy = newSupertypeHierarchy(new NullProgressMonitor());
for (IType supertype: hierarchy.getSupertypes(origin)) {
if (!TestingFramework.isTestClassSuperType(supertype)) {
children.add(createTestClass(supertype));
}
}
} else {
for (IType type: getTypes()) {
if (isTestClass(type, testingFramework)) {
children.add(createTestClass(type));
}
}
}
this.children = children.toArray(new IModelElement[0]);
return this.children;
}
@Override
public boolean hasChildren() throws ModelException {
return getChildren().length > 0;
}
@Override
public String[] getSuperClasses() throws ModelException {
return origin.getSuperClasses();
}
@Override
public IField getField(String name) {
return origin.getField(name);
}
@Override
public IField[] getFields() throws ModelException {
return origin.getFields();
}
@Override
public IType getType(String name) {
return createTestClass(origin.getType(name));
}
@Override
public IType[] getTypes() throws ModelException {
List<IType> types= new ArrayList<IType>();
for (IType type: this.origin.getTypes()) {
types.add(createTestClass(type));
}
return types.toArray(new IType[0]);
}
@Override
public IMethod getMethod(String name) {
return createTestMethod(origin.getMethod(name));
}
@Override
public IMethod[] getMethods() throws ModelException {
List<IMethod> methods = new ArrayList<IMethod>();
if (origin.getResource() == null) return methods.toArray(new IMethod[0]);
for (IMethod method: origin.getMethods()) {
if (testingFramework.isTestMethod(method)) methods.add(createTestMethod(method));
}
return methods.toArray(new IMethod[0]);
}
@Override
public String getFullyQualifiedName(String enclosingTypeSeparator) {
return origin.getFullyQualifiedName(enclosingTypeSeparator);
}
@Override
public String getFullyQualifiedName() {
return origin.getFullyQualifiedName();
}
@Override
public void codeComplete(char[] snippet,
int insertion,
int position,
char[][] localVariableTypeNames,
char[][] localVariableNames,
int[] localVariableModifiers,
boolean isStatic,
CompletionRequestor requestor) throws ModelException {
origin.codeComplete(
snippet,
insertion,
position,
localVariableTypeNames,
localVariableNames,
localVariableModifiers,
isStatic,
requestor);
}
@Override
public void codeComplete(char[] snippet,
int insertion,
int position,
char[][] localVariableTypeNames,
char[][] localVariableNames,
int[] localVariableModifiers,
boolean isStatic,
CompletionRequestor requestor,
WorkingCopyOwner owner) throws ModelException {
origin.codeComplete(
snippet,
insertion,
position,
localVariableTypeNames,
localVariableNames,
localVariableModifiers,
isStatic,
requestor,
owner);
}
@Override
public IScriptFolder getScriptFolder() {
return origin.getScriptFolder();
}
@Override
public String getTypeQualifiedName() {
return origin.getTypeQualifiedName();
}
@Override
public String getTypeQualifiedName(String enclosingTypeSeparator) {
return origin.getTypeQualifiedName(enclosingTypeSeparator);
}
@Override
public IMethod[] findMethods(IMethod method) {
return origin.findMethods(method);
}
@Override
public ITypeHierarchy loadTypeHierachy(InputStream input,
IProgressMonitor monitor) throws ModelException {
return origin.loadTypeHierachy(input, monitor);
}
@Override
public ITypeHierarchy newSupertypeHierarchy(IProgressMonitor monitor) throws ModelException {
return origin.newSupertypeHierarchy(monitor);
}
@Override
public ITypeHierarchy newSupertypeHierarchy(ISourceModule[] workingCopies,
IProgressMonitor monitor) throws ModelException {
return origin.newSupertypeHierarchy(workingCopies, monitor);
}
@Override
public ITypeHierarchy newSupertypeHierarchy(WorkingCopyOwner owner,
IProgressMonitor monitor) throws ModelException {
return origin.newSupertypeHierarchy(owner, monitor);
}
@Override
public ITypeHierarchy newTypeHierarchy(IScriptProject project,
IProgressMonitor monitor) throws ModelException {
return origin.newTypeHierarchy(project, monitor);
}
@Override
public ITypeHierarchy newTypeHierarchy(IScriptProject project,
WorkingCopyOwner owner,
IProgressMonitor monitor) throws ModelException {
return origin.newTypeHierarchy(project, owner, monitor);
}
@Override
public ITypeHierarchy newTypeHierarchy(IProgressMonitor monitor) throws ModelException {
return origin.newTypeHierarchy(monitor);
}
@Override
public ITypeHierarchy newTypeHierarchy(ISourceModule[] workingCopies,
IProgressMonitor monitor) throws ModelException {
return origin.newTypeHierarchy(workingCopies, monitor);
}
@Override
public ITypeHierarchy newTypeHierarchy(WorkingCopyOwner owner,
IProgressMonitor monitor) throws ModelException {
return origin.newSupertypeHierarchy(owner, monitor);
}
@Override
public INamespace getNamespace() throws ModelException {
return origin.getNamespace();
}
public static boolean isTestClass(IType type, TestingFramework testingFramework) {
if (type == null) return false;
try {
if (!PHPFlags.isNamespace(type.getFlags())) {
return testingFramework.isTestClass(
(type instanceof TestClass) ? ((TestClass) type).origin : type);
} else {
for (IType child: type.getTypes()) {
if (isTestClass(child, testingFramework)) return true;
}
}
} catch (ModelException e) {}
return false;
}
public void setBaseType(IType baseType) {
this.baseType = baseType;
}
public boolean isSubtype(IType targetSuperType) throws ModelException {
ITypeHierarchy hierarchy = newSupertypeHierarchy(new NullProgressMonitor());
for (IType superType: hierarchy.getAllSuperclasses(origin)) {
if (superType.getElementName().equals(targetSuperType.getElementName())) {
return true;
}
}
return false;
}
public boolean isNamespace() {
try {
return PHPFlags.isNamespace(getFlags());
} catch (ModelException e) {
return false;
}
}
private TestClass createTestClass(IType type) {
if (type == null) return null;
TestClass testClass = new TestClass(type, testingFramework);
if (baseType != null) testClass.setBaseType(baseType);
return testClass;
}
private TestMethod createTestMethod(IMethod method) {
TestMethod testMethod = new TestMethod(method);
if (baseType != null) testMethod.setBaseType(baseType);
return testMethod;
}
}
| true | true | public IModelElement[] getChildren() throws ModelException {
if (this.children != null) return this.children;
List<IModelElement> children = new ArrayList<IModelElement>();
if (getFlags() != Modifiers.AccNameSpace) {
children.addAll(Arrays.asList(getMethods()));
ITypeHierarchy hierarchy = newSupertypeHierarchy(new NullProgressMonitor());
for (IType supertype: hierarchy.getSupertypes(origin)) {
if (!TestingFramework.isTestClassSuperType(supertype)) {
children.add(createTestClass(supertype));
}
}
} else {
for (IType type: getTypes()) {
if (isTestClass(type, testingFramework)) {
children.add(createTestClass(type));
}
}
}
this.children = children.toArray(new IModelElement[0]);
return this.children;
}
| public IModelElement[] getChildren() throws ModelException {
if (this.children != null) return this.children;
List<IModelElement> children = new ArrayList<IModelElement>();
if ((getFlags() & Modifiers.AccNameSpace) == 0) {
children.addAll(Arrays.asList(getMethods()));
ITypeHierarchy hierarchy = newSupertypeHierarchy(new NullProgressMonitor());
for (IType supertype: hierarchy.getSupertypes(origin)) {
if (!TestingFramework.isTestClassSuperType(supertype)) {
children.add(createTestClass(supertype));
}
}
} else {
for (IType type: getTypes()) {
if (isTestClass(type, testingFramework)) {
children.add(createTestClass(type));
}
}
}
this.children = children.toArray(new IModelElement[0]);
return this.children;
}
|
diff --git a/java/Apparat.Core/src/com/joa_ebert/apparat/taas/compiler/DefaultEnvironmentFactory.java b/java/Apparat.Core/src/com/joa_ebert/apparat/taas/compiler/DefaultEnvironmentFactory.java
index 8ad2aab..d0732a5 100644
--- a/java/Apparat.Core/src/com/joa_ebert/apparat/taas/compiler/DefaultEnvironmentFactory.java
+++ b/java/Apparat.Core/src/com/joa_ebert/apparat/taas/compiler/DefaultEnvironmentFactory.java
@@ -1,84 +1,84 @@
/*
* This file is part of Apparat.
*
* Apparat 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.
*
* Apparat 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 Apparat. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright (C) 2009 Joa Ebert
* http://www.joa-ebert.com/
*
*/
package com.joa_ebert.apparat.taas.compiler;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import com.joa_ebert.apparat.abc.Abc;
import com.joa_ebert.apparat.abc.AbcEnvironment;
import com.joa_ebert.apparat.abc.AbcException;
/**
* @author Joa Ebert
*
*/
public final class DefaultEnvironmentFactory
{
public static AbcEnvironment create() throws IOException
{
final Abc builtinABC = new Abc();
final Abc toplevelABC = new Abc();
final URL builtinURL = DefaultEnvironmentFactory.class
.getResource( "/com/joa_ebert/apparat/taas/compiler/builtin/builtin.abc" );
final URL toplevelURL = DefaultEnvironmentFactory.class
- .getResource( "/com/joa_ebert/apparat/taas/compiler/builtin/builtin.abc" );
+ .getResource( "/com/joa_ebert/apparat/taas/compiler/builtin/toplevel.abc" );
InputStream stream = null;
try
{
stream = builtinURL.openStream();
builtinABC.read( stream );
stream.close();
stream = toplevelURL.openStream();
toplevelABC.read( stream );
}
catch( final IOException exception )
{
exception.printStackTrace();
}
catch( final AbcException exception )
{
exception.printStackTrace();
}
finally
{
if( null != stream )
{
stream.close();
}
}
return new AbcEnvironment( new Abc[] {
builtinABC, toplevelABC
} );
}
private DefaultEnvironmentFactory()
{
}
}
| true | true | public static AbcEnvironment create() throws IOException
{
final Abc builtinABC = new Abc();
final Abc toplevelABC = new Abc();
final URL builtinURL = DefaultEnvironmentFactory.class
.getResource( "/com/joa_ebert/apparat/taas/compiler/builtin/builtin.abc" );
final URL toplevelURL = DefaultEnvironmentFactory.class
.getResource( "/com/joa_ebert/apparat/taas/compiler/builtin/builtin.abc" );
InputStream stream = null;
try
{
stream = builtinURL.openStream();
builtinABC.read( stream );
stream.close();
stream = toplevelURL.openStream();
toplevelABC.read( stream );
}
catch( final IOException exception )
{
exception.printStackTrace();
}
catch( final AbcException exception )
{
exception.printStackTrace();
}
finally
{
if( null != stream )
{
stream.close();
}
}
return new AbcEnvironment( new Abc[] {
builtinABC, toplevelABC
} );
}
| public static AbcEnvironment create() throws IOException
{
final Abc builtinABC = new Abc();
final Abc toplevelABC = new Abc();
final URL builtinURL = DefaultEnvironmentFactory.class
.getResource( "/com/joa_ebert/apparat/taas/compiler/builtin/builtin.abc" );
final URL toplevelURL = DefaultEnvironmentFactory.class
.getResource( "/com/joa_ebert/apparat/taas/compiler/builtin/toplevel.abc" );
InputStream stream = null;
try
{
stream = builtinURL.openStream();
builtinABC.read( stream );
stream.close();
stream = toplevelURL.openStream();
toplevelABC.read( stream );
}
catch( final IOException exception )
{
exception.printStackTrace();
}
catch( final AbcException exception )
{
exception.printStackTrace();
}
finally
{
if( null != stream )
{
stream.close();
}
}
return new AbcEnvironment( new Abc[] {
builtinABC, toplevelABC
} );
}
|
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/callgraph/launch/SystemTapLaunchConfigurationDelegate.java b/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/callgraph/launch/SystemTapLaunchConfigurationDelegate.java
index 2918cdfec..e63638471 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/callgraph/launch/SystemTapLaunchConfigurationDelegate.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/callgraph/launch/SystemTapLaunchConfigurationDelegate.java
@@ -1,424 +1,424 @@
/*******************************************************************************
* Copyright (c) 2009 Red Hat, Inc.
* 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:
* Red Hat - initial API and implementation
*******************************************************************************/
package org.eclipse.linuxtools.callgraph.launch;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtensionRegistry;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.IStreamListener;
import org.eclipse.debug.core.model.IProcess;
import org.eclipse.debug.core.model.IStreamMonitor;
import org.eclipse.linuxtools.callgraph.core.DocWriter;
import org.eclipse.linuxtools.callgraph.core.Helper;
import org.eclipse.linuxtools.callgraph.core.LaunchConfigurationConstants;
import org.eclipse.linuxtools.callgraph.core.PluginConstants;
import org.eclipse.linuxtools.callgraph.core.SystemTapCommandGenerator;
import org.eclipse.linuxtools.callgraph.core.SystemTapErrorHandler;
import org.eclipse.linuxtools.callgraph.core.SystemTapParser;
import org.eclipse.linuxtools.callgraph.core.SystemTapUIErrorMessages;
import org.eclipse.linuxtools.profiling.launch.ProfileLaunchConfigurationDelegate;
import org.eclipse.ui.console.TextConsole;
/**
* Delegate for Stap scripts. The Delegate generates part of the command string
* and schedules a job to finish generation of the command and execute.
*
*/
public class SystemTapLaunchConfigurationDelegate extends
ProfileLaunchConfigurationDelegate {
private static final String TEMP_ERROR_OUTPUT =
PluginConstants.getDefaultOutput() + "stapTempError.error"; //$NON-NLS-1$
private String cmd;
private File temporaryScript = null;
private String arguments = ""; //$NON-NLS-1$
private String scriptPath = ""; //$NON-NLS-1$
private String binaryPath = ""; //$NON-NLS-1$
private String outputPath = ""; //$NON-NLS-1$
private boolean needsBinary = false; // Set to false if we want to use SystemTap
private boolean needsArguments = false;
@SuppressWarnings("unused")
private boolean useColour = false;
private String binaryArguments = ""; //$NON-NLS-1$
private String partialCommand = ""; //$NON-NLS-1$
private String stap = ""; //$NON-NLS-1$
@Override
protected String getPluginID() {
return null;
}
/**
* Sets strings to blank, booleans to false and everything else to null
*/
private void initialize() {
temporaryScript = null;
arguments = ""; //$NON-NLS-1$
scriptPath = ""; //$NON-NLS-1$
binaryPath = ""; //$NON-NLS-1$
outputPath = ""; //$NON-NLS-1$
needsBinary = false; // Set to false if we want to use SystemTap
needsArguments = false;
useColour = false;
binaryArguments = ""; //$NON-NLS-1$
}
@Override
public void launch(ILaunchConfiguration config, String mode,
ILaunch launch, IProgressMonitor m) throws CoreException {
if (m == null) {
m = new NullProgressMonitor();
}
SubMonitor monitor = SubMonitor.convert(m,
"SystemTap runtime monitor", 5); //$NON-NLS-1$
initialize();
// check for cancellation
if (monitor.isCanceled()) {
return;
}
/*
* Set variables
*/
if (config.getAttribute(LaunchConfigurationConstants.USE_COLOUR,
LaunchConfigurationConstants.DEFAULT_USE_COLOUR))
useColour = true;
if (!config.getAttribute(LaunchConfigurationConstants.ARGUMENTS,
LaunchConfigurationConstants.DEFAULT_ARGUMENTS).equals(
LaunchConfigurationConstants.DEFAULT_ARGUMENTS)) {
arguments = config.getAttribute(
LaunchConfigurationConstants.ARGUMENTS,
LaunchConfigurationConstants.DEFAULT_ARGUMENTS);
needsArguments = true;
}
if (!config.getAttribute(LaunchConfigurationConstants.BINARY_PATH,
LaunchConfigurationConstants.DEFAULT_BINARY_PATH).equals(
LaunchConfigurationConstants.DEFAULT_BINARY_PATH)) {
binaryPath = config.getAttribute(
LaunchConfigurationConstants.BINARY_PATH,
LaunchConfigurationConstants.DEFAULT_BINARY_PATH);
needsBinary = true;
}
if (!config.getAttribute(LaunchConfigurationConstants.BINARY_ARGUMENTS,
LaunchConfigurationConstants.DEFAULT_BINARY_ARGUMENTS).equals(
LaunchConfigurationConstants.DEFAULT_BINARY_ARGUMENTS)) {
binaryArguments = config.getAttribute(
LaunchConfigurationConstants.BINARY_ARGUMENTS,
LaunchConfigurationConstants.DEFAULT_BINARY_ARGUMENTS);
}
if (!config.getAttribute(LaunchConfigurationConstants.SCRIPT_PATH,
LaunchConfigurationConstants.DEFAULT_SCRIPT_PATH).equals(
LaunchConfigurationConstants.DEFAULT_SCRIPT_PATH)) {
scriptPath = config.getAttribute(
LaunchConfigurationConstants.SCRIPT_PATH,
LaunchConfigurationConstants.DEFAULT_SCRIPT_PATH);
}
// Generate script if needed
if (config.getAttribute(LaunchConfigurationConstants.NEED_TO_GENERATE,
LaunchConfigurationConstants.DEFAULT_NEED_TO_GENERATE)) {
temporaryScript = new File(scriptPath);
temporaryScript.delete();
try {
temporaryScript.createNewFile();
FileWriter fstream = new FileWriter(temporaryScript);
BufferedWriter out = new BufferedWriter(fstream);
out.write(config.getAttribute(
LaunchConfigurationConstants.GENERATED_SCRIPT,
LaunchConfigurationConstants.DEFAULT_GENERATED_SCRIPT));
out.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
stap = config.getAttribute(LaunchConfigurationConstants.COMMAND,
PluginConstants.STAP_PATH);
/**
* Generate partial command
*/
partialCommand = ConfigurationOptionsSetter.setOptions(config);
outputPath = config.getAttribute(
LaunchConfigurationConstants.OUTPUT_PATH,
PluginConstants.getDefaultOutput());
partialCommand += "-o " + outputPath; //$NON-NLS-1$
// check for cancellation
if ( !testOutput(outputPath) || monitor.isCanceled() ) {
return;
}
finishLaunch(launch, config, partialCommand, m, true);
}
/**
* Returns the current SystemTap command, or returns an error message.
* @return
*/
public String getCommand() {
if (cmd.length() > 0)
return cmd;
else
return Messages.getString("SystemTapLaunchConfigurationDelegate.NoCommand"); //$NON-NLS-1$
}
private void finishLaunch(ILaunch launch, ILaunchConfiguration config, String options,
IProgressMonitor monitor, boolean retry) {
try {
// Check for cancellation
if (monitor.isCanceled() || launch == null) {
return;
}
monitor.worked(1);
// set the default source locator if required
setDefaultSourceLocator(launch, config);
/*
* Fetch a parser
*/
String parserClass = config.getAttribute(LaunchConfigurationConstants.PARSER_CLASS,
LaunchConfigurationConstants.DEFAULT_PARSER_CLASS);
IExtensionRegistry reg = Platform.getExtensionRegistry();
IConfigurationElement[] extensions = reg
.getConfigurationElementsFor(PluginConstants.PARSER_RESOURCE,
PluginConstants.PARSER_NAME,
parserClass);
if (extensions == null || extensions.length < 1) {
SystemTapUIErrorMessages mess = new SystemTapUIErrorMessages(Messages.getString("SystemTapLaunchConfigurationDelegate.InvalidParser1"), //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.InvalidParser1"), //$NON-NLS-1$ //$NON-NLS-2$
Messages.getString("SystemTapLaunchConfigurationDelegate.InvalidParser2") + //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.InvalidParser3") + parserClass); //$NON-NLS-1$
mess.schedule();
return;
}
IConfigurationElement element = extensions[0];
SystemTapParser parser =
(SystemTapParser) element.createExecutableExtension(PluginConstants.ATTR_CLASS);
//Set parser options
parser.setViewID(config.getAttribute(LaunchConfigurationConstants.VIEW_CLASS,
LaunchConfigurationConstants.VIEW_CLASS));
parser.setSourcePath(outputPath);
parser.setMonitor(SubMonitor.convert(monitor));
parser.setDone(false);
parser.setSecondaryID(config.getAttribute(LaunchConfigurationConstants.SECONDARY_VIEW_ID,
LaunchConfigurationConstants.DEFAULT_SECONDARY_VIEW_ID));
parser.setKillButtonEnabled(true);
if (element.getAttribute(PluginConstants.ATTR_REALTIME).equals(PluginConstants.VAL_TRUE)) {
parser.setRealTime(true);
parser.schedule();
}
monitor.worked(1);
/*
* Launch
*/
IProcess process = createProcess(config, launch);
monitor.worked(1);
StreamListener s = new StreamListener();
process.getStreamsProxy().getErrorStreamMonitor().addListener(s);
while (!process.isTerminated()) {
Thread.sleep(100);
if ((monitor != null && monitor.isCanceled()) || parser.isJobCancelled()) {
parser.cancelJob();
process.terminate();
return;
}
}
Thread.sleep(100);
s.close();
parser.setKillButtonEnabled(false);
if (process.getExitValue() != 0) {
parser.cancelJob();
SystemTapErrorHandler errorHandler = new SystemTapErrorHandler();
//Prepare stap information
errorHandler.appendToLog(config.getName() + Messages.getString("SystemTapLaunchConfigurationDelegate.stap_command") + cmd+ PluginConstants.NEW_LINE + PluginConstants.NEW_LINE);//$NON-NLS-1$
//Handle error from TEMP_ERROR_OUTPUT
errorHandler.handle(monitor, new FileReader(TEMP_ERROR_OUTPUT)); //$NON-NLS-1$
if ((monitor != null && monitor.isCanceled()))
return;
//If we are meant to retry, and the conditions for retry are met
//Currently conditions only met if there are mismatched probe points present
//TODO: Do we need a retry now that we cannot think of a case where we need to relaunch?
/*if (retry) {
SystemTapUIErrorMessages mess = new SystemTapUIErrorMessages(Messages.getString("SystemTapLaunchConfigurationDelegate.Relaunch1"), //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.Relaunch2"), //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.Relaunch3")); //$NON-NLS-1$
mess.schedule();
//If finishHandling determines that errors are not fixable, return
if (!errorHandler.finishHandling(monitor, scriptPath))
return;
//Abort job
if ((monitor != null && monitor.isCanceled()) || parser.isJobCancelled()) {
monitor.setCanceled(true);
parser.cancelJob();
return;
}
finishLaunch(launch, config, options, monitor, false);
return;
}*/
errorHandler.finishHandling(monitor, scriptPath);
- if (errorHandler.getErrorMessage().length() > 0) {
+ if (errorHandler.isErrorRecognized()) {
SystemTapUIErrorMessages errorDialog = new SystemTapUIErrorMessages
(Messages.getString("SystemTapLaunchConfigurationDelegate.CallGraphGenericError"), //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.CallGraphGenericError"), //$NON-NLS-1$
errorHandler.getErrorMessage());
errorDialog.schedule();
}
return;
}
if (! element.getAttribute(PluginConstants.ATTR_REALTIME).equals(PluginConstants.VAL_TRUE)) { //$NON-NLS-1$ //$NON-NLS-2$
parser.schedule();
} else {
//Parser already scheduled, but double-check
if (parser != null)
parser.cancelJob();
}
monitor.worked(1);
String message = generateErrorMessage(config.getName(), binaryArguments);
DocWriter dw = new DocWriter(Messages.getString("SystemTapLaunchConfigurationDelegate.DocWriterName"), //$NON-NLS-1$
((TextConsole)Helper.getConsoleByName(config.getName())), message);
dw.schedule();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (CoreException e) {
e.printStackTrace();
} finally {
monitor.done();
}
}
private String generateErrorMessage(String configName, String binaryCommand) {
String output = ""; //$NON-NLS-1$
if (binaryCommand == null || binaryCommand.length() < 0) {
output = PluginConstants.NEW_LINE +
PluginConstants.NEW_LINE + "-------------" + //$NON-NLS-1$
PluginConstants.NEW_LINE +
Messages.getString("SystemTapLaunchConfigurationDelegate.Relaunch10") //$NON-NLS-1$
+ configName + PluginConstants.NEW_LINE +
Messages.getString("SystemTapLaunchConfigurationDelegate.Relaunch8") + //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.Relaunch9") + //$NON-NLS-1$
"configuration in Profile As --> Profile Configurations." + //$NON-NLS-1$
PluginConstants.NEW_LINE + PluginConstants.NEW_LINE;
}
else {
output = PluginConstants.NEW_LINE
+ PluginConstants.NEW_LINE +"-------------" //$NON-NLS-1$
+ PluginConstants.NEW_LINE
+ Messages.getString("SystemTapLaunchConfigurationDelegate.EndMessage1") //$NON-NLS-1$
+ configName + PluginConstants.NEW_LINE +
Messages.getString("SystemTapLaunchConfigurationDelegate.EndMessage2") //$NON-NLS-1$
+ binaryCommand + PluginConstants.NEW_LINE +
Messages.getString("SystemTapLaunchConfigurationDelegate.EndMessage3") + //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.EndMessage4") + //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.EndMessage5") + //$NON-NLS-1$
PluginConstants.NEW_LINE + PluginConstants.NEW_LINE;
}
return output;
}
private class StreamListener implements IStreamListener{
private int counter;
private BufferedWriter bw;
public StreamListener() throws IOException {
File file = new File(TEMP_ERROR_OUTPUT);
file.delete();
file.createNewFile();
bw = Helper.setBufferedWriter(TEMP_ERROR_OUTPUT); //$NON-NLS-1$
counter = 0;
}
@Override
public void streamAppended(String text, IStreamMonitor monitor) {
try {
if (text.length() < 1) return;
counter++;
if (counter < PluginConstants.MAX_ERRORS)
bw.append(text);
} catch (IOException e) {
e.printStackTrace();
}
}
public void close() throws IOException {
bw.close();
}
}
@Override
public String generateCommand(ILaunchConfiguration config) {
// Generate the command
cmd = SystemTapCommandGenerator.generateCommand(scriptPath, binaryPath,
partialCommand, needsBinary, needsArguments, arguments, binaryArguments, stap);
return cmd;
}
}
| true | true | private void finishLaunch(ILaunch launch, ILaunchConfiguration config, String options,
IProgressMonitor monitor, boolean retry) {
try {
// Check for cancellation
if (monitor.isCanceled() || launch == null) {
return;
}
monitor.worked(1);
// set the default source locator if required
setDefaultSourceLocator(launch, config);
/*
* Fetch a parser
*/
String parserClass = config.getAttribute(LaunchConfigurationConstants.PARSER_CLASS,
LaunchConfigurationConstants.DEFAULT_PARSER_CLASS);
IExtensionRegistry reg = Platform.getExtensionRegistry();
IConfigurationElement[] extensions = reg
.getConfigurationElementsFor(PluginConstants.PARSER_RESOURCE,
PluginConstants.PARSER_NAME,
parserClass);
if (extensions == null || extensions.length < 1) {
SystemTapUIErrorMessages mess = new SystemTapUIErrorMessages(Messages.getString("SystemTapLaunchConfigurationDelegate.InvalidParser1"), //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.InvalidParser1"), //$NON-NLS-1$ //$NON-NLS-2$
Messages.getString("SystemTapLaunchConfigurationDelegate.InvalidParser2") + //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.InvalidParser3") + parserClass); //$NON-NLS-1$
mess.schedule();
return;
}
IConfigurationElement element = extensions[0];
SystemTapParser parser =
(SystemTapParser) element.createExecutableExtension(PluginConstants.ATTR_CLASS);
//Set parser options
parser.setViewID(config.getAttribute(LaunchConfigurationConstants.VIEW_CLASS,
LaunchConfigurationConstants.VIEW_CLASS));
parser.setSourcePath(outputPath);
parser.setMonitor(SubMonitor.convert(monitor));
parser.setDone(false);
parser.setSecondaryID(config.getAttribute(LaunchConfigurationConstants.SECONDARY_VIEW_ID,
LaunchConfigurationConstants.DEFAULT_SECONDARY_VIEW_ID));
parser.setKillButtonEnabled(true);
if (element.getAttribute(PluginConstants.ATTR_REALTIME).equals(PluginConstants.VAL_TRUE)) {
parser.setRealTime(true);
parser.schedule();
}
monitor.worked(1);
/*
* Launch
*/
IProcess process = createProcess(config, launch);
monitor.worked(1);
StreamListener s = new StreamListener();
process.getStreamsProxy().getErrorStreamMonitor().addListener(s);
while (!process.isTerminated()) {
Thread.sleep(100);
if ((monitor != null && monitor.isCanceled()) || parser.isJobCancelled()) {
parser.cancelJob();
process.terminate();
return;
}
}
Thread.sleep(100);
s.close();
parser.setKillButtonEnabled(false);
if (process.getExitValue() != 0) {
parser.cancelJob();
SystemTapErrorHandler errorHandler = new SystemTapErrorHandler();
//Prepare stap information
errorHandler.appendToLog(config.getName() + Messages.getString("SystemTapLaunchConfigurationDelegate.stap_command") + cmd+ PluginConstants.NEW_LINE + PluginConstants.NEW_LINE);//$NON-NLS-1$
//Handle error from TEMP_ERROR_OUTPUT
errorHandler.handle(monitor, new FileReader(TEMP_ERROR_OUTPUT)); //$NON-NLS-1$
if ((monitor != null && monitor.isCanceled()))
return;
//If we are meant to retry, and the conditions for retry are met
//Currently conditions only met if there are mismatched probe points present
//TODO: Do we need a retry now that we cannot think of a case where we need to relaunch?
/*if (retry) {
SystemTapUIErrorMessages mess = new SystemTapUIErrorMessages(Messages.getString("SystemTapLaunchConfigurationDelegate.Relaunch1"), //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.Relaunch2"), //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.Relaunch3")); //$NON-NLS-1$
mess.schedule();
//If finishHandling determines that errors are not fixable, return
if (!errorHandler.finishHandling(monitor, scriptPath))
return;
//Abort job
if ((monitor != null && monitor.isCanceled()) || parser.isJobCancelled()) {
monitor.setCanceled(true);
parser.cancelJob();
return;
}
finishLaunch(launch, config, options, monitor, false);
return;
}*/
errorHandler.finishHandling(monitor, scriptPath);
if (errorHandler.getErrorMessage().length() > 0) {
SystemTapUIErrorMessages errorDialog = new SystemTapUIErrorMessages
(Messages.getString("SystemTapLaunchConfigurationDelegate.CallGraphGenericError"), //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.CallGraphGenericError"), //$NON-NLS-1$
errorHandler.getErrorMessage());
errorDialog.schedule();
}
return;
}
if (! element.getAttribute(PluginConstants.ATTR_REALTIME).equals(PluginConstants.VAL_TRUE)) { //$NON-NLS-1$ //$NON-NLS-2$
parser.schedule();
} else {
//Parser already scheduled, but double-check
if (parser != null)
parser.cancelJob();
}
monitor.worked(1);
String message = generateErrorMessage(config.getName(), binaryArguments);
DocWriter dw = new DocWriter(Messages.getString("SystemTapLaunchConfigurationDelegate.DocWriterName"), //$NON-NLS-1$
((TextConsole)Helper.getConsoleByName(config.getName())), message);
dw.schedule();
} catch (IOException e) {
| private void finishLaunch(ILaunch launch, ILaunchConfiguration config, String options,
IProgressMonitor monitor, boolean retry) {
try {
// Check for cancellation
if (monitor.isCanceled() || launch == null) {
return;
}
monitor.worked(1);
// set the default source locator if required
setDefaultSourceLocator(launch, config);
/*
* Fetch a parser
*/
String parserClass = config.getAttribute(LaunchConfigurationConstants.PARSER_CLASS,
LaunchConfigurationConstants.DEFAULT_PARSER_CLASS);
IExtensionRegistry reg = Platform.getExtensionRegistry();
IConfigurationElement[] extensions = reg
.getConfigurationElementsFor(PluginConstants.PARSER_RESOURCE,
PluginConstants.PARSER_NAME,
parserClass);
if (extensions == null || extensions.length < 1) {
SystemTapUIErrorMessages mess = new SystemTapUIErrorMessages(Messages.getString("SystemTapLaunchConfigurationDelegate.InvalidParser1"), //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.InvalidParser1"), //$NON-NLS-1$ //$NON-NLS-2$
Messages.getString("SystemTapLaunchConfigurationDelegate.InvalidParser2") + //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.InvalidParser3") + parserClass); //$NON-NLS-1$
mess.schedule();
return;
}
IConfigurationElement element = extensions[0];
SystemTapParser parser =
(SystemTapParser) element.createExecutableExtension(PluginConstants.ATTR_CLASS);
//Set parser options
parser.setViewID(config.getAttribute(LaunchConfigurationConstants.VIEW_CLASS,
LaunchConfigurationConstants.VIEW_CLASS));
parser.setSourcePath(outputPath);
parser.setMonitor(SubMonitor.convert(monitor));
parser.setDone(false);
parser.setSecondaryID(config.getAttribute(LaunchConfigurationConstants.SECONDARY_VIEW_ID,
LaunchConfigurationConstants.DEFAULT_SECONDARY_VIEW_ID));
parser.setKillButtonEnabled(true);
if (element.getAttribute(PluginConstants.ATTR_REALTIME).equals(PluginConstants.VAL_TRUE)) {
parser.setRealTime(true);
parser.schedule();
}
monitor.worked(1);
/*
* Launch
*/
IProcess process = createProcess(config, launch);
monitor.worked(1);
StreamListener s = new StreamListener();
process.getStreamsProxy().getErrorStreamMonitor().addListener(s);
while (!process.isTerminated()) {
Thread.sleep(100);
if ((monitor != null && monitor.isCanceled()) || parser.isJobCancelled()) {
parser.cancelJob();
process.terminate();
return;
}
}
Thread.sleep(100);
s.close();
parser.setKillButtonEnabled(false);
if (process.getExitValue() != 0) {
parser.cancelJob();
SystemTapErrorHandler errorHandler = new SystemTapErrorHandler();
//Prepare stap information
errorHandler.appendToLog(config.getName() + Messages.getString("SystemTapLaunchConfigurationDelegate.stap_command") + cmd+ PluginConstants.NEW_LINE + PluginConstants.NEW_LINE);//$NON-NLS-1$
//Handle error from TEMP_ERROR_OUTPUT
errorHandler.handle(monitor, new FileReader(TEMP_ERROR_OUTPUT)); //$NON-NLS-1$
if ((monitor != null && monitor.isCanceled()))
return;
//If we are meant to retry, and the conditions for retry are met
//Currently conditions only met if there are mismatched probe points present
//TODO: Do we need a retry now that we cannot think of a case where we need to relaunch?
/*if (retry) {
SystemTapUIErrorMessages mess = new SystemTapUIErrorMessages(Messages.getString("SystemTapLaunchConfigurationDelegate.Relaunch1"), //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.Relaunch2"), //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.Relaunch3")); //$NON-NLS-1$
mess.schedule();
//If finishHandling determines that errors are not fixable, return
if (!errorHandler.finishHandling(monitor, scriptPath))
return;
//Abort job
if ((monitor != null && monitor.isCanceled()) || parser.isJobCancelled()) {
monitor.setCanceled(true);
parser.cancelJob();
return;
}
finishLaunch(launch, config, options, monitor, false);
return;
}*/
errorHandler.finishHandling(monitor, scriptPath);
if (errorHandler.isErrorRecognized()) {
SystemTapUIErrorMessages errorDialog = new SystemTapUIErrorMessages
(Messages.getString("SystemTapLaunchConfigurationDelegate.CallGraphGenericError"), //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.CallGraphGenericError"), //$NON-NLS-1$
errorHandler.getErrorMessage());
errorDialog.schedule();
}
return;
}
if (! element.getAttribute(PluginConstants.ATTR_REALTIME).equals(PluginConstants.VAL_TRUE)) { //$NON-NLS-1$ //$NON-NLS-2$
parser.schedule();
} else {
//Parser already scheduled, but double-check
if (parser != null)
parser.cancelJob();
}
monitor.worked(1);
String message = generateErrorMessage(config.getName(), binaryArguments);
DocWriter dw = new DocWriter(Messages.getString("SystemTapLaunchConfigurationDelegate.DocWriterName"), //$NON-NLS-1$
((TextConsole)Helper.getConsoleByName(config.getName())), message);
dw.schedule();
} catch (IOException e) {
|
diff --git a/as/plugins/org.jboss.ide.eclipse.as.ui/jbossui/org/jboss/ide/eclipse/as/ui/editor/DeploySection.java b/as/plugins/org.jboss.ide.eclipse.as.ui/jbossui/org/jboss/ide/eclipse/as/ui/editor/DeploySection.java
index 828f46a4c..ea15de0fe 100755
--- a/as/plugins/org.jboss.ide.eclipse.as.ui/jbossui/org/jboss/ide/eclipse/as/ui/editor/DeploySection.java
+++ b/as/plugins/org.jboss.ide.eclipse.as.ui/jbossui/org/jboss/ide/eclipse/as/ui/editor/DeploySection.java
@@ -1,459 +1,460 @@
/**
* JBoss, a Division of Red Hat
* Copyright 2006, Red Hat Middleware, LLC, and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This 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.1 of
* the License, or (at your option) any later version.
*
* This software 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 software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.ide.eclipse.as.ui.editor;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.forms.IFormColors;
import org.eclipse.ui.forms.widgets.ExpandableComposite;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Section;
import org.eclipse.wst.server.core.IRuntime;
import org.eclipse.wst.server.ui.editor.ServerEditorSection;
import org.eclipse.wst.server.ui.internal.command.ServerCommand;
import org.jboss.ide.eclipse.as.core.JBossServerCorePlugin;
import org.jboss.ide.eclipse.as.core.server.IDeployableServer;
import org.jboss.ide.eclipse.as.core.server.IJBossServerConstants;
import org.jboss.ide.eclipse.as.core.server.IJBossServerRuntime;
import org.jboss.ide.eclipse.as.core.server.internal.DeployableServer;
import org.jboss.ide.eclipse.as.core.server.internal.ServerAttributeHelper;
import org.jboss.ide.eclipse.as.ui.Messages;
/**
*
* @author Rob Stryker <[email protected]>
*
*/
public class DeploySection extends ServerEditorSection {
private Text deployText, tempDeployText;
private Button metadataRadio, serverRadio, customRadio, currentSelection;
private Button deployButton, tempDeployButton;
private ModifyListener deployListener, tempDeployListener;
private SelectionListener radioListener;
private ServerAttributeHelper helper;
private String lastCustomDeploy, lastCustomTemp;
public DeploySection() {
}
public void init(IEditorSite site, IEditorInput input) {
super.init(site, input);
helper = new ServerAttributeHelper(server.getOriginal(), server);
}
public void createSection(Composite parent) {
super.createSection(parent);
FormToolkit toolkit = new FormToolkit(parent.getDisplay());
Section section = toolkit.createSection(parent, ExpandableComposite.TWISTIE|ExpandableComposite.EXPANDED|ExpandableComposite.TITLE_BAR);
section.setText(Messages.swf_DeployEditorHeading);
section.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL));
Composite composite = toolkit.createComposite(section);
composite.setLayout(new FormLayout());
Label descriptionLabel = toolkit.createLabel(composite, Messages.swf_DeploymentDescription);
Control top = descriptionLabel;
if( getRuntime() != null ) {
Composite inner = toolkit.createComposite(composite);
inner.setLayout(new GridLayout(1, false));
metadataRadio = toolkit.createButton(inner, Messages.EditorUseWorkspaceMetadata, SWT.RADIO);
serverRadio = toolkit.createButton(inner, Messages.EditorUseServersDeployFolder, SWT.RADIO);
customRadio = toolkit.createButton(inner, Messages.EditorUseCustomDeployFolder, SWT.RADIO);
metadataRadio.setSelection(getDeployType().equals(IDeployableServer.DEPLOY_METADATA));
serverRadio.setSelection(getDeployType().equals(IDeployableServer.DEPLOY_SERVER));
customRadio.setSelection(getDeployType().equals(IDeployableServer.DEPLOY_CUSTOM));
currentSelection = metadataRadio.getSelection() ? metadataRadio :
serverRadio.getSelection() ? serverRadio :
customRadio;
radioListener = new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
public void widgetSelected(SelectionEvent e) {
if( e.getSource() == currentSelection )
return; // do nothing
execute(new RadioClickedCommand((Button)e.getSource(), currentSelection));
currentSelection = (Button)e.getSource();
} };
metadataRadio.addSelectionListener(radioListener);
serverRadio.addSelectionListener(radioListener);
customRadio.addSelectionListener(radioListener);
FormData radios = new FormData();
radios.top = new FormAttachment(descriptionLabel,5);
radios.left = new FormAttachment(0,5);
radios.right = new FormAttachment(100,-5);
inner.setLayoutData(radios);
top = inner;
}
Label label = toolkit.createLabel(composite, Messages.swf_DeployDirectory);
label.setForeground(toolkit.getColors().getColor(IFormColors.TITLE));
deployText = toolkit.createText(composite, getDeployDir(), SWT.BORDER);
deployListener = new ModifyListener() {
public void modifyText(ModifyEvent e) {
execute(new SetDeployDirCommand());
}
};
deployText.addModifyListener(deployListener);
deployButton = toolkit.createButton(composite, Messages.browse, SWT.PUSH);
deployButton.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
}
public void widgetSelected(SelectionEvent e) {
DirectoryDialog d = new DirectoryDialog(new Shell());
d.setFilterPath(makeGlobal(deployText.getText()));
String x = d.open();
if( x != null ) {
deployText.setText(makeRelative(x));
}
}
});
Label tempDeployLabel = toolkit.createLabel(composite, Messages.swf_TempDeployDirectory);
tempDeployLabel.setForeground(toolkit.getColors().getColor(IFormColors.TITLE));
tempDeployText = toolkit.createText(composite, getTempDeployDir(), SWT.BORDER);
tempDeployListener = new ModifyListener() {
public void modifyText(ModifyEvent e) {
execute(new SetTempDeployDirCommand());
}
};
tempDeployText.addModifyListener(tempDeployListener);
tempDeployButton = toolkit.createButton(composite, Messages.browse, SWT.PUSH);
tempDeployButton.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
}
public void widgetSelected(SelectionEvent e) {
DirectoryDialog d = new DirectoryDialog(new Shell());
d.setFilterPath(makeGlobal(tempDeployText.getText()));
String x = d.open();
if( x != null )
tempDeployText.setText(makeRelative(x));
}
});
deployText.setEnabled(customRadio == null || customRadio.getSelection());
tempDeployText.setEnabled(customRadio == null || customRadio.getSelection());
FormData descriptionLabelData = new FormData();
descriptionLabelData.left = new FormAttachment(0,5);
descriptionLabelData.top = new FormAttachment(0,5);
descriptionLabel.setLayoutData(descriptionLabelData);
// first row
FormData labelData = new FormData();
labelData.left = new FormAttachment(0,5);
labelData.right = new FormAttachment(deployText,-5);
labelData.top = new FormAttachment(top,5);
label.setLayoutData(labelData);
FormData textData = new FormData();
textData.left = new FormAttachment(deployButton, -305);
textData.top = new FormAttachment(top,5);
textData.right = new FormAttachment(deployButton, -5);
deployText.setLayoutData(textData);
FormData buttonData = new FormData();
buttonData.right = new FormAttachment(100,-5);
buttonData.left = new FormAttachment(100, -100);
buttonData.top = new FormAttachment(top,2);
deployButton.setLayoutData(buttonData);
// second row
FormData tempLabelData = new FormData();
tempLabelData.left = new FormAttachment(0,5);
tempLabelData.right = new FormAttachment(deployText, -5);
tempLabelData.top = new FormAttachment(deployText,5);
tempDeployLabel.setLayoutData(tempLabelData);
FormData tempTextData = new FormData();
tempTextData.left = new FormAttachment(tempDeployButton, -305);
tempTextData.top = new FormAttachment(deployText,5);
tempTextData.right = new FormAttachment(tempDeployButton, -5);
tempDeployText.setLayoutData(tempTextData);
FormData tempButtonData = new FormData();
tempButtonData.right = new FormAttachment(100,-5);
tempButtonData.left = new FormAttachment(100,-100);
tempButtonData.top = new FormAttachment(deployText,5);
tempDeployButton.setLayoutData(tempButtonData);
toolkit.paintBordersFor(composite);
section.setClient(composite);
+ getSaveStatus();
}
private String getDeployType() {
return getServer().getDeployLocationType();
}
private String getDeployDir() {
return server.getRuntime() == null ? "" : makeRelative(getServer().getDeployFolder());
}
private String getTempDeployDir() {
return server.getRuntime() == null ? "" : makeRelative(getServer().getTempDeployFolder());
}
private IDeployableServer getServer() {
return (IDeployableServer)server.loadAdapter(IDeployableServer.class, new NullProgressMonitor());
}
public IStatus[] getSaveStatus() {
String error = "";
List<Status> status = new ArrayList<Status>();
if(!new File(makeGlobal(deployText.getText())).exists()) {
String msg = NLS.bind(Messages.EditorDeployDNE, deployText.getText());
status.add(new Status(IStatus.ERROR, JBossServerCorePlugin.PLUGIN_ID, msg));
error = msg + "\n";
}
if(!new File(makeGlobal(tempDeployText.getText())).exists()) {
String msg = NLS.bind(Messages.EditorTempDeployDNE, tempDeployText.getText());
status.add(new Status(IStatus.ERROR, JBossServerCorePlugin.PLUGIN_ID, msg));
error = error + msg + "\n";
}
setErrorMessage(error.equals("") ? null : error);
return status.size() == 0 ? null : status.toArray(new IStatus[status.size()]);
}
public class SetDeployDirCommand extends ServerCommand {
private String oldDir;
private String newDir;
private Text text;
private ModifyListener listener;
public SetDeployDirCommand() {
super(DeploySection.this.server, Messages.EditorSetDeployLabel);
this.text = deployText;
this.newDir = deployText.getText();
this.listener = deployListener;
this.oldDir = helper.getAttribute(IDeployableServer.DEPLOY_DIRECTORY, "");
}
public void execute() {
helper.setAttribute(IDeployableServer.DEPLOY_DIRECTORY, newDir);
lastCustomDeploy = newDir;
getSaveStatus();
}
public void undo() {
text.removeModifyListener(listener);
helper.setAttribute(IDeployableServer.DEPLOY_DIRECTORY, oldDir);
text.setText(oldDir);
text.addModifyListener(listener);
getSaveStatus();
}
}
public class SetTempDeployDirCommand extends ServerCommand {
private String oldDir;
private String newDir;
private Text text;
private ModifyListener listener;
public SetTempDeployDirCommand() {
super(DeploySection.this.server, Messages.EditorSetTempDeployLabel);
text = tempDeployText;
newDir = tempDeployText.getText();
listener = tempDeployListener;
oldDir = helper.getAttribute(IDeployableServer.TEMP_DEPLOY_DIRECTORY, "");
}
public void execute() {
helper.setAttribute(IDeployableServer.TEMP_DEPLOY_DIRECTORY, newDir);
lastCustomTemp = newDir;
getSaveStatus();
}
public void undo() {
text.removeModifyListener(listener);
helper.setAttribute(IDeployableServer.TEMP_DEPLOY_DIRECTORY, oldDir);
text.setText(oldDir);
text.addModifyListener(listener);
getSaveStatus();
}
}
public class RadioClickedCommand extends ServerCommand {
private Button newSelection, oldSelection;
private String oldDir, newDir;
private String oldTemp, newTemp;
private String id;
public RadioClickedCommand(Button clicked, Button previous) {
super(DeploySection.this.server, Messages.EditorSetRadioClicked);
newSelection = clicked;
oldSelection = previous;
id = DeploySection.this.server.getId();
}
public void execute() {
boolean custom = newSelection == customRadio;
deployText.setEnabled(custom);
tempDeployText.setEnabled(custom);
deployButton.setEnabled(custom);
tempDeployButton.setEnabled(custom);
oldDir = deployText.getText();
oldTemp = tempDeployText.getText();
String type;
if( newSelection == metadataRadio ) {
newDir = IJBossServerConstants.PLUGIN_LOCATION.append(id.replace(' ', '_')).
append(IJBossServerConstants.DEPLOY).makeAbsolute().toString();
newTemp = IJBossServerConstants.PLUGIN_LOCATION.append(id.replace(' ', '_')).
append(IJBossServerConstants.TEMP_DEPLOY).makeAbsolute().toString();
type = IDeployableServer.DEPLOY_METADATA;
new File(newDir).mkdirs();
new File(newTemp).mkdirs();
} else if( newSelection == serverRadio ) {
IRuntime rt = DeploySection.this.server.getRuntime();
IJBossServerRuntime jbsrt = (IJBossServerRuntime)rt.loadAdapter(IJBossServerRuntime.class, new NullProgressMonitor());
String config = jbsrt.getJBossConfiguration();
newDir = new Path(IJBossServerConstants.SERVER)
.append(config)
.append(IJBossServerConstants.DEPLOY).makeRelative().toString();
newTemp = new Path(IJBossServerConstants.SERVER).append(config)
.append(IJBossServerConstants.TMP)
.append(IJBossServerConstants.JBOSSTOOLS_TMP).makeRelative().toString();
new File(newTemp).mkdirs();
type = IDeployableServer.DEPLOY_SERVER;
} else {
newDir = lastCustomDeploy;
newTemp = lastCustomTemp;
type = IDeployableServer.DEPLOY_CUSTOM;
}
if( !newSelection.getSelection() ) {
// REDO, so no one actually clicked the radio. UGH!
oldSelection.removeSelectionListener(radioListener);
oldSelection.setSelection(false);
oldSelection.addSelectionListener(radioListener);
newSelection.removeSelectionListener(radioListener);
newSelection.setSelection(true);
newSelection.addSelectionListener(radioListener);
}
newDir = newDir == null ? oldDir : newDir;
newTemp = newTemp == null ? oldTemp : newTemp;
deployText.removeModifyListener(deployListener);
helper.setAttribute(IDeployableServer.DEPLOY_DIRECTORY, newDir);
deployText.setText(newDir);
deployText.addModifyListener(deployListener);
tempDeployText.removeModifyListener(tempDeployListener);
helper.setAttribute(IDeployableServer.TEMP_DEPLOY_DIRECTORY, newTemp);
tempDeployText.setText(newTemp);
tempDeployText.addModifyListener(tempDeployListener);
helper.setAttribute(IDeployableServer.DEPLOY_DIRECTORY_TYPE, type);
getSaveStatus();
}
public void undo() {
deployText.removeModifyListener(deployListener);
helper.setAttribute(IDeployableServer.DEPLOY_DIRECTORY, oldDir);
deployText.setText(oldDir);
deployText.addModifyListener(deployListener);
tempDeployText.removeModifyListener(tempDeployListener);
helper.setAttribute(IDeployableServer.TEMP_DEPLOY_DIRECTORY, oldTemp);
tempDeployText.setText(oldTemp);
tempDeployText.addModifyListener(tempDeployListener);
oldSelection.removeSelectionListener(radioListener);
oldSelection.setSelection(true);
oldSelection.addSelectionListener(radioListener);
newSelection.removeSelectionListener(radioListener);
newSelection.setSelection(false);
newSelection.addSelectionListener(radioListener);
deployText.setEnabled(customRadio.getSelection());
tempDeployText.setEnabled(customRadio.getSelection());
String oldType = oldSelection == customRadio ? IDeployableServer.DEPLOY_CUSTOM :
oldSelection == serverRadio ? IDeployableServer.DEPLOY_SERVER :
IDeployableServer.DEPLOY_METADATA;
helper.setAttribute(IDeployableServer.DEPLOY_DIRECTORY_TYPE, oldType);
getSaveStatus();
}
}
public void dispose() {
// ignore
}
private String makeGlobal(String path) {
return DeployableServer.makeGlobal(getRuntime(), new Path(path)).toString();
}
private String makeRelative(String path) {
if (getRuntime() == null) {
return path;
}
return DeployableServer.makeRelative(getRuntime(), new Path(path)).toString();
}
private IJBossServerRuntime getRuntime() {
IRuntime r = server.getRuntime();
IJBossServerRuntime ajbsrt = null;
if (r != null) {
ajbsrt = (IJBossServerRuntime) r
.loadAdapter(IJBossServerRuntime.class,
new NullProgressMonitor());
}
return ajbsrt;
}
}
| true | true | public void createSection(Composite parent) {
super.createSection(parent);
FormToolkit toolkit = new FormToolkit(parent.getDisplay());
Section section = toolkit.createSection(parent, ExpandableComposite.TWISTIE|ExpandableComposite.EXPANDED|ExpandableComposite.TITLE_BAR);
section.setText(Messages.swf_DeployEditorHeading);
section.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL));
Composite composite = toolkit.createComposite(section);
composite.setLayout(new FormLayout());
Label descriptionLabel = toolkit.createLabel(composite, Messages.swf_DeploymentDescription);
Control top = descriptionLabel;
if( getRuntime() != null ) {
Composite inner = toolkit.createComposite(composite);
inner.setLayout(new GridLayout(1, false));
metadataRadio = toolkit.createButton(inner, Messages.EditorUseWorkspaceMetadata, SWT.RADIO);
serverRadio = toolkit.createButton(inner, Messages.EditorUseServersDeployFolder, SWT.RADIO);
customRadio = toolkit.createButton(inner, Messages.EditorUseCustomDeployFolder, SWT.RADIO);
metadataRadio.setSelection(getDeployType().equals(IDeployableServer.DEPLOY_METADATA));
serverRadio.setSelection(getDeployType().equals(IDeployableServer.DEPLOY_SERVER));
customRadio.setSelection(getDeployType().equals(IDeployableServer.DEPLOY_CUSTOM));
currentSelection = metadataRadio.getSelection() ? metadataRadio :
serverRadio.getSelection() ? serverRadio :
customRadio;
radioListener = new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
public void widgetSelected(SelectionEvent e) {
if( e.getSource() == currentSelection )
return; // do nothing
execute(new RadioClickedCommand((Button)e.getSource(), currentSelection));
currentSelection = (Button)e.getSource();
} };
metadataRadio.addSelectionListener(radioListener);
serverRadio.addSelectionListener(radioListener);
customRadio.addSelectionListener(radioListener);
FormData radios = new FormData();
radios.top = new FormAttachment(descriptionLabel,5);
radios.left = new FormAttachment(0,5);
radios.right = new FormAttachment(100,-5);
inner.setLayoutData(radios);
top = inner;
}
Label label = toolkit.createLabel(composite, Messages.swf_DeployDirectory);
label.setForeground(toolkit.getColors().getColor(IFormColors.TITLE));
deployText = toolkit.createText(composite, getDeployDir(), SWT.BORDER);
deployListener = new ModifyListener() {
public void modifyText(ModifyEvent e) {
execute(new SetDeployDirCommand());
}
};
deployText.addModifyListener(deployListener);
deployButton = toolkit.createButton(composite, Messages.browse, SWT.PUSH);
deployButton.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
}
public void widgetSelected(SelectionEvent e) {
DirectoryDialog d = new DirectoryDialog(new Shell());
d.setFilterPath(makeGlobal(deployText.getText()));
String x = d.open();
if( x != null ) {
deployText.setText(makeRelative(x));
}
}
});
Label tempDeployLabel = toolkit.createLabel(composite, Messages.swf_TempDeployDirectory);
tempDeployLabel.setForeground(toolkit.getColors().getColor(IFormColors.TITLE));
tempDeployText = toolkit.createText(composite, getTempDeployDir(), SWT.BORDER);
tempDeployListener = new ModifyListener() {
public void modifyText(ModifyEvent e) {
execute(new SetTempDeployDirCommand());
}
};
tempDeployText.addModifyListener(tempDeployListener);
tempDeployButton = toolkit.createButton(composite, Messages.browse, SWT.PUSH);
tempDeployButton.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
}
public void widgetSelected(SelectionEvent e) {
DirectoryDialog d = new DirectoryDialog(new Shell());
d.setFilterPath(makeGlobal(tempDeployText.getText()));
String x = d.open();
if( x != null )
tempDeployText.setText(makeRelative(x));
}
});
deployText.setEnabled(customRadio == null || customRadio.getSelection());
tempDeployText.setEnabled(customRadio == null || customRadio.getSelection());
FormData descriptionLabelData = new FormData();
descriptionLabelData.left = new FormAttachment(0,5);
descriptionLabelData.top = new FormAttachment(0,5);
descriptionLabel.setLayoutData(descriptionLabelData);
// first row
FormData labelData = new FormData();
labelData.left = new FormAttachment(0,5);
labelData.right = new FormAttachment(deployText,-5);
labelData.top = new FormAttachment(top,5);
label.setLayoutData(labelData);
FormData textData = new FormData();
textData.left = new FormAttachment(deployButton, -305);
textData.top = new FormAttachment(top,5);
textData.right = new FormAttachment(deployButton, -5);
deployText.setLayoutData(textData);
FormData buttonData = new FormData();
buttonData.right = new FormAttachment(100,-5);
buttonData.left = new FormAttachment(100, -100);
buttonData.top = new FormAttachment(top,2);
deployButton.setLayoutData(buttonData);
// second row
FormData tempLabelData = new FormData();
tempLabelData.left = new FormAttachment(0,5);
tempLabelData.right = new FormAttachment(deployText, -5);
tempLabelData.top = new FormAttachment(deployText,5);
tempDeployLabel.setLayoutData(tempLabelData);
FormData tempTextData = new FormData();
tempTextData.left = new FormAttachment(tempDeployButton, -305);
tempTextData.top = new FormAttachment(deployText,5);
tempTextData.right = new FormAttachment(tempDeployButton, -5);
tempDeployText.setLayoutData(tempTextData);
FormData tempButtonData = new FormData();
tempButtonData.right = new FormAttachment(100,-5);
tempButtonData.left = new FormAttachment(100,-100);
tempButtonData.top = new FormAttachment(deployText,5);
tempDeployButton.setLayoutData(tempButtonData);
toolkit.paintBordersFor(composite);
section.setClient(composite);
}
| public void createSection(Composite parent) {
super.createSection(parent);
FormToolkit toolkit = new FormToolkit(parent.getDisplay());
Section section = toolkit.createSection(parent, ExpandableComposite.TWISTIE|ExpandableComposite.EXPANDED|ExpandableComposite.TITLE_BAR);
section.setText(Messages.swf_DeployEditorHeading);
section.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL));
Composite composite = toolkit.createComposite(section);
composite.setLayout(new FormLayout());
Label descriptionLabel = toolkit.createLabel(composite, Messages.swf_DeploymentDescription);
Control top = descriptionLabel;
if( getRuntime() != null ) {
Composite inner = toolkit.createComposite(composite);
inner.setLayout(new GridLayout(1, false));
metadataRadio = toolkit.createButton(inner, Messages.EditorUseWorkspaceMetadata, SWT.RADIO);
serverRadio = toolkit.createButton(inner, Messages.EditorUseServersDeployFolder, SWT.RADIO);
customRadio = toolkit.createButton(inner, Messages.EditorUseCustomDeployFolder, SWT.RADIO);
metadataRadio.setSelection(getDeployType().equals(IDeployableServer.DEPLOY_METADATA));
serverRadio.setSelection(getDeployType().equals(IDeployableServer.DEPLOY_SERVER));
customRadio.setSelection(getDeployType().equals(IDeployableServer.DEPLOY_CUSTOM));
currentSelection = metadataRadio.getSelection() ? metadataRadio :
serverRadio.getSelection() ? serverRadio :
customRadio;
radioListener = new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
public void widgetSelected(SelectionEvent e) {
if( e.getSource() == currentSelection )
return; // do nothing
execute(new RadioClickedCommand((Button)e.getSource(), currentSelection));
currentSelection = (Button)e.getSource();
} };
metadataRadio.addSelectionListener(radioListener);
serverRadio.addSelectionListener(radioListener);
customRadio.addSelectionListener(radioListener);
FormData radios = new FormData();
radios.top = new FormAttachment(descriptionLabel,5);
radios.left = new FormAttachment(0,5);
radios.right = new FormAttachment(100,-5);
inner.setLayoutData(radios);
top = inner;
}
Label label = toolkit.createLabel(composite, Messages.swf_DeployDirectory);
label.setForeground(toolkit.getColors().getColor(IFormColors.TITLE));
deployText = toolkit.createText(composite, getDeployDir(), SWT.BORDER);
deployListener = new ModifyListener() {
public void modifyText(ModifyEvent e) {
execute(new SetDeployDirCommand());
}
};
deployText.addModifyListener(deployListener);
deployButton = toolkit.createButton(composite, Messages.browse, SWT.PUSH);
deployButton.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
}
public void widgetSelected(SelectionEvent e) {
DirectoryDialog d = new DirectoryDialog(new Shell());
d.setFilterPath(makeGlobal(deployText.getText()));
String x = d.open();
if( x != null ) {
deployText.setText(makeRelative(x));
}
}
});
Label tempDeployLabel = toolkit.createLabel(composite, Messages.swf_TempDeployDirectory);
tempDeployLabel.setForeground(toolkit.getColors().getColor(IFormColors.TITLE));
tempDeployText = toolkit.createText(composite, getTempDeployDir(), SWT.BORDER);
tempDeployListener = new ModifyListener() {
public void modifyText(ModifyEvent e) {
execute(new SetTempDeployDirCommand());
}
};
tempDeployText.addModifyListener(tempDeployListener);
tempDeployButton = toolkit.createButton(composite, Messages.browse, SWT.PUSH);
tempDeployButton.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
}
public void widgetSelected(SelectionEvent e) {
DirectoryDialog d = new DirectoryDialog(new Shell());
d.setFilterPath(makeGlobal(tempDeployText.getText()));
String x = d.open();
if( x != null )
tempDeployText.setText(makeRelative(x));
}
});
deployText.setEnabled(customRadio == null || customRadio.getSelection());
tempDeployText.setEnabled(customRadio == null || customRadio.getSelection());
FormData descriptionLabelData = new FormData();
descriptionLabelData.left = new FormAttachment(0,5);
descriptionLabelData.top = new FormAttachment(0,5);
descriptionLabel.setLayoutData(descriptionLabelData);
// first row
FormData labelData = new FormData();
labelData.left = new FormAttachment(0,5);
labelData.right = new FormAttachment(deployText,-5);
labelData.top = new FormAttachment(top,5);
label.setLayoutData(labelData);
FormData textData = new FormData();
textData.left = new FormAttachment(deployButton, -305);
textData.top = new FormAttachment(top,5);
textData.right = new FormAttachment(deployButton, -5);
deployText.setLayoutData(textData);
FormData buttonData = new FormData();
buttonData.right = new FormAttachment(100,-5);
buttonData.left = new FormAttachment(100, -100);
buttonData.top = new FormAttachment(top,2);
deployButton.setLayoutData(buttonData);
// second row
FormData tempLabelData = new FormData();
tempLabelData.left = new FormAttachment(0,5);
tempLabelData.right = new FormAttachment(deployText, -5);
tempLabelData.top = new FormAttachment(deployText,5);
tempDeployLabel.setLayoutData(tempLabelData);
FormData tempTextData = new FormData();
tempTextData.left = new FormAttachment(tempDeployButton, -305);
tempTextData.top = new FormAttachment(deployText,5);
tempTextData.right = new FormAttachment(tempDeployButton, -5);
tempDeployText.setLayoutData(tempTextData);
FormData tempButtonData = new FormData();
tempButtonData.right = new FormAttachment(100,-5);
tempButtonData.left = new FormAttachment(100,-100);
tempButtonData.top = new FormAttachment(deployText,5);
tempDeployButton.setLayoutData(tempButtonData);
toolkit.paintBordersFor(composite);
section.setClient(composite);
getSaveStatus();
}
|
diff --git a/hadoop-mapreduce-project/src/contrib/streaming/src/java/org/apache/hadoop/streaming/StreamJob.java b/hadoop-mapreduce-project/src/contrib/streaming/src/java/org/apache/hadoop/streaming/StreamJob.java
index a019be7f34..b68e73e34b 100644
--- a/hadoop-mapreduce-project/src/contrib/streaming/src/java/org/apache/hadoop/streaming/StreamJob.java
+++ b/hadoop-mapreduce-project/src/contrib/streaming/src/java/org/apache/hadoop/streaming/StreamJob.java
@@ -1,1098 +1,1098 @@
/**
* 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.hadoop.streaming;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.TreeMap;
import java.util.TreeSet;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapreduce.MRConfig;
import org.apache.hadoop.mapreduce.MRJobConfig;
import org.apache.hadoop.mapreduce.filecache.DistributedCache;
import org.apache.hadoop.mapreduce.server.jobtracker.JTConfig;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.FileAlreadyExistsException;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.FileOutputFormat;
import org.apache.hadoop.mapred.InvalidJobConfException;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.JobID;
import org.apache.hadoop.mapred.KeyValueTextInputFormat;
import org.apache.hadoop.mapred.OutputFormat;
import org.apache.hadoop.mapred.RunningJob;
import org.apache.hadoop.mapred.SequenceFileAsTextInputFormat;
import org.apache.hadoop.mapred.SequenceFileInputFormat;
import org.apache.hadoop.mapred.TextInputFormat;
import org.apache.hadoop.mapred.TextOutputFormat;
import org.apache.hadoop.mapred.lib.LazyOutputFormat;
import org.apache.hadoop.mapred.lib.aggregate.ValueAggregatorCombiner;
import org.apache.hadoop.mapred.lib.aggregate.ValueAggregatorReducer;
import org.apache.hadoop.streaming.io.IdentifierResolver;
import org.apache.hadoop.streaming.io.InputWriter;
import org.apache.hadoop.streaming.io.OutputReader;
import org.apache.hadoop.util.GenericOptionsParser;
import org.apache.hadoop.util.ReflectionUtils;
import org.apache.hadoop.util.RunJar;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.Tool;
/** All the client-side work happens here.
* (Jar packaging, MapRed job submission and monitoring)
*/
public class StreamJob implements Tool {
protected static final Log LOG = LogFactory.getLog(StreamJob.class.getName());
final static String REDUCE_NONE = "NONE";
/** -----------Streaming CLI Implementation **/
private CommandLineParser parser = new BasicParser();
private Options allOptions;
/**@deprecated use StreamJob() with ToolRunner or set the
* Configuration using {@link #setConf(Configuration)} and
* run with {@link #run(String[])}.
*/
@Deprecated
public StreamJob(String[] argv, boolean mayExit) {
this();
argv_ = argv;
this.config_ = new Configuration();
}
public StreamJob() {
setupOptions();
this.config_ = new Configuration();
}
@Override
public Configuration getConf() {
return config_;
}
@Override
public void setConf(Configuration conf) {
this.config_ = conf;
}
@Override
public int run(String[] args) throws Exception {
try {
this.argv_ = args;
init();
preProcessArgs();
parseArgv();
if (printUsage) {
printUsage(detailedUsage_);
return 0;
}
postProcessArgs();
setJobConf();
} catch (IllegalArgumentException ex) {
//ignore, since log will already be printed
// print the log in debug mode.
LOG.debug("Error in streaming job", ex);
return 1;
}
return submitAndMonitorJob();
}
/**
* This method creates a streaming job from the given argument list.
* The created object can be used and/or submitted to a jobtracker for
* execution by a job agent such as JobControl
* @param argv the list args for creating a streaming job
* @return the created JobConf object
* @throws IOException
*/
static public JobConf createJob(String[] argv) throws IOException {
StreamJob job = new StreamJob();
job.argv_ = argv;
job.init();
job.preProcessArgs();
job.parseArgv();
job.postProcessArgs();
job.setJobConf();
return job.jobConf_;
}
/**
* This is the method that actually
* intializes the job conf and submits the job
* to the jobtracker
* @throws IOException
* @deprecated use {@link #run(String[])} instead.
*/
@Deprecated
public int go() throws IOException {
try {
return run(argv_);
}
catch (Exception ex) {
throw new IOException(ex.getMessage());
}
}
protected void init() {
try {
env_ = new Environment();
} catch (IOException io) {
throw new RuntimeException(io);
}
}
void preProcessArgs() {
verbose_ = false;
// Unset HADOOP_ROOT_LOGGER in case streaming job
// invokes additional hadoop commands.
addTaskEnvironment_ = "HADOOP_ROOT_LOGGER=";
}
void postProcessArgs() throws IOException {
if (inputSpecs_.size() == 0) {
fail("Required argument: -input <name>");
}
if (output_ == null) {
fail("Required argument: -output ");
}
msg("addTaskEnvironment=" + addTaskEnvironment_);
for (final String packageFile : packageFiles_) {
File f = new File(packageFile);
if (f.isFile()) {
shippedCanonFiles_.add(f.getCanonicalPath());
}
}
msg("shippedCanonFiles_=" + shippedCanonFiles_);
// careful with class names..
mapCmd_ = unqualifyIfLocalPath(mapCmd_);
comCmd_ = unqualifyIfLocalPath(comCmd_);
redCmd_ = unqualifyIfLocalPath(redCmd_);
}
String unqualifyIfLocalPath(String cmd) throws IOException {
if (cmd == null) {
//
} else {
String prog = cmd;
String args = "";
int s = cmd.indexOf(" ");
if (s != -1) {
prog = cmd.substring(0, s);
args = cmd.substring(s + 1);
}
String progCanon;
try {
progCanon = new File(prog).getCanonicalPath();
} catch (IOException io) {
progCanon = prog;
}
boolean shipped = shippedCanonFiles_.contains(progCanon);
msg("shipped: " + shipped + " " + progCanon);
if (shipped) {
// Change path to simple filename.
// That way when PipeMapRed calls Runtime.exec(),
// it will look for the excutable in Task's working dir.
// And this is where TaskRunner unjars our job jar.
prog = new File(prog).getName();
if (args.length() > 0) {
cmd = prog + " " + args;
} else {
cmd = prog;
}
}
}
msg("cmd=" + cmd);
return cmd;
}
void parseArgv() {
CommandLine cmdLine = null;
try {
cmdLine = parser.parse(allOptions, argv_);
} catch(Exception oe) {
LOG.error(oe.getMessage());
exitUsage(argv_.length > 0 && "-info".equals(argv_[0]));
}
if (cmdLine != null) {
detailedUsage_ = cmdLine.hasOption("info");
if (cmdLine.hasOption("help") || detailedUsage_) {
printUsage = true;
return;
}
verbose_ = cmdLine.hasOption("verbose");
background_ = cmdLine.hasOption("background");
debug_ = cmdLine.hasOption("debug")? debug_ + 1 : debug_;
String[] values = cmdLine.getOptionValues("input");
if (values != null && values.length > 0) {
for (String input : values) {
inputSpecs_.add(input);
}
}
output_ = cmdLine.getOptionValue("output");
mapCmd_ = cmdLine.getOptionValue("mapper");
comCmd_ = cmdLine.getOptionValue("combiner");
redCmd_ = cmdLine.getOptionValue("reducer");
lazyOutput_ = cmdLine.hasOption("lazyOutput");
values = cmdLine.getOptionValues("file");
if (values != null && values.length > 0) {
LOG.warn("-file option is deprecated, please use generic option" +
" -files instead.");
String fileList = null;
for (String file : values) {
packageFiles_.add(file);
try {
URI pathURI = new URI(file);
Path path = new Path(pathURI);
FileSystem localFs = FileSystem.getLocal(config_);
String finalPath = path.makeQualified(localFs).toString();
fileList = fileList == null ? finalPath : fileList + "," + finalPath;
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
config_.set("tmpfiles", config_.get("tmpfiles", "") +
(fileList == null ? "" : fileList));
validate(packageFiles_);
}
String fsName = cmdLine.getOptionValue("dfs");
if (null != fsName){
LOG.warn("-dfs option is deprecated, please use -fs instead.");
config_.set("fs.default.name", fsName);
}
additionalConfSpec_ = cmdLine.getOptionValue("additionalconfspec");
inputFormatSpec_ = cmdLine.getOptionValue("inputformat");
outputFormatSpec_ = cmdLine.getOptionValue("outputformat");
numReduceTasksSpec_ = cmdLine.getOptionValue("numReduceTasks");
partitionerSpec_ = cmdLine.getOptionValue("partitioner");
inReaderSpec_ = cmdLine.getOptionValue("inputreader");
mapDebugSpec_ = cmdLine.getOptionValue("mapdebug");
reduceDebugSpec_ = cmdLine.getOptionValue("reducedebug");
ioSpec_ = cmdLine.getOptionValue("io");
String[] car = cmdLine.getOptionValues("cacheArchive");
if (null != car && car.length > 0){
LOG.warn("-cacheArchive option is deprecated, please use -archives instead.");
for(String s : car){
cacheArchives = (cacheArchives == null)?s :cacheArchives + "," + s;
}
}
String[] caf = cmdLine.getOptionValues("cacheFile");
if (null != caf && caf.length > 0){
LOG.warn("-cacheFile option is deprecated, please use -files instead.");
for(String s : caf){
cacheFiles = (cacheFiles == null)?s :cacheFiles + "," + s;
}
}
String[] jobconf = cmdLine.getOptionValues("jobconf");
if (null != jobconf && jobconf.length > 0){
LOG.warn("-jobconf option is deprecated, please use -D instead.");
for(String s : jobconf){
String[] parts = s.split("=", 2);
config_.set(parts[0], parts[1]);
}
}
String[] cmd = cmdLine.getOptionValues("cmdenv");
if (null != cmd && cmd.length > 0){
for(String s : cmd) {
if (addTaskEnvironment_.length() > 0) {
addTaskEnvironment_ += " ";
}
addTaskEnvironment_ += s;
}
}
} else {
exitUsage(argv_.length > 0 && "-info".equals(argv_[0]));
}
}
protected void msg(String msg) {
if (verbose_) {
System.out.println("STREAM: " + msg);
}
}
private Option createOption(String name, String desc,
String argName, int max, boolean required){
return OptionBuilder
.withArgName(argName)
.hasArgs(max)
.withDescription(desc)
.isRequired(required)
.create(name);
}
private Option createBoolOption(String name, String desc){
return OptionBuilder.withDescription(desc).create(name);
}
private void validate(final List<String> values)
throws IllegalArgumentException {
for (String file : values) {
File f = new File(file);
if (!f.canRead()) {
fail("File: " + f.getAbsolutePath()
+ " does not exist, or is not readable.");
}
}
}
private void setupOptions(){
// input and output are not required for -info and -help options,
// though they are required for streaming job to be run.
Option input = createOption("input",
"DFS input file(s) for the Map step",
"path",
Integer.MAX_VALUE,
false);
Option output = createOption("output",
"DFS output directory for the Reduce step",
"path", 1, false);
Option mapper = createOption("mapper",
"The streaming command to run", "cmd", 1, false);
Option combiner = createOption("combiner",
"The streaming command to run", "cmd", 1, false);
// reducer could be NONE
Option reducer = createOption("reducer",
"The streaming command to run", "cmd", 1, false);
Option file = createOption("file",
"File to be shipped in the Job jar file",
"file", Integer.MAX_VALUE, false);
Option dfs = createOption("dfs",
"Optional. Override DFS configuration", "<h:p>|local", 1, false);
Option additionalconfspec = createOption("additionalconfspec",
"Optional.", "spec", 1, false);
Option inputformat = createOption("inputformat",
"Optional.", "spec", 1, false);
Option outputformat = createOption("outputformat",
"Optional.", "spec", 1, false);
Option partitioner = createOption("partitioner",
"Optional.", "spec", 1, false);
Option numReduceTasks = createOption("numReduceTasks",
"Optional.", "spec",1, false );
Option inputreader = createOption("inputreader",
"Optional.", "spec", 1, false);
Option mapDebug = createOption("mapdebug",
"Optional.", "spec", 1, false);
Option reduceDebug = createOption("reducedebug",
"Optional", "spec",1, false);
Option jobconf =
createOption("jobconf",
"(n=v) Optional. Add or override a JobConf property.",
"spec", 1, false);
Option cmdenv =
createOption("cmdenv", "(n=v) Pass env.var to streaming commands.",
"spec", 1, false);
Option cacheFile = createOption("cacheFile",
"File name URI", "fileNameURI", Integer.MAX_VALUE, false);
Option cacheArchive = createOption("cacheArchive",
"File name URI", "fileNameURI", Integer.MAX_VALUE, false);
Option io = createOption("io",
"Optional.", "spec", 1, false);
// boolean properties
Option background = createBoolOption("background", "Submit the job and don't wait till it completes.");
Option verbose = createBoolOption("verbose", "print verbose output");
Option info = createBoolOption("info", "print verbose output");
Option help = createBoolOption("help", "print this help message");
Option debug = createBoolOption("debug", "print debug output");
Option lazyOutput = createBoolOption("lazyOutput", "create outputs lazily");
allOptions = new Options().
addOption(input).
addOption(output).
addOption(mapper).
addOption(combiner).
addOption(reducer).
addOption(file).
addOption(dfs).
addOption(additionalconfspec).
addOption(inputformat).
addOption(outputformat).
addOption(partitioner).
addOption(numReduceTasks).
addOption(inputreader).
addOption(mapDebug).
addOption(reduceDebug).
addOption(jobconf).
addOption(cmdenv).
addOption(cacheFile).
addOption(cacheArchive).
addOption(io).
addOption(background).
addOption(verbose).
addOption(info).
addOption(debug).
addOption(help).
addOption(lazyOutput);
}
public void exitUsage(boolean detailed) {
printUsage(detailed);
fail("");
}
private void printUsage(boolean detailed) {
System.out.println("Usage: $HADOOP_PREFIX/bin/hadoop jar hadoop-streaming.jar"
+ " [options]");
System.out.println("Options:");
System.out.println(" -input <path> DFS input file(s) for the Map"
+ " step.");
System.out.println(" -output <path> DFS output directory for the"
+ " Reduce step.");
System.out.println(" -mapper <cmd|JavaClassName> Optional. Command"
+ " to be run as mapper.");
System.out.println(" -combiner <cmd|JavaClassName> Optional. Command"
+ " to be run as combiner.");
System.out.println(" -reducer <cmd|JavaClassName> Optional. Command"
+ " to be run as reducer.");
System.out.println(" -file <file> Optional. File/dir to be "
+ "shipped in the Job jar file.\n" +
" Deprecated. Use generic option \"-files\" instead.");
System.out.println(" -inputformat <TextInputFormat(default)"
+ "|SequenceFileAsTextInputFormat|JavaClassName>\n"
+ " Optional. The input format class.");
System.out.println(" -outputformat <TextOutputFormat(default)"
+ "|JavaClassName>\n"
+ " Optional. The output format class.");
System.out.println(" -partitioner <JavaClassName> Optional. The"
+ " partitioner class.");
System.out.println(" -numReduceTasks <num> Optional. Number of reduce "
+ "tasks.");
System.out.println(" -inputreader <spec> Optional. Input recordreader"
+ " spec.");
System.out.println(" -cmdenv <n>=<v> Optional. Pass env.var to"
+ " streaming commands.");
System.out.println(" -mapdebug <cmd> Optional. "
+ "To run this script when a map task fails.");
System.out.println(" -reducedebug <cmd> Optional."
+ " To run this script when a reduce task fails.");
System.out.println(" -io <identifier> Optional. Format to use"
+ " for input to and output");
System.out.println(" from mapper/reducer commands");
System.out.println(" -lazyOutput Optional. Lazily create Output.");
System.out.println(" -background Optional. Submit the job and don't wait till it completes.");
System.out.println(" -verbose Optional. Print verbose output.");
System.out.println(" -info Optional. Print detailed usage.");
System.out.println(" -help Optional. Print help message.");
System.out.println();
GenericOptionsParser.printGenericCommandUsage(System.out);
if (!detailed) {
System.out.println();
System.out.println("For more details about these options:");
System.out.println("Use " +
"$HADOOP_PREFIX/bin/hadoop jar hadoop-streaming.jar -info");
return;
}
System.out.println();
System.out.println("Usage tips:");
System.out.println("In -input: globbing on <path> is supported and can "
+ "have multiple -input");
System.out.println();
System.out.println("Default Map input format: a line is a record in UTF-8 "
+ "the key part ends at first");
System.out.println(" TAB, the rest of the line is the value");
System.out.println();
System.out.println("To pass a Custom input format:");
System.out.println(" -inputformat package.MyInputFormat");
System.out.println();
System.out.println("Similarly, to pass a custom output format:");
System.out.println(" -outputformat package.MyOutputFormat");
System.out.println();
System.out.println("The files with extensions .class and .jar/.zip," +
" specified for the -file");
System.out.println(" argument[s], end up in \"classes\" and \"lib\" " +
"directories respectively inside");
System.out.println(" the working directory when the mapper and reducer are"
+ " run. All other files");
System.out.println(" specified for the -file argument[s]" +
" end up in the working directory when the");
System.out.println(" mapper and reducer are run. The location of this " +
"working directory is");
System.out.println(" unspecified.");
System.out.println();
System.out.println("To set the number of reduce tasks (num. of output " +
"files) as, say 10:");
System.out.println(" Use -numReduceTasks 10");
System.out.println("To skip the sort/combine/shuffle/sort/reduce step:");
System.out.println(" Use -numReduceTasks 0");
System.out.println(" Map output then becomes a 'side-effect " +
"output' rather than a reduce input.");
System.out.println(" This speeds up processing. This also feels " +
"more like \"in-place\" processing");
System.out.println(" because the input filename and the map " +
"input order are preserved.");
System.out.println(" This is equivalent to -reducer NONE");
System.out.println();
System.out.println("To speed up the last maps:");
System.out.println(" -D " + MRJobConfig.MAP_SPECULATIVE + "=true");
System.out.println("To speed up the last reduces:");
System.out.println(" -D " + MRJobConfig.REDUCE_SPECULATIVE + "=true");
System.out.println("To name the job (appears in the JobTracker Web UI):");
System.out.println(" -D " + MRJobConfig.JOB_NAME + "='My Job'");
System.out.println("To change the local temp directory:");
System.out.println(" -D dfs.data.dir=/tmp/dfs");
System.out.println(" -D stream.tmpdir=/tmp/streaming");
System.out.println("Additional local temp directories with -jt local:");
System.out.println(" -D " + MRConfig.LOCAL_DIR + "=/tmp/local");
System.out.println(" -D " + JTConfig.JT_SYSTEM_DIR + "=/tmp/system");
System.out.println(" -D " + MRConfig.TEMP_DIR + "=/tmp/temp");
System.out.println("To treat tasks with non-zero exit status as SUCCEDED:");
System.out.println(" -D stream.non.zero.exit.is.failure=false");
System.out.println("Use a custom hadoop streaming build along with standard"
+ " hadoop install:");
System.out.println(" $HADOOP_PREFIX/bin/hadoop jar " +
"/path/my-hadoop-streaming.jar [...]\\");
System.out.println(" [...] -D stream.shipped.hadoopstreaming=" +
"/path/my-hadoop-streaming.jar");
System.out.println("For more details about jobconf parameters see:");
System.out.println(" http://wiki.apache.org/hadoop/JobConfFile");
System.out.println("To set an environement variable in a streaming " +
"command:");
System.out.println(" -cmdenv EXAMPLE_DIR=/home/example/dictionaries/");
System.out.println();
System.out.println("Shortcut:");
System.out.println(" setenv HSTREAMING \"$HADOOP_PREFIX/bin/hadoop jar " +
"hadoop-streaming.jar\"");
System.out.println();
System.out.println("Example: $HSTREAMING -mapper " +
"\"/usr/local/bin/perl5 filter.pl\"");
System.out.println(" -file /local/filter.pl -input " +
"\"/logs/0604*/*\" [...]");
System.out.println(" Ships a script, invokes the non-shipped perl " +
"interpreter. Shipped files go to");
System.out.println(" the working directory so filter.pl is found by perl. "
+ "Input files are all the");
System.out.println(" daily logs for days in month 2006-04");
}
public void fail(String message) {
System.err.println(message);
System.err.println("Try -help for more information");
throw new IllegalArgumentException(message);
}
// --------------------------------------------
protected String getHadoopClientHome() {
String h = env_.getProperty("HADOOP_PREFIX"); // standard Hadoop
if (h == null) {
//fail("Missing required environment variable: HADOOP_PREFIX");
h = "UNDEF";
}
return h;
}
protected boolean isLocalHadoop() {
return StreamUtil.isLocalJobTracker(jobConf_);
}
@Deprecated
protected String getClusterNick() {
return "default";
}
/** @return path to the created Jar file or null if no files are necessary.
*/
protected String packageJobJar() throws IOException {
ArrayList<String> unjarFiles = new ArrayList<String>();
// Runtime code: ship same version of code as self (job submitter code)
// usually found in: build/contrib or build/hadoop-<version>-dev-streaming.jar
// First try an explicit spec: it's too hard to find our own location in this case:
// $HADOOP_PREFIX/bin/hadoop jar /not/first/on/classpath/custom-hadoop-streaming.jar
// where findInClasspath() would find the version of hadoop-streaming.jar in $HADOOP_PREFIX
String runtimeClasses = config_.get("stream.shipped.hadoopstreaming"); // jar or class dir
if (runtimeClasses == null) {
runtimeClasses = StreamUtil.findInClasspath(StreamJob.class.getName());
}
if (runtimeClasses == null) {
throw new IOException("runtime classes not found: " + getClass().getPackage());
} else {
msg("Found runtime classes in: " + runtimeClasses);
}
if (isLocalHadoop()) {
// don't package class files (they might get unpackaged in "." and then
// hide the intended CLASSPATH entry)
// we still package everything else (so that scripts and executable are found in
// Task workdir like distributed Hadoop)
} else {
if (new File(runtimeClasses).isDirectory()) {
packageFiles_.add(runtimeClasses);
} else {
unjarFiles.add(runtimeClasses);
}
}
if (packageFiles_.size() + unjarFiles.size() == 0) {
return null;
}
String tmp = jobConf_.get("stream.tmpdir"); //, "/tmp/${mapreduce.job.user.name}/"
File tmpDir = (tmp == null) ? null : new File(tmp);
// tmpDir=null means OS default tmp dir
File jobJar = File.createTempFile("streamjob", ".jar", tmpDir);
System.out.println("packageJobJar: " + packageFiles_ + " " + unjarFiles + " " + jobJar
+ " tmpDir=" + tmpDir);
if (debug_ == 0) {
jobJar.deleteOnExit();
}
JarBuilder builder = new JarBuilder();
if (verbose_) {
builder.setVerbose(true);
}
String jobJarName = jobJar.getAbsolutePath();
builder.merge(packageFiles_, unjarFiles, jobJarName);
return jobJarName;
}
/**
* get the uris of all the files/caches
*/
protected void getURIs(String lcacheArchives, String lcacheFiles) {
String archives[] = StringUtils.getStrings(lcacheArchives);
String files[] = StringUtils.getStrings(lcacheFiles);
fileURIs = StringUtils.stringToURI(files);
archiveURIs = StringUtils.stringToURI(archives);
}
protected void setJobConf() throws IOException {
if (additionalConfSpec_ != null) {
LOG.warn("-additionalconfspec option is deprecated, please use -conf instead.");
config_.addResource(new Path(additionalConfSpec_));
}
// general MapRed job properties
- jobConf_ = new JobConf(config_);
+ jobConf_ = new JobConf(config_, StreamJob.class);
// All streaming jobs get the task timeout value
// from the configuration settings.
// The correct FS must be set before this is called!
// (to resolve local vs. dfs drive letter differences)
// (mapreduce.job.working.dir will be lazily initialized ONCE and depends on FS)
for (int i = 0; i < inputSpecs_.size(); i++) {
FileInputFormat.addInputPaths(jobConf_,
(String) inputSpecs_.get(i));
}
String defaultPackage = this.getClass().getPackage().getName();
Class c;
Class fmt = null;
if (inReaderSpec_ == null && inputFormatSpec_ == null) {
fmt = TextInputFormat.class;
} else if (inputFormatSpec_ != null) {
if (inputFormatSpec_.equals(TextInputFormat.class.getName())
|| inputFormatSpec_.equals(TextInputFormat.class.getCanonicalName())
|| inputFormatSpec_.equals(TextInputFormat.class.getSimpleName())) {
fmt = TextInputFormat.class;
} else if (inputFormatSpec_.equals(KeyValueTextInputFormat.class
.getName())
|| inputFormatSpec_.equals(KeyValueTextInputFormat.class
.getCanonicalName())
|| inputFormatSpec_.equals(KeyValueTextInputFormat.class.getSimpleName())) {
if (inReaderSpec_ == null) {
fmt = KeyValueTextInputFormat.class;
}
} else if (inputFormatSpec_.equals(SequenceFileInputFormat.class
.getName())
|| inputFormatSpec_
.equals(org.apache.hadoop.mapred.SequenceFileInputFormat.class
.getCanonicalName())
|| inputFormatSpec_
.equals(org.apache.hadoop.mapred.SequenceFileInputFormat.class.getSimpleName())) {
if (inReaderSpec_ == null) {
fmt = SequenceFileInputFormat.class;
}
} else if (inputFormatSpec_.equals(SequenceFileAsTextInputFormat.class
.getName())
|| inputFormatSpec_.equals(SequenceFileAsTextInputFormat.class
.getCanonicalName())
|| inputFormatSpec_.equals(SequenceFileAsTextInputFormat.class.getSimpleName())) {
fmt = SequenceFileAsTextInputFormat.class;
} else {
c = StreamUtil.goodClassOrNull(jobConf_, inputFormatSpec_, defaultPackage);
if (c != null) {
fmt = c;
} else {
fail("-inputformat : class not found : " + inputFormatSpec_);
}
}
}
if (fmt == null) {
fmt = StreamInputFormat.class;
}
jobConf_.setInputFormat(fmt);
if (ioSpec_ != null) {
jobConf_.set("stream.map.input", ioSpec_);
jobConf_.set("stream.map.output", ioSpec_);
jobConf_.set("stream.reduce.input", ioSpec_);
jobConf_.set("stream.reduce.output", ioSpec_);
}
Class<? extends IdentifierResolver> idResolverClass =
jobConf_.getClass("stream.io.identifier.resolver.class",
IdentifierResolver.class, IdentifierResolver.class);
IdentifierResolver idResolver = ReflectionUtils.newInstance(idResolverClass, jobConf_);
idResolver.resolve(jobConf_.get("stream.map.input", IdentifierResolver.TEXT_ID));
jobConf_.setClass("stream.map.input.writer.class",
idResolver.getInputWriterClass(), InputWriter.class);
idResolver.resolve(jobConf_.get("stream.reduce.input", IdentifierResolver.TEXT_ID));
jobConf_.setClass("stream.reduce.input.writer.class",
idResolver.getInputWriterClass(), InputWriter.class);
jobConf_.set("stream.addenvironment", addTaskEnvironment_);
boolean isMapperACommand = false;
if (mapCmd_ != null) {
c = StreamUtil.goodClassOrNull(jobConf_, mapCmd_, defaultPackage);
if (c != null) {
jobConf_.setMapperClass(c);
} else {
isMapperACommand = true;
jobConf_.setMapperClass(PipeMapper.class);
jobConf_.setMapRunnerClass(PipeMapRunner.class);
jobConf_.set("stream.map.streamprocessor",
URLEncoder.encode(mapCmd_, "UTF-8"));
}
}
if (comCmd_ != null) {
c = StreamUtil.goodClassOrNull(jobConf_, comCmd_, defaultPackage);
if (c != null) {
jobConf_.setCombinerClass(c);
} else {
jobConf_.setCombinerClass(PipeCombiner.class);
jobConf_.set("stream.combine.streamprocessor", URLEncoder.encode(
comCmd_, "UTF-8"));
}
}
if (numReduceTasksSpec_!= null) {
int numReduceTasks = Integer.parseInt(numReduceTasksSpec_);
jobConf_.setNumReduceTasks(numReduceTasks);
}
boolean isReducerACommand = false;
if (redCmd_ != null) {
if (redCmd_.equals(REDUCE_NONE)) {
jobConf_.setNumReduceTasks(0);
}
if (jobConf_.getNumReduceTasks() != 0) {
if (redCmd_.compareToIgnoreCase("aggregate") == 0) {
jobConf_.setReducerClass(ValueAggregatorReducer.class);
jobConf_.setCombinerClass(ValueAggregatorCombiner.class);
} else {
c = StreamUtil.goodClassOrNull(jobConf_, redCmd_, defaultPackage);
if (c != null) {
jobConf_.setReducerClass(c);
} else {
isReducerACommand = true;
jobConf_.setReducerClass(PipeReducer.class);
jobConf_.set("stream.reduce.streamprocessor", URLEncoder.encode(
redCmd_, "UTF-8"));
}
}
}
}
idResolver.resolve(jobConf_.get("stream.map.output",
IdentifierResolver.TEXT_ID));
jobConf_.setClass("stream.map.output.reader.class",
idResolver.getOutputReaderClass(), OutputReader.class);
if (isMapperACommand) {
// if mapper is a command, then map output key/value classes come from the
// idResolver
jobConf_.setMapOutputKeyClass(idResolver.getOutputKeyClass());
jobConf_.setMapOutputValueClass(idResolver.getOutputValueClass());
if (jobConf_.getNumReduceTasks() == 0) {
jobConf_.setOutputKeyClass(idResolver.getOutputKeyClass());
jobConf_.setOutputValueClass(idResolver.getOutputValueClass());
}
}
idResolver.resolve(jobConf_.get("stream.reduce.output",
IdentifierResolver.TEXT_ID));
jobConf_.setClass("stream.reduce.output.reader.class",
idResolver.getOutputReaderClass(), OutputReader.class);
if (isReducerACommand) {
// if reducer is a command, then output key/value classes come from the
// idResolver
jobConf_.setOutputKeyClass(idResolver.getOutputKeyClass());
jobConf_.setOutputValueClass(idResolver.getOutputValueClass());
}
if (inReaderSpec_ != null) {
String[] args = inReaderSpec_.split(",");
String readerClass = args[0];
// this argument can only be a Java class
c = StreamUtil.goodClassOrNull(jobConf_, readerClass, defaultPackage);
if (c != null) {
jobConf_.set("stream.recordreader.class", c.getName());
} else {
fail("-inputreader: class not found: " + readerClass);
}
for (int i = 1; i < args.length; i++) {
String[] nv = args[i].split("=", 2);
String k = "stream.recordreader." + nv[0];
String v = (nv.length > 1) ? nv[1] : "";
jobConf_.set(k, v);
}
}
FileOutputFormat.setOutputPath(jobConf_, new Path(output_));
fmt = null;
if (outputFormatSpec_!= null) {
c = StreamUtil.goodClassOrNull(jobConf_, outputFormatSpec_, defaultPackage);
if (c != null) {
fmt = c;
} else {
fail("-outputformat : class not found : " + outputFormatSpec_);
}
}
if (fmt == null) {
fmt = TextOutputFormat.class;
}
if (lazyOutput_) {
LazyOutputFormat.setOutputFormatClass(jobConf_, fmt);
} else {
jobConf_.setOutputFormat(fmt);
}
if (partitionerSpec_!= null) {
c = StreamUtil.goodClassOrNull(jobConf_, partitionerSpec_, defaultPackage);
if (c != null) {
jobConf_.setPartitionerClass(c);
} else {
fail("-partitioner : class not found : " + partitionerSpec_);
}
}
if(mapDebugSpec_ != null){
jobConf_.setMapDebugScript(mapDebugSpec_);
}
if(reduceDebugSpec_ != null){
jobConf_.setReduceDebugScript(reduceDebugSpec_);
}
// last, allow user to override anything
// (although typically used with properties we didn't touch)
jar_ = packageJobJar();
if (jar_ != null) {
jobConf_.setJar(jar_);
}
if ((cacheArchives != null) || (cacheFiles != null)){
getURIs(cacheArchives, cacheFiles);
boolean b = DistributedCache.checkURIs(fileURIs, archiveURIs);
if (!b)
fail(LINK_URI);
}
DistributedCache.createSymlink(jobConf_);
// set the jobconf for the caching parameters
if (cacheArchives != null)
DistributedCache.setCacheArchives(archiveURIs, jobConf_);
if (cacheFiles != null)
DistributedCache.setCacheFiles(fileURIs, jobConf_);
if (verbose_) {
listJobConfProperties();
}
msg("submitting to jobconf: " + getJobTrackerHostPort());
}
/**
* Prints out the jobconf properties on stdout
* when verbose is specified.
*/
protected void listJobConfProperties()
{
msg("==== JobConf properties:");
TreeMap<String,String> sorted = new TreeMap<String,String>();
for (final Map.Entry<String, String> en : jobConf_) {
sorted.put(en.getKey(), en.getValue());
}
for (final Map.Entry<String,String> en: sorted.entrySet()) {
msg(en.getKey() + "=" + en.getValue());
}
msg("====");
}
protected String getJobTrackerHostPort() {
return jobConf_.get(JTConfig.JT_IPC_ADDRESS);
}
protected void jobInfo() {
if (isLocalHadoop()) {
LOG.info("Job running in-process (local Hadoop)");
} else {
String hp = getJobTrackerHostPort();
LOG.info("To kill this job, run:");
LOG.info(getHadoopClientHome() + "/bin/hadoop job -D" + JTConfig.JT_IPC_ADDRESS + "=" + hp + " -kill "
+ jobId_);
//LOG.info("Job file: " + running_.getJobFile());
LOG.info("Tracking URL: " + StreamUtil.qualifyHost(running_.getTrackingURL()));
}
}
// Based on JobClient
public int submitAndMonitorJob() throws IOException {
if (jar_ != null && isLocalHadoop()) {
// getAbs became required when shell and subvm have different working dirs...
File wd = new File(".").getAbsoluteFile();
RunJar.unJar(new File(jar_), wd);
}
// if jobConf_ changes must recreate a JobClient
jc_ = new JobClient(jobConf_);
running_ = null;
try {
running_ = jc_.submitJob(jobConf_);
jobId_ = running_.getID();
jobInfo();
if (background_) {
LOG.info("Job is running in background.");
} else if (!jc_.monitorAndPrintJob(jobConf_, running_)) {
LOG.error("Job not Successful!");
return 1;
}
LOG.info("Output directory: " + output_);
} catch(FileNotFoundException fe) {
LOG.error("Error launching job , bad input path : " + fe.getMessage());
return 2;
} catch(InvalidJobConfException je) {
LOG.error("Error launching job , Invalid job conf : " + je.getMessage());
return 3;
} catch(FileAlreadyExistsException fae) {
LOG.error("Error launching job , Output path already exists : "
+ fae.getMessage());
return 4;
} catch(IOException ioe) {
LOG.error("Error Launching job : " + ioe.getMessage());
return 5;
} catch (InterruptedException ie) {
LOG.error("Error monitoring job : " + ie.getMessage());
return 6;
} finally {
jc_.close();
}
return 0;
}
protected String[] argv_;
protected boolean background_;
protected boolean verbose_;
protected boolean detailedUsage_;
protected boolean printUsage = false;
protected int debug_;
protected Environment env_;
protected String jar_;
protected boolean localHadoop_;
protected Configuration config_;
protected JobConf jobConf_;
protected JobClient jc_;
// command-line arguments
protected ArrayList<String> inputSpecs_ = new ArrayList<String>();
protected TreeSet<String> seenPrimary_ = new TreeSet<String>();
protected boolean hasSimpleInputSpecs_;
protected ArrayList<String> packageFiles_ = new ArrayList<String>();
protected ArrayList<String> shippedCanonFiles_ = new ArrayList<String>();
//protected TreeMap<String, String> userJobConfProps_ = new TreeMap<String, String>();
protected String output_;
protected String mapCmd_;
protected String comCmd_;
protected String redCmd_;
protected String cacheFiles;
protected String cacheArchives;
protected URI[] fileURIs;
protected URI[] archiveURIs;
protected String inReaderSpec_;
protected String inputFormatSpec_;
protected String outputFormatSpec_;
protected String partitionerSpec_;
protected String numReduceTasksSpec_;
protected String additionalConfSpec_;
protected String mapDebugSpec_;
protected String reduceDebugSpec_;
protected String ioSpec_;
protected boolean lazyOutput_;
// Use to communicate config to the external processes (ex env.var.HADOOP_USER)
// encoding "a=b c=d"
protected String addTaskEnvironment_;
protected boolean outputSingleNode_;
protected long minRecWrittenToEnableSkip_;
protected RunningJob running_;
protected JobID jobId_;
protected static final String LINK_URI = "You need to specify the uris as scheme://path#linkname," +
"Please specify a different link name for all of your caching URIs";
}
| true | true | protected void setJobConf() throws IOException {
if (additionalConfSpec_ != null) {
LOG.warn("-additionalconfspec option is deprecated, please use -conf instead.");
config_.addResource(new Path(additionalConfSpec_));
}
// general MapRed job properties
jobConf_ = new JobConf(config_);
// All streaming jobs get the task timeout value
// from the configuration settings.
// The correct FS must be set before this is called!
// (to resolve local vs. dfs drive letter differences)
// (mapreduce.job.working.dir will be lazily initialized ONCE and depends on FS)
for (int i = 0; i < inputSpecs_.size(); i++) {
FileInputFormat.addInputPaths(jobConf_,
(String) inputSpecs_.get(i));
}
String defaultPackage = this.getClass().getPackage().getName();
Class c;
Class fmt = null;
if (inReaderSpec_ == null && inputFormatSpec_ == null) {
fmt = TextInputFormat.class;
} else if (inputFormatSpec_ != null) {
if (inputFormatSpec_.equals(TextInputFormat.class.getName())
|| inputFormatSpec_.equals(TextInputFormat.class.getCanonicalName())
|| inputFormatSpec_.equals(TextInputFormat.class.getSimpleName())) {
fmt = TextInputFormat.class;
} else if (inputFormatSpec_.equals(KeyValueTextInputFormat.class
.getName())
|| inputFormatSpec_.equals(KeyValueTextInputFormat.class
.getCanonicalName())
|| inputFormatSpec_.equals(KeyValueTextInputFormat.class.getSimpleName())) {
if (inReaderSpec_ == null) {
fmt = KeyValueTextInputFormat.class;
}
} else if (inputFormatSpec_.equals(SequenceFileInputFormat.class
.getName())
|| inputFormatSpec_
.equals(org.apache.hadoop.mapred.SequenceFileInputFormat.class
.getCanonicalName())
|| inputFormatSpec_
.equals(org.apache.hadoop.mapred.SequenceFileInputFormat.class.getSimpleName())) {
if (inReaderSpec_ == null) {
fmt = SequenceFileInputFormat.class;
}
} else if (inputFormatSpec_.equals(SequenceFileAsTextInputFormat.class
.getName())
|| inputFormatSpec_.equals(SequenceFileAsTextInputFormat.class
.getCanonicalName())
|| inputFormatSpec_.equals(SequenceFileAsTextInputFormat.class.getSimpleName())) {
fmt = SequenceFileAsTextInputFormat.class;
} else {
c = StreamUtil.goodClassOrNull(jobConf_, inputFormatSpec_, defaultPackage);
if (c != null) {
fmt = c;
} else {
fail("-inputformat : class not found : " + inputFormatSpec_);
}
}
}
if (fmt == null) {
fmt = StreamInputFormat.class;
}
jobConf_.setInputFormat(fmt);
if (ioSpec_ != null) {
jobConf_.set("stream.map.input", ioSpec_);
jobConf_.set("stream.map.output", ioSpec_);
jobConf_.set("stream.reduce.input", ioSpec_);
jobConf_.set("stream.reduce.output", ioSpec_);
}
Class<? extends IdentifierResolver> idResolverClass =
jobConf_.getClass("stream.io.identifier.resolver.class",
IdentifierResolver.class, IdentifierResolver.class);
IdentifierResolver idResolver = ReflectionUtils.newInstance(idResolverClass, jobConf_);
idResolver.resolve(jobConf_.get("stream.map.input", IdentifierResolver.TEXT_ID));
jobConf_.setClass("stream.map.input.writer.class",
idResolver.getInputWriterClass(), InputWriter.class);
idResolver.resolve(jobConf_.get("stream.reduce.input", IdentifierResolver.TEXT_ID));
jobConf_.setClass("stream.reduce.input.writer.class",
idResolver.getInputWriterClass(), InputWriter.class);
jobConf_.set("stream.addenvironment", addTaskEnvironment_);
boolean isMapperACommand = false;
if (mapCmd_ != null) {
c = StreamUtil.goodClassOrNull(jobConf_, mapCmd_, defaultPackage);
if (c != null) {
jobConf_.setMapperClass(c);
} else {
isMapperACommand = true;
jobConf_.setMapperClass(PipeMapper.class);
jobConf_.setMapRunnerClass(PipeMapRunner.class);
jobConf_.set("stream.map.streamprocessor",
URLEncoder.encode(mapCmd_, "UTF-8"));
}
}
if (comCmd_ != null) {
c = StreamUtil.goodClassOrNull(jobConf_, comCmd_, defaultPackage);
if (c != null) {
jobConf_.setCombinerClass(c);
} else {
jobConf_.setCombinerClass(PipeCombiner.class);
jobConf_.set("stream.combine.streamprocessor", URLEncoder.encode(
comCmd_, "UTF-8"));
}
}
if (numReduceTasksSpec_!= null) {
int numReduceTasks = Integer.parseInt(numReduceTasksSpec_);
jobConf_.setNumReduceTasks(numReduceTasks);
}
boolean isReducerACommand = false;
if (redCmd_ != null) {
if (redCmd_.equals(REDUCE_NONE)) {
jobConf_.setNumReduceTasks(0);
}
if (jobConf_.getNumReduceTasks() != 0) {
if (redCmd_.compareToIgnoreCase("aggregate") == 0) {
jobConf_.setReducerClass(ValueAggregatorReducer.class);
jobConf_.setCombinerClass(ValueAggregatorCombiner.class);
} else {
c = StreamUtil.goodClassOrNull(jobConf_, redCmd_, defaultPackage);
if (c != null) {
jobConf_.setReducerClass(c);
} else {
isReducerACommand = true;
jobConf_.setReducerClass(PipeReducer.class);
jobConf_.set("stream.reduce.streamprocessor", URLEncoder.encode(
redCmd_, "UTF-8"));
}
}
}
}
idResolver.resolve(jobConf_.get("stream.map.output",
IdentifierResolver.TEXT_ID));
jobConf_.setClass("stream.map.output.reader.class",
idResolver.getOutputReaderClass(), OutputReader.class);
if (isMapperACommand) {
// if mapper is a command, then map output key/value classes come from the
// idResolver
jobConf_.setMapOutputKeyClass(idResolver.getOutputKeyClass());
jobConf_.setMapOutputValueClass(idResolver.getOutputValueClass());
if (jobConf_.getNumReduceTasks() == 0) {
jobConf_.setOutputKeyClass(idResolver.getOutputKeyClass());
jobConf_.setOutputValueClass(idResolver.getOutputValueClass());
}
}
idResolver.resolve(jobConf_.get("stream.reduce.output",
IdentifierResolver.TEXT_ID));
jobConf_.setClass("stream.reduce.output.reader.class",
idResolver.getOutputReaderClass(), OutputReader.class);
if (isReducerACommand) {
// if reducer is a command, then output key/value classes come from the
// idResolver
jobConf_.setOutputKeyClass(idResolver.getOutputKeyClass());
jobConf_.setOutputValueClass(idResolver.getOutputValueClass());
}
if (inReaderSpec_ != null) {
String[] args = inReaderSpec_.split(",");
String readerClass = args[0];
// this argument can only be a Java class
c = StreamUtil.goodClassOrNull(jobConf_, readerClass, defaultPackage);
if (c != null) {
jobConf_.set("stream.recordreader.class", c.getName());
} else {
fail("-inputreader: class not found: " + readerClass);
}
for (int i = 1; i < args.length; i++) {
String[] nv = args[i].split("=", 2);
String k = "stream.recordreader." + nv[0];
String v = (nv.length > 1) ? nv[1] : "";
jobConf_.set(k, v);
}
}
FileOutputFormat.setOutputPath(jobConf_, new Path(output_));
fmt = null;
if (outputFormatSpec_!= null) {
c = StreamUtil.goodClassOrNull(jobConf_, outputFormatSpec_, defaultPackage);
if (c != null) {
fmt = c;
} else {
fail("-outputformat : class not found : " + outputFormatSpec_);
}
}
if (fmt == null) {
fmt = TextOutputFormat.class;
}
if (lazyOutput_) {
LazyOutputFormat.setOutputFormatClass(jobConf_, fmt);
} else {
jobConf_.setOutputFormat(fmt);
}
if (partitionerSpec_!= null) {
c = StreamUtil.goodClassOrNull(jobConf_, partitionerSpec_, defaultPackage);
if (c != null) {
jobConf_.setPartitionerClass(c);
} else {
fail("-partitioner : class not found : " + partitionerSpec_);
}
}
if(mapDebugSpec_ != null){
jobConf_.setMapDebugScript(mapDebugSpec_);
}
if(reduceDebugSpec_ != null){
jobConf_.setReduceDebugScript(reduceDebugSpec_);
}
// last, allow user to override anything
// (although typically used with properties we didn't touch)
jar_ = packageJobJar();
if (jar_ != null) {
jobConf_.setJar(jar_);
}
if ((cacheArchives != null) || (cacheFiles != null)){
getURIs(cacheArchives, cacheFiles);
boolean b = DistributedCache.checkURIs(fileURIs, archiveURIs);
if (!b)
fail(LINK_URI);
}
DistributedCache.createSymlink(jobConf_);
// set the jobconf for the caching parameters
if (cacheArchives != null)
DistributedCache.setCacheArchives(archiveURIs, jobConf_);
if (cacheFiles != null)
DistributedCache.setCacheFiles(fileURIs, jobConf_);
if (verbose_) {
listJobConfProperties();
}
msg("submitting to jobconf: " + getJobTrackerHostPort());
}
| protected void setJobConf() throws IOException {
if (additionalConfSpec_ != null) {
LOG.warn("-additionalconfspec option is deprecated, please use -conf instead.");
config_.addResource(new Path(additionalConfSpec_));
}
// general MapRed job properties
jobConf_ = new JobConf(config_, StreamJob.class);
// All streaming jobs get the task timeout value
// from the configuration settings.
// The correct FS must be set before this is called!
// (to resolve local vs. dfs drive letter differences)
// (mapreduce.job.working.dir will be lazily initialized ONCE and depends on FS)
for (int i = 0; i < inputSpecs_.size(); i++) {
FileInputFormat.addInputPaths(jobConf_,
(String) inputSpecs_.get(i));
}
String defaultPackage = this.getClass().getPackage().getName();
Class c;
Class fmt = null;
if (inReaderSpec_ == null && inputFormatSpec_ == null) {
fmt = TextInputFormat.class;
} else if (inputFormatSpec_ != null) {
if (inputFormatSpec_.equals(TextInputFormat.class.getName())
|| inputFormatSpec_.equals(TextInputFormat.class.getCanonicalName())
|| inputFormatSpec_.equals(TextInputFormat.class.getSimpleName())) {
fmt = TextInputFormat.class;
} else if (inputFormatSpec_.equals(KeyValueTextInputFormat.class
.getName())
|| inputFormatSpec_.equals(KeyValueTextInputFormat.class
.getCanonicalName())
|| inputFormatSpec_.equals(KeyValueTextInputFormat.class.getSimpleName())) {
if (inReaderSpec_ == null) {
fmt = KeyValueTextInputFormat.class;
}
} else if (inputFormatSpec_.equals(SequenceFileInputFormat.class
.getName())
|| inputFormatSpec_
.equals(org.apache.hadoop.mapred.SequenceFileInputFormat.class
.getCanonicalName())
|| inputFormatSpec_
.equals(org.apache.hadoop.mapred.SequenceFileInputFormat.class.getSimpleName())) {
if (inReaderSpec_ == null) {
fmt = SequenceFileInputFormat.class;
}
} else if (inputFormatSpec_.equals(SequenceFileAsTextInputFormat.class
.getName())
|| inputFormatSpec_.equals(SequenceFileAsTextInputFormat.class
.getCanonicalName())
|| inputFormatSpec_.equals(SequenceFileAsTextInputFormat.class.getSimpleName())) {
fmt = SequenceFileAsTextInputFormat.class;
} else {
c = StreamUtil.goodClassOrNull(jobConf_, inputFormatSpec_, defaultPackage);
if (c != null) {
fmt = c;
} else {
fail("-inputformat : class not found : " + inputFormatSpec_);
}
}
}
if (fmt == null) {
fmt = StreamInputFormat.class;
}
jobConf_.setInputFormat(fmt);
if (ioSpec_ != null) {
jobConf_.set("stream.map.input", ioSpec_);
jobConf_.set("stream.map.output", ioSpec_);
jobConf_.set("stream.reduce.input", ioSpec_);
jobConf_.set("stream.reduce.output", ioSpec_);
}
Class<? extends IdentifierResolver> idResolverClass =
jobConf_.getClass("stream.io.identifier.resolver.class",
IdentifierResolver.class, IdentifierResolver.class);
IdentifierResolver idResolver = ReflectionUtils.newInstance(idResolverClass, jobConf_);
idResolver.resolve(jobConf_.get("stream.map.input", IdentifierResolver.TEXT_ID));
jobConf_.setClass("stream.map.input.writer.class",
idResolver.getInputWriterClass(), InputWriter.class);
idResolver.resolve(jobConf_.get("stream.reduce.input", IdentifierResolver.TEXT_ID));
jobConf_.setClass("stream.reduce.input.writer.class",
idResolver.getInputWriterClass(), InputWriter.class);
jobConf_.set("stream.addenvironment", addTaskEnvironment_);
boolean isMapperACommand = false;
if (mapCmd_ != null) {
c = StreamUtil.goodClassOrNull(jobConf_, mapCmd_, defaultPackage);
if (c != null) {
jobConf_.setMapperClass(c);
} else {
isMapperACommand = true;
jobConf_.setMapperClass(PipeMapper.class);
jobConf_.setMapRunnerClass(PipeMapRunner.class);
jobConf_.set("stream.map.streamprocessor",
URLEncoder.encode(mapCmd_, "UTF-8"));
}
}
if (comCmd_ != null) {
c = StreamUtil.goodClassOrNull(jobConf_, comCmd_, defaultPackage);
if (c != null) {
jobConf_.setCombinerClass(c);
} else {
jobConf_.setCombinerClass(PipeCombiner.class);
jobConf_.set("stream.combine.streamprocessor", URLEncoder.encode(
comCmd_, "UTF-8"));
}
}
if (numReduceTasksSpec_!= null) {
int numReduceTasks = Integer.parseInt(numReduceTasksSpec_);
jobConf_.setNumReduceTasks(numReduceTasks);
}
boolean isReducerACommand = false;
if (redCmd_ != null) {
if (redCmd_.equals(REDUCE_NONE)) {
jobConf_.setNumReduceTasks(0);
}
if (jobConf_.getNumReduceTasks() != 0) {
if (redCmd_.compareToIgnoreCase("aggregate") == 0) {
jobConf_.setReducerClass(ValueAggregatorReducer.class);
jobConf_.setCombinerClass(ValueAggregatorCombiner.class);
} else {
c = StreamUtil.goodClassOrNull(jobConf_, redCmd_, defaultPackage);
if (c != null) {
jobConf_.setReducerClass(c);
} else {
isReducerACommand = true;
jobConf_.setReducerClass(PipeReducer.class);
jobConf_.set("stream.reduce.streamprocessor", URLEncoder.encode(
redCmd_, "UTF-8"));
}
}
}
}
idResolver.resolve(jobConf_.get("stream.map.output",
IdentifierResolver.TEXT_ID));
jobConf_.setClass("stream.map.output.reader.class",
idResolver.getOutputReaderClass(), OutputReader.class);
if (isMapperACommand) {
// if mapper is a command, then map output key/value classes come from the
// idResolver
jobConf_.setMapOutputKeyClass(idResolver.getOutputKeyClass());
jobConf_.setMapOutputValueClass(idResolver.getOutputValueClass());
if (jobConf_.getNumReduceTasks() == 0) {
jobConf_.setOutputKeyClass(idResolver.getOutputKeyClass());
jobConf_.setOutputValueClass(idResolver.getOutputValueClass());
}
}
idResolver.resolve(jobConf_.get("stream.reduce.output",
IdentifierResolver.TEXT_ID));
jobConf_.setClass("stream.reduce.output.reader.class",
idResolver.getOutputReaderClass(), OutputReader.class);
if (isReducerACommand) {
// if reducer is a command, then output key/value classes come from the
// idResolver
jobConf_.setOutputKeyClass(idResolver.getOutputKeyClass());
jobConf_.setOutputValueClass(idResolver.getOutputValueClass());
}
if (inReaderSpec_ != null) {
String[] args = inReaderSpec_.split(",");
String readerClass = args[0];
// this argument can only be a Java class
c = StreamUtil.goodClassOrNull(jobConf_, readerClass, defaultPackage);
if (c != null) {
jobConf_.set("stream.recordreader.class", c.getName());
} else {
fail("-inputreader: class not found: " + readerClass);
}
for (int i = 1; i < args.length; i++) {
String[] nv = args[i].split("=", 2);
String k = "stream.recordreader." + nv[0];
String v = (nv.length > 1) ? nv[1] : "";
jobConf_.set(k, v);
}
}
FileOutputFormat.setOutputPath(jobConf_, new Path(output_));
fmt = null;
if (outputFormatSpec_!= null) {
c = StreamUtil.goodClassOrNull(jobConf_, outputFormatSpec_, defaultPackage);
if (c != null) {
fmt = c;
} else {
fail("-outputformat : class not found : " + outputFormatSpec_);
}
}
if (fmt == null) {
fmt = TextOutputFormat.class;
}
if (lazyOutput_) {
LazyOutputFormat.setOutputFormatClass(jobConf_, fmt);
} else {
jobConf_.setOutputFormat(fmt);
}
if (partitionerSpec_!= null) {
c = StreamUtil.goodClassOrNull(jobConf_, partitionerSpec_, defaultPackage);
if (c != null) {
jobConf_.setPartitionerClass(c);
} else {
fail("-partitioner : class not found : " + partitionerSpec_);
}
}
if(mapDebugSpec_ != null){
jobConf_.setMapDebugScript(mapDebugSpec_);
}
if(reduceDebugSpec_ != null){
jobConf_.setReduceDebugScript(reduceDebugSpec_);
}
// last, allow user to override anything
// (although typically used with properties we didn't touch)
jar_ = packageJobJar();
if (jar_ != null) {
jobConf_.setJar(jar_);
}
if ((cacheArchives != null) || (cacheFiles != null)){
getURIs(cacheArchives, cacheFiles);
boolean b = DistributedCache.checkURIs(fileURIs, archiveURIs);
if (!b)
fail(LINK_URI);
}
DistributedCache.createSymlink(jobConf_);
// set the jobconf for the caching parameters
if (cacheArchives != null)
DistributedCache.setCacheArchives(archiveURIs, jobConf_);
if (cacheFiles != null)
DistributedCache.setCacheFiles(fileURIs, jobConf_);
if (verbose_) {
listJobConfProperties();
}
msg("submitting to jobconf: " + getJobTrackerHostPort());
}
|
diff --git a/src/terminator/model/TerminalModel.java b/src/terminator/model/TerminalModel.java
index bbad828..966c2a4 100644
--- a/src/terminator/model/TerminalModel.java
+++ b/src/terminator/model/TerminalModel.java
@@ -1,463 +1,463 @@
package terminator.model;
import java.awt.*;
import java.util.*;
import javax.swing.*;
import e.util.*;
import terminator.terminal.*;
import terminator.view.*;
public class TerminalModel {
private TerminalView view;
private int width;
private int height;
private ArrayList<TextLine> textLines = new ArrayList<TextLine>();
private short currentStyle = StyledText.getDefaultStyle();
private int firstScrollLineIndex;
private int lastScrollLineIndex;
private Location cursorPosition;
private int lastValidStartIndex = 0;
private boolean insertMode = false;
private int maxLineWidth = width;
// Used for reducing the number of lines changed events sent up to the view.
private int firstLineChanged;
public TerminalModel(TerminalView view, int width, int height) {
this.view = view;
setSize(width, height);
cursorPosition = view.getCursorPosition();
}
public void updateMaxLineWidth(int aLineWidth) {
maxLineWidth = Math.max(getMaxLineWidth(), aLineWidth);
}
public int getMaxLineWidth() {
return Math.max(maxLineWidth, width);
}
public void checkInvariant() {
int highestStartLineIndex = -1;
for (int lineNumber = 0; lineNumber <= lastValidStartIndex; ++ lineNumber) {
int thisStartLineIndex = textLines.get(lineNumber).getLineStartIndex();
if (thisStartLineIndex <= highestStartLineIndex) {
throw new RuntimeException("the lineStartIndex must increase monotonically as the line number increases");
}
highestStartLineIndex = thisStartLineIndex;
}
}
public void sizeChanged(Dimension sizeInChars) {
setSize(sizeInChars.width, sizeInChars.height);
cursorPosition = getLocationWithinBounds(cursorPosition);
}
private Location getLocationWithinBounds(Location location) {
if (location == null) {
return location;
}
int lineIndex = Math.min(location.getLineIndex(), textLines.size() - 1);
int charOffset = Math.min(location.getCharOffset(), width - 1);
return new Location(lineIndex, charOffset);
}
private int getNextTabPosition(int charOffset) {
// No special tab to our right; return the default 8-separated tab stop.
return (charOffset + 8) & ~7;
}
/** Returns the length of the indexed line including the terminating NL. */
public int getLineLength(int lineIndex) {
return getTextLine(lineIndex).length() + 1;
}
/** Returns the start character index of the indexed line. */
public int getStartIndex(int lineIndex) {
ensureValidStartIndex(lineIndex);
return getTextLine(lineIndex).getLineStartIndex();
}
/**
* Returns a Location describing the line and offset at which the given char index exists.
* If the index is actually larger than the screen area, returns a 'fake' location to the right
* of the end of the last line.
*/
public Location getLocationFromCharIndex(int charIndex) {
int lowLine = 0;
int highLine = textLines.size();
while (highLine - lowLine > 1) {
int midLine = (lowLine + highLine) / 2;
int mid = getStartIndex(midLine);
if (mid <= charIndex) {
lowLine = midLine;
} else {
highLine = midLine;
}
}
return new Location(lowLine, charIndex - getStartIndex(lowLine));
}
/** Returns the char index equivalent to the given Location. */
public int getCharIndexFromLocation(Location location) {
return getStartIndex(location.getLineIndex()) + location.getCharOffset();
}
/** Returns the count of all characters in the buffer, including NLs. */
public int length() {
int lastIndex = textLines.size() - 1;
return getStartIndex(lastIndex) + getLineLength(lastIndex);
}
private void lineIsDirty(int dirtyLineIndex) {
lastValidStartIndex = Math.min(lastValidStartIndex, dirtyLineIndex + 1);
}
private void ensureValidStartIndex(int lineIndex) {
if (lineIndex > lastValidStartIndex) {
for (int i = lastValidStartIndex; i < lineIndex; i++) {
TextLine line = getTextLine(i);
getTextLine(i + 1).setLineStartIndex(line.getLineStartIndex() + line.lengthIncludingNewline());
}
lastValidStartIndex = lineIndex;
}
}
public int getLineCount() {
return textLines.size();
}
public void linesChangedFrom(int firstLineChanged) {
this.firstLineChanged = Math.min(this.firstLineChanged, firstLineChanged);
}
public Dimension getCurrentSizeInChars() {
return new Dimension(getMaxLineWidth(), getLineCount());
}
public Location getCursorPosition() {
return cursorPosition;
}
public void processActions(TerminalAction[] actions) {
firstLineChanged = Integer.MAX_VALUE;
boolean wereAtBottom = view.isAtBottom();
boolean needsScroll = false;
Dimension initialSize = getCurrentSizeInChars();
for (TerminalAction action : actions) {
action.perform(this);
}
if (firstLineChanged != Integer.MAX_VALUE) {
needsScroll = true;
view.linesChangedFrom(firstLineChanged);
}
Dimension finalSize = getCurrentSizeInChars();
if (initialSize.equals(finalSize) == false) {
view.sizeChanged(initialSize, finalSize);
}
if (needsScroll) {
view.scrollOnTtyOutput(wereAtBottom);
}
view.setCursorPosition(cursorPosition);
}
public void setStyle(short style) {
this.currentStyle = style;
}
public short getStyle() {
return currentStyle;
}
public void moveToLine(int index) {
if (index > getFirstDisplayLine() + lastScrollLineIndex) {
insertLine(index);
} else {
cursorPosition = new Location(index, cursorPosition.getCharOffset());
}
}
public void insertLine(int index) {
insertLine(index, new TextLine());
}
public void insertLine(int index, TextLine lineToInsert) {
// Use a private copy of the first display line throughout this method to avoid mutation
// caused by textLines.add()/textLines.remove().
final int firstDisplayLine = getFirstDisplayLine();
lineIsDirty(firstDisplayLine);
if (index > firstDisplayLine + lastScrollLineIndex) {
for (int i = firstDisplayLine + lastScrollLineIndex + 1; i <= index; i++) {
textLines.add(i, lineToInsert);
}
- if (firstScrollLineIndex > 0) {
+ if (true || firstScrollLineIndex > 0) {
// If the program has defined scroll bounds, newline-adding actually chucks away
// the first scroll line, rather than just scrolling everything upwards like we normally
// do. This makes vim work better. Also, if we're using the alternate buffer, we
// don't add anything going off the top into the history.
int removeIndex = firstDisplayLine + firstScrollLineIndex;
textLines.remove(removeIndex);
linesChangedFrom(removeIndex);
view.repaint();
} else {
cursorPosition = new Location(index, cursorPosition.getCharOffset());
}
} else {
textLines.remove(firstDisplayLine + lastScrollLineIndex);
textLines.add(index, lineToInsert);
linesChangedFrom(index);
cursorPosition = new Location(index, cursorPosition.getCharOffset());
}
checkInvariant();
}
public int getFirstDisplayLine() {
return textLines.size() - height;
}
public int getWidth() {
return width;
}
public TextLine getTextLine(int index) {
if (index >= textLines.size()) {
Log.warn("TextLine requested for index " + index + ", size of buffer is " + textLines.size() + ".", new Exception("stack trace"));
return new TextLine();
}
return textLines.get(index);
}
public void setSize(int width, int height) {
this.width = width;
lineIsDirty(0);
if (this.height > height && textLines.size() >= this.height) {
for (int i = 0; i < (this.height - height); i++) {
int lineToRemove = textLines.size() - 1;
if (getTextLine(lineToRemove).length() == 0 && cursorPosition.getLineIndex() != lineToRemove) {
textLines.remove(lineToRemove);
}
}
} else if (this.height < height) {
for (int i = 0; i < (height - this.height); i++) {
if (getFirstDisplayLine() <= 0) {
textLines.add(new TextLine());
}
}
}
this.height = height;
firstScrollLineIndex = 0;
lastScrollLineIndex = height - 1;
while (getFirstDisplayLine() < 0) {
textLines.add(new TextLine());
}
checkInvariant();
}
public void setInsertMode(boolean insertMode) {
this.insertMode = insertMode;
}
/**
* Process the characters in the given line. The string is composed of
* normal printable characters, escape sequences having been extracted
* elsewhere.
*/
public void processLine(String untranslatedLine) {
String line = view.getTerminalControl().translate(untranslatedLine);
TextLine textLine = getTextLine(cursorPosition.getLineIndex());
if (insertMode) {
//Log.warn("Inserting text \"" + line + "\" at " + cursorPosition + ".");
textLine.insertTextAt(cursorPosition.getCharOffset(), line, currentStyle);
} else {
//Log.warn("Writing text \"" + line + "\" at " + cursorPosition + ".");
textLine.writeTextAt(cursorPosition.getCharOffset(), line, currentStyle);
}
textAdded(line.length());
}
private void textAdded(int length) {
TextLine textLine = getTextLine(cursorPosition.getLineIndex());
updateMaxLineWidth(textLine.length());
lineIsDirty(cursorPosition.getLineIndex() + 1); // cursorPosition's line still has a valid *start* index.
linesChangedFrom(cursorPosition.getLineIndex());
moveCursorHorizontally(length);
}
public void processSpecialCharacter(char ch) {
switch (ch) {
case Ascii.CR:
cursorPosition = new Location(cursorPosition.getLineIndex(), 0);
return;
case Ascii.LF:
moveToLine(cursorPosition.getLineIndex() + 1);
return;
case Ascii.VT:
moveCursorVertically(1);
return;
case Ascii.HT:
insertTab();
return;
case Ascii.BS:
moveCursorHorizontally(-1);
return;
default:
Log.warn("Unsupported special character: " + ((int) ch));
}
}
private void insertTab() {
int nextTabLocation = getNextTabPosition(cursorPosition.getCharOffset());
TextLine textLine = getTextLine(cursorPosition.getLineIndex());
int startOffset = cursorPosition.getCharOffset();
int tabLength = nextTabLocation - startOffset;
// We want to insert our special tabbing characters (see getTabString) when inserting a tab or outputting one at the end of a line, so that text copied from the output of (say) cat(1) will be pasted with tabs preserved.
boolean endOfLine = (startOffset == textLine.length());
if (insertMode || endOfLine) {
textLine.insertTabAt(startOffset, tabLength, currentStyle);
} else {
// Emacs, source of all bloat, uses \t\b\t sequences around tab stops (in lines with no \t characters) if you hold down right arrow. The call to textAdded below moves the cursor, which is all we're supposed to do.
}
textAdded(tabLength);
}
/** Sets whether the cursor should be visible. */
public void setCursorVisible(boolean isDisplayed) {
view.setCursorVisible(isDisplayed);
}
/** Inserts lines at the current cursor position. */
public void insertLines(int count) {
for (int i = 0; i < count; i++) {
insertLine(cursorPosition.getLineIndex());
}
}
public void deleteCharacters(int count) {
TextLine line = getTextLine(cursorPosition.getLineIndex());
int start = cursorPosition.getCharOffset();
int end = start + count;
line.killText(start, end);
lineIsDirty(cursorPosition.getLineIndex() + 1); // cursorPosition.y's line still has a valid *start* index.
linesChangedFrom(cursorPosition.getLineIndex());
}
public void killHorizontally(boolean fromStart, boolean toEnd) {
TextLine line = getTextLine(cursorPosition.getLineIndex());
int oldLineLength = line.length();
int start = fromStart ? 0 : cursorPosition.getCharOffset();
int end = toEnd ? oldLineLength : cursorPosition.getCharOffset();
line.killText(start, end);
lineIsDirty(cursorPosition.getLineIndex() + 1); // cursorPosition.y's line still has a valid *start* index.
linesChangedFrom(cursorPosition.getLineIndex());
}
/** Erases from either the top or the cursor, to either the bottom or the cursor. */
public void eraseInPage(boolean fromTop, boolean toBottom) {
// Should produce "hi\nwo":
// echo $'\n\n\nworld\x1b[A\rhi\x1b[B\x1b[J'
// Should produce " ld":
// echo $'\n\n\nworld\x1b[A\rhi\x1b[B\x1b[1J'
// Should clear the screen:
// echo $'\n\n\nworld\x1b[A\rhi\x1b[B\x1b[2J'
int start = fromTop ? getFirstDisplayLine() : cursorPosition.getLineIndex();
int startClearing = fromTop ? start : start + 1;
int endClearing = toBottom ? getLineCount() : cursorPosition.getLineIndex();
for (int i = startClearing; i < endClearing; i++) {
getTextLine(i).clear();
}
TextLine line = getTextLine(cursorPosition.getLineIndex());
int oldLineLength = line.length();
if (fromTop) {
// The current position is always erased, hence the + 1.
// Is overwriting with spaces in the currentStyle correct?
line.writeTextAt(0, StringUtilities.nCopies(cursorPosition.getCharOffset() + 1, ' '), currentStyle);
}
if (toBottom) {
line.killText(cursorPosition.getCharOffset(), oldLineLength);
}
lineIsDirty(start + 1);
linesChangedFrom(start);
}
/**
* Sets the position of the cursor to the given x and y coordinates, counted from 1,1 at the top-left corner.
* If either x or y is -1, that coordinate is left unchanged.
*/
public void setCursorPosition(int x, int y) {
// Although the cursor positions are supposed to be measured
// from (1,1), there's nothing to stop a badly-behaved program
// from sending (0,0). ASUS routers do this (they're rubbish).
int charOffset = cursorPosition.getCharOffset();
if (x != -1) {
// Translate from 1-based coordinates to 0-based.
charOffset = Math.max(0, x - 1);
charOffset = Math.min(charOffset, width - 1);
}
int lineIndex = cursorPosition.getLineIndex();
if (y != -1) {
// Translate from 1-based coordinates to 0-based.
int lineOffsetFromStartOfDisplay = Math.max(0, y - 1);
lineOffsetFromStartOfDisplay = Math.min(lineOffsetFromStartOfDisplay, height - 1);
// Although the escape sequence was in terms of a line on the display, we need to take the lines above the display into account.
lineIndex = getFirstDisplayLine() + lineOffsetFromStartOfDisplay;
}
cursorPosition = new Location(lineIndex, charOffset);
}
/** Moves the cursor horizontally by the number of characters in xDiff, negative for left, positive for right. */
public void moveCursorHorizontally(int xDiff) {
int charOffset = cursorPosition.getCharOffset() + xDiff;
int lineIndex = cursorPosition.getLineIndex();
// Test cases:
// /bin/echo -e 'hello\n\bhello'
// /bin/echo -e 'hello\n\033[1Dhello'
if (charOffset < 0) {
charOffset = 0;
}
// Constraining charOffset here stops line editing working properly on Titan serial consoles.
//charOffset = Math.min(charOffset, width - 1);
cursorPosition = new Location(lineIndex, charOffset);
}
/** Moves the cursor vertically by the number of characters in yDiff, negative for up, positive for down. */
public void moveCursorVertically(int yDiff) {
int y = cursorPosition.getLineIndex() + yDiff;
y = Math.max(getFirstDisplayLine(), y);
y = Math.min(y, textLines.size() - 1);
cursorPosition = new Location(y, cursorPosition.getCharOffset());
}
/** Sets the first and last lines to scroll. If both are -1, make the entire screen scroll. */
public void setScrollingRegion(int firstLine, int lastLine) {
firstScrollLineIndex = ((firstLine == -1) ? 1 : firstLine) - 1;
lastScrollLineIndex = ((lastLine == -1) ? height : lastLine) - 1;
}
/** Scrolls the display up by one line. */
public void scrollDisplayUp() {
int addIndex = getFirstDisplayLine() + firstScrollLineIndex;
int removeIndex = getFirstDisplayLine() + lastScrollLineIndex + 1;
textLines.add(addIndex, new TextLine());
textLines.remove(removeIndex);
lineIsDirty(addIndex);
linesChangedFrom(addIndex);
view.repaint();
checkInvariant();
}
/** Delete one line, moving everything below up and inserting a blank line at the bottom. */
public void deleteLine() {
int removeIndex = cursorPosition.getLineIndex();
int addIndex = getFirstDisplayLine() + lastScrollLineIndex + 1;
textLines.add(addIndex, new TextLine());
textLines.remove(removeIndex);
lineIsDirty(removeIndex);
linesChangedFrom(removeIndex);
view.repaint();
checkInvariant();
}
}
| true | true | public void insertLine(int index, TextLine lineToInsert) {
// Use a private copy of the first display line throughout this method to avoid mutation
// caused by textLines.add()/textLines.remove().
final int firstDisplayLine = getFirstDisplayLine();
lineIsDirty(firstDisplayLine);
if (index > firstDisplayLine + lastScrollLineIndex) {
for (int i = firstDisplayLine + lastScrollLineIndex + 1; i <= index; i++) {
textLines.add(i, lineToInsert);
}
if (firstScrollLineIndex > 0) {
// If the program has defined scroll bounds, newline-adding actually chucks away
// the first scroll line, rather than just scrolling everything upwards like we normally
// do. This makes vim work better. Also, if we're using the alternate buffer, we
// don't add anything going off the top into the history.
int removeIndex = firstDisplayLine + firstScrollLineIndex;
textLines.remove(removeIndex);
linesChangedFrom(removeIndex);
view.repaint();
} else {
cursorPosition = new Location(index, cursorPosition.getCharOffset());
}
} else {
textLines.remove(firstDisplayLine + lastScrollLineIndex);
textLines.add(index, lineToInsert);
linesChangedFrom(index);
cursorPosition = new Location(index, cursorPosition.getCharOffset());
}
checkInvariant();
}
| public void insertLine(int index, TextLine lineToInsert) {
// Use a private copy of the first display line throughout this method to avoid mutation
// caused by textLines.add()/textLines.remove().
final int firstDisplayLine = getFirstDisplayLine();
lineIsDirty(firstDisplayLine);
if (index > firstDisplayLine + lastScrollLineIndex) {
for (int i = firstDisplayLine + lastScrollLineIndex + 1; i <= index; i++) {
textLines.add(i, lineToInsert);
}
if (true || firstScrollLineIndex > 0) {
// If the program has defined scroll bounds, newline-adding actually chucks away
// the first scroll line, rather than just scrolling everything upwards like we normally
// do. This makes vim work better. Also, if we're using the alternate buffer, we
// don't add anything going off the top into the history.
int removeIndex = firstDisplayLine + firstScrollLineIndex;
textLines.remove(removeIndex);
linesChangedFrom(removeIndex);
view.repaint();
} else {
cursorPosition = new Location(index, cursorPosition.getCharOffset());
}
} else {
textLines.remove(firstDisplayLine + lastScrollLineIndex);
textLines.add(index, lineToInsert);
linesChangedFrom(index);
cursorPosition = new Location(index, cursorPosition.getCharOffset());
}
checkInvariant();
}
|
diff --git a/maven-python-mojos/maven-bdd-plugin/src/main/java/com/github/mojo/bdd/AbstractBddMojo.java b/maven-python-mojos/maven-bdd-plugin/src/main/java/com/github/mojo/bdd/AbstractBddMojo.java
index 900eae7..031cce4 100644
--- a/maven-python-mojos/maven-bdd-plugin/src/main/java/com/github/mojo/bdd/AbstractBddMojo.java
+++ b/maven-python-mojos/maven-bdd-plugin/src/main/java/com/github/mojo/bdd/AbstractBddMojo.java
@@ -1,269 +1,269 @@
package com.github.mojo.bdd;
import static com.google.common.collect.Lists.*;
import static com.google.common.collect.Sets.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.io.IOUtils;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugin.logging.Log;
import org.javatuples.Pair;
/**
* Common class for BDD test runs
*
* @author Jacek Furmankiewicz
*/
@EqualsAndHashCode(of = "toolName", callSuper = false)
public abstract class AbstractBddMojo extends AbstractMojo {
public static final String REPORTS_FOLDER = "bdd-reports";
public static final String PYTHON = "python";
/**
* @parameter default-value="${project.basedir}"
*/
@Getter
@Setter
private File projectDirectory;
/**
* @parameter default-value="${project.build.directory}"
*/
@Getter
@Setter
private File buildDirectory;
/**
* The name of the Python interpreter
* @parameter default-value="python"
*/
@Getter
@Setter
private String python;
/**
* The working directory from which the tests will be launched, can be a relative path
* @parameter default-value="src/test/python"
*/
@Getter
@Setter
private String workingDirectory;
@Getter
@Setter
private String toolName;
@Getter
@Setter
private String testReportName;
@Getter
@Setter
private String[] testCommands;
/**
* Extra command options appended to default test command
*/
@Getter
@Setter
private Set<String> requestOptions = newLinkedHashSet();
protected AbstractBddMojo(String toolName, String testReportName,String... testCommands) {
this.toolName = toolName;
this.testReportName = testReportName;
this.testCommands = testCommands;
}
/**
* Can be overriden in descendants to do Mojo-specific stuff
*/
protected void preExecute() throws MojoExecutionException, MojoFailureException {
requestOptions.clear();
}
/**
* Can be overriden in descendants for any post-processing Only called upon
* success
*
* @param output
*/
protected void postExecute(StringBuilder output) throws MojoExecutionException, MojoFailureException {
}
/*
* (non-Javadoc)
*
* @see org.apache.maven.plugin.AbstractMojo#execute()
*/
public void execute() throws MojoExecutionException, MojoFailureException {
createReportsFolder();
try {
preExecute();
File directory = new File(projectDirectory,this.workingDirectory);
if (directory.exists()) {
getLog().info("");
getLog().info("Running " + toolName + " from " + workingDirectory + " with " + python);
getLog().info("");
Pair<Integer, StringBuilder> output = getOutput(directory,true, getCommands());
StringBuilder bld = output.getValue1();
writeReport(testReportName, bld.toString(), getLog());
if (bld.length() == 0) {
getLog().warn(toolName + " did not return any output. No unit test(s) found?");
throw new MojoFailureException(toolName + " did not return any output. No unit test(s) found?");
}
if (output.getValue0() != 0) {
- throw new MojoFailureException(toolName + " unit test(s) failed");
+ throw new MojoFailureException(toolName + " unit test(s) failed. Return code : " + output.getValue0());
}
postExecute(bld);
} else {
getLog().warn("No " + toolName + " unit test(s) found. Please create some in " + directory.getPath());
throw new MojoFailureException("No " + toolName + " unit test(s) found. Please create some in " + directory.getPath());
}
} catch (MojoFailureException ex) {
throw ex;
} catch (MojoExecutionException ex) {
throw ex;
} catch (Exception ex) {
getLog().error(ex);
throw new MojoExecutionException("Failed to run " + toolName + " unit test(s)", ex);
} finally {
// TODO: cleanup
}
}
private void createReportsFolder() throws MojoExecutionException {
File reports = new File(buildDirectory, REPORTS_FOLDER);
if (reports.exists()) {
if (!reports.isDirectory()) {
throw new MojoExecutionException("Unable to create reports folder in " + reports.getAbsolutePath()
+ ", a file already exists with that name");
}
} else {
if (!reports.mkdirs()) {
throw new MojoExecutionException("Unable to create reports folder in " + reports.getAbsolutePath());
}
}
}
private void writeReport(String reportName, String body, Log log) throws MojoExecutionException {
File reportsFolder = new File(buildDirectory, REPORTS_FOLDER);
File report = new File(reportsFolder, reportName);
if (report.exists()) {
if (!report.delete()) {
throw new MojoExecutionException("Failed to delete " + report.getAbsolutePath());
}
} else {
try {
log.info("");
log.info("Writing report to " + report.getAbsolutePath());
IOUtils.write(body, new FileOutputStream(report));
} catch (Exception e) {
throw new MojoExecutionException("Failed to write report " + report.getAbsolutePath(), e);
}
}
}
/**
* Figures out the actual commands to run via shell
*/
private String[] getCommands() throws IOException, InterruptedException, MojoFailureException {
List<String> commands = newLinkedList();
//handle running in different Python interpeter via 'python2.6 `which nosetests`' type of trick - Linux only
if (PYTHON.equals(this.python)) {
//default Python - nothing special to do
commands.addAll(Arrays.asList(testCommands));
} else {
commands.add(python);
//'which' on Linux will find the original path of the main shell script file (e.g. nosetests or lettuce)
// Sorry Windows users...that's what you get for being on Windows
Pair<Integer,StringBuilder> output = getOutput(null, false,"which",testCommands[0]);
if (output.getValue0() != 0) {
throw new MojoFailureException("Unable to find system location of " + testCommands[0] + " using `which`.\n" +
"Are you on Windows? Multiple Python interpreters are supported on Linux only.");
} else {
String shellPath = output.getValue1().toString();
commands.add(shellPath); //the full path to the shell script for the BDD tool
commands.addAll(Arrays.asList(Arrays.copyOfRange(testCommands, 1, testCommands.length)));
}
}
//merge default + request specific cmmands
commands.addAll(requestOptions);
return commands.toArray(new String[commands.size()]);
}
//runs a shell command and captures the output
private Pair<Integer,StringBuilder> getOutput(File directory, boolean logOutput, String... commands) throws IOException, InterruptedException {
StringBuilder bld = new StringBuilder();
ProcessBuilder t = new ProcessBuilder(commands);
//log
StringBuilder exec = new StringBuilder();
for(String command : commands) {
if (exec.length() > 0) {
exec.append(" ");
}
exec.append(command);
}
getLog().info("Executing '" + exec.toString() + "'");
if (directory != null) {
t.directory(directory);
}
t.redirectErrorStream(true);
Process pr = t.start();
BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = "";
while ((line = buf.readLine()) != null) {
if (bld.length() > 0) {
bld.append("\n");
}
bld.append(line);
if (logOutput) {
getLog().info(line);
}
}
buf.close();
int exitCode = pr.waitFor();
return new Pair<Integer,StringBuilder>(exitCode,bld);
}
}
| true | true | public void execute() throws MojoExecutionException, MojoFailureException {
createReportsFolder();
try {
preExecute();
File directory = new File(projectDirectory,this.workingDirectory);
if (directory.exists()) {
getLog().info("");
getLog().info("Running " + toolName + " from " + workingDirectory + " with " + python);
getLog().info("");
Pair<Integer, StringBuilder> output = getOutput(directory,true, getCommands());
StringBuilder bld = output.getValue1();
writeReport(testReportName, bld.toString(), getLog());
if (bld.length() == 0) {
getLog().warn(toolName + " did not return any output. No unit test(s) found?");
throw new MojoFailureException(toolName + " did not return any output. No unit test(s) found?");
}
if (output.getValue0() != 0) {
throw new MojoFailureException(toolName + " unit test(s) failed");
}
postExecute(bld);
} else {
getLog().warn("No " + toolName + " unit test(s) found. Please create some in " + directory.getPath());
throw new MojoFailureException("No " + toolName + " unit test(s) found. Please create some in " + directory.getPath());
}
} catch (MojoFailureException ex) {
throw ex;
} catch (MojoExecutionException ex) {
throw ex;
} catch (Exception ex) {
getLog().error(ex);
throw new MojoExecutionException("Failed to run " + toolName + " unit test(s)", ex);
} finally {
// TODO: cleanup
}
}
| public void execute() throws MojoExecutionException, MojoFailureException {
createReportsFolder();
try {
preExecute();
File directory = new File(projectDirectory,this.workingDirectory);
if (directory.exists()) {
getLog().info("");
getLog().info("Running " + toolName + " from " + workingDirectory + " with " + python);
getLog().info("");
Pair<Integer, StringBuilder> output = getOutput(directory,true, getCommands());
StringBuilder bld = output.getValue1();
writeReport(testReportName, bld.toString(), getLog());
if (bld.length() == 0) {
getLog().warn(toolName + " did not return any output. No unit test(s) found?");
throw new MojoFailureException(toolName + " did not return any output. No unit test(s) found?");
}
if (output.getValue0() != 0) {
throw new MojoFailureException(toolName + " unit test(s) failed. Return code : " + output.getValue0());
}
postExecute(bld);
} else {
getLog().warn("No " + toolName + " unit test(s) found. Please create some in " + directory.getPath());
throw new MojoFailureException("No " + toolName + " unit test(s) found. Please create some in " + directory.getPath());
}
} catch (MojoFailureException ex) {
throw ex;
} catch (MojoExecutionException ex) {
throw ex;
} catch (Exception ex) {
getLog().error(ex);
throw new MojoExecutionException("Failed to run " + toolName + " unit test(s)", ex);
} finally {
// TODO: cleanup
}
}
|
diff --git a/src/CustomOreGen/mod_CustomOreGen.java b/src/CustomOreGen/mod_CustomOreGen.java
index 230a67b..432942d 100644
--- a/src/CustomOreGen/mod_CustomOreGen.java
+++ b/src/CustomOreGen/mod_CustomOreGen.java
@@ -1,248 +1,248 @@
package CustomOreGen;
import java.util.Iterator;
import java.util.Random;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.NetClientHandler;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.network.NetServerHandler;
import net.minecraft.network.packet.Packet250CustomPayload;
import net.minecraft.network.packet.Packet3Chat;
import net.minecraft.server.MinecraftServer;
import net.minecraft.src.BaseMod;
import net.minecraft.src.ModLoader;
import net.minecraft.world.World;
import net.minecraft.world.storage.WorldInfo;
import CustomOreGen.CustomPacketPayload.PayloadType;
import CustomOreGen.Client.ClientState;
import CustomOreGen.Client.ClientState.WireframeRenderMode;
import CustomOreGen.Server.ServerState;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class mod_CustomOreGen extends BaseMod
{
public String getVersion()
{
return "@VERSION@";
}
public String getPriorities()
{
return "after:*;";
}
public void load()
{
if (!CustomOreGenBase.hasFML())
{
CustomOreGenBase.log = ModLoader.getLogger();
}
if (!CustomOreGenBase.hasFML())
{
ModLoader.setInGameHook(this, true, false);
}
CustomPacketPayload.registerChannels(this);
}
public void modsLoaded()
{
CustomOreGenBase.onModPostLoad();
boolean found = false;
String failMods = null;
for (BaseMod mod : ModLoader.getLoadedMods()) {
if (mod == this)
{
found = true;
}
else if (found && mod != null)
{
failMods = (failMods == null ? "" : failMods + ", ") + mod.getName();
}
}
if (failMods == null)
{
CustomOreGenBase.log.finer("Confirmed that CustomOreGen has precedence during world generation");
}
else
{
CustomOreGenBase.log.warning("The following mods force ModLoader to load them *after* CustomOreGen: " + failMods + ". Distributions may not behave as expected if they (1) target custom biomes from or (2) replace ores placed by these mods.");
}
}
public void generateSurface(World world, Random rand, int blockX, int blockZ)
{
if (!CustomOreGenBase.hasFML())
{
ServerState.checkIfServerChanged(MinecraftServer.getServer(), world.getWorldInfo());
ServerState.onPopulateChunk(world, rand, blockX / 16, blockZ / 16);
}
}
public void generateNether(World world, Random rand, int blockX, int blockZ)
{
this.generateSurface(world, rand, blockX, blockZ);
}
@SideOnly(Side.CLIENT)
public boolean onTickInGame(float partialTick, Minecraft minecraft)
{
if (CustomOreGenBase.hasFML())
{
return false;
}
else
{
Minecraft mc = Minecraft.getMinecraft();
if (mc.isSingleplayer())
{
ServerState.checkIfServerChanged(MinecraftServer.getServer(), (WorldInfo)null);
}
if (mc.theWorld != null && ClientState.hasWorldChanged(mc.theWorld))
{
ClientState.onWorldChanged(mc.theWorld);
}
return true;
}
}
@SideOnly(Side.CLIENT)
public void clientCustomPayload(NetClientHandler handler, Packet250CustomPayload packet)
{
Minecraft mc = Minecraft.getMinecraft();
if (mc.theWorld != null && ClientState.hasWorldChanged(mc.theWorld))
{
ClientState.onWorldChanged(mc.theWorld);
}
CustomPacketPayload payload = CustomPacketPayload.decodePacket(packet);
if (payload != null)
{
switch (payload.type)
{
case DebuggingGeometryData:
ClientState.addDebuggingGeometry((GeometryData)payload.data);
break;
case DebuggingGeometryRenderMode:
String strMode = (String)payload.data;
if ("_DISABLE_".equals(strMode))
{
ClientState.dgEnabled = false;
return;
}
if (!CustomOreGenBase.hasForge())
{
- handler.handleChat(new Packet3Chat("{text: \"\u00a7cWarning: Minecraft Forge must be installed to view wireframes.\""));
+ handler.handleChat(new Packet3Chat("{text: \"\u00a7cWarning: Minecraft Forge must be installed to view wireframes.\"}"));
return;
}
if (strMode != null)
{
WireframeRenderMode idx = null;
for (WireframeRenderMode mode : WireframeRenderMode.values()) {
if (mode.name().equalsIgnoreCase(strMode))
{
idx = mode;
break;
}
}
if (idx != null)
{
ClientState.dgRenderingMode = idx;
}
else
{
- handler.handleChat(new Packet3Chat("{text: \"\u00a7cError: Invalid wireframe mode \'" + strMode + "\'\""));
+ handler.handleChat(new Packet3Chat("{text: \"\u00a7cError: Invalid wireframe mode \'" + strMode + "\'\"}"));
}
}
else
{
int var11 = ClientState.dgRenderingMode == null ? 0 : ClientState.dgRenderingMode.ordinal();
var11 = (var11 + 1) % WireframeRenderMode.values().length;
ClientState.dgRenderingMode = WireframeRenderMode.values()[var11];
}
handler.handleChat(new Packet3Chat("{text: \"COG Client wireframe mode: " + ClientState.dgRenderingMode.name() + "\"}"));
break;
case DebuggingGeometryReset:
ClientState.clearDebuggingGeometry();
break;
case MystcraftSymbolData:
if (!mc.isSingleplayer())
{
ClientState.addMystcraftSymbol((MystcraftSymbolData)payload.data);
}
break;
case CommandResponse:
mc.ingameGUI.getChatGUI().printChatMessage((String)payload.data);
break;
default:
throw new RuntimeException("Unhandled client packet type " + payload.type);
}
}
}
public void serverCustomPayload(NetServerHandler handler, Packet250CustomPayload packet)
{
World handlerWorld = handler.playerEntity == null ? null : handler.playerEntity.worldObj;
ServerState.checkIfServerChanged(MinecraftServer.getServer(), handlerWorld == null ? null : handlerWorld.getWorldInfo());
CustomPacketPayload payload = CustomPacketPayload.decodePacket(packet);
if (payload != null)
{
switch (payload.type)
{
case DebuggingGeometryRequest:
GeometryData geometryData = null;
if (handler.getPlayer().mcServer.getConfigurationManager().areCommandsAllowed(handler.getPlayer().username))
{
geometryData = ServerState.getDebuggingGeometryData((GeometryRequestData)payload.data);
}
if (geometryData == null)
{
(new CustomPacketPayload(PayloadType.DebuggingGeometryRenderMode, "_DISABLE_")).sendToClient(handler);
}
else
{
(new CustomPacketPayload(PayloadType.DebuggingGeometryData, geometryData)).sendToClient(handler);
}
break;
default:
throw new RuntimeException("Unhandled server packet type " + payload.type);
}
}
}
public void onClientLogin(net.minecraft.entity.player.EntityPlayer player)
{
World handlerWorld = player == null ? null : player.worldObj;
ServerState.checkIfServerChanged(MinecraftServer.getServer(), handlerWorld == null ? null : handlerWorld.getWorldInfo());
if (player != null)
{
ServerState.onClientLogin((EntityPlayerMP)player);
}
}
}
| false | true | public void clientCustomPayload(NetClientHandler handler, Packet250CustomPayload packet)
{
Minecraft mc = Minecraft.getMinecraft();
if (mc.theWorld != null && ClientState.hasWorldChanged(mc.theWorld))
{
ClientState.onWorldChanged(mc.theWorld);
}
CustomPacketPayload payload = CustomPacketPayload.decodePacket(packet);
if (payload != null)
{
switch (payload.type)
{
case DebuggingGeometryData:
ClientState.addDebuggingGeometry((GeometryData)payload.data);
break;
case DebuggingGeometryRenderMode:
String strMode = (String)payload.data;
if ("_DISABLE_".equals(strMode))
{
ClientState.dgEnabled = false;
return;
}
if (!CustomOreGenBase.hasForge())
{
handler.handleChat(new Packet3Chat("{text: \"\u00a7cWarning: Minecraft Forge must be installed to view wireframes.\""));
return;
}
if (strMode != null)
{
WireframeRenderMode idx = null;
for (WireframeRenderMode mode : WireframeRenderMode.values()) {
if (mode.name().equalsIgnoreCase(strMode))
{
idx = mode;
break;
}
}
if (idx != null)
{
ClientState.dgRenderingMode = idx;
}
else
{
handler.handleChat(new Packet3Chat("{text: \"\u00a7cError: Invalid wireframe mode \'" + strMode + "\'\""));
}
}
else
{
int var11 = ClientState.dgRenderingMode == null ? 0 : ClientState.dgRenderingMode.ordinal();
var11 = (var11 + 1) % WireframeRenderMode.values().length;
ClientState.dgRenderingMode = WireframeRenderMode.values()[var11];
}
handler.handleChat(new Packet3Chat("{text: \"COG Client wireframe mode: " + ClientState.dgRenderingMode.name() + "\"}"));
break;
case DebuggingGeometryReset:
ClientState.clearDebuggingGeometry();
break;
case MystcraftSymbolData:
if (!mc.isSingleplayer())
{
ClientState.addMystcraftSymbol((MystcraftSymbolData)payload.data);
}
break;
case CommandResponse:
mc.ingameGUI.getChatGUI().printChatMessage((String)payload.data);
break;
default:
throw new RuntimeException("Unhandled client packet type " + payload.type);
}
}
}
| public void clientCustomPayload(NetClientHandler handler, Packet250CustomPayload packet)
{
Minecraft mc = Minecraft.getMinecraft();
if (mc.theWorld != null && ClientState.hasWorldChanged(mc.theWorld))
{
ClientState.onWorldChanged(mc.theWorld);
}
CustomPacketPayload payload = CustomPacketPayload.decodePacket(packet);
if (payload != null)
{
switch (payload.type)
{
case DebuggingGeometryData:
ClientState.addDebuggingGeometry((GeometryData)payload.data);
break;
case DebuggingGeometryRenderMode:
String strMode = (String)payload.data;
if ("_DISABLE_".equals(strMode))
{
ClientState.dgEnabled = false;
return;
}
if (!CustomOreGenBase.hasForge())
{
handler.handleChat(new Packet3Chat("{text: \"\u00a7cWarning: Minecraft Forge must be installed to view wireframes.\"}"));
return;
}
if (strMode != null)
{
WireframeRenderMode idx = null;
for (WireframeRenderMode mode : WireframeRenderMode.values()) {
if (mode.name().equalsIgnoreCase(strMode))
{
idx = mode;
break;
}
}
if (idx != null)
{
ClientState.dgRenderingMode = idx;
}
else
{
handler.handleChat(new Packet3Chat("{text: \"\u00a7cError: Invalid wireframe mode \'" + strMode + "\'\"}"));
}
}
else
{
int var11 = ClientState.dgRenderingMode == null ? 0 : ClientState.dgRenderingMode.ordinal();
var11 = (var11 + 1) % WireframeRenderMode.values().length;
ClientState.dgRenderingMode = WireframeRenderMode.values()[var11];
}
handler.handleChat(new Packet3Chat("{text: \"COG Client wireframe mode: " + ClientState.dgRenderingMode.name() + "\"}"));
break;
case DebuggingGeometryReset:
ClientState.clearDebuggingGeometry();
break;
case MystcraftSymbolData:
if (!mc.isSingleplayer())
{
ClientState.addMystcraftSymbol((MystcraftSymbolData)payload.data);
}
break;
case CommandResponse:
mc.ingameGUI.getChatGUI().printChatMessage((String)payload.data);
break;
default:
throw new RuntimeException("Unhandled client packet type " + payload.type);
}
}
}
|
diff --git a/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/CLImage.java b/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/CLImage.java
index 9b811252..46069470 100644
--- a/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/CLImage.java
+++ b/libraries/OpenCL/JavaCL/src/main/java/com/nativelibs4java/opencl/CLImage.java
@@ -1,170 +1,170 @@
/*
Copyright (c) 2009 Olivier Chafik (http://ochafik.free.fr/)
This file is part of OpenCL4Java (http://code.google.com/p/nativelibs4java/wiki/OpenCL).
OpenCL4Java 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.1 of the License, or
(at your option) any later version.
OpenCL4Java 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 OpenCL4Java. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nativelibs4java.opencl;
import com.nativelibs4java.opencl.library.OpenCLLibrary;
import com.nativelibs4java.opencl.library.cl_image_format;
import com.nativelibs4java.util.NIOUtils;
import com.ochafik.lang.jnaerator.runtime.NativeSize;
import com.ochafik.lang.jnaerator.runtime.NativeSizeByReference;
import com.ochafik.util.listenable.Pair;
import static com.nativelibs4java.opencl.library.OpenCLLibrary.*;
import com.sun.jna.*;
import com.sun.jna.ptr.*;
import java.nio.*;
import static com.nativelibs4java.opencl.JavaCL.*;
import static com.nativelibs4java.opencl.CLException.*;
import static com.nativelibs4java.util.JNAUtils.*;
import static com.nativelibs4java.util.NIOUtils.*;
/**
* OpenCL Image Memory Object.<br/>
* An image object is used to store a two- or three- dimensional texture, frame-buffer or image<br/>
* An image object is used to represent a buffer that can be used as a texture or a frame-buffer. The elements of an image object are selected from a list of predefined image formats.
* @author Oliveir Chafik
*/
public abstract class CLImage extends CLMem {
CLImageFormat format;
CLImage(CLContext context, cl_mem entity, CLImageFormat format) {
super(context, -1, entity);
this.format = format;
}
/**
* Return image format descriptor specified when image is created with CLContext.create{Input|Output|InputOutput}{2D|3D}.
*/
@InfoName("CL_IMAGE_FORMAT")
public CLImageFormat getFormat() {
if (format == null) {
/// TODO: DOES NOT SEEM TO WORK ON MAC OS X 10.6.1 / CPU
cl_image_format fmt = new cl_image_format();
fmt.use(infos.getMemory(getEntity(), CL_IMAGE_FORMAT));
format = new CLImageFormat(fmt);
}
return format;
}
/**
* Return size of each element of the image memory object given by image. <br/>
* An element is made up of n channels. The value of n is given in cl_image_format descriptor.
*/
@InfoName("CL_IMAGE_ELEMENT_SIZE")
public long getElementSize() {
return infos.getIntOrLong(getEntity(), CL_IMAGE_ELEMENT_SIZE);
}
protected CLEvent read(CLQueue queue, NativeSize[] origin, NativeSize[] region, long rowPitch, long slicePitch, Buffer out, boolean blocking, CLEvent... eventsToWaitFor) {
/*if (!out.isDirect()) {
}*/
cl_event[] eventOut = blocking ? null : CLEvent.new_event_out(eventsToWaitFor);
cl_event[] evts = CLEvent.to_cl_event_array(eventsToWaitFor);
error(CL.clEnqueueReadImage(queue.getEntity(), getEntity(),
blocking ? CL_TRUE : CL_FALSE,
origin,
region,
toNS(rowPitch),
toNS(slicePitch),
Native.getDirectBufferPointer(out),
evts == null ? 0 : evts.length, evts,
eventOut
));
return CLEvent.createEvent(queue, eventOut);
}
protected CLEvent write(CLQueue queue, NativeSize[] origin, NativeSize[] region, long rowPitch, long slicePitch, Buffer in, boolean blocking, CLEvent... eventsToWaitFor) {
boolean indirect = !in.isDirect();
if (indirect)
in = directCopy(in, getContext().getByteOrder());
cl_event[] eventOut = blocking ? null : CLEvent.new_event_out(eventsToWaitFor);
cl_event[] evts = CLEvent.to_cl_event_array(eventsToWaitFor);
- error(CL.clEnqueueReadImage(queue.getEntity(), getEntity(),
+ error(CL.clEnqueueWriteImage(queue.getEntity(), getEntity(),
blocking ? CL_TRUE : CL_FALSE,
origin,
region,
toNS(rowPitch),
toNS(slicePitch),
Native.getDirectBufferPointer(in),
evts == null ? 0 : evts.length, evts,
eventOut
));
CLEvent evt = CLEvent.createEvent(queue, eventOut);
if (indirect && !blocking) {
final Buffer toHold = in;
evt.invokeUponCompletion(new Runnable() {
public void run() {
// Make sure the GC held a reference to directData until the write was completed !
toHold.rewind();
}
});
}
return evt;
}
protected Pair<ByteBuffer, CLEvent> map(CLQueue queue, MapFlags flags,
NativeSize[] offset3, NativeSize[] length3,
Long imageRowPitch,
Long imageSlicePitch,
boolean blocking, CLEvent... eventsToWaitFor)
{
//checkBounds(offset, length);
cl_event[] eventOut = blocking ? null : CLEvent.new_event_out(eventsToWaitFor);
IntBuffer pErr = NIOUtils.directInts(1, ByteOrder.nativeOrder());
cl_event[] evts = CLEvent.to_cl_event_array(eventsToWaitFor);
Pointer p = CL.clEnqueueMapImage(
queue.getEntity(), getEntity(), blocking ? CL_TRUE : CL_FALSE,
flags.getValue(),
offset3,
length3,
imageRowPitch == null ? null : new NativeSizeByReference(toNS(imageRowPitch)),
imageSlicePitch == null ? null : new NativeSizeByReference(toNS(imageSlicePitch)),
evts == null ? 0 : evts.length, evts,
eventOut,
pErr
);
error(pErr.get());
return new Pair<ByteBuffer, CLEvent>(
p.getByteBuffer(0, getByteCount()),
CLEvent.createEvent(queue, eventOut)
);
}
/**
* @see CLImage2D#map(com.nativelibs4java.opencl.CLQueue, com.nativelibs4java.opencl.CLMem.MapFlags, com.nativelibs4java.opencl.CLEvent[])
* @see CLImage3D#map(com.nativelibs4java.opencl.CLQueue, com.nativelibs4java.opencl.CLMem.MapFlags, com.nativelibs4java.opencl.CLEvent[])
* @param queue
* @param buffer
* @param eventsToWaitFor
* @return
*/
public CLEvent unmap(CLQueue queue, ByteBuffer buffer, CLEvent... eventsToWaitFor) {
cl_event[] eventOut = CLEvent.new_event_out(eventsToWaitFor);
cl_event[] evts = CLEvent.to_cl_event_array(eventsToWaitFor);
error(CL.clEnqueueUnmapMemObject(queue.getEntity(), getEntity(), Native.getDirectBufferPointer(buffer), evts == null ? 0 : evts.length, evts, eventOut));
return CLEvent.createEvent(queue, eventOut);
}
}
| true | true | protected CLEvent write(CLQueue queue, NativeSize[] origin, NativeSize[] region, long rowPitch, long slicePitch, Buffer in, boolean blocking, CLEvent... eventsToWaitFor) {
boolean indirect = !in.isDirect();
if (indirect)
in = directCopy(in, getContext().getByteOrder());
cl_event[] eventOut = blocking ? null : CLEvent.new_event_out(eventsToWaitFor);
cl_event[] evts = CLEvent.to_cl_event_array(eventsToWaitFor);
error(CL.clEnqueueReadImage(queue.getEntity(), getEntity(),
blocking ? CL_TRUE : CL_FALSE,
origin,
region,
toNS(rowPitch),
toNS(slicePitch),
Native.getDirectBufferPointer(in),
evts == null ? 0 : evts.length, evts,
eventOut
));
CLEvent evt = CLEvent.createEvent(queue, eventOut);
if (indirect && !blocking) {
final Buffer toHold = in;
evt.invokeUponCompletion(new Runnable() {
public void run() {
// Make sure the GC held a reference to directData until the write was completed !
toHold.rewind();
}
});
}
return evt;
}
| protected CLEvent write(CLQueue queue, NativeSize[] origin, NativeSize[] region, long rowPitch, long slicePitch, Buffer in, boolean blocking, CLEvent... eventsToWaitFor) {
boolean indirect = !in.isDirect();
if (indirect)
in = directCopy(in, getContext().getByteOrder());
cl_event[] eventOut = blocking ? null : CLEvent.new_event_out(eventsToWaitFor);
cl_event[] evts = CLEvent.to_cl_event_array(eventsToWaitFor);
error(CL.clEnqueueWriteImage(queue.getEntity(), getEntity(),
blocking ? CL_TRUE : CL_FALSE,
origin,
region,
toNS(rowPitch),
toNS(slicePitch),
Native.getDirectBufferPointer(in),
evts == null ? 0 : evts.length, evts,
eventOut
));
CLEvent evt = CLEvent.createEvent(queue, eventOut);
if (indirect && !blocking) {
final Buffer toHold = in;
evt.invokeUponCompletion(new Runnable() {
public void run() {
// Make sure the GC held a reference to directData until the write was completed !
toHold.rewind();
}
});
}
return evt;
}
|
diff --git a/hazelcast/src/test/java/ru/taskurotta/hz/test/DelayIQueueTest.java b/hazelcast/src/test/java/ru/taskurotta/hz/test/DelayIQueueTest.java
index 88e8575b..328ccac3 100644
--- a/hazelcast/src/test/java/ru/taskurotta/hz/test/DelayIQueueTest.java
+++ b/hazelcast/src/test/java/ru/taskurotta/hz/test/DelayIQueueTest.java
@@ -1,52 +1,52 @@
package ru.taskurotta.hz.test;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import org.junit.Test;
import ru.taskurotta.hazelcast.queue.delay.BaseQueueFactory;
import ru.taskurotta.hazelcast.queue.delay.CommonStorageFactory;
import ru.taskurotta.hazelcast.queue.delay.DelayIQueue;
import ru.taskurotta.hazelcast.queue.delay.QueueFactory;
import ru.taskurotta.hazelcast.queue.delay.StorageFactory;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
public class DelayIQueueTest {
@Test
public void CommonDelayIQueueTest() throws InterruptedException {
HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance();
try {
- StorageFactory storageFactory = new CommonStorageFactory(hazelcastInstance, "commonStorage", "");
+ StorageFactory storageFactory = new CommonStorageFactory(hazelcastInstance, "commonStorage", "1_seconds");
QueueFactory queueFactory = new BaseQueueFactory(hazelcastInstance, storageFactory);
DelayIQueue<String> delayIQueue = queueFactory.create("testQueue");
assertTrue(delayIQueue.add("test", 2, TimeUnit.SECONDS));
Object retrievedObject = delayIQueue.poll(0, TimeUnit.SECONDS);
assertNull(retrievedObject);
TimeUnit.SECONDS.sleep(1);
retrievedObject = delayIQueue.poll(0, TimeUnit.SECONDS);
assertNull(retrievedObject);
- retrievedObject = delayIQueue.poll(1, TimeUnit.SECONDS);
+ retrievedObject = delayIQueue.poll(2, TimeUnit.SECONDS);
assertNotNull(retrievedObject);
retrievedObject = delayIQueue.poll(1, TimeUnit.SECONDS);
assertNull(retrievedObject);
} finally {
hazelcastInstance.shutdown();
}
}
}
| false | true | public void CommonDelayIQueueTest() throws InterruptedException {
HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance();
try {
StorageFactory storageFactory = new CommonStorageFactory(hazelcastInstance, "commonStorage", "");
QueueFactory queueFactory = new BaseQueueFactory(hazelcastInstance, storageFactory);
DelayIQueue<String> delayIQueue = queueFactory.create("testQueue");
assertTrue(delayIQueue.add("test", 2, TimeUnit.SECONDS));
Object retrievedObject = delayIQueue.poll(0, TimeUnit.SECONDS);
assertNull(retrievedObject);
TimeUnit.SECONDS.sleep(1);
retrievedObject = delayIQueue.poll(0, TimeUnit.SECONDS);
assertNull(retrievedObject);
retrievedObject = delayIQueue.poll(1, TimeUnit.SECONDS);
assertNotNull(retrievedObject);
retrievedObject = delayIQueue.poll(1, TimeUnit.SECONDS);
assertNull(retrievedObject);
} finally {
hazelcastInstance.shutdown();
}
}
| public void CommonDelayIQueueTest() throws InterruptedException {
HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance();
try {
StorageFactory storageFactory = new CommonStorageFactory(hazelcastInstance, "commonStorage", "1_seconds");
QueueFactory queueFactory = new BaseQueueFactory(hazelcastInstance, storageFactory);
DelayIQueue<String> delayIQueue = queueFactory.create("testQueue");
assertTrue(delayIQueue.add("test", 2, TimeUnit.SECONDS));
Object retrievedObject = delayIQueue.poll(0, TimeUnit.SECONDS);
assertNull(retrievedObject);
TimeUnit.SECONDS.sleep(1);
retrievedObject = delayIQueue.poll(0, TimeUnit.SECONDS);
assertNull(retrievedObject);
retrievedObject = delayIQueue.poll(2, TimeUnit.SECONDS);
assertNotNull(retrievedObject);
retrievedObject = delayIQueue.poll(1, TimeUnit.SECONDS);
assertNull(retrievedObject);
} finally {
hazelcastInstance.shutdown();
}
}
|
diff --git a/vtk-amibe/src/org/jcae/vtk/MeshVisuReader.java b/vtk-amibe/src/org/jcae/vtk/MeshVisuReader.java
index 8c88627e..0de75d81 100644
--- a/vtk-amibe/src/org/jcae/vtk/MeshVisuReader.java
+++ b/vtk-amibe/src/org/jcae/vtk/MeshVisuReader.java
@@ -1,351 +1,349 @@
/*
* Project Info: http://jcae.sourceforge.net
*
* 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.1 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.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*
* (C) Copyright 2008, by EADS France
*/
package org.jcae.vtk;
import gnu.trove.TFloatArrayList;
import gnu.trove.TIntArrayList;
import gnu.trove.TIntHashSet;
import gnu.trove.TIntObjectHashMap;
import gnu.trove.TIntObjectIterator;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.DoubleBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.channels.FileChannel;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jcae.mesh.amibe.ds.AbstractHalfEdge;
import org.jcae.mesh.amibe.traits.MeshTraitsBuilder;
import org.jcae.mesh.amibe.traits.TriangleTraitsBuilder;
import org.jcae.mesh.oemm.MeshReader;
import org.jcae.mesh.oemm.OEMM;
import org.jcae.mesh.amibe.ds.Mesh;
import org.jcae.mesh.amibe.ds.Triangle;
import org.jcae.mesh.amibe.ds.Vertex;
import org.jcae.mesh.oemm.FakeNonReadVertex;
/**
* This class serves to two things :
* <p>In MeshVisuBuilder it reads a Mesh from the standard OEMM and build a Mesh Visu.
* This can be down using buildPreparationMeshVisu.
* </p>
* <p>
* In ViewableOEMM it reads directly in specialised *V files that contains directly the beams
* representing the mesh. This can be down using buildMeshVisu. Be careful, the edges in the boundaries
* of the octants are not loaded if the two octants that contains the boundarie are not loaded !
* </p>
* @author Julian Ibarz
*/
public class MeshVisuReader extends MeshReader
{
private static Logger LOGGER = Logger.getLogger(MeshVisuReader.class.getName());
/**
* This is the structure of the mesh of a leaf
*/
class MeshVisu
{
public int[] edges;
public int[] freeEdges;
public float[] nodes; // The nodes of the other leaves duplicated
}
// This contains the coordinates for the quads of the octree
private float[] nodesQuads;
private TIntObjectHashMap<MeshVisu> mapLeafToMeshVisu = new TIntObjectHashMap<MeshVisu>();
public MeshVisuReader(OEMM o)
{
super(o);
}
public float[] getNodesQuad()
{
if (nodesQuads == null)
nodesQuads = ArrayUtils.doubleToFloat(oemm.getCoords(true));
return nodesQuads;
}
public int[] getLeavesLoaded()
{
return mapLeafToMeshVisu.keys();
}
MeshVisu[] getMeshes()
{
MeshVisu[] values = new MeshVisu[mapLeafToMeshVisu.size()];
mapLeafToMeshVisu.getValues(values);
return values;
}
public void buildMeshVisu(int[] leaves)
{
if (LOGGER.isLoggable(Level.CONFIG))
LOGGER.log(Level.CONFIG, "Loading nodes: "+leaves);
TIntArrayList sortedLeaves = new TIntArrayList(leaves);
sortedLeaves.sort();
// Unload the mesh not used
for (int leaf : mapLeafToMeshVisu.keys())
{
if (sortedLeaves.binarySearch(leaf) < 0)
mapLeafToMeshVisu.remove(leaf);
}
for (int i = 0, n = sortedLeaves.size(); i < n; i++)
{
int leaf = sortedLeaves.get(i);
// If already loaded skip
if (mapLeafToMeshVisu.containsKey(leaf))
continue;
MeshVisu mesh = new MeshVisu();
readVerticesForVisu(mesh, oemm.leaves[leaf]);
readEdges(mesh, oemm.leaves[leaf]);
mapLeafToMeshVisu.put(leaf, mesh);
}
}
private void readVerticesForVisu(MeshVisu mesh, OEMM.Node current)
{
try
{
if (LOGGER.isLoggable(Level.FINE))
LOGGER.log(Level.FINE, "Reading " + current.vn + " vertices from " + getVerticesFile(oemm, current));
double[] xyz = new double[3];
mesh.nodes = new float[current.vn * 3];
FileChannel fc = new FileInputStream(getVerticesFile(oemm, current)).getChannel();
buffer.clear();
DoubleBuffer bbD = buffer.asDoubleBuffer();
int remaining = current.vn;
int offset = 0;
for (int nblock = (remaining * VERTEX_SIZE) / BUFFER_SIZE; nblock >= 0; --nblock)
{
buffer.rewind();
fc.read(buffer);
bbD.rewind();
int nf = BUFFER_SIZE / VERTEX_SIZE;
if (remaining < nf)
nf = remaining;
remaining -= nf;
for (int nr = 0; nr < nf; nr++)
{
bbD.get(xyz);
mesh.nodes[offset++] = (float) xyz[0];
mesh.nodes[offset++] = (float) xyz[1];
mesh.nodes[offset++] = (float) xyz[2];
}
}
fc.close();
}
catch (IOException ex)
{
LOGGER.severe("I/O error when reading file " + getVerticesFile(oemm, current));
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
/**
* Reads triangle file, create Triangle instances and store them into mesh.
*/
private void readEdges(MeshVisu mesh, OEMM.Node current)
{
try
{
FileChannel fc = new FileInputStream(MeshVisuBuilder.getEdgesFile(oemm, current)).getChannel();
String [] label = new String[] { "Reading edges", "Reading free edges" };
for (int i = 0; i < 2; ++i)
{
LOGGER.fine(label[i]);
// Read the number of edges components
ByteBuffer byteBuffer = ByteBuffer.allocate(Integer.SIZE / 8);
IntBuffer bufferInteger = byteBuffer.asIntBuffer();
byteBuffer.rewind();
fc.read(byteBuffer);
bufferInteger.rewind();
int nbrOfEdgesComponents = bufferInteger.get(0);
if (LOGGER.isLoggable(Level.FINE))
LOGGER.log(Level.FINE, "Reading " + (nbrOfEdgesComponents / 2) + " edges from " + MeshVisuBuilder.getEdgesFile(oemm, current));
// Read the edges
byteBuffer = ByteBuffer.allocate((Integer.SIZE / 8) * nbrOfEdgesComponents);
bufferInteger = byteBuffer.asIntBuffer();
byteBuffer.rewind();
fc.read(byteBuffer);
bufferInteger.rewind();
int[] temp = new int[nbrOfEdgesComponents];
bufferInteger.get(temp);
if (i == 0)
mesh.edges = temp;
else
mesh.freeEdges = temp;
}
// Read the number of fake vertices
ByteBuffer byteBuffer = ByteBuffer.allocate(Integer.SIZE / 8);
IntBuffer bufferInteger = byteBuffer.asIntBuffer();
byteBuffer.rewind();
fc.read(byteBuffer);
bufferInteger.rewind();
int nbrOfFakeVerticesComponent = bufferInteger.get(0);
// Read fake vertices
if (LOGGER.isLoggable(Level.FINE))
LOGGER.log(Level.FINE, "Reading " + (nbrOfFakeVerticesComponent / 3) + " fake vertices from " + MeshVisuBuilder.getEdgesFile(oemm, current));
byteBuffer = ByteBuffer.allocate((Float.SIZE / 8) * nbrOfFakeVerticesComponent);
FloatBuffer bufferFloat = byteBuffer.asFloatBuffer();
byteBuffer.rewind();
fc.read(byteBuffer);
bufferFloat.rewind();
float[] fakeVertices = new float[nbrOfFakeVerticesComponent];
bufferFloat.get(fakeVertices);
// Merging vertices and fake vertices
float[] vertices = mesh.nodes;
if (LOGGER.isLoggable(Level.FINE))
LOGGER.log(Level.FINE, "Merging " + fakeVertices.length + " into " + vertices.length + " vertices.");
mesh.nodes = new float[vertices.length + fakeVertices.length];
System.arraycopy(vertices, 0, mesh.nodes, 0, vertices.length);
System.arraycopy(fakeVertices, 0, mesh.nodes, vertices.length, fakeVertices.length);
}
catch (IOException ex)
{
LOGGER.severe("I/O error when reading indexed file " + getTrianglesFile(oemm, current));
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
MeshVisu buildMeshVisu(int leaf)
{
MeshTraitsBuilder mtb = new MeshTraitsBuilder();
mtb.addNodeList();
mtb.addTriangleList();
// Mesh need adjancy informations to compute the edges
TriangleTraitsBuilder ttb = mtb.getTriangleTraitsBuilder();
ttb.addHalfEdge();
mapNodeToNonReadVertexList = new TIntObjectHashMap<List<FakeNonReadVertex>>();
Mesh mesh = buildMesh(mtb, new TIntHashSet(new int[]{ leaf }));
return constructEdges(mesh, leaf);
}
private int getNbrOfFakeVertices()
{
int nbrOfFakeVertices = 0;
for (TIntObjectIterator<List<FakeNonReadVertex>> it = mapNodeToNonReadVertexList.iterator(); it.hasNext(); )
{
it.advance();
nbrOfFakeVertices += it.value().size();
}
return nbrOfFakeVertices;
}
private MeshVisu constructEdges(Mesh mesh, int leave)
{
MeshVisu toReturn = new MeshVisu();
TIntArrayList edges = new TIntArrayList(mesh.getTriangles().size() * 3);
// This is empiric allocation, in general freeEdges dont are very numerous
TIntArrayList freeEdges = new TIntArrayList(mesh.getTriangles().size());
TFloatArrayList nodes = new TFloatArrayList();
// offset is the number of non fake vertices
// (because we will append later real and fake vertices)
int offset = mesh.getNodes().size() - getNbrOfFakeVertices();
LOGGER.finer("offset of fake vertices " + offset);
// Compute offset
for (Triangle tri : mesh.getTriangles())
{
if (!tri.isReadable())
continue;
AbstractHalfEdge edge = tri.getAbstractHalfEdge();
for (int i = 0; i < 3; ++i)
{
edge = edge.next();
// Conditions
if (edge.hasAttributes(AbstractHalfEdge.MARKED))
continue;
if (!edge.origin().isReadable() || !edge.destination().isReadable())
continue;
// Mark the edge
edge.setAttributes(AbstractHalfEdge.MARKED);
if (edge.hasSymmetricEdge())
edge.sym().setAttributes(AbstractHalfEdge.MARKED);
TIntArrayList fakeEdges = null;
// Save the edge
if (edge.hasAttributes(AbstractHalfEdge.BOUNDARY))
fakeEdges = freeEdges;
else
fakeEdges = edges;
Vertex vertex = edge.origin();
int ID = -1;
for (int j = 0; j < 2; ++j)
{
if (j == 0)
vertex = edge.origin();
else
vertex = edge.destination();
if (vertex instanceof FakeNonReadVertex)
{
ID = offset;
- double[] coords = vertex.getUV();
- assert coords.length == 3;
- nodes.add((float) coords[0]);
- nodes.add((float) coords[1]);
- nodes.add((float) coords[2]);
+ nodes.add((float) vertex.getX());
+ nodes.add((float) vertex.getY());
+ nodes.add((float) vertex.getZ());
++offset;
} else
ID = vertex.getLabel() - oemm.leaves[leave].minIndex;
fakeEdges.add(ID);
}
}
}
toReturn.edges = edges.toNativeArray();
toReturn.freeEdges = freeEdges.toNativeArray();
toReturn.nodes = nodes.toNativeArray();
return toReturn;
}
}
| true | true | private MeshVisu constructEdges(Mesh mesh, int leave)
{
MeshVisu toReturn = new MeshVisu();
TIntArrayList edges = new TIntArrayList(mesh.getTriangles().size() * 3);
// This is empiric allocation, in general freeEdges dont are very numerous
TIntArrayList freeEdges = new TIntArrayList(mesh.getTriangles().size());
TFloatArrayList nodes = new TFloatArrayList();
// offset is the number of non fake vertices
// (because we will append later real and fake vertices)
int offset = mesh.getNodes().size() - getNbrOfFakeVertices();
LOGGER.finer("offset of fake vertices " + offset);
// Compute offset
for (Triangle tri : mesh.getTriangles())
{
if (!tri.isReadable())
continue;
AbstractHalfEdge edge = tri.getAbstractHalfEdge();
for (int i = 0; i < 3; ++i)
{
edge = edge.next();
// Conditions
if (edge.hasAttributes(AbstractHalfEdge.MARKED))
continue;
if (!edge.origin().isReadable() || !edge.destination().isReadable())
continue;
// Mark the edge
edge.setAttributes(AbstractHalfEdge.MARKED);
if (edge.hasSymmetricEdge())
edge.sym().setAttributes(AbstractHalfEdge.MARKED);
TIntArrayList fakeEdges = null;
// Save the edge
if (edge.hasAttributes(AbstractHalfEdge.BOUNDARY))
fakeEdges = freeEdges;
else
fakeEdges = edges;
Vertex vertex = edge.origin();
int ID = -1;
for (int j = 0; j < 2; ++j)
{
if (j == 0)
vertex = edge.origin();
else
vertex = edge.destination();
if (vertex instanceof FakeNonReadVertex)
{
ID = offset;
double[] coords = vertex.getUV();
assert coords.length == 3;
nodes.add((float) coords[0]);
nodes.add((float) coords[1]);
nodes.add((float) coords[2]);
++offset;
} else
ID = vertex.getLabel() - oemm.leaves[leave].minIndex;
fakeEdges.add(ID);
}
}
}
toReturn.edges = edges.toNativeArray();
toReturn.freeEdges = freeEdges.toNativeArray();
toReturn.nodes = nodes.toNativeArray();
return toReturn;
}
| private MeshVisu constructEdges(Mesh mesh, int leave)
{
MeshVisu toReturn = new MeshVisu();
TIntArrayList edges = new TIntArrayList(mesh.getTriangles().size() * 3);
// This is empiric allocation, in general freeEdges dont are very numerous
TIntArrayList freeEdges = new TIntArrayList(mesh.getTriangles().size());
TFloatArrayList nodes = new TFloatArrayList();
// offset is the number of non fake vertices
// (because we will append later real and fake vertices)
int offset = mesh.getNodes().size() - getNbrOfFakeVertices();
LOGGER.finer("offset of fake vertices " + offset);
// Compute offset
for (Triangle tri : mesh.getTriangles())
{
if (!tri.isReadable())
continue;
AbstractHalfEdge edge = tri.getAbstractHalfEdge();
for (int i = 0; i < 3; ++i)
{
edge = edge.next();
// Conditions
if (edge.hasAttributes(AbstractHalfEdge.MARKED))
continue;
if (!edge.origin().isReadable() || !edge.destination().isReadable())
continue;
// Mark the edge
edge.setAttributes(AbstractHalfEdge.MARKED);
if (edge.hasSymmetricEdge())
edge.sym().setAttributes(AbstractHalfEdge.MARKED);
TIntArrayList fakeEdges = null;
// Save the edge
if (edge.hasAttributes(AbstractHalfEdge.BOUNDARY))
fakeEdges = freeEdges;
else
fakeEdges = edges;
Vertex vertex = edge.origin();
int ID = -1;
for (int j = 0; j < 2; ++j)
{
if (j == 0)
vertex = edge.origin();
else
vertex = edge.destination();
if (vertex instanceof FakeNonReadVertex)
{
ID = offset;
nodes.add((float) vertex.getX());
nodes.add((float) vertex.getY());
nodes.add((float) vertex.getZ());
++offset;
} else
ID = vertex.getLabel() - oemm.leaves[leave].minIndex;
fakeEdges.add(ID);
}
}
}
toReturn.edges = edges.toNativeArray();
toReturn.freeEdges = freeEdges.toNativeArray();
toReturn.nodes = nodes.toNativeArray();
return toReturn;
}
|
diff --git a/src/main/java/net/croxis/plugins/civilmineation/SignInteractListener.java b/src/main/java/net/croxis/plugins/civilmineation/SignInteractListener.java
index cc0c8b6..5cbc849 100644
--- a/src/main/java/net/croxis/plugins/civilmineation/SignInteractListener.java
+++ b/src/main/java/net/croxis/plugins/civilmineation/SignInteractListener.java
@@ -1,90 +1,93 @@
package net.croxis.plugins.civilmineation;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.block.Sign;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
public class SignInteractListener implements Listener{
@EventHandler
public void onBlockInteract(PlayerInteractEvent event){
//Left click is click, Right click is cycle
//Debug lines to see what the null error is from
//error is right clicking bottom block
+ if (event.getClickedBlock() == null){
+ return;
+ }
event.getClickedBlock();
event.getClickedBlock().getType();
if (event.getClickedBlock().getType().equals(Material.WALL_SIGN)
|| event.getClickedBlock().getType().equals(Material.SIGN)
|| event.getClickedBlock().getType().equals(Material.SIGN_POST)){
if (event.getAction().equals(Action.LEFT_CLICK_BLOCK)){
PlotComponent plot = CivAPI.getPlot(event.getClickedBlock().getChunk());
if (plot == null)
return;
if (plot.getCity() == null)
return;
// Immgration
CityComponent city = CivAPI.plugin.getDatabase().find(CityComponent.class).where()
.eq("charter_x", event.getClickedBlock().getX())
.eq("charter_y", event.getClickedBlock().getY()+1)
.eq("charter_z", event.getClickedBlock().getZ()).findUnique();
if (city == null)
return;
if (plot.getCity().getName().equalsIgnoreCase(city.getName())){
Sign sign = (Sign) event.getClickedBlock().getState();
if (sign.getLine(3).contains("Open") && sign.getLine(0).contains("=Demographics=")){
ResidentComponent resident = CivAPI.getResident(event.getPlayer());
if (CivAPI.addResident(resident, city))
CivAPI.broadcastToCity("Welcome " + resident.getName() + " to our city!", city);
}
}
} else if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK)){
if (event.getClickedBlock().getType().equals(Material.WALL_SIGN)){
Sign sign = (Sign) event.getClickedBlock().getState();
ResidentComponent resident = CivAPI.getResident(event.getPlayer());
if (sign.getLine(0).contains("=Demographics=")){
Civilmineation.log("Demographics update click");
PlotComponent plot = CivAPI.getPlot(event.getClickedBlock().getChunk());
if (plot == null){
Civilmineation.log("a");
return;
}
if (plot.getCity() == null){
Civilmineation.log("b");
return;
}
if (resident.getCity() == null){
Civilmineation.log("c");
return;
}
if (!plot.getCity().getName().equalsIgnoreCase(resident.getCity().getName())){
Civilmineation.log("d");
Civilmineation.log(plot.getCity().getName());
Civilmineation.log(resident.getCity().getName());
return;
}
if (resident.isMayor() || resident.isCityAssistant()){
Civilmineation.log("e");
if (sign.getLine(3).contains("Open")) {
sign.setLine(3, ChatColor.RED + "Closed");
sign.update();
} else {
sign.setLine(3, ChatColor.GREEN + "Open");
sign.update();
}
}
} else if (sign.getLine(0).contains("City Charter") && (resident.isMayor() || resident.isCityAssistant())){
Civilmineation.log("City charter update click");
CivAPI.updateCityCharter(CivAPI.getCity(sign.getLocation()));
}
}
}
}
}
}
| true | true | public void onBlockInteract(PlayerInteractEvent event){
//Left click is click, Right click is cycle
//Debug lines to see what the null error is from
//error is right clicking bottom block
event.getClickedBlock();
event.getClickedBlock().getType();
if (event.getClickedBlock().getType().equals(Material.WALL_SIGN)
|| event.getClickedBlock().getType().equals(Material.SIGN)
|| event.getClickedBlock().getType().equals(Material.SIGN_POST)){
if (event.getAction().equals(Action.LEFT_CLICK_BLOCK)){
PlotComponent plot = CivAPI.getPlot(event.getClickedBlock().getChunk());
if (plot == null)
return;
if (plot.getCity() == null)
return;
// Immgration
CityComponent city = CivAPI.plugin.getDatabase().find(CityComponent.class).where()
.eq("charter_x", event.getClickedBlock().getX())
.eq("charter_y", event.getClickedBlock().getY()+1)
.eq("charter_z", event.getClickedBlock().getZ()).findUnique();
if (city == null)
return;
if (plot.getCity().getName().equalsIgnoreCase(city.getName())){
Sign sign = (Sign) event.getClickedBlock().getState();
if (sign.getLine(3).contains("Open") && sign.getLine(0).contains("=Demographics=")){
ResidentComponent resident = CivAPI.getResident(event.getPlayer());
if (CivAPI.addResident(resident, city))
CivAPI.broadcastToCity("Welcome " + resident.getName() + " to our city!", city);
}
}
} else if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK)){
if (event.getClickedBlock().getType().equals(Material.WALL_SIGN)){
Sign sign = (Sign) event.getClickedBlock().getState();
ResidentComponent resident = CivAPI.getResident(event.getPlayer());
if (sign.getLine(0).contains("=Demographics=")){
Civilmineation.log("Demographics update click");
PlotComponent plot = CivAPI.getPlot(event.getClickedBlock().getChunk());
if (plot == null){
Civilmineation.log("a");
return;
}
if (plot.getCity() == null){
Civilmineation.log("b");
return;
}
if (resident.getCity() == null){
Civilmineation.log("c");
return;
}
if (!plot.getCity().getName().equalsIgnoreCase(resident.getCity().getName())){
Civilmineation.log("d");
Civilmineation.log(plot.getCity().getName());
Civilmineation.log(resident.getCity().getName());
return;
}
if (resident.isMayor() || resident.isCityAssistant()){
Civilmineation.log("e");
if (sign.getLine(3).contains("Open")) {
sign.setLine(3, ChatColor.RED + "Closed");
sign.update();
} else {
sign.setLine(3, ChatColor.GREEN + "Open");
sign.update();
}
}
} else if (sign.getLine(0).contains("City Charter") && (resident.isMayor() || resident.isCityAssistant())){
Civilmineation.log("City charter update click");
CivAPI.updateCityCharter(CivAPI.getCity(sign.getLocation()));
}
}
}
}
}
| public void onBlockInteract(PlayerInteractEvent event){
//Left click is click, Right click is cycle
//Debug lines to see what the null error is from
//error is right clicking bottom block
if (event.getClickedBlock() == null){
return;
}
event.getClickedBlock();
event.getClickedBlock().getType();
if (event.getClickedBlock().getType().equals(Material.WALL_SIGN)
|| event.getClickedBlock().getType().equals(Material.SIGN)
|| event.getClickedBlock().getType().equals(Material.SIGN_POST)){
if (event.getAction().equals(Action.LEFT_CLICK_BLOCK)){
PlotComponent plot = CivAPI.getPlot(event.getClickedBlock().getChunk());
if (plot == null)
return;
if (plot.getCity() == null)
return;
// Immgration
CityComponent city = CivAPI.plugin.getDatabase().find(CityComponent.class).where()
.eq("charter_x", event.getClickedBlock().getX())
.eq("charter_y", event.getClickedBlock().getY()+1)
.eq("charter_z", event.getClickedBlock().getZ()).findUnique();
if (city == null)
return;
if (plot.getCity().getName().equalsIgnoreCase(city.getName())){
Sign sign = (Sign) event.getClickedBlock().getState();
if (sign.getLine(3).contains("Open") && sign.getLine(0).contains("=Demographics=")){
ResidentComponent resident = CivAPI.getResident(event.getPlayer());
if (CivAPI.addResident(resident, city))
CivAPI.broadcastToCity("Welcome " + resident.getName() + " to our city!", city);
}
}
} else if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK)){
if (event.getClickedBlock().getType().equals(Material.WALL_SIGN)){
Sign sign = (Sign) event.getClickedBlock().getState();
ResidentComponent resident = CivAPI.getResident(event.getPlayer());
if (sign.getLine(0).contains("=Demographics=")){
Civilmineation.log("Demographics update click");
PlotComponent plot = CivAPI.getPlot(event.getClickedBlock().getChunk());
if (plot == null){
Civilmineation.log("a");
return;
}
if (plot.getCity() == null){
Civilmineation.log("b");
return;
}
if (resident.getCity() == null){
Civilmineation.log("c");
return;
}
if (!plot.getCity().getName().equalsIgnoreCase(resident.getCity().getName())){
Civilmineation.log("d");
Civilmineation.log(plot.getCity().getName());
Civilmineation.log(resident.getCity().getName());
return;
}
if (resident.isMayor() || resident.isCityAssistant()){
Civilmineation.log("e");
if (sign.getLine(3).contains("Open")) {
sign.setLine(3, ChatColor.RED + "Closed");
sign.update();
} else {
sign.setLine(3, ChatColor.GREEN + "Open");
sign.update();
}
}
} else if (sign.getLine(0).contains("City Charter") && (resident.isMayor() || resident.isCityAssistant())){
Civilmineation.log("City charter update click");
CivAPI.updateCityCharter(CivAPI.getCity(sign.getLocation()));
}
}
}
}
}
|
diff --git a/src/org/thestaticvoid/iriverter/Converter.java b/src/org/thestaticvoid/iriverter/Converter.java
index f2f11d5..37860a0 100755
--- a/src/org/thestaticvoid/iriverter/Converter.java
+++ b/src/org/thestaticvoid/iriverter/Converter.java
@@ -1,455 +1,457 @@
package org.thestaticvoid.iriverter;
import java.io.*;
import java.util.*;
public class Converter extends Thread {
private List jobs, notSplitVideos;
private ProgressDialogInfo progressDialogInfo;
private Process proc;
private boolean isCanceled;
private int exitCode;
public Converter(List jobs, ProgressDialogInfo progressDialogInfo) {
this.jobs = Converter.checkForOverwritingFiles(Converter.expandSingleJobsToMultiple(Converter.removeInvalidJobs(jobs)));
this.progressDialogInfo = progressDialogInfo;
isCanceled = false;
notSplitVideos = new ArrayList();
progressDialogInfo.setTotalJobs(this.jobs.size());
}
public static List removeInvalidJobs(List jobs) {
List newJobs = new ArrayList();
for (int i = 0; i < jobs.size(); i++) {
boolean validOutput = true;
if (jobs.get(i) instanceof OutputVideoInfo) {
OutputVideoInfo outputVideoInfo = (OutputVideoInfo) jobs.get(i);
if (outputVideoInfo.getOutputVideo().equals(""))
continue;
if (!outputVideoInfo.getOutputVideo().endsWith("." + ConverterOptions.getCurrentProfile().getWrapperFormat()) && !outputVideoInfo.getOutputVideo().equals(""))
outputVideoInfo.setOutputVideo(outputVideoInfo.getOutputVideo() + "." + ConverterOptions.getCurrentProfile().getWrapperFormat());
if (!new File(outputVideoInfo.getOutputVideo()).getParentFile().exists())
validOutput = new File(outputVideoInfo.getOutputVideo()).getParentFile().mkdirs();
validOutput = validOutput && new File(outputVideoInfo.getOutputVideo()).getParentFile().canWrite();
}
if (jobs.get(i) instanceof SingleVideoInfo) {
SingleVideoInfo singleVideoInfo = (SingleVideoInfo) jobs.get(i);
if (new File(singleVideoInfo.getInputVideo()).exists() && validOutput)
newJobs.add(singleVideoInfo);
} else if (jobs.get(i) instanceof DirectoryInfo) {
DirectoryInfo directoryInfo = (DirectoryInfo) jobs.get(i);
if (new File(directoryInfo.getInputDirectory()).exists() && !directoryInfo.getOutputDirectory().equals(""))
if (!new File(directoryInfo.getOutputDirectory()).exists())
validOutput = new File(directoryInfo.getOutputDirectory()).mkdirs();
if (validOutput)
newJobs.add(directoryInfo);
} else if (jobs.get(i) instanceof DVDInfo) {
DVDInfo dvdInfo = (DVDInfo) jobs.get(i);
if (!dvdInfo.getDrive().equals("") && validOutput)
newJobs.add(dvdInfo);
} else if (jobs.get(i) instanceof ManualSplitInfo) {
ManualSplitInfo manualSplitInfo = (ManualSplitInfo) jobs.get(i);
if (!manualSplitInfo.getVideo().equals("") && manualSplitInfo.getMarks().length > 2)
newJobs.add(manualSplitInfo);
} else if (jobs.get(i) instanceof JoinVideosInfo) {
JoinVideosInfo joinVideosInfo = (JoinVideosInfo) jobs.get(i);
if (joinVideosInfo.getInputVideos().length > 0 && validOutput)
newJobs.add(joinVideosInfo);
}
}
return newJobs;
}
public static List expandSingleJobsToMultiple(List jobs) {
List newJobs = new ArrayList();
for (int i = 0; i < jobs.size(); i++)
if (jobs.get(i) instanceof DirectoryInfo)
newJobs.addAll(convertDirectoryToSingleVideos((DirectoryInfo) jobs.get(i)));
else if (jobs.get(i) instanceof DVDInfo)
newJobs.addAll(separateDVDChaptersToSingleDVDJobs((DVDInfo) jobs.get(i)));
else if (jobs.get(i) instanceof ManualSplitInfo)
newJobs.addAll(separateMultipleSplitJobsToOneSplitJob((ManualSplitInfo) jobs.get(i)));
else
newJobs.add(jobs.get(i));
return newJobs;
}
public static List convertDirectoryToSingleVideos(DirectoryInfo directoryInfo) {
List newJobs = new ArrayList();
String[] directory = new File(directoryInfo.getInputDirectory()).list(new VideoFileFilter());
for (int i = 0; i < directory.length; i++)
if (new File(directoryInfo.getInputDirectory() + File.separator + directory[i]).isDirectory() && directoryInfo.getConvertSubdirectories())
newJobs.addAll(convertDirectoryToSingleVideos(new DirectoryAdapter(directoryInfo.getInputDirectory() + File.separator + directory[i], directoryInfo.getOutputDirectory() + File.separator + directory[i], directoryInfo.getConvertSubdirectories())));
else if (new File(directoryInfo.getInputDirectory() + File.separator + directory[i]).isFile())
newJobs.add(new SingleVideoAdapter(directoryInfo.getInputDirectory() + File.separator + directory[i], directoryInfo.getOutputDirectory() + File.separator + directory[i].substring(0, directory[i].lastIndexOf('.')) + "." + ConverterOptions.getCurrentProfile().getProfileName() + ".avi"));
return newJobs;
}
public static List separateDVDChaptersToSingleDVDJobs(DVDInfo dvdInfo) {
List newJobs = new ArrayList();
Chapters[] chapters = dvdInfo.getChapters();
if (chapters == null)
newJobs.add(dvdInfo);
else
for (int i = 0; i < chapters.length; i++) {
String outputVideo = "";
if (chapters[i].getFirstChapter() == chapters[i].getLastChapter())
outputVideo = dvdInfo.getOutputVideo().substring(0, dvdInfo.getOutputVideo().lastIndexOf('.')) + ".ch" + chapters[i].getFirstChapterPadded() + ".avi";
else
outputVideo = dvdInfo.getOutputVideo().substring(0, dvdInfo.getOutputVideo().lastIndexOf('.')) + ".ch" + chapters[i].getFirstChapterPadded() + "-" + chapters[i].getLastChapterPadded() + ".avi";
newJobs.add(new DVDAdapter(dvdInfo.getDrive(), dvdInfo.getTitle(), new Chapters[]{chapters[i]}, dvdInfo.getAudioStream(), dvdInfo.getSubtitles(), outputVideo));
}
return newJobs;
}
public static List separateMultipleSplitJobsToOneSplitJob(ManualSplitInfo manualSplitInfo) {
List newJobs = new ArrayList();
for (int i = 0; (i + 1) < manualSplitInfo.getMarks().length; i++)
newJobs.add(new ManualSplitAdapter(manualSplitInfo.getVideo(), new Mark[]{manualSplitInfo.getMarks()[i], manualSplitInfo.getMarks()[i + 1]}, i + 1));
return newJobs;
}
public static List checkForOverwritingFiles(List jobs) {
List newJobs = new ArrayList();
for (int i = 0; i < jobs.size(); i++) {
if (!(jobs.get(i) instanceof OutputVideoInfo))
newJobs.add(jobs.get(i));
else if (new File(((OutputVideoInfo) jobs.get(i)).getOutputVideo()).exists()) {
if (OverwriteDialog.overwriteFile(((OutputVideoInfo) jobs.get(i)).getOutputVideo()))
newJobs.add(jobs.get(i));
} else
newJobs.add(jobs.get(i));
}
return newJobs;
}
public void run() {
for (int i = 0; i < jobs.size() && !isCanceled; i++) {
progressDialogInfo.setCurrentJob(i + 1);
if (jobs.get(i) instanceof SingleVideoInfo)
convertSingleVideo((SingleVideoInfo) jobs.get(i));;
if (jobs.get(i) instanceof DVDInfo)
convertDVD((DVDInfo) jobs.get(i));
if (jobs.get(i) instanceof ManualSplitInfo)
manuallySplitVideo((ManualSplitInfo) jobs.get(i));
if (jobs.get(i) instanceof JoinVideosInfo)
joinVideos((JoinVideosInfo) jobs.get(i));
}
if (!isCanceled)
progressDialogInfo.complete(exitCode == 0);
}
public void cancel() {
isCanceled = true;
if (proc != null)
proc.destroy();
}
private List prepareBaseCommandList(String inputVideo, String outputVideo, MPlayerInfo info) {
List commandList = new ArrayList();
commandList.add(MPlayerInfo.getMPlayerPath() + "mencoder");
commandList.add(inputVideo);
commandList.add("-o");
commandList.add(outputVideo);
if (ConverterOptions.getCurrentProfile().getWrapperFormat().equals("mp4")) {
commandList.add("-of");
commandList.add("lavf");
commandList.add("-lavfopts");
commandList.add("format=mp4:i_certify_that_my_video_stream_does_not_use_b_frames");
}
commandList.add("-ovc");
if (ConverterOptions.getCurrentProfile().getVideoFormat().equals("h264")) {
commandList.add("x264");
commandList.add("-x264encopts");
commandList.add("bitrate=" + ConverterOptions.getVideoBitrate() + ":bframes=0:level_idc=13:nocabac");
} else {
commandList.add("xvid");
commandList.add("-xvidencopts");
commandList.add("bitrate=" + ConverterOptions.getVideoBitrate() + ":max_bframes=0");
}
commandList.add("-oac");
if (ConverterOptions.getCurrentProfile().getAudioFormat().equals("aac")) {
commandList.add("faac");
commandList.add("-faacopts");
commandList.add("br=" + ConverterOptions.getAudioBitrate() + ":object=1");
} else {
commandList.add("mp3lame");
commandList.add("-lameopts");
commandList.add("mode=2:cbr:br=" + ConverterOptions.getAudioBitrate());
}
double ofps = (info.getFrameRate() > ConverterOptions.getCurrentProfile().getMaxFrameRate() ? ConverterOptions.getCurrentProfile().getMaxFrameRate() : info.getFrameRate());
- commandList.add("-vf");
- commandList.add("filmdint=io=" + ((int) Math.round(info.getFrameRate() * 1000)) + ":" + ((int) Math.round(ofps * 1000)));
+ if (info.getFrameRate() != ofps && info.getFrameRate() < 1000) { // HACK: wmv always shows 1000 fps
+ commandList.add("-vf-add");
+ commandList.add("filmdint=io=" + ((int) Math.round(info.getFrameRate() * 1000)) + ":" + ((int) Math.round(ofps * 1000)));
+ }
int scaledWidth = ConverterOptions.getDimensions().getWidth();
int scaledHeight = (info.getDimensions().getHeight() * ConverterOptions.getDimensions().getWidth()) / info.getDimensions().getWidth();
if (scaledHeight > ConverterOptions.getDimensions().getHeight()) {
scaledWidth = (scaledWidth * ConverterOptions.getDimensions().getHeight()) / scaledHeight;
scaledHeight = ConverterOptions.getDimensions().getHeight();
}
commandList.add("-vf-add");
if (ConverterOptions.getPanAndScan())
commandList.add("scale=" + ((int) ((info.getDimensions().getWidth()) * (((double) ConverterOptions.getDimensions().getHeight()) / (double) info.getDimensions().getHeight()))) + ":" + ConverterOptions.getDimensions().getHeight() + ",crop=" + ConverterOptions.getDimensions().getWidth() + ":" + ConverterOptions.getDimensions().getHeight());
else
commandList.add("scale=" + scaledWidth + ":" + scaledHeight + ",expand=" + ConverterOptions.getDimensions().getWidth() + ":" + ConverterOptions.getDimensions().getHeight());
commandList.add("-vf-add");
commandList.add("harddup");
if (ConverterOptions.getVolumeFilter() == VolumeFilter.VOLNORM) {
commandList.add("-af");
commandList.add("volnorm");
} else if (ConverterOptions.getVolumeFilter() == VolumeFilter.VOLUME) {
commandList.add("-af");
commandList.add("volume=" + ConverterOptions.getGain());
}
commandList.add("-ofps");
commandList.add("" + ofps);
commandList.add("-srate");
commandList.add("44100");
if (!ConverterOptions.getAutoSync()) {
commandList.add("-delay");
commandList.add("" + (ConverterOptions.getAudioDelay() / 1000.0));
}
return commandList;
}
public void convertSingleVideo(SingleVideoInfo singleVideoInfo) {
Logger.logMessage("Single Video: " + singleVideoInfo.getInputVideo(), Logger.INFO);
progressDialogInfo.setInputVideo(new File(singleVideoInfo.getInputVideo()).getName());
progressDialogInfo.setOutputVideo(new File(singleVideoInfo.getOutputVideo()).getName());
progressDialogInfo.setStatus("Gathering information about the input video...");
MPlayerInfo info = new MPlayerInfo(singleVideoInfo.getInputVideo());
if (!info.videoSupported()) {
Logger.logMessage("Unsupported video", Logger.ERROR);
return;
}
List commandList = prepareBaseCommandList(singleVideoInfo.getInputVideo(), singleVideoInfo.getOutputVideo(), info);
String[] command = new String[commandList.size()];
for (int i = 0; i < command.length; i++)
command[i] = (String) commandList.get(i);
if (!isCanceled) {
new File(singleVideoInfo.getOutputVideo()).getParentFile().mkdirs();
progressDialogInfo.setStatus("Converting");
splitVideo(singleVideoInfo.getOutputVideo(), runConversionCommand(command));
}
}
public void convertDVD(DVDInfo dvdInfo) {
String inputVideo = "Title " + dvdInfo.getTitle() + " of the DVD at " + dvdInfo.getDrive();
Chapters[] chapters = dvdInfo.getChapters();
if (chapters != null) {
if (chapters[0].getFirstChapter() == chapters[0].getLastChapter())
inputVideo = "Chapter " + chapters[0].getFirstChapter() + " of " + inputVideo;
else
inputVideo = "Chapters " + chapters[0].getFirstChapter() + "-" + chapters[0].getLastChapter() + " of " + inputVideo;
}
Logger.logMessage("DVD: " + inputVideo, Logger.INFO);
progressDialogInfo.setInputVideo(inputVideo);
progressDialogInfo.setOutputVideo(new File(dvdInfo.getOutputVideo()).getName());
progressDialogInfo.setStatus("Gathering information about the input video...");
MPlayerInfo info = new MPlayerInfo("dvd://" + dvdInfo.getTitle(), dvdInfo.getDrive());
List commandList = prepareBaseCommandList("dvd://" + dvdInfo.getTitle(), dvdInfo.getOutputVideo(), info);
commandList.add("-dvd-device");
commandList.add(dvdInfo.getDrive());
if (dvdInfo.getAudioStream() > -1) {
commandList.add("-aid");
commandList.add("" + dvdInfo.getAudioStream());
}
if (dvdInfo.getSubtitles() > -1) {
commandList.add("-sid");
commandList.add("" + dvdInfo.getSubtitles());
}
if (dvdInfo.getChapters() != null) {
commandList.add("-chapter");
commandList.add(dvdInfo.getChapters()[0].getFirstChapter() + "-" + dvdInfo.getChapters()[0].getLastChapter());
}
String[] command = new String[commandList.size()];
for (int i = 0; i < command.length; i++)
command[i] = (String) commandList.get(i);
if (!isCanceled) {
new File(dvdInfo.getOutputVideo()).getParentFile().mkdirs();
progressDialogInfo.setStatus("Converting");
splitVideo(dvdInfo.getOutputVideo(), runConversionCommand(command));
}
}
public void manuallySplitVideo(ManualSplitInfo manualSplitInfo) {
Logger.logMessage("Manual Split: " + manualSplitInfo.getVideo(), Logger.INFO);
String outputVideo = manualSplitInfo.getVideo().substring(0, manualSplitInfo.getVideo().lastIndexOf('.')) + ".part" + manualSplitInfo.getPart() + ".avi";
progressDialogInfo.setInputVideo(manualSplitInfo.getVideo());
progressDialogInfo.setOutputVideo(outputVideo);
progressDialogInfo.setStatus("Splitting");
if (manualSplitInfo.getMarks()[0].getTime() == Mark.START_MARK)
runConversionCommand(new String[]{MPlayerInfo.getMPlayerPath() + "mencoder", manualSplitInfo.getVideo(), "-o", outputVideo, "-ovc", "copy", "-oac", "copy", "-endpos", "" + manualSplitInfo.getMarks()[1].getTime()});
else if (manualSplitInfo.getMarks()[1].getTime() == Mark.END_MARK)
runConversionCommand(new String[]{MPlayerInfo.getMPlayerPath() + "mencoder", manualSplitInfo.getVideo(), "-o", outputVideo, "-ovc", "copy", "-oac", "copy", "-ss", "" + manualSplitInfo.getMarks()[0].getTime()});
else
runConversionCommand(new String[]{MPlayerInfo.getMPlayerPath() + "mencoder", manualSplitInfo.getVideo(), "-o", outputVideo, "-ovc", "copy", "-oac", "copy", "-ss", "" + manualSplitInfo.getMarks()[0].getTime(), "-endpos", "" + (manualSplitInfo.getMarks()[1].getTime() - manualSplitInfo.getMarks()[0].getTime())});
}
public void joinVideos(JoinVideosInfo joinVideosInfo) {
try {
String[] inputVideos = joinVideosInfo.getInputVideos();
/* String[] tempVideos = new String[inputVideos.length];
for (int i = 0; i < inputVideos.length; i++) {
File tempFile = File.createTempFile("iriverter-", ".avi");
tempFile.deleteOnExit();
progressDialogInfo.setInputVideo(new File(inputVideos[i]).getName());
progressDialogInfo.setOutputVideo(tempFile.getName());
progressDialogInfo.setStatus("Fixing header");
runConversionCommand(new String[]{MPlayerInfo.getMPlayerPath() + "mencoder", "-idx", inputVideos[i], "-o", tempFile.toString(), "-ovc", "copy", "-oac", "copy"});
tempVideos[i] = tempFile.toString();
} */
File tempFile = File.createTempFile("iriverter-", ".avi");
tempFile.deleteOnExit();
Logger.logMessage("Join Videos: " + tempFile, Logger.INFO);
progressDialogInfo.setOutputVideo(tempFile.getName());
progressDialogInfo.setStatus("Concatenating videos to a temporary file...");
FileOutputStream out = new FileOutputStream(tempFile);
// SequenceInputStream in = new SequenceInputStream(new ListOfFiles(tempVideos, progressDialogInfo));
SequenceInputStream in = new SequenceInputStream(new ListOfFiles(inputVideos, progressDialogInfo));
byte[] bytes = new byte[4096];
int length;
while ((length = in.read(bytes)) != -1 && !isCanceled)
out.write(bytes, 0, length);
progressDialogInfo.setPercentComplete(100);
if (!isCanceled) {
Logger.logMessage("Writing header...", Logger.INFO);
progressDialogInfo.setInputVideo(tempFile.getName());
progressDialogInfo.setOutputVideo(new File(joinVideosInfo.getOutputVideo()).getName());
progressDialogInfo.setStatus("Writing header");
splitVideo(joinVideosInfo.getOutputVideo(), runConversionCommand(new String[]{MPlayerInfo.getMPlayerPath() + "mencoder", "-forceidx", tempFile.toString(), "-o", joinVideosInfo.getOutputVideo(), "-ovc", "copy", "-oac", "copy"}));
}
} catch (IOException e) {
// empty
}
}
public int runConversionCommand(String[] command) {
MencoderStreamParser inputStream = null;
MencoderStreamParser errorStream = null;
String commandStr = "";
for (int i = 0; i < command.length; i++)
commandStr += command[i] + " ";
Logger.logMessage(commandStr, Logger.INFO);
try {
proc = Runtime.getRuntime().exec(command);
inputStream = new MencoderStreamParser(progressDialogInfo);
inputStream.parse(new BufferedReader(new InputStreamReader(proc.getInputStream())));
errorStream = new MencoderStreamParser(progressDialogInfo);
errorStream.parse(new BufferedReader(new InputStreamReader(proc.getErrorStream())));
exitCode = proc.waitFor();
proc = null;
} catch (Exception e) {
e.printStackTrace();
}
if (exitCode != 0)
isCanceled = true;
return isCanceled ? 0 : ((errorStream.getLength() > -1) ? errorStream.getLength() : inputStream.getLength());
}
public void splitVideo(String inputVideo, int length) {
if (length < ConverterOptions.getSplitTime() * 60)
return;
if (!ConverterOptions.getAutoSplit()) {
notSplitVideos.add(inputVideo);
return;
}
int pieces = (length / (ConverterOptions.getSplitTime() * 60)) + 1;
for (int i = 0; i < pieces; i++) {
String outputVideo = inputVideo.substring(0, inputVideo.lastIndexOf('.')) + ".part" + (i + 1) + ".avi";
progressDialogInfo.setInputVideo(new File(inputVideo).getName());
progressDialogInfo.setOutputVideo(new File(outputVideo).getName());
progressDialogInfo.setStatus("Splitting");
if ((i + 1) == 1)
runConversionCommand(new String[]{MPlayerInfo.getMPlayerPath() + "mencoder", inputVideo, "-o", outputVideo, "-ovc", "copy", "-oac", "copy", "-endpos", "" + (length / pieces)});
else if ((i + 1) == pieces)
runConversionCommand(new String[]{MPlayerInfo.getMPlayerPath() + "mencoder", inputVideo, "-o", outputVideo, "-ovc", "copy", "-oac", "copy", "-ss", "" + (length / pieces) * i});
else
runConversionCommand(new String[]{MPlayerInfo.getMPlayerPath() + "mencoder", inputVideo, "-o", outputVideo, "-ovc", "copy", "-oac", "copy", "-ss", "" + (length / pieces) * i, "-endpos", "" + (length / pieces)});
}
}
public List getNotSplitVideos() {
return notSplitVideos;
}
}
| true | true | private List prepareBaseCommandList(String inputVideo, String outputVideo, MPlayerInfo info) {
List commandList = new ArrayList();
commandList.add(MPlayerInfo.getMPlayerPath() + "mencoder");
commandList.add(inputVideo);
commandList.add("-o");
commandList.add(outputVideo);
if (ConverterOptions.getCurrentProfile().getWrapperFormat().equals("mp4")) {
commandList.add("-of");
commandList.add("lavf");
commandList.add("-lavfopts");
commandList.add("format=mp4:i_certify_that_my_video_stream_does_not_use_b_frames");
}
commandList.add("-ovc");
if (ConverterOptions.getCurrentProfile().getVideoFormat().equals("h264")) {
commandList.add("x264");
commandList.add("-x264encopts");
commandList.add("bitrate=" + ConverterOptions.getVideoBitrate() + ":bframes=0:level_idc=13:nocabac");
} else {
commandList.add("xvid");
commandList.add("-xvidencopts");
commandList.add("bitrate=" + ConverterOptions.getVideoBitrate() + ":max_bframes=0");
}
commandList.add("-oac");
if (ConverterOptions.getCurrentProfile().getAudioFormat().equals("aac")) {
commandList.add("faac");
commandList.add("-faacopts");
commandList.add("br=" + ConverterOptions.getAudioBitrate() + ":object=1");
} else {
commandList.add("mp3lame");
commandList.add("-lameopts");
commandList.add("mode=2:cbr:br=" + ConverterOptions.getAudioBitrate());
}
double ofps = (info.getFrameRate() > ConverterOptions.getCurrentProfile().getMaxFrameRate() ? ConverterOptions.getCurrentProfile().getMaxFrameRate() : info.getFrameRate());
commandList.add("-vf");
commandList.add("filmdint=io=" + ((int) Math.round(info.getFrameRate() * 1000)) + ":" + ((int) Math.round(ofps * 1000)));
int scaledWidth = ConverterOptions.getDimensions().getWidth();
int scaledHeight = (info.getDimensions().getHeight() * ConverterOptions.getDimensions().getWidth()) / info.getDimensions().getWidth();
if (scaledHeight > ConverterOptions.getDimensions().getHeight()) {
scaledWidth = (scaledWidth * ConverterOptions.getDimensions().getHeight()) / scaledHeight;
scaledHeight = ConverterOptions.getDimensions().getHeight();
}
commandList.add("-vf-add");
if (ConverterOptions.getPanAndScan())
commandList.add("scale=" + ((int) ((info.getDimensions().getWidth()) * (((double) ConverterOptions.getDimensions().getHeight()) / (double) info.getDimensions().getHeight()))) + ":" + ConverterOptions.getDimensions().getHeight() + ",crop=" + ConverterOptions.getDimensions().getWidth() + ":" + ConverterOptions.getDimensions().getHeight());
else
commandList.add("scale=" + scaledWidth + ":" + scaledHeight + ",expand=" + ConverterOptions.getDimensions().getWidth() + ":" + ConverterOptions.getDimensions().getHeight());
commandList.add("-vf-add");
commandList.add("harddup");
if (ConverterOptions.getVolumeFilter() == VolumeFilter.VOLNORM) {
commandList.add("-af");
commandList.add("volnorm");
} else if (ConverterOptions.getVolumeFilter() == VolumeFilter.VOLUME) {
commandList.add("-af");
commandList.add("volume=" + ConverterOptions.getGain());
}
commandList.add("-ofps");
commandList.add("" + ofps);
commandList.add("-srate");
commandList.add("44100");
if (!ConverterOptions.getAutoSync()) {
commandList.add("-delay");
commandList.add("" + (ConverterOptions.getAudioDelay() / 1000.0));
}
return commandList;
}
| private List prepareBaseCommandList(String inputVideo, String outputVideo, MPlayerInfo info) {
List commandList = new ArrayList();
commandList.add(MPlayerInfo.getMPlayerPath() + "mencoder");
commandList.add(inputVideo);
commandList.add("-o");
commandList.add(outputVideo);
if (ConverterOptions.getCurrentProfile().getWrapperFormat().equals("mp4")) {
commandList.add("-of");
commandList.add("lavf");
commandList.add("-lavfopts");
commandList.add("format=mp4:i_certify_that_my_video_stream_does_not_use_b_frames");
}
commandList.add("-ovc");
if (ConverterOptions.getCurrentProfile().getVideoFormat().equals("h264")) {
commandList.add("x264");
commandList.add("-x264encopts");
commandList.add("bitrate=" + ConverterOptions.getVideoBitrate() + ":bframes=0:level_idc=13:nocabac");
} else {
commandList.add("xvid");
commandList.add("-xvidencopts");
commandList.add("bitrate=" + ConverterOptions.getVideoBitrate() + ":max_bframes=0");
}
commandList.add("-oac");
if (ConverterOptions.getCurrentProfile().getAudioFormat().equals("aac")) {
commandList.add("faac");
commandList.add("-faacopts");
commandList.add("br=" + ConverterOptions.getAudioBitrate() + ":object=1");
} else {
commandList.add("mp3lame");
commandList.add("-lameopts");
commandList.add("mode=2:cbr:br=" + ConverterOptions.getAudioBitrate());
}
double ofps = (info.getFrameRate() > ConverterOptions.getCurrentProfile().getMaxFrameRate() ? ConverterOptions.getCurrentProfile().getMaxFrameRate() : info.getFrameRate());
if (info.getFrameRate() != ofps && info.getFrameRate() < 1000) { // HACK: wmv always shows 1000 fps
commandList.add("-vf-add");
commandList.add("filmdint=io=" + ((int) Math.round(info.getFrameRate() * 1000)) + ":" + ((int) Math.round(ofps * 1000)));
}
int scaledWidth = ConverterOptions.getDimensions().getWidth();
int scaledHeight = (info.getDimensions().getHeight() * ConverterOptions.getDimensions().getWidth()) / info.getDimensions().getWidth();
if (scaledHeight > ConverterOptions.getDimensions().getHeight()) {
scaledWidth = (scaledWidth * ConverterOptions.getDimensions().getHeight()) / scaledHeight;
scaledHeight = ConverterOptions.getDimensions().getHeight();
}
commandList.add("-vf-add");
if (ConverterOptions.getPanAndScan())
commandList.add("scale=" + ((int) ((info.getDimensions().getWidth()) * (((double) ConverterOptions.getDimensions().getHeight()) / (double) info.getDimensions().getHeight()))) + ":" + ConverterOptions.getDimensions().getHeight() + ",crop=" + ConverterOptions.getDimensions().getWidth() + ":" + ConverterOptions.getDimensions().getHeight());
else
commandList.add("scale=" + scaledWidth + ":" + scaledHeight + ",expand=" + ConverterOptions.getDimensions().getWidth() + ":" + ConverterOptions.getDimensions().getHeight());
commandList.add("-vf-add");
commandList.add("harddup");
if (ConverterOptions.getVolumeFilter() == VolumeFilter.VOLNORM) {
commandList.add("-af");
commandList.add("volnorm");
} else if (ConverterOptions.getVolumeFilter() == VolumeFilter.VOLUME) {
commandList.add("-af");
commandList.add("volume=" + ConverterOptions.getGain());
}
commandList.add("-ofps");
commandList.add("" + ofps);
commandList.add("-srate");
commandList.add("44100");
if (!ConverterOptions.getAutoSync()) {
commandList.add("-delay");
commandList.add("" + (ConverterOptions.getAudioDelay() / 1000.0));
}
return commandList;
}
|
diff --git a/BarcodeScanner/src/com/github/barcodescanner/database/DatabaseActivity.java b/BarcodeScanner/src/com/github/barcodescanner/database/DatabaseActivity.java
index eed340f..79643ce 100644
--- a/BarcodeScanner/src/com/github/barcodescanner/database/DatabaseActivity.java
+++ b/BarcodeScanner/src/com/github/barcodescanner/database/DatabaseActivity.java
@@ -1,326 +1,327 @@
package com.github.barcodescanner.database;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import com.github.barcodescanner.R;
import com.github.barcodescanner.activities.EmptyDatabaseActivity;
import com.github.barcodescanner.activities.MainActivity;
import com.github.barcodescanner.product.AddManuallyActivity;
import com.github.barcodescanner.product.Product;
import com.github.barcodescanner.product.ProductActivity;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
@SuppressLint("Recycle")
public class DatabaseActivity extends ListActivity {
@SuppressWarnings("unused")
private static final String TAG = "DatabaseActivity";
private DatabaseHelper db;
private List<Product> items = new ArrayList<Product>();
private ListView list;
private boolean adminMode;
private EditText searchBar;
private String searchQuery;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_database);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
adminMode = getIntent().getExtras().getBoolean("adminMode");
DatabaseHelperFactory.init(this);
db = DatabaseHelperFactory.getInstance();
list = (ListView) findViewById(android.R.id.list);
}
@Override
protected void onResume() {
super.onResume();
searchQuery = "";
updateSpecialAdapter();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.database, menu);
setupSearch(menu);
return true;
}
private void setupSearch(Menu menu) {
searchBar = (EditText) menu.findItem(R.id.database_menu_search).getActionView();
searchBar.setEms(10);
searchBar.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
searchBar.setHint(R.string.database_search_hint);
+ searchBar.setCompoundDrawablesWithIntrinsicBounds(R.drawable.action_search, 0, 0, 0);
searchQuery = "";
updateSpecialAdapter();
/**
* Enabling Search Filter
* */
searchBar.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When a user has changed the text in the search widget, we
// update the search query and the special adapter.
searchQuery = cs.toString();
updateSpecialAdapter();
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// Not used, but must be implemented.
}
@Override
public void afterTextChanged(Editable arg0) {
// Not used, but must be implemented.
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent;
switch (item.getItemId()) {
case R.id.database_menu_search:
// This "hack" is to make sure that the keyboard shows up when the
// search bar gains focus. Oh, the things we have to do when we roll
// with our own widgets!
(new Handler()).postDelayed(new Runnable() {
public void run() {
searchBar.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(),
MotionEvent.ACTION_DOWN, 0, 0, 0));
searchBar.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(),
MotionEvent.ACTION_UP, 0, 0, 0));
}
}, 50);
return true;
case R.id.database_menu_create:
intent = new Intent(this, AddManuallyActivity.class);
intent.putExtra("adminMode", adminMode);
startActivity(intent);
return true;
case android.R.id.home:
intent = new Intent(this, MainActivity.class);
intent.putExtra("adminMode", adminMode);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
ViewGroup currentRow = (ViewGroup) getListView().getChildAt(position);
TextView nameView = (TextView) currentRow.getChildAt(0);
TextView priceView = (TextView) currentRow.getChildAt(1);
TextView idView = (TextView) currentRow.getChildAt(2);
String productName = nameView.getText().toString();
Integer productPrice = Integer.parseInt(priceView.getText().toString());
String productId = idView.getText().toString();
Bundle productBundle = new Bundle();
productBundle.putString("productName", productName);
productBundle.putInt("productPrice", productPrice);
productBundle.putString("productId", productId);
productBundle.putBoolean("adminMode", adminMode);
Intent intent = new Intent(this, ProductActivity.class);
intent.putExtras(productBundle);
startActivity(intent);
}
/**
* Updates the SpecialAdapter, which in turn updates the view of the list of
* all the items in the database.
*/
private void updateSpecialAdapter() {
if (db.getProducts().size() == 0) {
searchBar.setHint(R.string.database_empty);
searchBar.clearFocus();
searchBar.setFocusableInTouchMode(false);
searchBar.setFocusable(false);
Intent intent = new Intent(this, EmptyDatabaseActivity.class);
intent.putExtra("adminMode", adminMode);
startActivity(intent);
finish();
}
items = filterList(db.getProducts(), searchQuery);
SpecialAdapter adapter = new SpecialAdapter(this, items);
list.setAdapter(adapter);
}
/**
* A static class that helps the SpecialAdapter generate the database view.
*/
static class ViewHolder {
TextView name, price, id;
}
/**
* Given a listView containing product information and the edit and delete
* buttons, this function takes the product information and asks the
* database to remove the corresponding product, and then updates the
* Special Adapter that handles the database view.
*
* @param listView
* the view containing the information of the product to be
* removed
*/
private void deleteItem(ViewGroup listView) {
if (adminMode) {
ViewGroup currentRow = (ViewGroup) listView.getChildAt(0);
TextView nameView = (TextView) currentRow.getChildAt(0);
TextView idView = (TextView) currentRow.getChildAt(2);
String name = nameView.getText().toString();
String id = idView.getText().toString();
db.removeProduct(id);
Context context = getApplicationContext();
CharSequence text = getString(R.string.database_toast_deleted, name);
Toast toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
toast.show();
// TODO Add confirmation dialog?
updateSpecialAdapter();
}
}
/**
* A special adapter that generates the view that shows the items in the
* database.
*/
private class SpecialAdapter extends BaseAdapter {
// Defining the background color of rows. The row will alternate between
// grey light and grey dark.
private int[] colors = new int[] { 0xAA999999, 0xAA7d7d7d };
private LayoutInflater mInflater;
// The variable that will hold our text data to be tied to list.
private List<Product> data;
public SpecialAdapter(Context context, List<Product> items) {
mInflater = LayoutInflater.from(context);
this.data = items;
}
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
/**
* Given a view, this function returns a view that shows each item in
* the database in a top-down fashion. Every other item has a darker
* gray background, in order to more easily differentiate between each
* item.
*
* @param int position
* @param View
* convertView The view to add all the items to.
* @param ViewGroup
* parent Not used, but this function overrides another
* function so it stays
*
* @return The finished view that shows all the items in the database.
*/
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// A ViewHolder keeps references to children views to avoid
// unnecessary calls to findViewById() on each row.
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.price = (TextView) convertView.findViewById(R.id.price);
holder.id = (TextView) convertView.findViewById(R.id.id);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// Bind the data efficiently with the holder.
holder.name.setText(data.get(position).getName());
holder.price.setText("" + data.get(position).getPrice());
holder.id.setText(data.get(position).getBarcode());
// Set the background color depending of odd/even colorPos result
int colorPos = position % colors.length;
convertView.setBackgroundColor(colors[colorPos]);
return convertView;
}
}
private List<Product> filterList(List<Product> list, String s) {
if (s.equals("")) {
return list;
}
List<Product> newList = new ArrayList<Product>();
for (Product p : list) {
if (p.getName().toLowerCase(Locale.ENGLISH).contains(s.toLowerCase(Locale.ENGLISH))) {
newList.add(p);
}
}
return newList;
}
}
| true | true | private void setupSearch(Menu menu) {
searchBar = (EditText) menu.findItem(R.id.database_menu_search).getActionView();
searchBar.setEms(10);
searchBar.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
searchBar.setHint(R.string.database_search_hint);
searchQuery = "";
updateSpecialAdapter();
/**
* Enabling Search Filter
* */
searchBar.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When a user has changed the text in the search widget, we
// update the search query and the special adapter.
searchQuery = cs.toString();
updateSpecialAdapter();
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// Not used, but must be implemented.
}
@Override
public void afterTextChanged(Editable arg0) {
// Not used, but must be implemented.
}
});
}
| private void setupSearch(Menu menu) {
searchBar = (EditText) menu.findItem(R.id.database_menu_search).getActionView();
searchBar.setEms(10);
searchBar.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
searchBar.setHint(R.string.database_search_hint);
searchBar.setCompoundDrawablesWithIntrinsicBounds(R.drawable.action_search, 0, 0, 0);
searchQuery = "";
updateSpecialAdapter();
/**
* Enabling Search Filter
* */
searchBar.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When a user has changed the text in the search widget, we
// update the search query and the special adapter.
searchQuery = cs.toString();
updateSpecialAdapter();
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// Not used, but must be implemented.
}
@Override
public void afterTextChanged(Editable arg0) {
// Not used, but must be implemented.
}
});
}
|
diff --git a/plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/io/api/DirectoryApiConnectionWrapper.java b/plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/io/api/DirectoryApiConnectionWrapper.java
index c4e802a0f..13b906cf1 100644
--- a/plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/io/api/DirectoryApiConnectionWrapper.java
+++ b/plugins/connection.core/src/main/java/org/apache/directory/studio/connection/core/io/api/DirectoryApiConnectionWrapper.java
@@ -1,1255 +1,1256 @@
/*
* 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.directory.studio.connection.core.io.api;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import javax.naming.ContextNotEmptyException;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.ModificationItem;
import javax.naming.directory.SearchControls;
import javax.naming.ldap.Control;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import javax.security.auth.login.AppConfigurationEntry;
import javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag;
import javax.security.auth.login.Configuration;
import org.apache.commons.lang.StringUtils;
import org.apache.directory.ldap.client.api.CramMd5Request;
import org.apache.directory.ldap.client.api.DigestMd5Request;
import org.apache.directory.ldap.client.api.GssApiRequest;
import org.apache.directory.ldap.client.api.LdapConnectionConfig;
import org.apache.directory.ldap.client.api.LdapNetworkConnection;
import org.apache.directory.ldap.client.api.exception.InvalidConnectionException;
import org.apache.directory.shared.ldap.codec.protocol.mina.LdapProtocolCodecActivator;
import org.apache.directory.shared.ldap.model.cursor.SearchCursor;
import org.apache.directory.shared.ldap.model.entry.AttributeUtils;
import org.apache.directory.shared.ldap.model.entry.DefaultModification;
import org.apache.directory.shared.ldap.model.entry.Modification;
import org.apache.directory.shared.ldap.model.entry.ModificationOperation;
import org.apache.directory.shared.ldap.model.exception.LdapInvalidAttributeValueException;
import org.apache.directory.shared.ldap.model.message.AddRequest;
import org.apache.directory.shared.ldap.model.message.AddRequestImpl;
import org.apache.directory.shared.ldap.model.message.AddResponse;
import org.apache.directory.shared.ldap.model.message.AliasDerefMode;
import org.apache.directory.shared.ldap.model.message.BindRequest;
import org.apache.directory.shared.ldap.model.message.BindRequestImpl;
import org.apache.directory.shared.ldap.model.message.BindResponse;
import org.apache.directory.shared.ldap.model.message.DeleteRequest;
import org.apache.directory.shared.ldap.model.message.DeleteRequestImpl;
import org.apache.directory.shared.ldap.model.message.DeleteResponse;
import org.apache.directory.shared.ldap.model.message.LdapResult;
import org.apache.directory.shared.ldap.model.message.ModifyDnRequest;
import org.apache.directory.shared.ldap.model.message.ModifyDnRequestImpl;
import org.apache.directory.shared.ldap.model.message.ModifyDnResponse;
import org.apache.directory.shared.ldap.model.message.ModifyRequest;
import org.apache.directory.shared.ldap.model.message.ModifyRequestImpl;
import org.apache.directory.shared.ldap.model.message.ModifyResponse;
import org.apache.directory.shared.ldap.model.message.ResultCodeEnum;
import org.apache.directory.shared.ldap.model.message.ResultResponse;
import org.apache.directory.shared.ldap.model.message.SearchRequest;
import org.apache.directory.shared.ldap.model.message.SearchRequestImpl;
import org.apache.directory.shared.ldap.model.message.SearchScope;
import org.apache.directory.shared.ldap.model.name.Dn;
import org.apache.directory.studio.common.core.jobs.StudioProgressMonitor;
import org.apache.directory.studio.connection.core.Connection;
import org.apache.directory.studio.connection.core.Connection.AliasDereferencingMethod;
import org.apache.directory.studio.connection.core.Connection.ReferralHandlingMethod;
import org.apache.directory.studio.connection.core.ConnectionCoreConstants;
import org.apache.directory.studio.connection.core.ConnectionCorePlugin;
import org.apache.directory.studio.connection.core.ConnectionParameter;
import org.apache.directory.studio.connection.core.ConnectionParameter.EncryptionMethod;
import org.apache.directory.studio.connection.core.IAuthHandler;
import org.apache.directory.studio.connection.core.ICredentials;
import org.apache.directory.studio.connection.core.IJndiLogger;
import org.apache.directory.studio.connection.core.Messages;
import org.apache.directory.studio.connection.core.Utils;
import org.apache.directory.studio.connection.core.io.ConnectionWrapper;
import org.apache.directory.studio.connection.core.io.StudioNamingEnumeration;
import org.apache.directory.studio.connection.core.io.StudioTrustManager;
import org.apache.directory.studio.connection.core.io.jndi.CancelException;
import org.apache.directory.studio.connection.core.io.jndi.ReferralsInfo;
import org.eclipse.core.runtime.Preferences;
import org.eclipse.osgi.util.NLS;
/**
* A ConnectionWrapper is a wrapper for a real directory connection implementation.
*
* @author <a href="mailto:[email protected]">Apache Directory Project</a>
*/
public class DirectoryApiConnectionWrapper implements ConnectionWrapper
{
/** The search request number */
private static int SEARCH_RESQUEST_NUM = 0;
/** The connection*/
private Connection connection;
/** The LDAP Connection Configuration */
private LdapConnectionConfig ldapConnectionConfig;
/** The LDAP Connection */
private LdapNetworkConnection ldapConnection;
/** Indicates if the wrapper is connected */
private boolean isConnected = false;
/** The current job thread */
private Thread jobThread;
/** The bind principal */
private String bindPrincipal;
/** The bind password */
private String bindPassword;
/**
* Creates a new instance of JNDIConnectionContext.
*
* @param connection the connection
*/
public DirectoryApiConnectionWrapper( Connection connection )
{
this.connection = connection;
// Nasty hack to get the 'org.apache.directory.shared.ldap.protocol.codec'
// bundle started.
// Instantiating one of this bundle class will trigger the start of the bundle
// thanks to the lazy activation policy
// DO NOT REMOVE
LdapProtocolCodecActivator.lazyStart();
}
/**
* {@inheritDoc}
*/
public void connect( StudioProgressMonitor monitor )
{
ldapConnection = null;
isConnected = false;
jobThread = null;
try
{
doConnect( monitor );
}
catch ( Exception e )
{
disconnect();
monitor.reportError( e );
}
}
private void doConnect( final StudioProgressMonitor monitor ) throws Exception
{
ldapConnection = null;
isConnected = true;
ldapConnectionConfig = new LdapConnectionConfig();
ldapConnectionConfig.setLdapHost( connection.getHost() );
ldapConnectionConfig.setLdapPort( connection.getPort() );
ldapConnectionConfig.setName( connection.getBindPrincipal() );
ldapConnectionConfig.setCredentials( connection.getBindPassword() );
if ( ( connection.getEncryptionMethod() == EncryptionMethod.LDAPS )
|| ( connection.getEncryptionMethod() == EncryptionMethod.START_TLS ) )
{
ldapConnectionConfig.setUseSsl( connection.getEncryptionMethod() == EncryptionMethod.LDAPS );
try
{
// get default trust managers (using JVM "cacerts" key store)
TrustManagerFactory factory = TrustManagerFactory.getInstance( TrustManagerFactory
.getDefaultAlgorithm() );
factory.init( ( KeyStore ) null );
TrustManager[] defaultTrustManagers = factory.getTrustManagers();
// create wrappers around the trust managers
StudioTrustManager[] trustManagers = new StudioTrustManager[defaultTrustManagers.length];
for ( int i = 0; i < defaultTrustManagers.length; i++ )
{
trustManagers[i] = new StudioTrustManager( ( X509TrustManager ) defaultTrustManagers[i] );
trustManagers[i].setHost( connection.getHost() );
}
ldapConnectionConfig.setTrustManagers( trustManagers );
}
catch ( Exception e )
{
e.printStackTrace();
throw new RuntimeException( e );
}
}
InnerRunnable runnable = new InnerRunnable()
{
public void run()
{
try
{
ldapConnection = new LdapNetworkConnection( ldapConnectionConfig );
// Connecting
boolean connected = ldapConnection.connect();
if ( !connected )
{
throw new Exception( "Unable to connect" );
}
// Start TLS
if ( connection.getConnectionParameter().getEncryptionMethod() == ConnectionParameter.EncryptionMethod.START_TLS )
{
ldapConnection.startTls();
}
}
catch ( Exception e )
{
exception = e;
try
{
if ( ldapConnection != null )
{
ldapConnection.close();
}
}
catch ( Exception exception )
{
// Nothing to do
}
finally
{
ldapConnection = null;
}
}
}
};
runAndMonitor( runnable, monitor );
if ( runnable.getException() != null )
{
throw runnable.getException();
}
}
/**
* {@inheritDoc}
*/
public void disconnect()
{
if ( jobThread != null )
{
Thread t = jobThread;
jobThread = null;
t.interrupt();
}
if ( ldapConnection != null )
{
try
{
ldapConnection.unBind();
ldapConnection.close();
}
catch ( Exception e )
{
// ignore
}
ldapConnection = null;
}
isConnected = false;
System.gc();
}
/**
* {@inheritDoc}
*/
public void bind( StudioProgressMonitor monitor )
{
try
{
doBind( monitor );
}
catch ( Exception e )
{
disconnect();
monitor.reportError( e );
}
}
private void doBind( final StudioProgressMonitor monitor ) throws Exception
{
if ( ldapConnection != null && isConnected )
{
InnerRunnable runnable = new InnerRunnable()
{
public void run()
{
try
{
BindResponse bindResponse = null;
// Setup credentials
IAuthHandler authHandler = ConnectionCorePlugin.getDefault().getAuthHandler();
if ( authHandler == null )
{
Exception exception = new Exception( Messages.model__no_auth_handler );
monitor.setCanceled( true );
monitor.reportError( Messages.model__no_auth_handler, exception );
throw exception;
}
ICredentials credentials = authHandler.getCredentials( connection.getConnectionParameter() );
if ( credentials == null )
{
Exception exception = new Exception();
monitor.setCanceled( true );
monitor.reportError( Messages.model__no_credentials, exception );
throw exception;
}
if ( credentials.getBindPrincipal() == null || credentials.getBindPassword() == null )
{
Exception exception = new Exception( Messages.model__no_credentials );
monitor.reportError( Messages.model__no_credentials, exception );
throw exception;
}
bindPrincipal = credentials.getBindPrincipal();
bindPassword = credentials.getBindPassword();
// Simple Authentication
if ( connection.getConnectionParameter().getAuthMethod() == ConnectionParameter.AuthenticationMethod.SIMPLE )
{
BindRequest bindRequest = new BindRequestImpl();
bindRequest.setName( new Dn( bindPrincipal ) );
+ bindRequest.setCredentials( bindPassword );
bindResponse = ldapConnection.bind( bindRequest );
}
// CRAM-MD5 Authentication
else if ( connection.getConnectionParameter().getAuthMethod() == ConnectionParameter.AuthenticationMethod.SASL_CRAM_MD5 )
{
CramMd5Request cramMd5Request = new CramMd5Request();
cramMd5Request.setUsername( bindPrincipal );
cramMd5Request.setCredentials( bindPassword );
cramMd5Request.setQualityOfProtection( connection.getConnectionParameter().getSaslQop() );
cramMd5Request.setSecurityStrength( connection.getConnectionParameter()
.getSaslSecurityStrength() );
cramMd5Request.setMutualAuthentication( connection.getConnectionParameter()
.isSaslMutualAuthentication() );
bindResponse = ldapConnection.bind( cramMd5Request );
}
// DIGEST-MD5 Authentication
else if ( connection.getConnectionParameter().getAuthMethod() == ConnectionParameter.AuthenticationMethod.SASL_DIGEST_MD5 )
{
DigestMd5Request digestMd5Request = new DigestMd5Request();
digestMd5Request.setUsername( bindPrincipal );
digestMd5Request.setCredentials( bindPassword );
digestMd5Request.setRealmName( connection.getConnectionParameter().getSaslRealm() );
digestMd5Request.setQualityOfProtection( connection.getConnectionParameter().getSaslQop() );
digestMd5Request.setSecurityStrength( connection.getConnectionParameter()
.getSaslSecurityStrength() );
digestMd5Request.setMutualAuthentication( connection.getConnectionParameter()
.isSaslMutualAuthentication() );
bindResponse = ldapConnection.bind( digestMd5Request );
}
// GSSAPI Authentication
else if ( connection.getConnectionParameter().getAuthMethod() == ConnectionParameter.AuthenticationMethod.SASL_GSSAPI )
{
GssApiRequest gssApiRequest = new GssApiRequest();
Preferences preferences = ConnectionCorePlugin.getDefault().getPluginPreferences();
boolean useKrb5SystemProperties = preferences
.getBoolean( ConnectionCoreConstants.PREFERENCE_USE_KRB5_SYSTEM_PROPERTIES );
String krb5LoginModule = preferences
.getString( ConnectionCoreConstants.PREFERENCE_KRB5_LOGIN_MODULE );
if ( !useKrb5SystemProperties )
{
gssApiRequest.setUsername( bindPrincipal );
gssApiRequest.setCredentials( bindPassword );
gssApiRequest.setQualityOfProtection( connection
.getConnectionParameter().getSaslQop() );
gssApiRequest.setSecurityStrength( connection
.getConnectionParameter()
.getSaslSecurityStrength() );
gssApiRequest.setMutualAuthentication( connection
.getConnectionParameter()
.isSaslMutualAuthentication() );
gssApiRequest
.setLoginModuleConfiguration( new InnerConfiguration(
krb5LoginModule ) );
switch ( connection.getConnectionParameter().getKrb5Configuration() )
{
case FILE:
gssApiRequest.setKrb5ConfFilePath( connection.getConnectionParameter()
.getKrb5ConfigurationFile() );
break;
case MANUAL:
gssApiRequest.setRealmName( connection.getConnectionParameter().getKrb5Realm() );
gssApiRequest.setKdcHost( connection.getConnectionParameter().getKrb5KdcHost() );
gssApiRequest.setKdcPort( connection.getConnectionParameter().getKrb5KdcPort() );
break;
}
}
bindResponse = ldapConnection.bind( gssApiRequest );
}
checkResponse( bindResponse );
}
catch ( Exception e )
{
exception = e;
}
}
};
runAndMonitor( runnable, monitor );
if ( runnable.getException() != null )
{
throw runnable.getException();
}
}
else
{
throw new Exception( "No Connection" );
}
}
/***
* {@inheritDoc}
*/
public void unbind()
{
disconnect();
}
/**
* {@inheritDoc}
*/
public boolean isConnected()
{
return ( ldapConnection != null && ldapConnection.isConnected() );
}
/**
* {@inheritDoc}
*/
public void setBinaryAttributes( Collection<String> binaryAttributes )
{
}
/**
* {@inheritDoc}
*/
public StudioNamingEnumeration search( final String searchBase, final String filter,
final SearchControls searchControls, final AliasDereferencingMethod aliasesDereferencingMethod,
final ReferralHandlingMethod referralsHandlingMethod, final Control[] controls,
final StudioProgressMonitor monitor, final ReferralsInfo referralsInfo )
{
final long requestNum = SEARCH_RESQUEST_NUM++;
InnerRunnable runnable = new InnerRunnable()
{
public void run()
{
try
{
// Preparing the search request
SearchRequest request = new SearchRequestImpl();
request.setBase( new Dn( searchBase ) );
request.setFilter( filter );
request.setScope( convertSearchScope( searchControls ) );
if ( searchControls.getReturningAttributes() != null )
{
request.addAttributes( searchControls.getReturningAttributes() );
}
request.addAllControls( convertControls( controls ) );
request.setSizeLimit( searchControls.getCountLimit() );
request.setTimeLimit( searchControls.getTimeLimit() );
request.setDerefAliases( convertAliasDerefMode( aliasesDereferencingMethod ) );
// Performing the search operation
SearchCursor cursor = ldapConnection.search( request );
// Returning the result of the search
namingEnumeration = new CursorStudioNamingEnumeration( connection, cursor, searchBase, filter,
searchControls,
aliasesDereferencingMethod, referralsHandlingMethod, controls, requestNum, monitor,
referralsInfo );
}
catch ( Exception e )
{
exception = e;
}
NamingException ne = null;
if ( exception != null )
{
ne = new NamingException( exception.getMessage() );
}
for ( IJndiLogger logger : getJndiLoggers() )
{
if ( namingEnumeration != null )
{
logger.logSearchRequest( connection, searchBase, filter, searchControls,
aliasesDereferencingMethod, controls, requestNum, ne );
}
else
{
logger.logSearchRequest( connection, searchBase, filter, searchControls,
aliasesDereferencingMethod, controls, requestNum, ne );
logger.logSearchResultDone( connection, 0, requestNum, ne );
}
}
}
};
try
{
checkConnectionAndRunAndMonitor( runnable, monitor );
}
catch ( Exception e )
{
monitor.reportError( e );
return null;
}
if ( runnable.isCanceled() )
{
monitor.setCanceled( true );
}
if ( runnable.getException() != null )
{
monitor.reportError( runnable.getException() );
return null;
}
else
{
return runnable.getResult();
}
}
/**
* Converts the search scope.
*
* @param searchControls
* the search controls
* @return
* the associated search scope
*/
private SearchScope convertSearchScope( SearchControls searchControls )
{
int scope = searchControls.getSearchScope();
if ( scope == SearchControls.OBJECT_SCOPE )
{
return SearchScope.OBJECT;
}
else if ( scope == SearchControls.ONELEVEL_SCOPE )
{
return SearchScope.ONELEVEL;
}
else if ( scope == SearchControls.SUBTREE_SCOPE )
{
return SearchScope.SUBTREE;
}
else
{
return SearchScope.SUBTREE;
}
}
/**
* Converts the controls.
*
* @param controls
* an array of controls
* @return
* an array of converted controls
*/
private org.apache.directory.shared.ldap.model.message.Control[] convertControls( Control[] controls )
throws Exception
{
if ( controls != null )
{
org.apache.directory.shared.ldap.model.message.Control[] returningControls =
new org.apache.directory.shared.ldap.model.message.Control[controls.length];
for ( int i = 0; i < controls.length; i++ )
{
Control control = controls[i];
org.apache.directory.shared.ldap.model.message.Control returningControl;
returningControl = ldapConnection.getCodecService().fromJndiControl( control );
returningControls[i] = returningControl;
}
return returningControls;
}
else
{
return new org.apache.directory.shared.ldap.model.message.Control[0];
}
}
/**
* Converts the Alias Dereferencing method.
*
* @param aliasesDereferencingMethod
* the Alias Dereferencing method.
* @return
* the converted Alias Dereferencing method.
*/
private AliasDerefMode convertAliasDerefMode( AliasDereferencingMethod aliasesDereferencingMethod )
{
switch ( aliasesDereferencingMethod )
{
case ALWAYS:
return AliasDerefMode.DEREF_ALWAYS;
case FINDING:
return AliasDerefMode.DEREF_FINDING_BASE_OBJ;
case NEVER:
return AliasDerefMode.NEVER_DEREF_ALIASES;
case SEARCH:
return AliasDerefMode.DEREF_IN_SEARCHING;
default:
return AliasDerefMode.DEREF_ALWAYS;
}
}
/**
* {@inheritDoc}
*/
public void modifyEntry( final String dn, final ModificationItem[] modificationItems, final Control[] controls,
final StudioProgressMonitor monitor, final ReferralsInfo referralsInfo )
{
if ( connection.isReadOnly() )
{
monitor.reportError( NLS.bind( Messages.error__connection_is_readonly, connection.getName() ) );
return;
}
InnerRunnable runnable = new InnerRunnable()
{
public void run()
{
try
{
// Preparing the modify request
ModifyRequest request = new ModifyRequestImpl();
request.setName( new Dn( dn ) );
Modification[] modifications = convertModificationItems( modificationItems );
if ( modifications != null )
{
for ( Modification modification : modifications )
{
request.addModification( modification );
}
}
request.addAllControls( convertControls( controls ) );
// Performing the modify operation
ModifyResponse modifyResponse = ldapConnection.modify( request );
// Checking the response
checkResponse( modifyResponse );
}
catch ( Exception e )
{
exception = e;
}
NamingException ne = null;
if ( exception != null )
{
ne = new NamingException( exception.getMessage() );
}
for ( IJndiLogger logger : getJndiLoggers() )
{
logger.logChangetypeModify( connection, dn, modificationItems, controls, ne );
}
}
};
try
{
checkConnectionAndRunAndMonitor( runnable, monitor );
}
catch ( Exception e )
{
monitor.reportError( e );
}
if ( runnable.isCanceled() )
{
monitor.setCanceled( true );
}
if ( runnable.getException() != null )
{
monitor.reportError( runnable.getException() );
}
}
/**
* Converts modification items.
*
* @param modificationItems
* an array of modification items
* @return
* an array of converted modifications
*/
private Modification[] convertModificationItems( ModificationItem[] modificationItems )
{
if ( modificationItems != null )
{
List<Modification> modifications = new ArrayList<Modification>();
for ( ModificationItem modificationItem : modificationItems )
{
Modification modification = new DefaultModification();
try
{
modification.setAttribute( AttributeUtils.toApiAttribute( modificationItem.getAttribute() ) );
}
catch ( LdapInvalidAttributeValueException liave )
{
// TODO : handle the exception
}
modification.setOperation( convertModificationOperation( modificationItem.getModificationOp() ) );
modifications.add( modification );
}
return modifications.toArray( new Modification[0] );
}
else
{
return null;
}
}
/**
* Converts a modification operation.
*
* @param modificationOp
* a modification operation
* @return
* the converted modification operation
*/
private ModificationOperation convertModificationOperation( int modificationOp )
{
if ( modificationOp == DirContext.ADD_ATTRIBUTE )
{
return ModificationOperation.ADD_ATTRIBUTE;
}
else if ( modificationOp == DirContext.REPLACE_ATTRIBUTE )
{
return ModificationOperation.REPLACE_ATTRIBUTE;
}
else if ( modificationOp == DirContext.REMOVE_ATTRIBUTE )
{
return ModificationOperation.REMOVE_ATTRIBUTE;
}
return null;
}
/**
* {@inheritDoc}
*/
public void renameEntry( final String oldDn, final String newDn, final boolean deleteOldRdn,
final Control[] controls, final StudioProgressMonitor monitor, final ReferralsInfo referralsInfo )
{
if ( connection.isReadOnly() )
{
monitor.reportError( NLS.bind( Messages.error__connection_is_readonly, connection.getName() ) );
return;
}
InnerRunnable runnable = new InnerRunnable()
{
public void run()
{
try
{
// Preparing the rename request
ModifyDnRequest request = new ModifyDnRequestImpl();
request.setName( new Dn( oldDn ) );
request.setDeleteOldRdn( deleteOldRdn );
Dn newName = new Dn( newDn );
request.setNewRdn( newName.getRdn() );
request.setNewSuperior( newName.getParent() );
request.addAllControls( convertControls( controls ) );
// Performing the rename operation
ModifyDnResponse modifyDnResponse = ldapConnection.modifyDn( request );
// Checking the response
checkResponse( modifyDnResponse );
}
catch ( Exception e )
{
exception = e;
}
NamingException ne = null;
if ( exception != null )
{
ne = new NamingException( exception.getMessage() );
}
for ( IJndiLogger logger : getJndiLoggers() )
{
logger.logChangetypeModDn( connection, oldDn, newDn, deleteOldRdn, controls, ne );
}
}
};
try
{
checkConnectionAndRunAndMonitor( runnable, monitor );
}
catch ( Exception e )
{
monitor.reportError( e );
}
if ( runnable.isCanceled() )
{
monitor.setCanceled( true );
}
if ( runnable.getException() != null )
{
monitor.reportError( runnable.getException() );
}
}
/**
* {@inheritDoc}
*/
public void createEntry( final String dn, final Attributes attributes, final Control[] controls,
final StudioProgressMonitor monitor, final ReferralsInfo referralsInfo )
{
if ( connection.isReadOnly() )
{
monitor.reportError( NLS.bind( Messages.error__connection_is_readonly, connection.getName() ) );
return;
}
InnerRunnable runnable = new InnerRunnable()
{
public void run()
{
try
{
// Preparing the add request
AddRequest request = new AddRequestImpl();
request.setEntryDn( new Dn( dn ) );
request.setEntry( AttributeUtils.toEntry( attributes, new Dn( dn ) ) );
request.addAllControls( convertControls( controls ) );
// Performing the add operation
AddResponse addResponse = ldapConnection.add( request );
// Checking the response
checkResponse( addResponse );
}
catch ( Exception e )
{
exception = e;
}
NamingException ne = null;
if ( exception != null )
{
ne = new NamingException( exception.getMessage() );
}
for ( IJndiLogger logger : getJndiLoggers() )
{
logger.logChangetypeAdd( connection, dn, attributes, controls, ne );
}
}
};
try
{
checkConnectionAndRunAndMonitor( runnable, monitor );
}
catch ( Exception e )
{
monitor.reportError( e );
}
if ( runnable.isCanceled() )
{
monitor.setCanceled( true );
}
if ( runnable.getException() != null )
{
monitor.reportError( runnable.getException() );
}
}
/**
* {@inheritDoc}
*/
public void deleteEntry( final String dn, final Control[] controls, final StudioProgressMonitor monitor,
final ReferralsInfo referralsInfo )
{
if ( connection.isReadOnly() )
{
monitor.reportError( NLS.bind( Messages.error__connection_is_readonly, connection.getName() ) );
return;
}
InnerRunnable runnable = new InnerRunnable()
{
public void run()
{
try
{
// Preparing the delete request
DeleteRequest request = new DeleteRequestImpl();
request.setName( new Dn( dn ) );
request.addAllControls( convertControls( controls ) );
// Performing the delete operation
DeleteResponse deleteResponse = ldapConnection.delete( request );
// Checking the response
checkResponse( deleteResponse );
}
catch ( Exception e )
{
exception = e;
}
NamingException ne = null;
if ( exception != null )
{
ne = new NamingException( exception.getMessage() );
}
for ( IJndiLogger logger : getJndiLoggers() )
{
logger.logChangetypeDelete( connection, dn, controls, ne );
}
}
};
try
{
checkConnectionAndRunAndMonitor( runnable, monitor );
}
catch ( Exception e )
{
monitor.reportError( e );
}
if ( runnable.isCanceled() )
{
monitor.setCanceled( true );
}
if ( runnable.getException() != null )
{
monitor.reportError( runnable.getException() );
}
}
/**
* Inner runnable used in connection wrapper operations.
*
* @author <a href="mailto:[email protected]">Apache Directory Project</a>
*/
abstract class InnerRunnable implements Runnable
{
protected StudioNamingEnumeration namingEnumeration = null;
protected Exception exception = null;
protected boolean canceled = false;
/**
* Gets the exception.
*
* @return the exception
*/
public Exception getException()
{
return exception;
}
/**
* Gets the result.
*
* @return the result
*/
public StudioNamingEnumeration getResult()
{
return namingEnumeration;
}
/**
* Checks if is canceled.
*
* @return true, if is canceled
*/
public boolean isCanceled()
{
return canceled;
}
/**
* Reset.
*/
public void reset()
{
namingEnumeration = null;
exception = null;
canceled = false;
}
}
private void checkConnectionAndRunAndMonitor( final InnerRunnable runnable, final StudioProgressMonitor monitor )
throws Exception
{
// check connection
if ( !isConnected || ldapConnection == null )
{
doConnect( monitor );
doBind( monitor );
}
if ( ldapConnection == null )
{
throw new NamingException( "No Connection" );
}
// loop for reconnection
for ( int i = 0; i <= 1; i++ )
{
runAndMonitor( runnable, monitor );
// check reconnection
if ( i == 0
&& runnable.getException() != null
&& ( ( runnable.getException() instanceof InvalidConnectionException ) ) )
{
doConnect( monitor );
doBind( monitor );
runnable.reset();
}
else
{
break;
}
}
}
private void runAndMonitor( final InnerRunnable runnable, final StudioProgressMonitor monitor )
throws CancelException
{
if ( !monitor.isCanceled() )
{
// monitor
StudioProgressMonitor.CancelListener listener = new StudioProgressMonitor.CancelListener()
{
public void cancelRequested( StudioProgressMonitor.CancelEvent event )
{
if ( monitor.isCanceled() )
{
if ( jobThread != null && jobThread.isAlive() )
{
jobThread.interrupt();
}
if ( ldapConnection != null )
{
try
{
ldapConnection.close();
}
catch ( Exception e )
{
}
isConnected = false;
ldapConnection = null;
System.gc();
}
isConnected = false;
}
}
};
monitor.addCancelListener( listener );
jobThread = Thread.currentThread();
// run
try
{
// try {
// Thread.sleep(5000);
// } catch (InterruptedException e) {
// System.out.println(System.currentTimeMillis() + ": sleep
// interrupted!");
// }
// System.out.println(System.currentTimeMillis() + ": " +
// runnable);
runnable.run();
}
finally
{
monitor.removeCancelListener( listener );
jobThread = null;
}
if ( monitor.isCanceled() )
{
throw new CancelException();
}
}
}
private final class InnerConfiguration extends Configuration
{
private String krb5LoginModule;
private AppConfigurationEntry[] configList = null;
public InnerConfiguration( String krb5LoginModule )
{
this.krb5LoginModule = krb5LoginModule;
}
public AppConfigurationEntry[] getAppConfigurationEntry( String applicationName )
{
if ( configList == null )
{
HashMap<String, Object> options = new HashMap<String, Object>();
// TODO: this only works for Sun JVM
options.put( "refreshKrb5Config", "true" );
switch ( connection.getConnectionParameter().getKrb5CredentialConfiguration() )
{
case USE_NATIVE:
options.put( "useTicketCache", "true" );
options.put( "doNotPrompt", "true" );
break;
case OBTAIN_TGT:
options.put( "doNotPrompt", "false" );
break;
}
configList = new AppConfigurationEntry[1];
configList[0] = new AppConfigurationEntry( krb5LoginModule, LoginModuleControlFlag.REQUIRED, options );
}
return configList;
}
public void refresh()
{
}
}
private List<IJndiLogger> getJndiLoggers()
{
return ConnectionCorePlugin.getDefault().getJndiLoggers();
}
/**
* Checks the given response.
*
* @param response
* the response
* @throws Exception
* if the LDAP result associated with the response is not a success
*/
private void checkResponse( ResultResponse response ) throws Exception
{
if ( response != null )
{
LdapResult ldapResult = response.getLdapResult();
if ( ldapResult != null )
{
// NOT_ALLOWED_ON_NON_LEAF error (thrown when deleting a entry with children
if ( ResultCodeEnum.NOT_ALLOWED_ON_NON_LEAF.equals( ldapResult.getResultCode() ) )
{
throw new ContextNotEmptyException( ldapResult.getDiagnosticMessage() );
}
// Different from SUCCESS, we throw a generic exception
else if ( !ResultCodeEnum.SUCCESS.equals( ldapResult.getResultCode() ) )
{
int code = ldapResult.getResultCode().getResultCode();
String message = ldapResult.getDiagnosticMessage();
// Checking if we got a message from the LDAP result
if ( StringUtils.isEmpty( message ) )
{
// Assigning the generic result code description
message = Utils.getResultCodeDescription( code );
}
throw new Exception( NLS.bind( "[LDAP: error code {0} - {1}]", new String[]
{ code + "", message } ) );
}
}
}
}
}
| true | true | private void doBind( final StudioProgressMonitor monitor ) throws Exception
{
if ( ldapConnection != null && isConnected )
{
InnerRunnable runnable = new InnerRunnable()
{
public void run()
{
try
{
BindResponse bindResponse = null;
// Setup credentials
IAuthHandler authHandler = ConnectionCorePlugin.getDefault().getAuthHandler();
if ( authHandler == null )
{
Exception exception = new Exception( Messages.model__no_auth_handler );
monitor.setCanceled( true );
monitor.reportError( Messages.model__no_auth_handler, exception );
throw exception;
}
ICredentials credentials = authHandler.getCredentials( connection.getConnectionParameter() );
if ( credentials == null )
{
Exception exception = new Exception();
monitor.setCanceled( true );
monitor.reportError( Messages.model__no_credentials, exception );
throw exception;
}
if ( credentials.getBindPrincipal() == null || credentials.getBindPassword() == null )
{
Exception exception = new Exception( Messages.model__no_credentials );
monitor.reportError( Messages.model__no_credentials, exception );
throw exception;
}
bindPrincipal = credentials.getBindPrincipal();
bindPassword = credentials.getBindPassword();
// Simple Authentication
if ( connection.getConnectionParameter().getAuthMethod() == ConnectionParameter.AuthenticationMethod.SIMPLE )
{
BindRequest bindRequest = new BindRequestImpl();
bindRequest.setName( new Dn( bindPrincipal ) );
bindResponse = ldapConnection.bind( bindRequest );
}
// CRAM-MD5 Authentication
else if ( connection.getConnectionParameter().getAuthMethod() == ConnectionParameter.AuthenticationMethod.SASL_CRAM_MD5 )
{
CramMd5Request cramMd5Request = new CramMd5Request();
cramMd5Request.setUsername( bindPrincipal );
cramMd5Request.setCredentials( bindPassword );
cramMd5Request.setQualityOfProtection( connection.getConnectionParameter().getSaslQop() );
cramMd5Request.setSecurityStrength( connection.getConnectionParameter()
.getSaslSecurityStrength() );
cramMd5Request.setMutualAuthentication( connection.getConnectionParameter()
.isSaslMutualAuthentication() );
bindResponse = ldapConnection.bind( cramMd5Request );
}
// DIGEST-MD5 Authentication
else if ( connection.getConnectionParameter().getAuthMethod() == ConnectionParameter.AuthenticationMethod.SASL_DIGEST_MD5 )
{
DigestMd5Request digestMd5Request = new DigestMd5Request();
digestMd5Request.setUsername( bindPrincipal );
digestMd5Request.setCredentials( bindPassword );
digestMd5Request.setRealmName( connection.getConnectionParameter().getSaslRealm() );
digestMd5Request.setQualityOfProtection( connection.getConnectionParameter().getSaslQop() );
digestMd5Request.setSecurityStrength( connection.getConnectionParameter()
.getSaslSecurityStrength() );
digestMd5Request.setMutualAuthentication( connection.getConnectionParameter()
.isSaslMutualAuthentication() );
bindResponse = ldapConnection.bind( digestMd5Request );
}
// GSSAPI Authentication
else if ( connection.getConnectionParameter().getAuthMethod() == ConnectionParameter.AuthenticationMethod.SASL_GSSAPI )
{
GssApiRequest gssApiRequest = new GssApiRequest();
Preferences preferences = ConnectionCorePlugin.getDefault().getPluginPreferences();
boolean useKrb5SystemProperties = preferences
.getBoolean( ConnectionCoreConstants.PREFERENCE_USE_KRB5_SYSTEM_PROPERTIES );
String krb5LoginModule = preferences
.getString( ConnectionCoreConstants.PREFERENCE_KRB5_LOGIN_MODULE );
if ( !useKrb5SystemProperties )
{
gssApiRequest.setUsername( bindPrincipal );
gssApiRequest.setCredentials( bindPassword );
gssApiRequest.setQualityOfProtection( connection
.getConnectionParameter().getSaslQop() );
gssApiRequest.setSecurityStrength( connection
.getConnectionParameter()
.getSaslSecurityStrength() );
gssApiRequest.setMutualAuthentication( connection
.getConnectionParameter()
.isSaslMutualAuthentication() );
gssApiRequest
.setLoginModuleConfiguration( new InnerConfiguration(
krb5LoginModule ) );
switch ( connection.getConnectionParameter().getKrb5Configuration() )
{
case FILE:
gssApiRequest.setKrb5ConfFilePath( connection.getConnectionParameter()
.getKrb5ConfigurationFile() );
break;
case MANUAL:
gssApiRequest.setRealmName( connection.getConnectionParameter().getKrb5Realm() );
gssApiRequest.setKdcHost( connection.getConnectionParameter().getKrb5KdcHost() );
gssApiRequest.setKdcPort( connection.getConnectionParameter().getKrb5KdcPort() );
break;
}
}
bindResponse = ldapConnection.bind( gssApiRequest );
}
checkResponse( bindResponse );
}
catch ( Exception e )
{
exception = e;
}
}
};
runAndMonitor( runnable, monitor );
if ( runnable.getException() != null )
{
throw runnable.getException();
}
}
else
{
throw new Exception( "No Connection" );
}
}
| private void doBind( final StudioProgressMonitor monitor ) throws Exception
{
if ( ldapConnection != null && isConnected )
{
InnerRunnable runnable = new InnerRunnable()
{
public void run()
{
try
{
BindResponse bindResponse = null;
// Setup credentials
IAuthHandler authHandler = ConnectionCorePlugin.getDefault().getAuthHandler();
if ( authHandler == null )
{
Exception exception = new Exception( Messages.model__no_auth_handler );
monitor.setCanceled( true );
monitor.reportError( Messages.model__no_auth_handler, exception );
throw exception;
}
ICredentials credentials = authHandler.getCredentials( connection.getConnectionParameter() );
if ( credentials == null )
{
Exception exception = new Exception();
monitor.setCanceled( true );
monitor.reportError( Messages.model__no_credentials, exception );
throw exception;
}
if ( credentials.getBindPrincipal() == null || credentials.getBindPassword() == null )
{
Exception exception = new Exception( Messages.model__no_credentials );
monitor.reportError( Messages.model__no_credentials, exception );
throw exception;
}
bindPrincipal = credentials.getBindPrincipal();
bindPassword = credentials.getBindPassword();
// Simple Authentication
if ( connection.getConnectionParameter().getAuthMethod() == ConnectionParameter.AuthenticationMethod.SIMPLE )
{
BindRequest bindRequest = new BindRequestImpl();
bindRequest.setName( new Dn( bindPrincipal ) );
bindRequest.setCredentials( bindPassword );
bindResponse = ldapConnection.bind( bindRequest );
}
// CRAM-MD5 Authentication
else if ( connection.getConnectionParameter().getAuthMethod() == ConnectionParameter.AuthenticationMethod.SASL_CRAM_MD5 )
{
CramMd5Request cramMd5Request = new CramMd5Request();
cramMd5Request.setUsername( bindPrincipal );
cramMd5Request.setCredentials( bindPassword );
cramMd5Request.setQualityOfProtection( connection.getConnectionParameter().getSaslQop() );
cramMd5Request.setSecurityStrength( connection.getConnectionParameter()
.getSaslSecurityStrength() );
cramMd5Request.setMutualAuthentication( connection.getConnectionParameter()
.isSaslMutualAuthentication() );
bindResponse = ldapConnection.bind( cramMd5Request );
}
// DIGEST-MD5 Authentication
else if ( connection.getConnectionParameter().getAuthMethod() == ConnectionParameter.AuthenticationMethod.SASL_DIGEST_MD5 )
{
DigestMd5Request digestMd5Request = new DigestMd5Request();
digestMd5Request.setUsername( bindPrincipal );
digestMd5Request.setCredentials( bindPassword );
digestMd5Request.setRealmName( connection.getConnectionParameter().getSaslRealm() );
digestMd5Request.setQualityOfProtection( connection.getConnectionParameter().getSaslQop() );
digestMd5Request.setSecurityStrength( connection.getConnectionParameter()
.getSaslSecurityStrength() );
digestMd5Request.setMutualAuthentication( connection.getConnectionParameter()
.isSaslMutualAuthentication() );
bindResponse = ldapConnection.bind( digestMd5Request );
}
// GSSAPI Authentication
else if ( connection.getConnectionParameter().getAuthMethod() == ConnectionParameter.AuthenticationMethod.SASL_GSSAPI )
{
GssApiRequest gssApiRequest = new GssApiRequest();
Preferences preferences = ConnectionCorePlugin.getDefault().getPluginPreferences();
boolean useKrb5SystemProperties = preferences
.getBoolean( ConnectionCoreConstants.PREFERENCE_USE_KRB5_SYSTEM_PROPERTIES );
String krb5LoginModule = preferences
.getString( ConnectionCoreConstants.PREFERENCE_KRB5_LOGIN_MODULE );
if ( !useKrb5SystemProperties )
{
gssApiRequest.setUsername( bindPrincipal );
gssApiRequest.setCredentials( bindPassword );
gssApiRequest.setQualityOfProtection( connection
.getConnectionParameter().getSaslQop() );
gssApiRequest.setSecurityStrength( connection
.getConnectionParameter()
.getSaslSecurityStrength() );
gssApiRequest.setMutualAuthentication( connection
.getConnectionParameter()
.isSaslMutualAuthentication() );
gssApiRequest
.setLoginModuleConfiguration( new InnerConfiguration(
krb5LoginModule ) );
switch ( connection.getConnectionParameter().getKrb5Configuration() )
{
case FILE:
gssApiRequest.setKrb5ConfFilePath( connection.getConnectionParameter()
.getKrb5ConfigurationFile() );
break;
case MANUAL:
gssApiRequest.setRealmName( connection.getConnectionParameter().getKrb5Realm() );
gssApiRequest.setKdcHost( connection.getConnectionParameter().getKrb5KdcHost() );
gssApiRequest.setKdcPort( connection.getConnectionParameter().getKrb5KdcPort() );
break;
}
}
bindResponse = ldapConnection.bind( gssApiRequest );
}
checkResponse( bindResponse );
}
catch ( Exception e )
{
exception = e;
}
}
};
runAndMonitor( runnable, monitor );
if ( runnable.getException() != null )
{
throw runnable.getException();
}
}
else
{
throw new Exception( "No Connection" );
}
}
|
diff --git a/src/scratchpad/src/org/apache/poi/hwpf/converter/AbstractWordConverter.java b/src/scratchpad/src/org/apache/poi/hwpf/converter/AbstractWordConverter.java
index 38968f082..dbb337a8f 100644
--- a/src/scratchpad/src/org/apache/poi/hwpf/converter/AbstractWordConverter.java
+++ b/src/scratchpad/src/org/apache/poi/hwpf/converter/AbstractWordConverter.java
@@ -1,808 +1,808 @@
/* ====================================================================
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.poi.hwpf.converter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.HWPFDocumentCore;
import org.apache.poi.hwpf.converter.FontReplacer.Triplet;
import org.apache.poi.hwpf.model.Field;
import org.apache.poi.hwpf.model.FieldsDocumentPart;
import org.apache.poi.hwpf.model.ListFormatOverride;
import org.apache.poi.hwpf.model.ListTables;
import org.apache.poi.hwpf.usermodel.Bookmark;
import org.apache.poi.hwpf.usermodel.CharacterRun;
import org.apache.poi.hwpf.usermodel.Notes;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.hwpf.usermodel.Section;
import org.apache.poi.hwpf.usermodel.Table;
import org.apache.poi.hwpf.usermodel.TableCell;
import org.apache.poi.hwpf.usermodel.TableRow;
import org.apache.poi.util.POILogFactory;
import org.apache.poi.util.POILogger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public abstract class AbstractWordConverter
{
private static final byte BEL_MARK = 7;
private static final byte FIELD_BEGIN_MARK = 19;
private static final byte FIELD_END_MARK = 21;
private static final byte FIELD_SEPARATOR_MARK = 20;
private static final POILogger logger = POILogFactory
.getLogger( AbstractWordConverter.class );
private static final byte SPECCHAR_AUTONUMBERED_FOOTNOTE_REFERENCE = 2;
private static final char UNICODECHAR_NONBREAKING_HYPHEN = '\u2011';
private static final char UNICODECHAR_ZERO_WIDTH_SPACE = '\u200b';
private final Set<Bookmark> bookmarkStack = new LinkedHashSet<Bookmark>();
private FontReplacer fontReplacer = new DefaultFontReplacer();
protected Triplet getCharacterRunTriplet( CharacterRun characterRun )
{
Triplet original = new Triplet();
original.bold = characterRun.isBold();
original.italic = characterRun.isItalic();
original.fontName = characterRun.getFontName();
Triplet updated = getFontReplacer().update( original );
return updated;
}
public abstract Document getDocument();
public FontReplacer getFontReplacer()
{
return fontReplacer;
}
protected int getNumberColumnsSpanned( int[] tableCellEdges,
int currentEdgeIndex, TableCell tableCell )
{
int nextEdgeIndex = currentEdgeIndex;
int colSpan = 0;
int cellRightEdge = tableCell.getLeftEdge() + tableCell.getWidth();
while ( tableCellEdges[nextEdgeIndex] < cellRightEdge )
{
colSpan++;
nextEdgeIndex++;
}
return colSpan;
}
protected int getNumberRowsSpanned( Table table, int currentRowIndex,
int currentColumnIndex, TableCell tableCell )
{
if ( !tableCell.isFirstVerticallyMerged() )
return 1;
final int numRows = table.numRows();
int count = 1;
for ( int r1 = currentRowIndex + 1; r1 < numRows; r1++ )
{
TableRow nextRow = table.getRow( r1 );
if ( nextRow.numCells() < currentColumnIndex )
break;
TableCell nextCell = nextRow.getCell( currentColumnIndex );
if ( !nextCell.isVerticallyMerged()
|| nextCell.isFirstVerticallyMerged() )
break;
count++;
}
return count;
}
protected int getTableCellEdgesIndexSkipCount( Table table, int r,
int[] tableCellEdges, int currentEdgeIndex, int c,
TableCell tableCell )
{
TableCell upperCell = null;
for ( int r1 = r - 1; r1 >= 0; r1-- )
{
final TableCell prevCell = table.getRow( r1 ).getCell( c );
if ( prevCell != null && prevCell.isFirstVerticallyMerged() )
{
upperCell = prevCell;
break;
}
}
if ( upperCell == null )
{
logger.log( POILogger.WARN, "First vertically merged cell for ",
tableCell, " not found" );
return 0;
}
return getNumberColumnsSpanned( tableCellEdges, currentEdgeIndex,
tableCell );
}
protected abstract void outputCharacters( Element block,
CharacterRun characterRun, String text );
/**
* Wrap range into bookmark(s) and process it. All bookmarks have starts
* equal to range start and ends equal to range end. Usually it's only one
* bookmark.
*/
protected abstract void processBookmarks( HWPFDocumentCore wordDocument,
Element currentBlock, Range range, int currentTableLevel,
List<Bookmark> rangeBookmarks );
protected boolean processCharacters( HWPFDocumentCore document,
int currentTableLevel, Range range, final Element block )
{
if ( range == null )
return false;
boolean haveAnyText = false;
if ( document instanceof HWPFDocument )
{
final HWPFDocument doc = (HWPFDocument) document;
Map<Integer, List<Bookmark>> rangeBookmarks = doc.getBookmarks()
.getBookmarksStartedBetween( range.getStartOffset(),
range.getEndOffset() );
if ( rangeBookmarks != null && !rangeBookmarks.isEmpty() )
{
boolean processedAny = processRangeBookmarks( doc,
currentTableLevel, range, block, rangeBookmarks );
if ( processedAny )
return true;
}
}
for ( int c = 0; c < range.numCharacterRuns(); c++ )
{
CharacterRun characterRun = range.getCharacterRun( c );
if ( characterRun == null )
throw new AssertionError();
if ( document instanceof HWPFDocument
&& ( (HWPFDocument) document ).getPicturesTable()
.hasPicture( characterRun ) )
{
HWPFDocument newFormat = (HWPFDocument) document;
Picture picture = newFormat.getPicturesTable().extractPicture(
characterRun, true );
processImage( block, characterRun.text().charAt( 0 ) == 0x01,
picture );
continue;
}
String text = characterRun.text();
if ( text.getBytes().length == 0 )
continue;
if ( characterRun.isSpecialCharacter() )
{
if ( text.charAt( 0 ) == SPECCHAR_AUTONUMBERED_FOOTNOTE_REFERENCE
&& ( document instanceof HWPFDocument ) )
{
HWPFDocument doc = (HWPFDocument) document;
processNoteAnchor( doc, characterRun, block );
continue;
}
}
if ( text.getBytes()[0] == FIELD_BEGIN_MARK )
{
if ( document instanceof HWPFDocument )
{
Field aliveField = ( (HWPFDocument) document )
.getFieldsTables().lookupFieldByStartOffset(
FieldsDocumentPart.MAIN,
characterRun.getStartOffset() );
if ( aliveField != null )
{
processField( ( (HWPFDocument) document ), range,
currentTableLevel, aliveField, block );
int continueAfter = aliveField.getFieldEndOffset();
while ( c < range.numCharacterRuns()
&& range.getCharacterRun( c ).getEndOffset() <= continueAfter )
c++;
if ( c < range.numCharacterRuns() )
c--;
continue;
}
}
int skipTo = tryDeadField( document, range, currentTableLevel,
c, block );
if ( skipTo != c )
{
c = skipTo;
continue;
}
continue;
}
if ( text.getBytes()[0] == FIELD_SEPARATOR_MARK )
{
// shall not appear without FIELD_BEGIN_MARK
continue;
}
if ( text.getBytes()[0] == FIELD_END_MARK )
{
// shall not appear without FIELD_BEGIN_MARK
continue;
}
if ( characterRun.isSpecialCharacter() || characterRun.isObj()
|| characterRun.isOle2() )
{
continue;
}
if ( text.endsWith( "\r" )
|| ( text.charAt( text.length() - 1 ) == BEL_MARK && currentTableLevel != Integer.MIN_VALUE ) )
text = text.substring( 0, text.length() - 1 );
{
// line breaks
StringBuilder stringBuilder = new StringBuilder();
for ( char charChar : text.toCharArray() )
{
if ( charChar == 11 )
{
if ( stringBuilder.length() > 0 )
{
outputCharacters( block, characterRun,
stringBuilder.toString() );
stringBuilder.setLength( 0 );
}
processLineBreak( block, characterRun );
}
else if ( charChar == 30 )
{
// Non-breaking hyphens are stored as ASCII 30
stringBuilder.append( UNICODECHAR_NONBREAKING_HYPHEN );
}
else if ( charChar == 31 )
{
// Non-required hyphens to zero-width space
stringBuilder.append( UNICODECHAR_ZERO_WIDTH_SPACE );
}
- else if ( charChar > 0x20 || charChar == 0x09
+ else if ( charChar >= 0x20 || charChar == 0x09
|| charChar == 0x0A || charChar == 0x0D )
{
stringBuilder.append( charChar );
}
}
if ( stringBuilder.length() > 0 )
{
outputCharacters( block, characterRun,
stringBuilder.toString() );
stringBuilder.setLength( 0 );
}
}
haveAnyText |= text.trim().length() != 0;
}
return haveAnyText;
}
protected void processDeadField( HWPFDocumentCore wordDocument,
Element currentBlock, Range range, int currentTableLevel,
int beginMark, int separatorMark, int endMark )
{
StringBuilder debug = new StringBuilder( "Unsupported field type: \n" );
for ( int i = beginMark; i <= endMark; i++ )
{
debug.append( "\t" );
debug.append( range.getCharacterRun( i ) );
debug.append( "\n" );
}
logger.log( POILogger.WARN, debug );
Range deadFieldValueSubrage = new Range( range.getCharacterRun(
separatorMark ).getStartOffset() + 1, range.getCharacterRun(
endMark ).getStartOffset(), range )
{
@Override
public String toString()
{
return "DeadFieldValueSubrange (" + super.toString() + ")";
}
};
// just output field value
if ( separatorMark + 1 < endMark )
processCharacters( wordDocument, currentTableLevel,
deadFieldValueSubrage, currentBlock );
return;
}
public void processDocument( HWPFDocumentCore wordDocument )
{
final SummaryInformation summaryInformation = wordDocument
.getSummaryInformation();
if ( summaryInformation != null )
{
processDocumentInformation( summaryInformation );
}
processDocumentPart( wordDocument, wordDocument.getRange() );
}
protected abstract void processDocumentInformation(
SummaryInformation summaryInformation );
protected void processDocumentPart( HWPFDocumentCore wordDocument,
final Range range )
{
if ( range.numSections() == 1 )
{
processSingleSection( wordDocument, range.getSection( 0 ) );
return;
}
for ( int s = 0; s < range.numSections(); s++ )
{
processSection( wordDocument, range.getSection( s ), s );
}
}
protected abstract void processEndnoteAutonumbered( HWPFDocument doc,
int noteIndex, Element block, Range endnoteTextRange );
protected void processField( HWPFDocument hwpfDocument, Range parentRange,
int currentTableLevel, Field field, Element currentBlock )
{
switch ( field.getType() )
{
case 37: // page reference
{
final Range firstSubrange = field.firstSubrange( parentRange );
if ( firstSubrange != null )
{
String formula = firstSubrange.text();
Pattern pagerefPattern = Pattern
.compile( "[ \\t\\r\\n]*PAGEREF ([^ ]*)[ \\t\\r\\n]*\\\\h[ \\t\\r\\n]*" );
Matcher matcher = pagerefPattern.matcher( formula );
if ( matcher.find() )
{
String pageref = matcher.group( 1 );
processPageref( hwpfDocument, currentBlock,
field.secondSubrange( parentRange ),
currentTableLevel, pageref );
return;
}
}
break;
}
case 88: // hyperlink
{
final Range firstSubrange = field.firstSubrange( parentRange );
if ( firstSubrange != null )
{
String formula = firstSubrange.text();
Pattern hyperlinkPattern = Pattern
.compile( "[ \\t\\r\\n]*HYPERLINK \"(.*)\"[ \\t\\r\\n]*" );
Matcher matcher = hyperlinkPattern.matcher( formula );
if ( matcher.find() )
{
String hyperlink = matcher.group( 1 );
processHyperlink( hwpfDocument, currentBlock,
field.secondSubrange( parentRange ),
currentTableLevel, hyperlink );
return;
}
}
break;
}
}
logger.log( POILogger.WARN, parentRange + " contains " + field
+ " with unsupported type or format" );
processCharacters( hwpfDocument, currentTableLevel,
field.secondSubrange( parentRange ), currentBlock );
}
protected Field processField( HWPFDocumentCore wordDocument,
Range charactersRange, int currentTableLevel, int startOffset,
Element currentBlock )
{
if ( !( wordDocument instanceof HWPFDocument ) )
return null;
HWPFDocument hwpfDocument = (HWPFDocument) wordDocument;
Field field = hwpfDocument.getFieldsTables().lookupFieldByStartOffset(
FieldsDocumentPart.MAIN, startOffset );
if ( field == null )
return null;
processField( hwpfDocument, charactersRange, currentTableLevel, field,
currentBlock );
return field;
}
protected abstract void processFootnoteAutonumbered( HWPFDocument doc,
int noteIndex, Element block, Range footnoteTextRange );
protected abstract void processHyperlink( HWPFDocumentCore wordDocument,
Element currentBlock, Range textRange, int currentTableLevel,
String hyperlink );
protected abstract void processImage( Element currentBlock,
boolean inlined, Picture picture );
protected abstract void processLineBreak( Element block,
CharacterRun characterRun );
protected void processNoteAnchor( HWPFDocument doc,
CharacterRun characterRun, final Element block )
{
{
Notes footnotes = doc.getFootnotes();
int noteIndex = footnotes
.getNoteIndexByAnchorPosition( characterRun
.getStartOffset() );
if ( noteIndex != -1 )
{
Range footnoteRange = doc.getFootnoteRange();
int rangeStartOffset = footnoteRange.getStartOffset();
int noteTextStartOffset = footnotes
.getNoteTextStartOffset( noteIndex );
int noteTextEndOffset = footnotes
.getNoteTextEndOffset( noteIndex );
Range noteTextRange = new Range( rangeStartOffset
+ noteTextStartOffset, rangeStartOffset
+ noteTextEndOffset, doc );
processFootnoteAutonumbered( doc, noteIndex, block,
noteTextRange );
return;
}
}
{
Notes endnotes = doc.getEndnotes();
int noteIndex = endnotes.getNoteIndexByAnchorPosition( characterRun
.getStartOffset() );
if ( noteIndex != -1 )
{
Range endnoteRange = doc.getEndnoteRange();
int rangeStartOffset = endnoteRange.getStartOffset();
int noteTextStartOffset = endnotes
.getNoteTextStartOffset( noteIndex );
int noteTextEndOffset = endnotes
.getNoteTextEndOffset( noteIndex );
Range noteTextRange = new Range( rangeStartOffset
+ noteTextStartOffset, rangeStartOffset
+ noteTextEndOffset, doc );
processEndnoteAutonumbered( doc, noteIndex, block,
noteTextRange );
return;
}
}
}
protected abstract void processPageref( HWPFDocumentCore wordDocument,
Element currentBlock, Range textRange, int currentTableLevel,
String pageref );
protected abstract void processParagraph( HWPFDocumentCore wordDocument,
Element parentFopElement, int currentTableLevel,
Paragraph paragraph, String bulletText );
protected void processParagraphes( HWPFDocumentCore wordDocument,
Element flow, Range range, int currentTableLevel )
{
final ListTables listTables = wordDocument.getListTables();
int currentListInfo = 0;
final int paragraphs = range.numParagraphs();
for ( int p = 0; p < paragraphs; p++ )
{
Paragraph paragraph = range.getParagraph( p );
if ( paragraph.isInTable()
&& paragraph.getTableLevel() != currentTableLevel )
{
if ( paragraph.getTableLevel() < currentTableLevel )
throw new IllegalStateException(
"Trying to process table cell with higher level ("
+ paragraph.getTableLevel()
+ ") than current table level ("
+ currentTableLevel
+ ") as inner table part" );
Table table = range.getTable( paragraph );
processTable( wordDocument, flow, table );
p += table.numParagraphs();
p--;
continue;
}
if ( paragraph.getIlfo() != currentListInfo )
{
currentListInfo = paragraph.getIlfo();
}
if ( currentListInfo != 0 )
{
if ( listTables != null )
{
final ListFormatOverride listFormatOverride = listTables
.getOverride( paragraph.getIlfo() );
String label = AbstractWordUtils.getBulletText( listTables,
paragraph, listFormatOverride.getLsid() );
processParagraph( wordDocument, flow, currentTableLevel,
paragraph, label );
}
else
{
logger.log( POILogger.WARN,
"Paragraph #" + paragraph.getStartOffset() + "-"
+ paragraph.getEndOffset()
+ " has reference to list structure #"
+ currentListInfo
+ ", but listTables not defined in file" );
processParagraph( wordDocument, flow, currentTableLevel,
paragraph, AbstractWordUtils.EMPTY );
}
}
else
{
processParagraph( wordDocument, flow, currentTableLevel,
paragraph, AbstractWordUtils.EMPTY );
}
}
}
private boolean processRangeBookmarks( HWPFDocumentCore document,
int currentTableLevel, Range range, final Element block,
Map<Integer, List<Bookmark>> rangeBookmakrs )
{
final int startOffset = range.getStartOffset();
final int endOffset = range.getEndOffset();
int beforeBookmarkStart = startOffset;
for ( Map.Entry<Integer, List<Bookmark>> entry : rangeBookmakrs
.entrySet() )
{
final List<Bookmark> startedAt = entry.getValue();
final List<Bookmark> bookmarks;
if ( entry.getKey().intValue() == startOffset
&& !bookmarkStack.isEmpty() )
{
/*
* we need to filter out some bookmarks because already
* processing them in caller methods
*/
List<Bookmark> filtered = new ArrayList<Bookmark>(
startedAt.size() );
for ( Bookmark bookmark : startedAt )
{
if ( this.bookmarkStack.contains( bookmark ) )
continue;
filtered.add( bookmark );
}
if ( filtered.isEmpty() )
// no bookmarks - skip to next start point
continue;
bookmarks = filtered;
}
else
{
bookmarks = startedAt;
}
// TODO: test me
/*
* we processing only bookmarks with max size, they shall be first
* in sorted list. Other bookmarks will be processed by called
* method
*/
final Bookmark firstBookmark = bookmarks.iterator().next();
final int startBookmarkOffset = firstBookmark.getStart();
final int endBookmarkOffset = Math.min( firstBookmark.getEnd(),
range.getEndOffset() );
List<Bookmark> toProcess = new ArrayList<Bookmark>(
bookmarks.size() );
for ( Bookmark bookmark : bookmarks )
{
if ( Math.min( bookmark.getEnd(), range.getEndOffset() ) != endBookmarkOffset )
break;
toProcess.add( bookmark );
}
if ( beforeBookmarkStart != startBookmarkOffset )
{
// we have range before bookmark
Range beforeBookmarkRange = new Range( beforeBookmarkStart,
startBookmarkOffset, range )
{
@Override
public String toString()
{
return "BeforeBookmarkRange (" + super.toString() + ")";
}
};
processCharacters( document, currentTableLevel,
beforeBookmarkRange, block );
}
Range bookmarkRange = new Range( startBookmarkOffset,
endBookmarkOffset, range )
{
@Override
public String toString()
{
return "BookmarkRange (" + super.toString() + ")";
}
};
bookmarkStack.addAll( toProcess );
try
{
processBookmarks( document, block, bookmarkRange,
currentTableLevel,
Collections.unmodifiableList( toProcess ) );
}
finally
{
bookmarkStack.removeAll( toProcess );
}
beforeBookmarkStart = endBookmarkOffset;
}
if ( beforeBookmarkStart == startOffset )
{
return false;
}
if ( beforeBookmarkStart != endOffset )
{
// we have range after last bookmark
Range afterLastBookmarkRange = new Range( beforeBookmarkStart,
endOffset, range )
{
@Override
public String toString()
{
return "AfterBookmarkRange (" + super.toString() + ")";
}
};
processCharacters( document, currentTableLevel,
afterLastBookmarkRange, block );
}
return true;
}
protected abstract void processSection( HWPFDocumentCore wordDocument,
Section section, int s );
protected void processSingleSection( HWPFDocumentCore wordDocument,
Section section )
{
processSection( wordDocument, section, 0 );
}
protected abstract void processTable( HWPFDocumentCore wordDocument,
Element flow, Table table );
public void setFontReplacer( FontReplacer fontReplacer )
{
this.fontReplacer = fontReplacer;
}
protected int tryDeadField( HWPFDocumentCore wordDocument, Range range,
int currentTableLevel, int beginMark, Element currentBlock )
{
int separatorMark = -1;
int endMark = -1;
for ( int c = beginMark + 1; c < range.numCharacterRuns(); c++ )
{
CharacterRun characterRun = range.getCharacterRun( c );
String text = characterRun.text();
if ( text.getBytes().length == 0 )
continue;
if ( text.getBytes()[0] == FIELD_BEGIN_MARK )
{
// nested?
Field possibleField = processField( wordDocument, range,
currentTableLevel, characterRun.getStartOffset(),
currentBlock );
if ( possibleField != null )
{
c = possibleField.getFieldEndOffset();
}
else
{
continue;
}
}
if ( text.getBytes()[0] == FIELD_SEPARATOR_MARK )
{
if ( separatorMark != -1 )
{
// double;
return beginMark;
}
separatorMark = c;
continue;
}
if ( text.getBytes()[0] == FIELD_END_MARK )
{
if ( endMark != -1 )
{
// double;
return beginMark;
}
endMark = c;
break;
}
}
if ( separatorMark == -1 || endMark == -1 )
return beginMark;
processDeadField( wordDocument, currentBlock, range, currentTableLevel,
beginMark, separatorMark, endMark );
return endMark;
}
}
| true | true | protected boolean processCharacters( HWPFDocumentCore document,
int currentTableLevel, Range range, final Element block )
{
if ( range == null )
return false;
boolean haveAnyText = false;
if ( document instanceof HWPFDocument )
{
final HWPFDocument doc = (HWPFDocument) document;
Map<Integer, List<Bookmark>> rangeBookmarks = doc.getBookmarks()
.getBookmarksStartedBetween( range.getStartOffset(),
range.getEndOffset() );
if ( rangeBookmarks != null && !rangeBookmarks.isEmpty() )
{
boolean processedAny = processRangeBookmarks( doc,
currentTableLevel, range, block, rangeBookmarks );
if ( processedAny )
return true;
}
}
for ( int c = 0; c < range.numCharacterRuns(); c++ )
{
CharacterRun characterRun = range.getCharacterRun( c );
if ( characterRun == null )
throw new AssertionError();
if ( document instanceof HWPFDocument
&& ( (HWPFDocument) document ).getPicturesTable()
.hasPicture( characterRun ) )
{
HWPFDocument newFormat = (HWPFDocument) document;
Picture picture = newFormat.getPicturesTable().extractPicture(
characterRun, true );
processImage( block, characterRun.text().charAt( 0 ) == 0x01,
picture );
continue;
}
String text = characterRun.text();
if ( text.getBytes().length == 0 )
continue;
if ( characterRun.isSpecialCharacter() )
{
if ( text.charAt( 0 ) == SPECCHAR_AUTONUMBERED_FOOTNOTE_REFERENCE
&& ( document instanceof HWPFDocument ) )
{
HWPFDocument doc = (HWPFDocument) document;
processNoteAnchor( doc, characterRun, block );
continue;
}
}
if ( text.getBytes()[0] == FIELD_BEGIN_MARK )
{
if ( document instanceof HWPFDocument )
{
Field aliveField = ( (HWPFDocument) document )
.getFieldsTables().lookupFieldByStartOffset(
FieldsDocumentPart.MAIN,
characterRun.getStartOffset() );
if ( aliveField != null )
{
processField( ( (HWPFDocument) document ), range,
currentTableLevel, aliveField, block );
int continueAfter = aliveField.getFieldEndOffset();
while ( c < range.numCharacterRuns()
&& range.getCharacterRun( c ).getEndOffset() <= continueAfter )
c++;
if ( c < range.numCharacterRuns() )
c--;
continue;
}
}
int skipTo = tryDeadField( document, range, currentTableLevel,
c, block );
if ( skipTo != c )
{
c = skipTo;
continue;
}
continue;
}
if ( text.getBytes()[0] == FIELD_SEPARATOR_MARK )
{
// shall not appear without FIELD_BEGIN_MARK
continue;
}
if ( text.getBytes()[0] == FIELD_END_MARK )
{
// shall not appear without FIELD_BEGIN_MARK
continue;
}
if ( characterRun.isSpecialCharacter() || characterRun.isObj()
|| characterRun.isOle2() )
{
continue;
}
if ( text.endsWith( "\r" )
|| ( text.charAt( text.length() - 1 ) == BEL_MARK && currentTableLevel != Integer.MIN_VALUE ) )
text = text.substring( 0, text.length() - 1 );
{
// line breaks
StringBuilder stringBuilder = new StringBuilder();
for ( char charChar : text.toCharArray() )
{
if ( charChar == 11 )
{
if ( stringBuilder.length() > 0 )
{
outputCharacters( block, characterRun,
stringBuilder.toString() );
stringBuilder.setLength( 0 );
}
processLineBreak( block, characterRun );
}
else if ( charChar == 30 )
{
// Non-breaking hyphens are stored as ASCII 30
stringBuilder.append( UNICODECHAR_NONBREAKING_HYPHEN );
}
else if ( charChar == 31 )
{
// Non-required hyphens to zero-width space
stringBuilder.append( UNICODECHAR_ZERO_WIDTH_SPACE );
}
else if ( charChar > 0x20 || charChar == 0x09
|| charChar == 0x0A || charChar == 0x0D )
{
stringBuilder.append( charChar );
}
}
if ( stringBuilder.length() > 0 )
{
outputCharacters( block, characterRun,
stringBuilder.toString() );
stringBuilder.setLength( 0 );
}
}
haveAnyText |= text.trim().length() != 0;
}
return haveAnyText;
}
| protected boolean processCharacters( HWPFDocumentCore document,
int currentTableLevel, Range range, final Element block )
{
if ( range == null )
return false;
boolean haveAnyText = false;
if ( document instanceof HWPFDocument )
{
final HWPFDocument doc = (HWPFDocument) document;
Map<Integer, List<Bookmark>> rangeBookmarks = doc.getBookmarks()
.getBookmarksStartedBetween( range.getStartOffset(),
range.getEndOffset() );
if ( rangeBookmarks != null && !rangeBookmarks.isEmpty() )
{
boolean processedAny = processRangeBookmarks( doc,
currentTableLevel, range, block, rangeBookmarks );
if ( processedAny )
return true;
}
}
for ( int c = 0; c < range.numCharacterRuns(); c++ )
{
CharacterRun characterRun = range.getCharacterRun( c );
if ( characterRun == null )
throw new AssertionError();
if ( document instanceof HWPFDocument
&& ( (HWPFDocument) document ).getPicturesTable()
.hasPicture( characterRun ) )
{
HWPFDocument newFormat = (HWPFDocument) document;
Picture picture = newFormat.getPicturesTable().extractPicture(
characterRun, true );
processImage( block, characterRun.text().charAt( 0 ) == 0x01,
picture );
continue;
}
String text = characterRun.text();
if ( text.getBytes().length == 0 )
continue;
if ( characterRun.isSpecialCharacter() )
{
if ( text.charAt( 0 ) == SPECCHAR_AUTONUMBERED_FOOTNOTE_REFERENCE
&& ( document instanceof HWPFDocument ) )
{
HWPFDocument doc = (HWPFDocument) document;
processNoteAnchor( doc, characterRun, block );
continue;
}
}
if ( text.getBytes()[0] == FIELD_BEGIN_MARK )
{
if ( document instanceof HWPFDocument )
{
Field aliveField = ( (HWPFDocument) document )
.getFieldsTables().lookupFieldByStartOffset(
FieldsDocumentPart.MAIN,
characterRun.getStartOffset() );
if ( aliveField != null )
{
processField( ( (HWPFDocument) document ), range,
currentTableLevel, aliveField, block );
int continueAfter = aliveField.getFieldEndOffset();
while ( c < range.numCharacterRuns()
&& range.getCharacterRun( c ).getEndOffset() <= continueAfter )
c++;
if ( c < range.numCharacterRuns() )
c--;
continue;
}
}
int skipTo = tryDeadField( document, range, currentTableLevel,
c, block );
if ( skipTo != c )
{
c = skipTo;
continue;
}
continue;
}
if ( text.getBytes()[0] == FIELD_SEPARATOR_MARK )
{
// shall not appear without FIELD_BEGIN_MARK
continue;
}
if ( text.getBytes()[0] == FIELD_END_MARK )
{
// shall not appear without FIELD_BEGIN_MARK
continue;
}
if ( characterRun.isSpecialCharacter() || characterRun.isObj()
|| characterRun.isOle2() )
{
continue;
}
if ( text.endsWith( "\r" )
|| ( text.charAt( text.length() - 1 ) == BEL_MARK && currentTableLevel != Integer.MIN_VALUE ) )
text = text.substring( 0, text.length() - 1 );
{
// line breaks
StringBuilder stringBuilder = new StringBuilder();
for ( char charChar : text.toCharArray() )
{
if ( charChar == 11 )
{
if ( stringBuilder.length() > 0 )
{
outputCharacters( block, characterRun,
stringBuilder.toString() );
stringBuilder.setLength( 0 );
}
processLineBreak( block, characterRun );
}
else if ( charChar == 30 )
{
// Non-breaking hyphens are stored as ASCII 30
stringBuilder.append( UNICODECHAR_NONBREAKING_HYPHEN );
}
else if ( charChar == 31 )
{
// Non-required hyphens to zero-width space
stringBuilder.append( UNICODECHAR_ZERO_WIDTH_SPACE );
}
else if ( charChar >= 0x20 || charChar == 0x09
|| charChar == 0x0A || charChar == 0x0D )
{
stringBuilder.append( charChar );
}
}
if ( stringBuilder.length() > 0 )
{
outputCharacters( block, characterRun,
stringBuilder.toString() );
stringBuilder.setLength( 0 );
}
}
haveAnyText |= text.trim().length() != 0;
}
return haveAnyText;
}
|
diff --git a/src/gui/VerJuzgado.java b/src/gui/VerJuzgado.java
index 4fd0bc5..23fa9cf 100644
--- a/src/gui/VerJuzgado.java
+++ b/src/gui/VerJuzgado.java
@@ -1,53 +1,53 @@
package gui;
import net.rim.device.api.ui.component.Dialog;
import persistence.Persistence;
import core.Juzgado;
public class VerJuzgado {
private VerJuzgadoScreen _screen;
private Juzgado _juzgado;
public VerJuzgado(Juzgado juzgado) {
_screen = new VerJuzgadoScreen(juzgado);
_juzgado = juzgado;
}
public VerJuzgadoScreen getScreen() {
return _screen;
}
public void actualizarJuzgado() {
if (_screen.isGuardado()) {
try {
Persistence persistence = new Persistence();
boolean cambio = false;
Juzgado juzgado = _screen.getJuzgado();
if (!juzgado.getNombre().equals(_screen.getNombre()))
cambio = true;
if (!juzgado.getCiudad().equals(_screen.getCiudad()))
cambio = true;
if (!juzgado.getTelefono().equals(_screen.getTelefono()))
cambio = true;
if (!juzgado.getDireccion().equals(_screen.getDireccion()))
cambio = true;
if (!juzgado.getTipo().equals(_screen.getTipo()))
cambio = true;
if (cambio) {
_juzgado = new Juzgado(_screen.getNombre(),
_screen.getCiudad(), _screen.getDireccion(),
- _screen.getTelefono(), _screen.getTipo());
+ _screen.getTelefono(), _screen.getTipo(), _juzgado.getId_juzgado());
persistence.actualizarJuzgado(_juzgado);
}
} catch (Exception e) {
Dialog.alert("actualizarJuzgado -> " + e.toString());
}
}
}
public Juzgado getJuzgado() {
return _juzgado;
}
}
| true | true | public void actualizarJuzgado() {
if (_screen.isGuardado()) {
try {
Persistence persistence = new Persistence();
boolean cambio = false;
Juzgado juzgado = _screen.getJuzgado();
if (!juzgado.getNombre().equals(_screen.getNombre()))
cambio = true;
if (!juzgado.getCiudad().equals(_screen.getCiudad()))
cambio = true;
if (!juzgado.getTelefono().equals(_screen.getTelefono()))
cambio = true;
if (!juzgado.getDireccion().equals(_screen.getDireccion()))
cambio = true;
if (!juzgado.getTipo().equals(_screen.getTipo()))
cambio = true;
if (cambio) {
_juzgado = new Juzgado(_screen.getNombre(),
_screen.getCiudad(), _screen.getDireccion(),
_screen.getTelefono(), _screen.getTipo());
persistence.actualizarJuzgado(_juzgado);
}
} catch (Exception e) {
Dialog.alert("actualizarJuzgado -> " + e.toString());
}
}
}
| public void actualizarJuzgado() {
if (_screen.isGuardado()) {
try {
Persistence persistence = new Persistence();
boolean cambio = false;
Juzgado juzgado = _screen.getJuzgado();
if (!juzgado.getNombre().equals(_screen.getNombre()))
cambio = true;
if (!juzgado.getCiudad().equals(_screen.getCiudad()))
cambio = true;
if (!juzgado.getTelefono().equals(_screen.getTelefono()))
cambio = true;
if (!juzgado.getDireccion().equals(_screen.getDireccion()))
cambio = true;
if (!juzgado.getTipo().equals(_screen.getTipo()))
cambio = true;
if (cambio) {
_juzgado = new Juzgado(_screen.getNombre(),
_screen.getCiudad(), _screen.getDireccion(),
_screen.getTelefono(), _screen.getTipo(), _juzgado.getId_juzgado());
persistence.actualizarJuzgado(_juzgado);
}
} catch (Exception e) {
Dialog.alert("actualizarJuzgado -> " + e.toString());
}
}
}
|
diff --git a/src/jtermios/windows/JTermiosImpl.java b/src/jtermios/windows/JTermiosImpl.java
index cd71d3c..eee501b 100644
--- a/src/jtermios/windows/JTermiosImpl.java
+++ b/src/jtermios/windows/JTermiosImpl.java
@@ -1,1226 +1,1225 @@
/*
* Copyright (c) 2011, Kustaa Nyholm / SpareTimeLabs
* All rights reserved.
*
* 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 of the Kustaa Nyholm or SpareTimeLabs 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 HOLDER 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 jtermios.windows;
import java.io.File;
import java.nio.ByteBuffer;
import java.util.*;
import java.util.regex.Pattern;
import com.sun.jna.*;
import com.sun.jna.ptr.IntByReference;
import static jtermios.JTermios.*;
import static jtermios.JTermios.JTermiosLogging.*;
import jtermios.*;
import jtermios.windows.WinAPI.*;
import static jtermios.windows.WinAPI.*;
import static jtermios.windows.WinAPI.DCB.*;
public class JTermiosImpl implements jtermios.JTermios.JTermiosInterface {
private volatile int m_ErrNo = 0;
private volatile boolean m_PortFDs[] = new boolean[FDSetImpl.FD_SET_SIZE];
private volatile Hashtable<Integer, Port> m_OpenPorts = new Hashtable<Integer, Port>();
private class Port {
volatile int m_FD = -1;
volatile boolean m_Locked;
volatile HANDLE m_Comm;
volatile int m_OpenFlags;
volatile DCB m_DCB = new DCB();
volatile COMMTIMEOUTS m_Timeouts = new COMMTIMEOUTS();
volatile COMSTAT m_COMSTAT = new COMSTAT();
volatile int[] m_ClearErr = { 0 };
volatile Memory m_RdBuffer = new Memory(2048);
volatile int[] m_RdErr = { 0 };
volatile int m_RdN[] = { 0 };
volatile OVERLAPPED m_RdOVL = new OVERLAPPED();
volatile Memory m_WrBuffer = new Memory(2048);
volatile COMSTAT m_WrStat = new COMSTAT();
volatile int[] m_WrErr = { 0 };
volatile int m_WrN[] = { 0 };
volatile int m_WritePending;
volatile OVERLAPPED m_WrOVL = new OVERLAPPED();
volatile boolean m_WaitPending;
volatile int m_SelN[] = { 0 };
volatile HANDLE m_CancelWaitSema4;
volatile OVERLAPPED m_SelOVL = new OVERLAPPED();
volatile IntByReference m_EventFlags = new IntByReference();
volatile Termios m_Termios = new Termios();
volatile int MSR; // initial value
// these cached values are used to detect changes in termios structure and speed up things by avoiding unnecessary updates
volatile int m_VTIME = -1;
volatile int m_VMIN = -1;
volatile int m_c_speed = -1;
volatile int m_c_cflag = -1;
volatile int m_c_iflag = -1;
volatile int m_c_oflag = -1;
synchronized public void fail() throws Fail {
int err = GetLastError();
Memory buffer = new Memory(2048);
int res = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, null, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buffer, (int) buffer.size(), null);
log = log && log(1, "fail() %s, Windows GetLastError()= %d, %s\n", lineno(1), err, buffer.getString(0, true));
// FIXME here convert from Windows error code to 'posix' error code
Fail f = new Fail();
throw f;
}
synchronized public void lock() throws InterruptedException {
while (m_Locked)
wait();
m_Locked = true;
}
synchronized public void unlock() {
if (!m_Locked)
throw new IllegalArgumentException("Port was not locked");
m_Locked = false;
notifyAll();
}
synchronized public void waitUnlock() {
while (m_Locked) {
try {
wait();
} catch (InterruptedException e) {
// interruption cannot cancel wait
}
}
}
public Port() {
synchronized (JTermiosImpl.this) {
m_FD = -1;
for (int i = 0; i < m_PortFDs.length; ++i) {
if (!m_PortFDs[i]) {
m_FD = i;
m_PortFDs[i] = true;
m_OpenPorts.put(m_FD, this);
m_CancelWaitSema4 = CreateEventA(null, false, false, null);
if (m_CancelWaitSema4 == null)
throw new RuntimeException("Unexpected failure of CreateEvent() call");
return;
}
}
throw new RuntimeException("Too many ports open");
}
}
public void close() {
synchronized (JTermiosImpl.this) {
if (m_FD >= 0) {
m_OpenPorts.remove(m_FD);
m_PortFDs[m_FD] = false;
m_FD = -1;
}
if (m_CancelWaitSema4 != null)
SetEvent(m_CancelWaitSema4);
if (m_Comm != null) {
ResetEvent(m_SelOVL.hEvent);
if (!CancelIoEx(m_Comm,null))
log = log && log(1, "CancelIo() failed, GetLastError()= %d, %s\n", GetLastError(), lineno(1));
if (!PurgeComm(m_Comm, PURGE_TXABORT + PURGE_TXCLEAR + PURGE_RXABORT + PURGE_RXCLEAR))
log = log && log(1, "PurgeComm() failed, GetLastError()= %d, %s\n", GetLastError(), lineno(1));
GetOverlappedResult(m_Comm, m_RdOVL, m_RdN, true);
GetOverlappedResult(m_Comm, m_WrOVL, m_WrN, true);
GetOverlappedResult(m_Comm, m_SelOVL, m_SelN, true);
}
HANDLE h; // / 'hEvent' might never have been 'read' so read it
// to this var first
synchronized (m_RdBuffer) {
h = (HANDLE) m_RdOVL.readField("hEvent");
m_RdOVL = null;
if (h != null && !h.equals(NULL) && !h.equals(INVALID_HANDLE_VALUE))
CloseHandle(h);
}
synchronized (m_WrBuffer) {
h = (HANDLE) m_WrOVL.readField("hEvent");
m_WrOVL = null;
if (h != null && !h.equals(NULL) && !h.equals(INVALID_HANDLE_VALUE))
CloseHandle(h);
}
// Ensure that select() is through before releasing the m_SelOVL
waitUnlock();
h = (HANDLE) m_SelOVL.readField("hEvent");
m_SelOVL = null;
if (h != null && !h.equals(NULL) && !h.equals(INVALID_HANDLE_VALUE))
CloseHandle(h);
if (m_Comm != null && m_Comm != NULL && m_Comm != INVALID_HANDLE_VALUE)
CloseHandle(m_Comm);
m_Comm = null;
}
}
};
static class Fail extends Exception {
}
static private class FDSetImpl extends FDSet {
static final int FD_SET_SIZE = 256; // Windows supports max 255 serial ports so this is enough
static final int NFBBITS = 32;
int[] bits = new int[(FD_SET_SIZE + NFBBITS - 1) / NFBBITS];
}
public JTermiosImpl() {
log = log && log(1, "instantiating %s\n", getClass().getCanonicalName());
}
public int errno() {
return m_ErrNo;
}
public void cfmakeraw(Termios termios) {
termios.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
termios.c_oflag &= ~OPOST;
termios.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
termios.c_cflag &= ~(CSIZE | PARENB);
termios.c_cflag |= CS8;
}
public int fcntl(int fd, int cmd, int arg) {
Port port = getPort(fd);
if (port == null)
return -1;
if (F_SETFL == cmd)
port.m_OpenFlags = arg;
else if (F_GETFL == cmd)
return port.m_OpenFlags;
else {
m_ErrNo = ENOTSUP;
return -1;
}
return 0;
}
public int tcdrain(int fd) {
Port port = getPort(fd);
if (port == null)
return -1;
try {
synchronized (port.m_WrBuffer) {
if (!FlushFileBuffers(port.m_Comm))
port.fail();
return 0;
}
} catch (Fail f) {
return -1;
}
}
public int cfgetispeed(Termios termios) {
return termios.c_ispeed;
}
public int cfgetospeed(Termios termios) {
return termios.c_ospeed;
}
public int cfsetispeed(Termios termios, int speed) {
termios.c_ispeed = speed;
return 0;
}// Error code for Interrupted = EINTR
public int cfsetospeed(Termios termios, int speed) {
termios.c_ospeed = speed;
return 0;
}
public int open(String filename, int flags) {
Port port = new Port();
port.m_OpenFlags = flags;
try {
if (!filename.startsWith("\\\\"))
filename = "\\\\.\\" + filename;
port.m_Comm = CreateFileW(new WString(filename), GENERIC_READ | GENERIC_WRITE, 0, null, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, null);
if (INVALID_HANDLE_VALUE == port.m_Comm) {
if (GetLastError() == ERROR_FILE_NOT_FOUND)
m_ErrNo = ENOENT;
else
m_ErrNo = EBUSY;
port.fail();
}
if (!SetupComm(port.m_Comm, (int) port.m_RdBuffer.size(), (int) port.m_WrBuffer.size()))
port.fail(); // FIXME what would be appropriate error code here
cfmakeraw(port.m_Termios);
cfsetispeed(port.m_Termios, B9600);
cfsetospeed(port.m_Termios, B9600);
port.m_Termios.c_cc[VTIME] = 0;
port.m_Termios.c_cc[VMIN] = 0;
updateFromTermios(port);
port.m_RdOVL.writeField("hEvent", CreateEventA(null, true, false, null));
if (port.m_RdOVL.hEvent == INVALID_HANDLE_VALUE)
port.fail();
port.m_WrOVL.writeField("hEvent", CreateEventA(null, true, false, null));
if (port.m_WrOVL.hEvent == INVALID_HANDLE_VALUE)
port.fail();
port.m_SelOVL.writeField("hEvent", CreateEventA(null, true, false, null));
if (port.m_SelOVL.hEvent == INVALID_HANDLE_VALUE)
port.fail();
return port.m_FD;
} catch (Exception f) {
if (port != null)
port.close();
return -1;
}
}
private static void nanoSleep(long nsec) throws Fail {
try {
Thread.sleep((int) (nsec / 1000000), (int) (nsec % 1000000));
} catch (InterruptedException ie) {
throw new Fail();
}
}
private int getCharBits(Termios tios) {
int cs = 8; // default to 8
if ((tios.c_cflag & CSIZE) == CS5)
cs = 5;
if ((tios.c_cflag & CSIZE) == CS6)
cs = 6;
if ((tios.c_cflag & CSIZE) == CS7)
cs = 7;
if ((tios.c_cflag & CSIZE) == CS8)
cs = 8;
if ((tios.c_cflag & CSTOPB) != 0)
cs++; // extra stop bit
if ((tios.c_cflag & PARENB) != 0)
cs++; // parity adds an other bit
cs += 1 + 1; // start bit + stop bit
return cs;
}
private static int min(int a, int b) {
return a < b ? a : b;
}
private static int max(int a, int b) {
return a > b ? a : b;
}
public int read(int fd, byte[] buffer, int length) {
Port port = getPort(fd);
if (port == null)
return -1;
synchronized (port.m_RdBuffer) {
try {
// limit reads to internal buffer size
if (length > port.m_RdBuffer.size())
length = (int) port.m_RdBuffer.size();
if (length == 0)
return 0;
int error;
if ((port.m_OpenFlags & O_NONBLOCK) != 0) {
clearCommErrors(port);
int available = port.m_COMSTAT.cbInQue;
if (available == 0) {
m_ErrNo = EAGAIN;
return -1;
}
length = min(length, available);
} else {
clearCommErrors(port);
int available = port.m_COMSTAT.cbInQue;
int vtime = 0xff & port.m_Termios.c_cc[VTIME];
int vmin = 0xff & port.m_Termios.c_cc[VMIN];
if (vmin == 0 && vtime == 0) {
// VMIN = 0 and VTIME = 0 => totally non blocking,if data is
// available, return it, ie this is poll operation
// For reference below commented out is how timeouts are set for this vtime/vmin combo
//touts.ReadIntervalTimeout = MAXDWORD;
//touts.ReadTotalTimeoutConstant = 0;
//touts.ReadTotalTimeoutMultiplier = 0;
if (available == 0)
return 0;
length = min(length, available);
}
if (vmin == 0 && vtime > 0) {
// VMIN = 0 and VTIME > 0 => timed read, return as soon as data is
// available, VTIME = total time
// For reference below commented out is how timeouts are set for this vtime/vmin combo
//touts.ReadIntervalTimeout = 0;
//touts.ReadTotalTimeoutConstant = vtime;
//touts.ReadTotalTimeoutMultiplier = 0;
// NOTE to behave like unix we should probably wait until there is something available
// and then try to do a read as many bytes as are available bytes at that point in time.
// As this is coded now, this will attempt to read as many bytes as requested and this may end up
// spending vtime in the read when a unix would return less bytes but as soon as they become
// available.
}
if (vmin > 0 && vtime > 0) {
// VMIN > 0 and VTIME > 0 => blocks until VMIN chars has arrived or between chars expired,
// note that this will block if nothing arrives
// For reference below commented out is how timeouts are set for this vtime/vmin combo
//touts.ReadIntervalTimeout = vtime;
//touts.ReadTotalTimeoutConstant = 0;
//touts.ReadTotalTimeoutMultiplier = 0;
length = min(max(vmin, available), length);
}
if (vmin > 0 && vtime == 0) {
// VMIN > 0 and VTIME = 0 => blocks until VMIN characters have been
// received
// For reference below commented out is how timeouts are set for this vtime/vmin combo
//touts.ReadIntervalTimeout = 0;
//touts.ReadTotalTimeoutConstant = 0;
//touts.ReadTotalTimeoutMultiplier = 0;
length = min(max(vmin, available), length);
}
}
if (!ResetEvent(port.m_RdOVL.hEvent))
port.fail();
if (!ReadFile(port.m_Comm, port.m_RdBuffer, length, port.m_RdN, port.m_RdOVL)) {
if (GetLastError() != ERROR_IO_PENDING)
port.fail();
if (WaitForSingleObject(port.m_RdOVL.hEvent, INFINITE) != WAIT_OBJECT_0)
port.fail();
if (!GetOverlappedResult(port.m_Comm, port.m_RdOVL, port.m_RdN, true))
port.fail();
}
port.m_RdBuffer.read(0, buffer, 0, port.m_RdN[0]);
return port.m_RdN[0];
} catch (Fail ie) {
return -1;
}
}
}
public int write(int fd, byte[] buffer, int length) {
Port port = getPort(fd);
if (port == null)
return -1;
synchronized (port.m_WrBuffer) {
try {
if (port.m_WritePending > 0) {
while (true) {
int res = WaitForSingleObject(port.m_WrOVL.hEvent, INFINITE);
if (res == WAIT_TIMEOUT) {
clearCommErrors(port);
log = log && log(1, "write pending, cbInQue %d cbOutQue %d\n", port.m_COMSTAT.cbInQue, port.m_COMSTAT.cbOutQue);
continue;
}
if (!GetOverlappedResult(port.m_Comm, port.m_WrOVL, port.m_WrN, false))
port.fail();
if (port.m_WrN[0] != port.m_WritePending) // I exptect this is never going to happen, if it does
new RuntimeException("Windows OVERLAPPED WriteFile failed to write all, tried to write " + port.m_WritePending + " but got " + port.m_WrN[0]);
break;
}
port.m_WritePending = 0;
}
if ((port.m_OpenFlags & O_NONBLOCK) != 0) {
if (!ClearCommError(port.m_Comm, port.m_WrErr, port.m_WrStat))
port.fail();
int room = (int) port.m_WrBuffer.size() - port.m_WrStat.cbOutQue;
if (length > room)
length = room;
}
int old_flag;
if (!ResetEvent(port.m_WrOVL.hEvent))
port.fail();
if (length > port.m_WrBuffer.size())
length = (int) port.m_WrBuffer.size();
port.m_WrBuffer.write(0, buffer, 0, length); // copy from buffer to Memory
boolean ok = WriteFile(port.m_Comm, port.m_WrBuffer, length, port.m_WrN, port.m_WrOVL);
if (!ok) {
if (GetLastError() != ERROR_IO_PENDING)
port.fail();
port.m_WritePending = length;
}
//
return length; // port.m_WrN[0];
} catch (Fail f) {
return -1;
}
}
}
public int close(int fd) {
Port port = getPort(fd);
if (port == null)
return -1;
port.close();
return 0;
}
public int tcflush(int fd, int queue) {
Port port = getPort(fd);
if (port == null)
return -1;
try {
if (queue == TCIFLUSH) {
if (!PurgeComm(port.m_Comm, PURGE_RXABORT))
port.fail();
} else if (queue == TCOFLUSH) {
if (!PurgeComm(port.m_Comm, PURGE_TXABORT))
port.fail();
} else if (queue == TCIOFLUSH) {
if (!PurgeComm(port.m_Comm, PURGE_TXABORT))
port.fail();
if (!PurgeComm(port.m_Comm, PURGE_RXABORT))
port.fail();
} else {
m_ErrNo = ENOTSUP;
return -1;
}
return 0;
} catch (Fail f) {
return -1;
}
}
/*
* (non-Javadoc) Basically this is wrong, as tcsetattr is supposed to set
* only those things it can support and tcgetattr is the used to see that
* what actually happened. In this instance tcsetattr never fails and
* tcgetattr always returns the last settings even though it possible (even
* likely) that tcsetattr was not able to carry out all settings, as there
* is no 1:1 mapping between Windows Comm API and posix/termios API.
*
* @see jtermios.JTermios.JTermiosInterface#tcgetattr(int, jtermios.Termios)
*/
public int tcgetattr(int fd, Termios termios) {
Port port = getPort(fd);
if (port == null)
return -1;
termios.set(port.m_Termios);
return 0;
}
public int tcsendbreak(int fd, int duration) {
Port port = getPort(fd);
if (port == null)
return -1;
try {
if (!SetCommBreak(port.m_Comm))
port.fail();
nanoSleep(duration * 250000000L);
if (!ClearCommBreak(port.m_Comm))
port.fail();
return 0;
} catch (Fail f) {
return -1;
}
}
public int tcsetattr(int fd, int cmd, Termios termios) {
if (cmd != TCSANOW)
log(0, "tcsetattr only supports TCSANOW\n");
Port port = getPort(fd);
if (port == null)
return -1;
synchronized (port.m_Termios) {
try {
port.m_Termios.set(termios);
updateFromTermios(port);
return 0;
} catch (Fail f) {
return -1;
}
}
}
// FIXME this needs serious code review from people who know this stuff...
public int updateFromTermios(Port port) throws Fail {
Termios tios = port.m_Termios;
int c_speed = tios.c_ospeed;
int c_cflag = tios.c_cflag;
int c_iflag = tios.c_iflag;
int c_oflag = tios.c_oflag;
if (c_speed != port.m_c_speed || c_cflag != port.m_c_cflag || c_iflag != port.m_c_iflag || c_oflag != port.m_c_oflag) {
DCB dcb = port.m_DCB;
if (!GetCommState(port.m_Comm, dcb))
port.fail();
dcb.DCBlength = dcb.size();
dcb.BaudRate = c_speed;
if (tios.c_ospeed != tios.c_ispeed)
log(0, "c_ospeed (%d) != c_ispeed (%d)\n", tios.c_ospeed, tios.c_ispeed);
int flags = 0;
// rxtx does: if ( s_termios->c_iflag & ISTRIP ) dcb.fBinary = FALSE;
// but Winapi doc says fBinary always true
flags |= fBinary;
if ((c_cflag & PARENB) != 0)
flags |= fParity;
if ((c_iflag & IXON) != 0)
flags |= fOutX;
if ((c_iflag & IXOFF) != 0)
flags |= fInX;
if ((c_iflag & IXANY) != 0)
flags |= fTXContinueOnXoff;
if ((c_iflag & CRTSCTS) != 0) {
flags |= fRtsControl;
flags |= fOutxCtsFlow;
}
// Following have no corresponding functionality in unix termios
// fOutxDsrFlow = 0x00000008;
// fDtrControl = 0x00000030;
// fDsrSensitivity = 0x00000040;
// fErrorChar = 0x00000400;
// fNull = 0x00000800;
// fAbortOnError = 0x00004000;
// fDummy2 = 0xFFFF8000;
dcb.fFlags = flags;
// Don't touch these, windows seems to use: XonLim 2048 XoffLim 512 and who am I to argue with those
//dcb.XonLim = 0;
//dcb.XoffLim = 128;
byte cs = 8;
int csize = c_cflag & CSIZE;
if (csize == CS5)
cs = 5;
if (csize == CS6)
cs = 6;
if (csize == CS7)
cs = 7;
if (csize == CS8)
cs = 8;
dcb.ByteSize = cs;
if ((c_cflag & PARENB) != 0) {
if ((c_cflag & PARODD) != 0 && (c_cflag & CMSPAR) != 0)
dcb.Parity = MARKPARITY;
else if ((c_cflag & PARODD) != 0)
dcb.Parity = ODDPARITY;
else if ((c_cflag & CMSPAR) != 0)
dcb.Parity = SPACEPARITY;
else
dcb.Parity = EVENPARITY;
} else
dcb.Parity = NOPARITY;
dcb.StopBits = (c_cflag & CSTOPB) != 0 ? ((csize == CS5) ? ONE5STOPBITS : TWOSTOPBITS) : ONESTOPBIT;
dcb.XonChar = tios.c_cc[VSTART]; // In theory these could change but they only get updated if the baudrate/char size changes so this could be a time bomb
dcb.XoffChar = tios.c_cc[VSTOP]; // In practice in PJC these are never changed so updating on the first pass is enough
dcb.ErrorChar = 0;
// rxtx has some thing like
// if ( EV_BREAK|EV_CTS|EV_DSR|EV_ERR|EV_RING | ( EV_RLSD & EV_RXFLAG )
// )
// dcb.EvtChar = '\n';
// else
// dcb.EvtChar = '\0';
// But those are all defines so there is something fishy there?
dcb.EvtChar = '\n';
dcb.EofChar = tios.c_cc[VEOF];
if (!SetCommState(port.m_Comm, dcb))
port.fail();
port.m_c_speed = c_speed;
port.m_c_cflag = c_cflag;
port.m_c_iflag = c_iflag;
port.m_c_oflag = c_oflag;
}
int vmin = port.m_Termios.c_cc[VMIN] & 0xFF;
int vtime = (port.m_Termios.c_cc[VTIME] & 0xFF) * 100;
if (vmin != port.m_VMIN || vtime != port.m_VTIME) {
COMMTIMEOUTS touts = port.m_Timeouts;
// There are really no write timeouts in classic unix termios
// FIXME test that we can still interrupt the tread
touts.WriteTotalTimeoutConstant = 0;
touts.WriteTotalTimeoutMultiplier = 0;
if (vmin == 0 && vtime == 0) {
// VMIN = 0 and VTIME = 0 => totally non blocking,if data is
// available, return it, ie this is poll operation
touts.ReadIntervalTimeout = MAXDWORD;
touts.ReadTotalTimeoutConstant = 0;
touts.ReadTotalTimeoutMultiplier = 0;
}
if (vmin == 0 && vtime > 0) {
// VMIN = 0 and VTIME > 0 => timed read, return as soon as data is
// available, VTIME = total time
touts.ReadIntervalTimeout = 0;
touts.ReadTotalTimeoutConstant = vtime;
touts.ReadTotalTimeoutMultiplier = 0;
}
if (vmin > 0 && vtime > 0) {
// VMIN > 0 and VTIME > 0 => blocks until VMIN chars has arrived or between chars expired,
// note that this will block if nothing arrives
touts.ReadIntervalTimeout = vtime;
touts.ReadTotalTimeoutConstant = 0;
touts.ReadTotalTimeoutMultiplier = 0;
}
if (vmin > 0 && vtime == 0) {
// VMIN > 0 and VTIME = 0 => blocks until VMIN characters have been
// received
touts.ReadIntervalTimeout = 0;
touts.ReadTotalTimeoutConstant = 0;
touts.ReadTotalTimeoutMultiplier = 0;
}
if (!SetCommTimeouts(port.m_Comm, port.m_Timeouts))
port.fail();
port.m_VMIN = vmin;
port.m_VTIME = vtime;
log = log && log(2, "vmin %d vtime %d ReadIntervalTimeout %d ReadTotalTimeoutConstant %d ReadTotalTimeoutMultiplier %d\n", vmin, vtime, touts.ReadIntervalTimeout, touts.ReadTotalTimeoutConstant, touts.ReadTotalTimeoutMultiplier);
}
return 0;
}
private int maskToFDSets(Port port, FDSet readfds, FDSet writefds, FDSet exceptfds, int ready) throws Fail {
clearCommErrors(port);
int emask = port.m_EventFlags.getValue();
int fd = port.m_FD;
if ((emask & EV_RXCHAR) != 0 && port.m_COMSTAT.cbInQue > 0) {
FD_SET(fd, readfds);
ready++;
}
if ((emask & EV_TXEMPTY) != 0 && port.m_COMSTAT.cbOutQue == 0) {
FD_SET(fd, writefds);
ready++;
}
return ready;
}
private void clearCommErrors(Port port) throws Fail {
synchronized (port.m_COMSTAT) {
if (!ClearCommError(port.m_Comm, port.m_ClearErr, port.m_COMSTAT))
port.fail();
}
}
public int select(int n, FDSet readfds, FDSet writefds, FDSet exceptfds, TimeVal timeout) {
// long T0 = System.currentTimeMillis();
int ready = 0;
LinkedList<Port> locked = new LinkedList<Port>();
try {
try {
LinkedList<Port> waiting = new LinkedList<Port>();
for (int fd = 0; fd < n; fd++) {
boolean rd = FD_ISSET(fd, readfds);
boolean wr = FD_ISSET(fd, writefds);
FD_CLR(fd, readfds);
FD_CLR(fd, writefds);
if (rd || wr) {
Port port = getPort(fd);
if (port == null)
return -1;
try {
port.lock();
locked.add(port);
clearCommErrors(port);
// check if there is data to be read, as WaitCommEvent
// does check for only *new* data that and thus
// might wait indefinitely if select() is called twice
// without first reading away all data
if (rd && port.m_COMSTAT.cbInQue > 0) {
FD_SET(fd, readfds);
ready++;
}
if (wr && port.m_COMSTAT.cbOutQue == 0) {
FD_SET(fd, writefds);
ready++;
}
if (port.m_WaitPending) {
if (!SetCommMask(port.m_Comm, 0))
port.fail();
- if (!GetOverlappedResult(port.m_Comm, port.m_SelOVL, port.m_SelN, false) && GetLastError() != ERROR_OPERATION_ABORTED)
- port.fail() ;
+ GetOverlappedResult(port.m_Comm, port.m_SelOVL, port.m_SelN, false) ;
port.m_WaitPending = false;
}
if (!ResetEvent(port.m_SelOVL.hEvent))
port.fail();
int flags = 0;
if (rd)
flags |= EV_RXCHAR;
if (wr)
flags |= EV_TXEMPTY;
if (!SetCommMask(port.m_Comm, flags))
port.fail();
if (WaitCommEvent(port.m_Comm, port.m_EventFlags, port.m_SelOVL)) {
if (!GetOverlappedResult(port.m_Comm, port.m_SelOVL, port.m_SelN, false))
port.fail();
// actually it seems that overlapped
// WaitCommEvent never returns true so we never get here
ready = maskToFDSets(port, readfds, writefds, exceptfds, ready);
} else {
// FIXME if the port dies on us what happens
if (GetLastError() != ERROR_IO_PENDING)
port.fail();
waiting.add(port);
port.m_WaitPending = true;
}
} catch (InterruptedException ie) {
m_ErrNo = EINTR;
return -1;
}
}
}
if (ready == 0) {
int waitn = waiting.size();
if (waitn > 0) {
HANDLE[] wobj = new HANDLE[waiting.size() * 2];
int i = 0;
for (Port port : waiting) {
wobj[i++] = port.m_SelOVL.hEvent;
wobj[i++] = port.m_CancelWaitSema4;
}
int tout = timeout != null ? (int) (timeout.tv_sec * 1000 + timeout.tv_usec / 1000) : INFINITE;
// int res = WaitForSingleObject(wobj[0], tout);
int res = WaitForMultipleObjects(waitn * 2, wobj, false, tout);
if (res == WAIT_TIMEOUT) {
// work around the fact that sometimes we miss
// events
for (Port port : waiting) {
clearCommErrors(port);
int[] mask = { 0 };
if (!GetCommMask(port.m_Comm, mask))
port.fail();
if (port.m_COMSTAT.cbInQue > 0 && ((mask[0] & EV_RXCHAR) != 0)) {
FD_SET(port.m_FD, readfds);
log = log && log(1, "missed EV_RXCHAR event\n");
return 1;
}
if (port.m_COMSTAT.cbOutQue == 0 && ((mask[0] & EV_TXEMPTY) != 0)) {
FD_SET(port.m_FD, writefds);
log = log && log(1, "missed EV_TXEMPTY event\n");
return 1;
}
}
}
if (res != WAIT_TIMEOUT) {
i = (res - WAIT_OBJECT_0) / 2;
if (i < 0 || i >= waitn)
throw new Fail();
if (((res - WAIT_OBJECT_0) & 1) == 1) {
// it was the cancel sema4 so just return
return 0;
}
Port port = waiting.get(i);
if (!GetOverlappedResult(port.m_Comm, port.m_SelOVL, port.m_SelN, false))
port.fail();
ready = maskToFDSets(port, readfds, writefds, exceptfds, ready);
port.m_WaitPending = false;
}
} else {
if (timeout != null)
nanoSleep(timeout.tv_sec * 1000000000L + timeout.tv_usec * 1000);
else {
m_ErrNo = EINVAL;
return -1;
}
return 0;
}
}
} catch (Fail f) {
f.printStackTrace();
return -1;
}
} finally {
for (Port port : locked)
port.unlock();
}
// long T1 = System.currentTimeMillis();
// System.err.println("select() " + (T1 - T0));
return ready;
}
public int poll(Pollfd fds[], int nfds, int timeout) {
m_ErrNo = EINVAL;
return -1;
}
public int poll(int fds[], int nfds, int timeout) {
m_ErrNo = EINVAL;
return -1;
}
public void perror(String msg) {
if (msg != null && msg.length() > 0)
System.out.print(msg + ": ");
System.out.printf("%d\n", m_ErrNo);
}
// This is a bit pointless function as Windows baudrate constants are
// just the baudrates so basically this is a no-op, it returns what it gets
// Note this assumes that the Bxxxx constants in JTermios have the default
// values ie the values are the baudrates.
private static int baudToDCB(int baud) {
switch (baud) {
case 110:
return CBR_110;
case 300:
return CBR_300;
case 600:
return CBR_600;
case 1200:
return CBR_1200;
case 2400:
return CBR_2400;
case 4800:
return CBR_4800;
case 9600:
return CBR_9600;
case 14400:
return CBR_14400;
case 19200:
return CBR_19200;
case 38400:
return CBR_38400;
case 57600:
return CBR_57600;
case 115200:
return CBR_115200;
case 128000:
return CBR_128000;
case 256000:
return CBR_256000;
default:
return baud;
}
}
public FDSet newFDSet() {
return new FDSetImpl();
}
public void FD_CLR(int fd, FDSet set) {
if (set == null)
return;
FDSetImpl p = (FDSetImpl) set;
p.bits[fd / FDSetImpl.NFBBITS] &= ~(1 << (fd % FDSetImpl.NFBBITS));
}
public boolean FD_ISSET(int fd, FDSet set) {
if (set == null)
return false;
FDSetImpl p = (FDSetImpl) set;
return (p.bits[fd / FDSetImpl.NFBBITS] & (1 << (fd % FDSetImpl.NFBBITS))) != 0;
}
public void FD_SET(int fd, FDSet set) {
if (set == null)
return;
FDSetImpl p = (FDSetImpl) set;
p.bits[fd / FDSetImpl.NFBBITS] |= 1 << (fd % FDSetImpl.NFBBITS);
}
public void FD_ZERO(FDSet set) {
if (set == null)
return;
FDSetImpl p = (FDSetImpl) set;
java.util.Arrays.fill(p.bits, 0);
}
public int ioctl(int fd, int cmd, int[] arg) {
Port port = getPort(fd);
if (port == null)
return -1;
try {
if (cmd == FIONREAD) {
clearCommErrors(port);
arg[0] = port.m_COMSTAT.cbInQue;
return 0;
} else if (cmd == TIOCMSET) {
int a = arg[0];
if ((a & TIOCM_DTR) != 0)
port.MSR |= TIOCM_DTR;
else
port.MSR &= ~TIOCM_DTR;
if (!EscapeCommFunction(port.m_Comm, ((a & TIOCM_DTR) != 0) ? SETDTR : CLRDTR))
port.fail();
if ((a & TIOCM_RTS) != 0)
port.MSR |= TIOCM_RTS;
else
port.MSR &= ~TIOCM_RTS;
if (!EscapeCommFunction(port.m_Comm, ((a & TIOCM_RTS) != 0) ? SETRTS : CLRRTS))
port.fail();
return 0;
} else if (cmd == TIOCMGET) {
int[] stat = { 0 };
if (!GetCommModemStatus(port.m_Comm, stat))
port.fail();
int s = stat[0];
int a = arg[0];
if ((s & MS_RLSD_ON) != 0)
a |= TIOCM_CAR;
else
a &= ~TIOCM_CAR;
if ((s & MS_RING_ON) != 0)
a |= TIOCM_RNG;
else
a &= ~TIOCM_RNG;
if ((s & MS_DSR_ON) != 0)
a |= TIOCM_DSR;
else
a &= ~TIOCM_DSR;
if ((s & MS_CTS_ON) != 0)
a |= TIOCM_CTS;
else
a &= ~TIOCM_CTS;
if ((port.MSR & TIOCM_DTR) != 0)
a |= TIOCM_DTR;
else
a &= ~TIOCM_DTR;
if ((port.MSR & TIOCM_RTS) != 0)
a |= TIOCM_RTS;
else
a &= ~TIOCM_RTS;
arg[0] = a;
return 0;
} else {
m_ErrNo = ENOTSUP;
return -1;
}
} catch (Fail f) {
return -1;
}
}
private void set_errno(int x) {
m_ErrNo = x;
}
private void report(String msg) {
System.err.print(msg);
}
private Port getPort(int fd) {
synchronized (this) {
Port port = m_OpenPorts.get(fd);
if (port == null)
m_ErrNo = EBADF;
return port;
}
}
private static String getString(char[] buffer, int offset) {
StringBuffer s = new StringBuffer();
char c;
while ((c = buffer[offset++]) != 0)
s.append((char) c);
return s.toString();
}
public String getPortNamePattern() {
return "^COM.*";
}
public List<String> getPortList() {
Pattern p = JTermios.getPortNamePattern(this);
char[] buffer;
int size = 0;
for (size = 16 * 1024; size < 256 * 1024; size *= 2) {
buffer = new char[size];
int res = QueryDosDeviceW(null, buffer, buffer.length);
if (res > 0) { //
LinkedList<String> list = new LinkedList<String>();
int offset = 0;
String port;
while ((port = getString(buffer, offset)).length() > 0) {
if (p.matcher(port).matches())
list.add(port);
offset += port.length() + 1;
}
return list;
} else {
int err = GetLastError();
if (err != ERROR_INSUFFICIENT_BUFFER) {
log = log && log(1, "QueryDosDeviceW() failed with GetLastError() = %d\n", err);
return null;
}
}
}
log = log && log(1, "Repeated QueryDosDeviceW() calls failed up to buffer size %d\n", size);
return null;
}
public void shutDown() {
for (Port port : m_OpenPorts.values()) {
try {
log = log && log(1, "shutDown() closing port %d\n", port.m_FD);
port.close();
} catch (Exception e) {
// should never happen
e.printStackTrace();
}
}
}
public int setspeed(int fd, Termios termios, int speed) {
int br = speed;
switch (speed) {
case 50:
br = B50;
break;
case 75:
br = B75;
break;
case 110:
br = B110;
break;
case 134:
br = B134;
break;
case 150:
br = B150;
break;
case 200:
br = B200;
break;
case 300:
br = B300;
break;
case 600:
br = B600;
break;
case 1200:
br = B1200;
break;
case 1800:
br = B1800;
break;
case 2400:
br = B2400;
break;
case 4800:
br = B4800;
break;
case 9600:
br = B9600;
break;
case 19200:
br = B19200;
break;
case 38400:
br = B38400;
break;
case 7200:
br = B7200;
break;
case 14400:
br = B14400;
break;
case 28800:
br = B28800;
break;
case 57600:
br = B57600;
break;
case 76800:
br = B76800;
break;
case 115200:
br = B115200;
break;
case 230400:
br = B230400;
break;
}
int r;
if ((r = cfsetispeed(termios, br)) != 0)
return r;
if ((r = cfsetospeed(termios, br)) != 0)
return r;
if ((r = tcsetattr(fd, TCSANOW, termios)) != 0)
return r;
return 0;
}
public int pipe(int[] fds) {
m_ErrNo = EMFILE; // pipe() not implemented on Windows backend
return -1;
}
}
| true | true | public int select(int n, FDSet readfds, FDSet writefds, FDSet exceptfds, TimeVal timeout) {
// long T0 = System.currentTimeMillis();
int ready = 0;
LinkedList<Port> locked = new LinkedList<Port>();
try {
try {
LinkedList<Port> waiting = new LinkedList<Port>();
for (int fd = 0; fd < n; fd++) {
boolean rd = FD_ISSET(fd, readfds);
boolean wr = FD_ISSET(fd, writefds);
FD_CLR(fd, readfds);
FD_CLR(fd, writefds);
if (rd || wr) {
Port port = getPort(fd);
if (port == null)
return -1;
try {
port.lock();
locked.add(port);
clearCommErrors(port);
// check if there is data to be read, as WaitCommEvent
// does check for only *new* data that and thus
// might wait indefinitely if select() is called twice
// without first reading away all data
if (rd && port.m_COMSTAT.cbInQue > 0) {
FD_SET(fd, readfds);
ready++;
}
if (wr && port.m_COMSTAT.cbOutQue == 0) {
FD_SET(fd, writefds);
ready++;
}
if (port.m_WaitPending) {
if (!SetCommMask(port.m_Comm, 0))
port.fail();
if (!GetOverlappedResult(port.m_Comm, port.m_SelOVL, port.m_SelN, false) && GetLastError() != ERROR_OPERATION_ABORTED)
port.fail() ;
port.m_WaitPending = false;
}
if (!ResetEvent(port.m_SelOVL.hEvent))
port.fail();
int flags = 0;
if (rd)
flags |= EV_RXCHAR;
if (wr)
flags |= EV_TXEMPTY;
if (!SetCommMask(port.m_Comm, flags))
port.fail();
if (WaitCommEvent(port.m_Comm, port.m_EventFlags, port.m_SelOVL)) {
if (!GetOverlappedResult(port.m_Comm, port.m_SelOVL, port.m_SelN, false))
port.fail();
// actually it seems that overlapped
// WaitCommEvent never returns true so we never get here
ready = maskToFDSets(port, readfds, writefds, exceptfds, ready);
} else {
// FIXME if the port dies on us what happens
if (GetLastError() != ERROR_IO_PENDING)
port.fail();
waiting.add(port);
port.m_WaitPending = true;
}
} catch (InterruptedException ie) {
m_ErrNo = EINTR;
return -1;
}
}
}
if (ready == 0) {
int waitn = waiting.size();
if (waitn > 0) {
HANDLE[] wobj = new HANDLE[waiting.size() * 2];
int i = 0;
for (Port port : waiting) {
wobj[i++] = port.m_SelOVL.hEvent;
wobj[i++] = port.m_CancelWaitSema4;
}
int tout = timeout != null ? (int) (timeout.tv_sec * 1000 + timeout.tv_usec / 1000) : INFINITE;
// int res = WaitForSingleObject(wobj[0], tout);
int res = WaitForMultipleObjects(waitn * 2, wobj, false, tout);
if (res == WAIT_TIMEOUT) {
// work around the fact that sometimes we miss
// events
for (Port port : waiting) {
clearCommErrors(port);
int[] mask = { 0 };
if (!GetCommMask(port.m_Comm, mask))
port.fail();
if (port.m_COMSTAT.cbInQue > 0 && ((mask[0] & EV_RXCHAR) != 0)) {
FD_SET(port.m_FD, readfds);
log = log && log(1, "missed EV_RXCHAR event\n");
return 1;
}
if (port.m_COMSTAT.cbOutQue == 0 && ((mask[0] & EV_TXEMPTY) != 0)) {
FD_SET(port.m_FD, writefds);
log = log && log(1, "missed EV_TXEMPTY event\n");
return 1;
}
}
}
if (res != WAIT_TIMEOUT) {
i = (res - WAIT_OBJECT_0) / 2;
if (i < 0 || i >= waitn)
throw new Fail();
if (((res - WAIT_OBJECT_0) & 1) == 1) {
// it was the cancel sema4 so just return
return 0;
}
Port port = waiting.get(i);
if (!GetOverlappedResult(port.m_Comm, port.m_SelOVL, port.m_SelN, false))
port.fail();
ready = maskToFDSets(port, readfds, writefds, exceptfds, ready);
port.m_WaitPending = false;
}
} else {
if (timeout != null)
nanoSleep(timeout.tv_sec * 1000000000L + timeout.tv_usec * 1000);
else {
m_ErrNo = EINVAL;
return -1;
}
return 0;
}
}
} catch (Fail f) {
f.printStackTrace();
return -1;
}
} finally {
for (Port port : locked)
port.unlock();
}
// long T1 = System.currentTimeMillis();
// System.err.println("select() " + (T1 - T0));
return ready;
}
| public int select(int n, FDSet readfds, FDSet writefds, FDSet exceptfds, TimeVal timeout) {
// long T0 = System.currentTimeMillis();
int ready = 0;
LinkedList<Port> locked = new LinkedList<Port>();
try {
try {
LinkedList<Port> waiting = new LinkedList<Port>();
for (int fd = 0; fd < n; fd++) {
boolean rd = FD_ISSET(fd, readfds);
boolean wr = FD_ISSET(fd, writefds);
FD_CLR(fd, readfds);
FD_CLR(fd, writefds);
if (rd || wr) {
Port port = getPort(fd);
if (port == null)
return -1;
try {
port.lock();
locked.add(port);
clearCommErrors(port);
// check if there is data to be read, as WaitCommEvent
// does check for only *new* data that and thus
// might wait indefinitely if select() is called twice
// without first reading away all data
if (rd && port.m_COMSTAT.cbInQue > 0) {
FD_SET(fd, readfds);
ready++;
}
if (wr && port.m_COMSTAT.cbOutQue == 0) {
FD_SET(fd, writefds);
ready++;
}
if (port.m_WaitPending) {
if (!SetCommMask(port.m_Comm, 0))
port.fail();
GetOverlappedResult(port.m_Comm, port.m_SelOVL, port.m_SelN, false) ;
port.m_WaitPending = false;
}
if (!ResetEvent(port.m_SelOVL.hEvent))
port.fail();
int flags = 0;
if (rd)
flags |= EV_RXCHAR;
if (wr)
flags |= EV_TXEMPTY;
if (!SetCommMask(port.m_Comm, flags))
port.fail();
if (WaitCommEvent(port.m_Comm, port.m_EventFlags, port.m_SelOVL)) {
if (!GetOverlappedResult(port.m_Comm, port.m_SelOVL, port.m_SelN, false))
port.fail();
// actually it seems that overlapped
// WaitCommEvent never returns true so we never get here
ready = maskToFDSets(port, readfds, writefds, exceptfds, ready);
} else {
// FIXME if the port dies on us what happens
if (GetLastError() != ERROR_IO_PENDING)
port.fail();
waiting.add(port);
port.m_WaitPending = true;
}
} catch (InterruptedException ie) {
m_ErrNo = EINTR;
return -1;
}
}
}
if (ready == 0) {
int waitn = waiting.size();
if (waitn > 0) {
HANDLE[] wobj = new HANDLE[waiting.size() * 2];
int i = 0;
for (Port port : waiting) {
wobj[i++] = port.m_SelOVL.hEvent;
wobj[i++] = port.m_CancelWaitSema4;
}
int tout = timeout != null ? (int) (timeout.tv_sec * 1000 + timeout.tv_usec / 1000) : INFINITE;
// int res = WaitForSingleObject(wobj[0], tout);
int res = WaitForMultipleObjects(waitn * 2, wobj, false, tout);
if (res == WAIT_TIMEOUT) {
// work around the fact that sometimes we miss
// events
for (Port port : waiting) {
clearCommErrors(port);
int[] mask = { 0 };
if (!GetCommMask(port.m_Comm, mask))
port.fail();
if (port.m_COMSTAT.cbInQue > 0 && ((mask[0] & EV_RXCHAR) != 0)) {
FD_SET(port.m_FD, readfds);
log = log && log(1, "missed EV_RXCHAR event\n");
return 1;
}
if (port.m_COMSTAT.cbOutQue == 0 && ((mask[0] & EV_TXEMPTY) != 0)) {
FD_SET(port.m_FD, writefds);
log = log && log(1, "missed EV_TXEMPTY event\n");
return 1;
}
}
}
if (res != WAIT_TIMEOUT) {
i = (res - WAIT_OBJECT_0) / 2;
if (i < 0 || i >= waitn)
throw new Fail();
if (((res - WAIT_OBJECT_0) & 1) == 1) {
// it was the cancel sema4 so just return
return 0;
}
Port port = waiting.get(i);
if (!GetOverlappedResult(port.m_Comm, port.m_SelOVL, port.m_SelN, false))
port.fail();
ready = maskToFDSets(port, readfds, writefds, exceptfds, ready);
port.m_WaitPending = false;
}
} else {
if (timeout != null)
nanoSleep(timeout.tv_sec * 1000000000L + timeout.tv_usec * 1000);
else {
m_ErrNo = EINVAL;
return -1;
}
return 0;
}
}
} catch (Fail f) {
f.printStackTrace();
return -1;
}
} finally {
for (Port port : locked)
port.unlock();
}
// long T1 = System.currentTimeMillis();
// System.err.println("select() " + (T1 - T0));
return ready;
}
|
diff --git a/ee3_common/com/pahimar/ee3/core/handlers/EntityLivingHandler.java b/ee3_common/com/pahimar/ee3/core/handlers/EntityLivingHandler.java
index 3c333750..dce6c0df 100644
--- a/ee3_common/com/pahimar/ee3/core/handlers/EntityLivingHandler.java
+++ b/ee3_common/com/pahimar/ee3/core/handlers/EntityLivingHandler.java
@@ -1,42 +1,42 @@
package com.pahimar.ee3.core.handlers;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.projectile.EntityArrow;
import net.minecraftforge.event.ForgeSubscribe;
import net.minecraftforge.event.entity.living.LivingDeathEvent;
import net.minecraftforge.event.entity.living.LivingEvent.LivingUpdateEvent;
import com.pahimar.ee3.core.helper.ItemDropHelper;
/**
* Equivalent-Exchange-3
*
* EntityLivingHandler
*
* @author pahimar
* @license Lesser GNU Public License v3 (http://www.gnu.org/licenses/lgpl.html)
*
*/
public class EntityLivingHandler {
@ForgeSubscribe
public void onEntityLivingUpdate(LivingUpdateEvent event) {
}
@ForgeSubscribe
public void onEntityLivingDeath(LivingDeathEvent event) {
if (event.source.getDamageType().equals("player")) {
ItemDropHelper.dropMiniumShard((EntityPlayer) event.source.getSourceOfDamage(), event.entityLiving);
}
if (event.source.getSourceOfDamage() instanceof EntityArrow) {
if (((EntityArrow) event.source.getSourceOfDamage()).shootingEntity != null) {
if (((EntityArrow) event.source.getSourceOfDamage()).shootingEntity instanceof EntityPlayer) {
- ItemDropHelper.dropMiniumShard((EntityPlayer) event.source.getSourceOfDamage(), event.entityLiving);
+ ItemDropHelper.dropMiniumShard((EntityPlayer) ((EntityArrow)event.source.getSourceOfDamage()).shootingEntity, event.entityLiving);
}
}
}
}
}
| true | true | public void onEntityLivingDeath(LivingDeathEvent event) {
if (event.source.getDamageType().equals("player")) {
ItemDropHelper.dropMiniumShard((EntityPlayer) event.source.getSourceOfDamage(), event.entityLiving);
}
if (event.source.getSourceOfDamage() instanceof EntityArrow) {
if (((EntityArrow) event.source.getSourceOfDamage()).shootingEntity != null) {
if (((EntityArrow) event.source.getSourceOfDamage()).shootingEntity instanceof EntityPlayer) {
ItemDropHelper.dropMiniumShard((EntityPlayer) event.source.getSourceOfDamage(), event.entityLiving);
}
}
}
}
| public void onEntityLivingDeath(LivingDeathEvent event) {
if (event.source.getDamageType().equals("player")) {
ItemDropHelper.dropMiniumShard((EntityPlayer) event.source.getSourceOfDamage(), event.entityLiving);
}
if (event.source.getSourceOfDamage() instanceof EntityArrow) {
if (((EntityArrow) event.source.getSourceOfDamage()).shootingEntity != null) {
if (((EntityArrow) event.source.getSourceOfDamage()).shootingEntity instanceof EntityPlayer) {
ItemDropHelper.dropMiniumShard((EntityPlayer) ((EntityArrow)event.source.getSourceOfDamage()).shootingEntity, event.entityLiving);
}
}
}
}
|
diff --git a/src/main/java/br/ufrj/dcc/compgraf/im/crop/CropMouseAdapter.java b/src/main/java/br/ufrj/dcc/compgraf/im/crop/CropMouseAdapter.java
index 5ebcea8..4028a3f 100644
--- a/src/main/java/br/ufrj/dcc/compgraf/im/crop/CropMouseAdapter.java
+++ b/src/main/java/br/ufrj/dcc/compgraf/im/crop/CropMouseAdapter.java
@@ -1,69 +1,71 @@
package br.ufrj.dcc.compgraf.im.crop;
import java.awt.Component;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import br.ufrj.dcc.compgraf.im.ui.UIContext;
import br.ufrj.dcc.compgraf.im.ui.swing.ext.ScrollablePicture;
public class CropMouseAdapter extends MouseAdapter
{
private static CropMouseAdapter instance;
private boolean nextClickIsCrop = false;
private CropMouseAdapter() {}
public static CropMouseAdapter instance()
{
if (instance == null)
instance = new CropMouseAdapter();
return instance;
}
@Override
public void mouseClicked(MouseEvent e)
{
if (!nextClickIsCrop)
{
Point clickedPixel = new Point(e.getX(), e.getY());
CropContext.instance().setClickedPixel(clickedPixel);
((Component) e.getSource()).repaint();
nextClickIsCrop = true;
}
else
{
CropContext cc = CropContext.instance();
int startx = (int) cc.getClickedPixel().getX();
int starty = (int) cc.getClickedPixel().getY();
int endx = (int) cc.getCurrentPixel().getX();
int endy = (int) cc.getCurrentPixel().getY();
BufferedImage cropped = new Cropper().crop(UIContext.instance().getCurrentImage(), startx, starty, endx, endy);
UIContext.instance().changeCurrentImage(cropped);
cc.setCropRunning(false);
ScrollablePicture pic = (ScrollablePicture) e.getSource();
pic.repaint();
+ pic.removeMouseListener(CropMouseAdapter.instance());
+ pic.removeMouseMotionListener(CropMouseAdapter.instance());
}
}
@Override
public void mouseMoved(MouseEvent e)
{
Point currentPixel = new Point(e.getX(), e.getY());
CropContext.instance().setCurrentPixel(currentPixel);
((Component) e.getSource()).repaint();
}
}
| true | true | public void mouseClicked(MouseEvent e)
{
if (!nextClickIsCrop)
{
Point clickedPixel = new Point(e.getX(), e.getY());
CropContext.instance().setClickedPixel(clickedPixel);
((Component) e.getSource()).repaint();
nextClickIsCrop = true;
}
else
{
CropContext cc = CropContext.instance();
int startx = (int) cc.getClickedPixel().getX();
int starty = (int) cc.getClickedPixel().getY();
int endx = (int) cc.getCurrentPixel().getX();
int endy = (int) cc.getCurrentPixel().getY();
BufferedImage cropped = new Cropper().crop(UIContext.instance().getCurrentImage(), startx, starty, endx, endy);
UIContext.instance().changeCurrentImage(cropped);
cc.setCropRunning(false);
ScrollablePicture pic = (ScrollablePicture) e.getSource();
pic.repaint();
}
}
| public void mouseClicked(MouseEvent e)
{
if (!nextClickIsCrop)
{
Point clickedPixel = new Point(e.getX(), e.getY());
CropContext.instance().setClickedPixel(clickedPixel);
((Component) e.getSource()).repaint();
nextClickIsCrop = true;
}
else
{
CropContext cc = CropContext.instance();
int startx = (int) cc.getClickedPixel().getX();
int starty = (int) cc.getClickedPixel().getY();
int endx = (int) cc.getCurrentPixel().getX();
int endy = (int) cc.getCurrentPixel().getY();
BufferedImage cropped = new Cropper().crop(UIContext.instance().getCurrentImage(), startx, starty, endx, endy);
UIContext.instance().changeCurrentImage(cropped);
cc.setCropRunning(false);
ScrollablePicture pic = (ScrollablePicture) e.getSource();
pic.repaint();
pic.removeMouseListener(CropMouseAdapter.instance());
pic.removeMouseMotionListener(CropMouseAdapter.instance());
}
}
|
diff --git a/src/main/java/com/yahoo/omid/tso/TSOServerConfig.java b/src/main/java/com/yahoo/omid/tso/TSOServerConfig.java
index f66d83c..f464651 100644
--- a/src/main/java/com/yahoo/omid/tso/TSOServerConfig.java
+++ b/src/main/java/com/yahoo/omid/tso/TSOServerConfig.java
@@ -1,108 +1,108 @@
/**
* Copyright (c) 2011 Yahoo! 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. See accompanying LICENSE file.
*/
package com.yahoo.omid.tso;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
/**
* Holds the configuration parameters of a TSO server instance.
*
*/
public class TSOServerConfig {
static public TSOServerConfig configFactory(){
return new TSOServerConfig();
}
static public TSOServerConfig configFactory(int port, int batch, boolean recoveryEnabled, int ensSize, int qSize, String zkservers){
return new TSOServerConfig(port, batch, recoveryEnabled, ensSize, qSize, zkservers);
}
static public TSOServerConfig parseConfig(String args[]){
- config = new TSOServerConfig();
+ TSOServerConfig config = new TSOServerConfig();
if (args.length == 0) {
new JCommander(config).usage();
System.exit(0);
}
new JCommander(config, args);
return config;
}
@Parameter(names = "-port", description = "Port reserved by the Status Oracle", required = true)
private int port;
@Parameter(names = "-batch", description = "Threshold for the batch sent to the WAL")
private int batch;
@Parameter(names = "-ha", description = "Highly Available status oracle: logs operations to the WAL and recovers from a crash")
private boolean recoveryEnabled;
@Parameter(names = "-zk", description = "ZooKeeper ensemble: host1:port1,host2:port2...")
private String zkServers;
@Parameter(names = "-ensemble", description = "WAL ensemble size")
private int ensemble;
@Parameter(names = "-quorum", description = "WAL quorum size")
private int quorum;
TSOServerConfig(){
this.port = Integer.parseInt(System.getProperty("PORT", "1234"));
this.batch = Integer.parseInt(System.getProperty("BATCH", "0"));
this.recoveryEnabled = Boolean.parseBoolean(System.getProperty("RECOVERABLE", "false"));
this.zkServers = System.getProperty("ZKSERVERS");
this.ensemble = Integer.parseInt(System.getProperty("ENSEMBLE", "3"));
this.quorum = Integer.parseInt(System.getProperty("QUORUM", "2"));
}
TSOServerConfig(int port, int batch, boolean recoveryEnabled, int ensemble, int quorum, String zkServers){
this.port = port;
this.batch = batch;
this.recoveryEnabled = recoveryEnabled;
this.zkServers = zkServers;
this.ensemble = ensemble;
this.quorum = quorum;
}
public int getPort(){
return port;
}
public int getBatchSize(){
return batch;
}
public boolean isRecoveryEnabled(){
return recoveryEnabled;
}
public String getZkServers(){
return zkServers;
}
public int getEnsembleSize(){
return ensemble;
}
public int getQuorumSize(){
return quorum;
}
}
| true | true | static public TSOServerConfig parseConfig(String args[]){
config = new TSOServerConfig();
if (args.length == 0) {
new JCommander(config).usage();
System.exit(0);
}
new JCommander(config, args);
return config;
}
| static public TSOServerConfig parseConfig(String args[]){
TSOServerConfig config = new TSOServerConfig();
if (args.length == 0) {
new JCommander(config).usage();
System.exit(0);
}
new JCommander(config, args);
return config;
}
|
diff --git a/src/org/logicprobe/LogicMail/util/UtilProxy.java b/src/org/logicprobe/LogicMail/util/UtilProxy.java
index eca60b8..377371e 100644
--- a/src/org/logicprobe/LogicMail/util/UtilProxy.java
+++ b/src/org/logicprobe/LogicMail/util/UtilProxy.java
@@ -1,115 +1,115 @@
/*-
* Copyright (c) 2006, Derek Konigsberg
* 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.logicprobe.LogicMail.util;
import java.io.IOException;
import org.logicprobe.LogicMail.AppInfo;
/**
* Proxy for utility classes and methods that may
* have multiple implementations depending on the
* project build configuration.
*/
public abstract class UtilProxy {
private static UtilProxy instance = null;
/**
* Creates a new instance of UtilProxy
*/
private static UtilProxy createUtilProxy() {
UtilProxy utilProxy = null;
String version = AppInfo.getVersion();
try {
- if(version.indexOf("BB v4.0") != -1) {
+ if(version.endsWith(".40")) {
utilProxy =
(UtilProxy)Class.forName("org.logicprobe.LogicMail.util.UtilProxyBB40").newInstance();
}
- else if(version.indexOf("BB v4.1") != -1) {
+ else if(version.endsWith(".41")) {
utilProxy =
(UtilProxy)Class.forName("org.logicprobe.LogicMail.util.UtilProxyBB41").newInstance();
}
} catch (ClassNotFoundException e) {
utilProxy = null;
} catch (InstantiationException e) {
utilProxy = null;
} catch (IllegalAccessException e) {
utilProxy = null;
}
return utilProxy;
}
public static synchronized UtilProxy getInstance() {
if(instance == null) {
instance = createUtilProxy();
if(instance == null) {
throw new RuntimeException("Application configuration error");
}
}
return instance;
}
/**
* Decode the Base64 encoded input and return the result.
*
* @param input The Base64 encoded input
* @return A byte array containing the decoded input.
* @throw IOException Thrown if a decoding error occurred.
*/
public abstract byte[] Base64Decode(String input) throws IOException;
/**
* Encodes the provided input into Base 64 and returns the encoded result.
*
* @param input The input data to encode
* @param inputOffset The offset into the array
* @param inputLength The length of the array
* @param insertCR Set to true if you want to insert a CR after every 76th encoded character
* @param insertLF Set to true if you want to insert a LF after every 76th encoded character
* @throw IOException Thrown if an encoding error occurred
* @return The encoded input as a byte array
*/
public abstract byte[] Base64Encode(byte[] input, int inputOffset, int inputLength, boolean insertCR, boolean insertLF) throws IOException;
/**
* Encodes the provided input into Base 64 and returns the encoded result.
*
* @param input The input data to encode
* @param inputOffset The offset into the array
* @param inputLength The length of the array
* @param insertCR Set to true if you want to insert a CR after every 76th encoded character
* @param insertLF Set to true if you want to insert a LF after every 76th encoded character
* @throw IOException Thrown if an encoding error occurred
* @return The encoded input as a string
*/
public abstract String Base64EncodeAsString(byte[] input, int inputOffset, int inputLength, boolean insertCR, boolean insertLF) throws IOException;
}
| false | true | private static UtilProxy createUtilProxy() {
UtilProxy utilProxy = null;
String version = AppInfo.getVersion();
try {
if(version.indexOf("BB v4.0") != -1) {
utilProxy =
(UtilProxy)Class.forName("org.logicprobe.LogicMail.util.UtilProxyBB40").newInstance();
}
else if(version.indexOf("BB v4.1") != -1) {
utilProxy =
(UtilProxy)Class.forName("org.logicprobe.LogicMail.util.UtilProxyBB41").newInstance();
}
} catch (ClassNotFoundException e) {
utilProxy = null;
} catch (InstantiationException e) {
utilProxy = null;
} catch (IllegalAccessException e) {
utilProxy = null;
}
return utilProxy;
}
| private static UtilProxy createUtilProxy() {
UtilProxy utilProxy = null;
String version = AppInfo.getVersion();
try {
if(version.endsWith(".40")) {
utilProxy =
(UtilProxy)Class.forName("org.logicprobe.LogicMail.util.UtilProxyBB40").newInstance();
}
else if(version.endsWith(".41")) {
utilProxy =
(UtilProxy)Class.forName("org.logicprobe.LogicMail.util.UtilProxyBB41").newInstance();
}
} catch (ClassNotFoundException e) {
utilProxy = null;
} catch (InstantiationException e) {
utilProxy = null;
} catch (IllegalAccessException e) {
utilProxy = null;
}
return utilProxy;
}
|
diff --git a/src/java/com/android/internal/telephony/gsm/GsmServiceStateTracker.java b/src/java/com/android/internal/telephony/gsm/GsmServiceStateTracker.java
index 56cf53a..808ec2b 100644
--- a/src/java/com/android/internal/telephony/gsm/GsmServiceStateTracker.java
+++ b/src/java/com/android/internal/telephony/gsm/GsmServiceStateTracker.java
@@ -1,1727 +1,1728 @@
/*
* Copyright (C) 2006 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.internal.telephony.gsm;
import com.android.internal.telephony.CommandException;
import com.android.internal.telephony.CommandsInterface;
import com.android.internal.telephony.DataConnectionTracker;
import com.android.internal.telephony.EventLogTags;
import com.android.internal.telephony.IccCard;
import com.android.internal.telephony.IccCardConstants;
import com.android.internal.telephony.IccCardStatus;
import com.android.internal.telephony.MccTable;
import com.android.internal.telephony.Phone;
import com.android.internal.telephony.RestrictedState;
import com.android.internal.telephony.RILConstants;
import com.android.internal.telephony.ServiceStateTracker;
import com.android.internal.telephony.TelephonyIntents;
import com.android.internal.telephony.TelephonyProperties;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.database.ContentObserver;
import android.os.AsyncResult;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.Registrant;
import android.os.RegistrantList;
import android.os.SystemClock;
import android.os.SystemProperties;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.telephony.ServiceState;
import android.telephony.SignalStrength;
import android.telephony.gsm.GsmCellLocation;
import android.text.TextUtils;
import android.util.EventLog;
import android.util.Log;
import android.util.TimeUtils;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.TimeZone;
/**
* {@hide}
*/
final class GsmServiceStateTracker extends ServiceStateTracker {
static final String LOG_TAG = "GSM";
static final boolean DBG = true;
GSMPhone phone;
GsmCellLocation cellLoc;
GsmCellLocation newCellLoc;
int mPreferredNetworkType;
private int gprsState = ServiceState.STATE_OUT_OF_SERVICE;
private int newGPRSState = ServiceState.STATE_OUT_OF_SERVICE;
private int mMaxDataCalls = 1;
private int mNewMaxDataCalls = 1;
private int mReasonDataDenied = -1;
private int mNewReasonDataDenied = -1;
/**
* GSM roaming status solely based on TS 27.007 7.2 CREG. Only used by
* handlePollStateResult to store CREG roaming result.
*/
private boolean mGsmRoaming = false;
/**
* Data roaming status solely based on TS 27.007 10.1.19 CGREG. Only used by
* handlePollStateResult to store CGREG roaming result.
*/
private boolean mDataRoaming = false;
/**
* Mark when service state is in emergency call only mode
*/
private boolean mEmergencyOnly = false;
/**
* Sometimes we get the NITZ time before we know what country we
* are in. Keep the time zone information from the NITZ string so
* we can fix the time zone once know the country.
*/
private boolean mNeedFixZoneAfterNitz = false;
private int mZoneOffset;
private boolean mZoneDst;
private long mZoneTime;
private boolean mGotCountryCode = false;
private ContentResolver cr;
/** Boolean is true is setTimeFromNITZString was called */
private boolean mNitzUpdatedTime = false;
String mSavedTimeZone;
long mSavedTime;
long mSavedAtTime;
/**
* We can't register for SIM_RECORDS_LOADED immediately because the
* SIMRecords object may not be instantiated yet.
*/
private boolean mNeedToRegForSimLoaded;
/** Started the recheck process after finding gprs should registered but not. */
private boolean mStartedGprsRegCheck = false;
/** Already sent the event-log for no gprs register. */
private boolean mReportedGprsNoReg = false;
/**
* The Notification object given to the NotificationManager.
*/
private Notification mNotification;
/** Wake lock used while setting time of day. */
private PowerManager.WakeLock mWakeLock;
private static final String WAKELOCK_TAG = "ServiceStateTracker";
/** Keep track of SPN display rules, so we only broadcast intent if something changes. */
private String curSpn = null;
private String curPlmn = null;
private int curSpnRule = 0;
/** waiting period before recheck gprs and voice registration. */
static final int DEFAULT_GPRS_CHECK_PERIOD_MILLIS = 60 * 1000;
/** Notification type. */
static final int PS_ENABLED = 1001; // Access Control blocks data service
static final int PS_DISABLED = 1002; // Access Control enables data service
static final int CS_ENABLED = 1003; // Access Control blocks all voice/sms service
static final int CS_DISABLED = 1004; // Access Control enables all voice/sms service
static final int CS_NORMAL_ENABLED = 1005; // Access Control blocks normal voice/sms service
static final int CS_EMERGENCY_ENABLED = 1006; // Access Control blocks emergency call service
/** Notification id. */
static final int PS_NOTIFICATION = 888; // Id to update and cancel PS restricted
static final int CS_NOTIFICATION = 999; // Id to update and cancel CS restricted
private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_LOCALE_CHANGED)) {
// update emergency string whenever locale changed
updateSpnDisplay();
}
}
};
private ContentObserver mAutoTimeObserver = new ContentObserver(new Handler()) {
@Override
public void onChange(boolean selfChange) {
Log.i("GsmServiceStateTracker", "Auto time state changed");
revertToNitzTime();
}
};
private ContentObserver mAutoTimeZoneObserver = new ContentObserver(new Handler()) {
@Override
public void onChange(boolean selfChange) {
Log.i("GsmServiceStateTracker", "Auto time zone state changed");
revertToNitzTimeZone();
}
};
public GsmServiceStateTracker(GSMPhone phone) {
super();
this.phone = phone;
cm = phone.mCM;
ss = new ServiceState();
newSS = new ServiceState();
cellLoc = new GsmCellLocation();
newCellLoc = new GsmCellLocation();
mSignalStrength = new SignalStrength();
PowerManager powerManager =
(PowerManager)phone.getContext().getSystemService(Context.POWER_SERVICE);
mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
cm.registerForAvailable(this, EVENT_RADIO_AVAILABLE, null);
cm.registerForRadioStateChanged(this, EVENT_RADIO_STATE_CHANGED, null);
cm.registerForVoiceNetworkStateChanged(this, EVENT_NETWORK_STATE_CHANGED, null);
cm.setOnNITZTime(this, EVENT_NITZ_TIME, null);
cm.setOnSignalStrengthUpdate(this, EVENT_SIGNAL_STRENGTH_UPDATE, null);
cm.setOnRestrictedStateChanged(this, EVENT_RESTRICTED_STATE_CHANGED, null);
phone.getIccCard().registerForReady(this, EVENT_SIM_READY, null);
// system setting property AIRPLANE_MODE_ON is set in Settings.
int airplaneMode = Settings.System.getInt(
phone.getContext().getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, 0);
mDesiredPowerState = ! (airplaneMode > 0);
cr = phone.getContext().getContentResolver();
cr.registerContentObserver(
Settings.System.getUriFor(Settings.System.AUTO_TIME), true,
mAutoTimeObserver);
cr.registerContentObserver(
Settings.System.getUriFor(Settings.System.AUTO_TIME_ZONE), true,
mAutoTimeZoneObserver);
setSignalStrengthDefaultValues();
mNeedToRegForSimLoaded = true;
// Monitor locale change
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_LOCALE_CHANGED);
phone.getContext().registerReceiver(mIntentReceiver, filter);
// Gsm doesn't support OTASP so its not needed
phone.notifyOtaspChanged(OTASP_NOT_NEEDED);
}
public void dispose() {
// Unregister for all events.
cm.unregisterForAvailable(this);
cm.unregisterForRadioStateChanged(this);
cm.unregisterForVoiceNetworkStateChanged(this);
phone.getIccCard().unregisterForReady(this);
phone.mIccRecords.unregisterForRecordsLoaded(this);
cm.unSetOnSignalStrengthUpdate(this);
cm.unSetOnRestrictedStateChanged(this);
cm.unSetOnNITZTime(this);
cr.unregisterContentObserver(this.mAutoTimeObserver);
cr.unregisterContentObserver(this.mAutoTimeZoneObserver);
}
protected void finalize() {
if(DBG) log("finalize");
}
@Override
protected Phone getPhone() {
return phone;
}
public void handleMessage (Message msg) {
AsyncResult ar;
int[] ints;
String[] strings;
Message message;
if (!phone.mIsTheCurrentActivePhone) {
Log.e(LOG_TAG, "Received message " + msg +
"[" + msg.what + "] while being destroyed. Ignoring.");
return;
}
switch (msg.what) {
case EVENT_RADIO_AVAILABLE:
//this is unnecessary
//setPowerStateToDesired();
break;
case EVENT_SIM_READY:
// Set the network type, in case the radio does not restore it.
cm.setCurrentPreferredNetworkType();
// The SIM is now ready i.e if it was locked
// it has been unlocked. At this stage, the radio is already
// powered on.
if (mNeedToRegForSimLoaded) {
phone.mIccRecords.registerForRecordsLoaded(this,
EVENT_SIM_RECORDS_LOADED, null);
mNeedToRegForSimLoaded = false;
}
boolean skipRestoringSelection = phone.getContext().getResources().getBoolean(
com.android.internal.R.bool.skip_restoring_network_selection);
if (!skipRestoringSelection) {
// restore the previous network selection.
phone.restoreSavedNetworkSelection(null);
}
pollState();
// Signal strength polling stops when radio is off
queueNextSignalStrengthPoll();
break;
case EVENT_RADIO_STATE_CHANGED:
// This will do nothing in the radio not
// available case
setPowerStateToDesired();
pollState();
break;
case EVENT_NETWORK_STATE_CHANGED:
pollState();
break;
case EVENT_GET_SIGNAL_STRENGTH:
// This callback is called when signal strength is polled
// all by itself
if (!(cm.getRadioState().isOn())) {
// Polling will continue when radio turns back on
return;
}
ar = (AsyncResult) msg.obj;
onSignalStrengthResult(ar);
queueNextSignalStrengthPoll();
break;
case EVENT_GET_LOC_DONE:
ar = (AsyncResult) msg.obj;
if (ar.exception == null) {
String states[] = (String[])ar.result;
int lac = -1;
int cid = -1;
if (states.length >= 3) {
try {
if (states[1] != null && states[1].length() > 0) {
lac = Integer.parseInt(states[1], 16);
}
if (states[2] != null && states[2].length() > 0) {
cid = Integer.parseInt(states[2], 16);
}
} catch (NumberFormatException ex) {
Log.w(LOG_TAG, "error parsing location: " + ex);
}
}
cellLoc.setLacAndCid(lac, cid);
phone.notifyLocationChanged();
}
// Release any temporary cell lock, which could have been
// acquired to allow a single-shot location update.
disableSingleLocationUpdate();
break;
case EVENT_POLL_STATE_REGISTRATION:
case EVENT_POLL_STATE_GPRS:
case EVENT_POLL_STATE_OPERATOR:
case EVENT_POLL_STATE_NETWORK_SELECTION_MODE:
ar = (AsyncResult) msg.obj;
handlePollStateResult(msg.what, ar);
break;
case EVENT_POLL_SIGNAL_STRENGTH:
// Just poll signal strength...not part of pollState()
cm.getSignalStrength(obtainMessage(EVENT_GET_SIGNAL_STRENGTH));
break;
case EVENT_NITZ_TIME:
ar = (AsyncResult) msg.obj;
String nitzString = (String)((Object[])ar.result)[0];
long nitzReceiveTime = ((Long)((Object[])ar.result)[1]).longValue();
setTimeFromNITZString(nitzString, nitzReceiveTime);
break;
case EVENT_SIGNAL_STRENGTH_UPDATE:
// This is a notification from
// CommandsInterface.setOnSignalStrengthUpdate
ar = (AsyncResult) msg.obj;
// The radio is telling us about signal strength changes
// we don't have to ask it
dontPollSignalStrength = true;
onSignalStrengthResult(ar);
break;
case EVENT_SIM_RECORDS_LOADED:
updateSpnDisplay();
break;
case EVENT_LOCATION_UPDATES_ENABLED:
ar = (AsyncResult) msg.obj;
if (ar.exception == null) {
cm.getVoiceRegistrationState(obtainMessage(EVENT_GET_LOC_DONE, null));
}
break;
case EVENT_SET_PREFERRED_NETWORK_TYPE:
ar = (AsyncResult) msg.obj;
// Don't care the result, only use for dereg network (COPS=2)
message = obtainMessage(EVENT_RESET_PREFERRED_NETWORK_TYPE, ar.userObj);
cm.setPreferredNetworkType(mPreferredNetworkType, message);
break;
case EVENT_RESET_PREFERRED_NETWORK_TYPE:
ar = (AsyncResult) msg.obj;
if (ar.userObj != null) {
AsyncResult.forMessage(((Message) ar.userObj)).exception
= ar.exception;
((Message) ar.userObj).sendToTarget();
}
break;
case EVENT_GET_PREFERRED_NETWORK_TYPE:
ar = (AsyncResult) msg.obj;
if (ar.exception == null) {
mPreferredNetworkType = ((int[])ar.result)[0];
} else {
mPreferredNetworkType = RILConstants.NETWORK_MODE_GLOBAL;
}
message = obtainMessage(EVENT_SET_PREFERRED_NETWORK_TYPE, ar.userObj);
int toggledNetworkType = RILConstants.NETWORK_MODE_GLOBAL;
cm.setPreferredNetworkType(toggledNetworkType, message);
break;
case EVENT_CHECK_REPORT_GPRS:
if (ss != null && !isGprsConsistent(gprsState, ss.getState())) {
// Can't register data service while voice service is ok
// i.e. CREG is ok while CGREG is not
// possible a network or baseband side error
GsmCellLocation loc = ((GsmCellLocation)phone.getCellLocation());
EventLog.writeEvent(EventLogTags.DATA_NETWORK_REGISTRATION_FAIL,
ss.getOperatorNumeric(), loc != null ? loc.getCid() : -1);
mReportedGprsNoReg = true;
}
mStartedGprsRegCheck = false;
break;
case EVENT_RESTRICTED_STATE_CHANGED:
// This is a notification from
// CommandsInterface.setOnRestrictedStateChanged
if (DBG) log("EVENT_RESTRICTED_STATE_CHANGED");
ar = (AsyncResult) msg.obj;
onRestrictedStateChanged(ar);
break;
default:
super.handleMessage(msg);
break;
}
}
protected void setPowerStateToDesired() {
// If we want it on and it's off, turn it on
if (mDesiredPowerState
&& cm.getRadioState() == CommandsInterface.RadioState.RADIO_OFF) {
cm.setRadioPower(true, null);
} else if (!mDesiredPowerState && cm.getRadioState().isOn()) {
// If it's on and available and we want it off gracefully
DataConnectionTracker dcTracker = phone.mDataConnectionTracker;
powerOffRadioSafely(dcTracker);
} // Otherwise, we're in the desired state
}
@Override
protected void hangupAndPowerOff() {
// hang up all active voice calls
if (phone.isInCall()) {
phone.mCT.ringingCall.hangupIfAlive();
phone.mCT.backgroundCall.hangupIfAlive();
phone.mCT.foregroundCall.hangupIfAlive();
}
cm.setRadioPower(false, null);
}
protected void updateSpnDisplay() {
int rule = phone.mIccRecords.getDisplayRule(ss.getOperatorNumeric());
String spn = phone.mIccRecords.getServiceProviderName();
String plmn = ss.getOperatorAlphaLong();
// For emergency calls only, pass the EmergencyCallsOnly string via EXTRA_PLMN
if (mEmergencyOnly && cm.getRadioState().isOn()) {
plmn = Resources.getSystem().
getText(com.android.internal.R.string.emergency_calls_only).toString();
if (DBG) log("updateSpnDisplay: emergency only and radio is on plmn='" + plmn + "'");
}
if (rule != curSpnRule
|| !TextUtils.equals(spn, curSpn)
|| !TextUtils.equals(plmn, curPlmn)) {
boolean showSpn = !mEmergencyOnly && !TextUtils.isEmpty(spn)
&& (rule & SIMRecords.SPN_RULE_SHOW_SPN) == SIMRecords.SPN_RULE_SHOW_SPN;
boolean showPlmn = !TextUtils.isEmpty(plmn) &&
(rule & SIMRecords.SPN_RULE_SHOW_PLMN) == SIMRecords.SPN_RULE_SHOW_PLMN;
if (DBG) {
log(String.format("updateSpnDisplay: changed sending intent" + " rule=" + rule +
" showPlmn='%b' plmn='%s' showSpn='%b' spn='%s'",
showPlmn, plmn, showSpn, spn));
}
Intent intent = new Intent(TelephonyIntents.SPN_STRINGS_UPDATED_ACTION);
intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
intent.putExtra(TelephonyIntents.EXTRA_SHOW_SPN, showSpn);
intent.putExtra(TelephonyIntents.EXTRA_SPN, spn);
intent.putExtra(TelephonyIntents.EXTRA_SHOW_PLMN, showPlmn);
intent.putExtra(TelephonyIntents.EXTRA_PLMN, plmn);
phone.getContext().sendStickyBroadcast(intent);
}
curSpnRule = rule;
curSpn = spn;
curPlmn = plmn;
}
/**
* Handle the result of one of the pollState()-related requests
*/
protected void handlePollStateResult (int what, AsyncResult ar) {
int ints[];
String states[];
// Ignore stale requests from last poll
if (ar.userObj != pollingContext) return;
if (ar.exception != null) {
CommandException.Error err=null;
if (ar.exception instanceof CommandException) {
err = ((CommandException)(ar.exception)).getCommandError();
}
if (err == CommandException.Error.RADIO_NOT_AVAILABLE) {
// Radio has crashed or turned off
cancelPollState();
return;
}
if (!cm.getRadioState().isOn()) {
// Radio has crashed or turned off
cancelPollState();
return;
}
if (err != CommandException.Error.OP_NOT_ALLOWED_BEFORE_REG_NW) {
loge("RIL implementation has returned an error where it must succeed" +
ar.exception);
}
} else try {
switch (what) {
case EVENT_POLL_STATE_REGISTRATION:
states = (String[])ar.result;
int lac = -1;
int cid = -1;
int regState = -1;
int reasonRegStateDenied = -1;
int psc = -1;
if (states.length > 0) {
try {
regState = Integer.parseInt(states[0]);
if (states.length >= 3) {
if (states[1] != null && states[1].length() > 0) {
lac = Integer.parseInt(states[1], 16);
}
if (states[2] != null && states[2].length() > 0) {
cid = Integer.parseInt(states[2], 16);
}
}
if (states.length > 14) {
if (states[14] != null && states[14].length() > 0) {
psc = Integer.parseInt(states[14], 16);
}
}
} catch (NumberFormatException ex) {
loge("error parsing RegistrationState: " + ex);
}
}
mGsmRoaming = regCodeIsRoaming(regState);
newSS.setState (regCodeToServiceState(regState));
if (regState == 10 || regState == 12 || regState == 13 || regState == 14) {
mEmergencyOnly = true;
} else {
mEmergencyOnly = false;
}
// LAC and CID are -1 if not avail
newCellLoc.setLacAndCid(lac, cid);
newCellLoc.setPsc(psc);
break;
case EVENT_POLL_STATE_GPRS:
states = (String[])ar.result;
int type = 0;
regState = -1;
mNewReasonDataDenied = -1;
mNewMaxDataCalls = 1;
if (states.length > 0) {
try {
regState = Integer.parseInt(states[0]);
// states[3] (if present) is the current radio technology
if (states.length >= 4 && states[3] != null) {
type = Integer.parseInt(states[3]);
}
if ((states.length >= 5 ) && (regState == 3)) {
mNewReasonDataDenied = Integer.parseInt(states[4]);
}
if (states.length >= 6) {
mNewMaxDataCalls = Integer.parseInt(states[5]);
}
} catch (NumberFormatException ex) {
loge("error parsing GprsRegistrationState: " + ex);
}
}
newGPRSState = regCodeToServiceState(regState);
mDataRoaming = regCodeIsRoaming(regState);
mNewRilRadioTechnology = type;
newSS.setRadioTechnology(type);
break;
case EVENT_POLL_STATE_OPERATOR:
String opNames[] = (String[])ar.result;
if (opNames != null && opNames.length >= 3) {
newSS.setOperatorName (opNames[0], opNames[1], opNames[2]);
}
break;
case EVENT_POLL_STATE_NETWORK_SELECTION_MODE:
ints = (int[])ar.result;
newSS.setIsManualSelection(ints[0] == 1);
break;
}
} catch (RuntimeException ex) {
loge("Exception while polling service state. Probably malformed RIL response." + ex);
}
pollingContext[0]--;
if (pollingContext[0] == 0) {
/**
* Since the roaming states of gsm service (from +CREG) and
* data service (from +CGREG) could be different, the new SS
* is set roaming while either one is roaming.
*
* There is an exception for the above rule. The new SS is not set
* as roaming while gsm service reports roaming but indeed it is
* not roaming between operators.
*/
boolean roaming = (mGsmRoaming || mDataRoaming);
if (mGsmRoaming && !isRoamingBetweenOperators(mGsmRoaming, newSS)) {
roaming = false;
}
newSS.setRoaming(roaming);
newSS.setEmergencyOnly(mEmergencyOnly);
pollStateDone();
}
}
private void setSignalStrengthDefaultValues() {
// TODO Make a constructor only has boolean gsm as parameter
mSignalStrength = new SignalStrength(99, -1, -1, -1, -1, -1, -1,
-1, -1, -1, SignalStrength.INVALID_SNR, -1, true);
}
/**
* A complete "service state" from our perspective is
* composed of a handful of separate requests to the radio.
*
* We make all of these requests at once, but then abandon them
* and start over again if the radio notifies us that some
* event has changed
*/
private void pollState() {
pollingContext = new int[1];
pollingContext[0] = 0;
switch (cm.getRadioState()) {
case RADIO_UNAVAILABLE:
newSS.setStateOutOfService();
newCellLoc.setStateInvalid();
setSignalStrengthDefaultValues();
mGotCountryCode = false;
mNitzUpdatedTime = false;
pollStateDone();
break;
case RADIO_OFF:
newSS.setStateOff();
newCellLoc.setStateInvalid();
setSignalStrengthDefaultValues();
mGotCountryCode = false;
mNitzUpdatedTime = false;
pollStateDone();
break;
default:
// Issue all poll-related commands at once
// then count down the responses, which
// are allowed to arrive out-of-order
pollingContext[0]++;
cm.getOperator(
obtainMessage(
EVENT_POLL_STATE_OPERATOR, pollingContext));
pollingContext[0]++;
cm.getDataRegistrationState(
obtainMessage(
EVENT_POLL_STATE_GPRS, pollingContext));
pollingContext[0]++;
cm.getVoiceRegistrationState(
obtainMessage(
EVENT_POLL_STATE_REGISTRATION, pollingContext));
pollingContext[0]++;
cm.getNetworkSelectionMode(
obtainMessage(
EVENT_POLL_STATE_NETWORK_SELECTION_MODE, pollingContext));
break;
}
}
private void pollStateDone() {
if (DBG) {
log("Poll ServiceState done: " +
" oldSS=[" + ss + "] newSS=[" + newSS +
"] oldGprs=" + gprsState + " newData=" + newGPRSState +
" oldMaxDataCalls=" + mMaxDataCalls +
" mNewMaxDataCalls=" + mNewMaxDataCalls +
" oldReasonDataDenied=" + mReasonDataDenied +
" mNewReasonDataDenied=" + mNewReasonDataDenied +
" oldType=" + ServiceState.rilRadioTechnologyToString(mRilRadioTechnology) +
" newType=" + ServiceState.rilRadioTechnologyToString(mNewRilRadioTechnology));
}
boolean hasRegistered =
ss.getState() != ServiceState.STATE_IN_SERVICE
&& newSS.getState() == ServiceState.STATE_IN_SERVICE;
boolean hasDeregistered =
ss.getState() == ServiceState.STATE_IN_SERVICE
&& newSS.getState() != ServiceState.STATE_IN_SERVICE;
boolean hasGprsAttached =
gprsState != ServiceState.STATE_IN_SERVICE
&& newGPRSState == ServiceState.STATE_IN_SERVICE;
boolean hasGprsDetached =
gprsState == ServiceState.STATE_IN_SERVICE
&& newGPRSState != ServiceState.STATE_IN_SERVICE;
boolean hasRadioTechnologyChanged = mRilRadioTechnology != mNewRilRadioTechnology;
boolean hasChanged = !newSS.equals(ss);
boolean hasRoamingOn = !ss.getRoaming() && newSS.getRoaming();
boolean hasRoamingOff = ss.getRoaming() && !newSS.getRoaming();
boolean hasLocationChanged = !newCellLoc.equals(cellLoc);
// Add an event log when connection state changes
if (ss.getState() != newSS.getState() || gprsState != newGPRSState) {
EventLog.writeEvent(EventLogTags.GSM_SERVICE_STATE_CHANGE,
ss.getState(), gprsState, newSS.getState(), newGPRSState);
}
ServiceState tss;
tss = ss;
ss = newSS;
newSS = tss;
// clean slate for next time
newSS.setStateOutOfService();
GsmCellLocation tcl = cellLoc;
cellLoc = newCellLoc;
newCellLoc = tcl;
// Add an event log when network type switched
// TODO: we may add filtering to reduce the event logged,
// i.e. check preferred network setting, only switch to 2G, etc
if (hasRadioTechnologyChanged) {
int cid = -1;
GsmCellLocation loc = ((GsmCellLocation)phone.getCellLocation());
if (loc != null) cid = loc.getCid();
EventLog.writeEvent(EventLogTags.GSM_RAT_SWITCHED, cid, mRilRadioTechnology,
mNewRilRadioTechnology);
if (DBG) {
log("RAT switched " + ServiceState.rilRadioTechnologyToString(mRilRadioTechnology) +
" -> " + ServiceState.rilRadioTechnologyToString(mNewRilRadioTechnology) +
" at cell " + cid);
}
}
gprsState = newGPRSState;
mReasonDataDenied = mNewReasonDataDenied;
mMaxDataCalls = mNewMaxDataCalls;
mRilRadioTechnology = mNewRilRadioTechnology;
// this new state has been applied - forget it until we get a new new state
mNewRilRadioTechnology = 0;
newSS.setStateOutOfService(); // clean slate for next time
if (hasRadioTechnologyChanged) {
phone.setSystemProperty(TelephonyProperties.PROPERTY_DATA_NETWORK_TYPE,
ServiceState.rilRadioTechnologyToString(mRilRadioTechnology));
}
if (hasRegistered) {
mNetworkAttachedRegistrants.notifyRegistrants();
if (DBG) {
log("pollStateDone: registering current mNitzUpdatedTime=" +
mNitzUpdatedTime + " changing to false");
}
mNitzUpdatedTime = false;
}
if (hasChanged) {
String operatorNumeric;
updateSpnDisplay();
phone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ALPHA,
ss.getOperatorAlphaLong());
String prevOperatorNumeric =
SystemProperties.get(TelephonyProperties.PROPERTY_OPERATOR_NUMERIC, "");
operatorNumeric = ss.getOperatorNumeric();
phone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_NUMERIC, operatorNumeric);
if (operatorNumeric == null) {
if (DBG) log("operatorNumeric is null");
phone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ISO_COUNTRY, "");
mGotCountryCode = false;
mNitzUpdatedTime = false;
} else {
String iso = "";
- String mcc = operatorNumeric.substring(0, 3);
+ String mcc = "";
try{
+ mcc = operatorNumeric.substring(0, 3);
iso = MccTable.countryCodeForMcc(Integer.parseInt(mcc));
} catch ( NumberFormatException ex){
loge("pollStateDone: countryCodeForMcc error" + ex);
} catch ( StringIndexOutOfBoundsException ex) {
loge("pollStateDone: countryCodeForMcc error" + ex);
}
phone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ISO_COUNTRY, iso);
mGotCountryCode = true;
TimeZone zone = null;
if (!mNitzUpdatedTime && !mcc.equals("000") && !TextUtils.isEmpty(iso) &&
getAutoTimeZone()) {
// Test both paths if ignore nitz is true
boolean testOneUniqueOffsetPath = SystemProperties.getBoolean(
TelephonyProperties.PROPERTY_IGNORE_NITZ, false) &&
((SystemClock.uptimeMillis() & 1) == 0);
ArrayList<TimeZone> uniqueZones = TimeUtils.getTimeZonesWithUniqueOffsets(iso);
if ((uniqueZones.size() == 1) || testOneUniqueOffsetPath) {
zone = uniqueZones.get(0);
if (DBG) {
log("pollStateDone: no nitz but one TZ for iso-cc=" + iso +
" with zone.getID=" + zone.getID() +
" testOneUniqueOffsetPath=" + testOneUniqueOffsetPath);
}
setAndBroadcastNetworkSetTimeZone(zone.getID());
} else {
if (DBG) {
log("pollStateDone: there are " + uniqueZones.size() +
" unique offsets for iso-cc='" + iso +
" testOneUniqueOffsetPath=" + testOneUniqueOffsetPath +
"', do nothing");
}
}
}
if (shouldFixTimeZoneNow(phone, operatorNumeric, prevOperatorNumeric,
mNeedFixZoneAfterNitz)) {
// If the offset is (0, false) and the timezone property
// is set, use the timezone property rather than
// GMT.
String zoneName = SystemProperties.get(TIMEZONE_PROPERTY);
if (DBG) {
log("pollStateDone: fix time zone zoneName='" + zoneName +
"' mZoneOffset=" + mZoneOffset + " mZoneDst=" + mZoneDst +
" iso-cc='" + iso +
"' iso-cc-idx=" + Arrays.binarySearch(GMT_COUNTRY_CODES, iso));
}
// "(mZoneOffset == 0) && (mZoneDst == false) &&
// (Arrays.binarySearch(GMT_COUNTRY_CODES, iso) < 0)"
// means that we received a NITZ string telling
// it is in GMT+0 w/ DST time zone
// BUT iso tells is NOT, e.g, a wrong NITZ reporting
// local time w/ 0 offset.
if ((mZoneOffset == 0) && (mZoneDst == false) &&
(zoneName != null) && (zoneName.length() > 0) &&
(Arrays.binarySearch(GMT_COUNTRY_CODES, iso) < 0)) {
zone = TimeZone.getDefault();
if (mNeedFixZoneAfterNitz) {
// For wrong NITZ reporting local time w/ 0 offset,
// need adjust time to reflect default timezone setting
long ctm = System.currentTimeMillis();
long tzOffset = zone.getOffset(ctm);
if (DBG) {
log("pollStateDone: tzOffset=" + tzOffset + " ltod=" +
TimeUtils.logTimeOfDay(ctm));
}
if (getAutoTime()) {
long adj = ctm - tzOffset;
if (DBG) log("pollStateDone: adj ltod=" +
TimeUtils.logTimeOfDay(adj));
setAndBroadcastNetworkSetTime(adj);
} else {
// Adjust the saved NITZ time to account for tzOffset.
mSavedTime = mSavedTime - tzOffset;
}
}
if (DBG) log("pollStateDone: using default TimeZone");
} else if (iso.equals("")){
// Country code not found. This is likely a test network.
// Get a TimeZone based only on the NITZ parameters (best guess).
zone = getNitzTimeZone(mZoneOffset, mZoneDst, mZoneTime);
if (DBG) log("pollStateDone: using NITZ TimeZone");
} else {
zone = TimeUtils.getTimeZone(mZoneOffset, mZoneDst, mZoneTime, iso);
if (DBG) log("pollStateDone: using getTimeZone(off, dst, time, iso)");
}
mNeedFixZoneAfterNitz = false;
if (zone != null) {
log("pollStateDone: zone != null zone.getID=" + zone.getID());
if (getAutoTimeZone()) {
setAndBroadcastNetworkSetTimeZone(zone.getID());
}
saveNitzTimeZone(zone.getID());
} else {
log("pollStateDone: zone == null");
}
}
}
phone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ISROAMING,
ss.getRoaming() ? "true" : "false");
phone.notifyServiceStateChanged(ss);
}
if (hasGprsAttached) {
mAttachedRegistrants.notifyRegistrants();
}
if (hasGprsDetached) {
mDetachedRegistrants.notifyRegistrants();
}
if (hasRadioTechnologyChanged) {
phone.notifyDataConnection(Phone.REASON_NW_TYPE_CHANGED);
}
if (hasRoamingOn) {
mRoamingOnRegistrants.notifyRegistrants();
}
if (hasRoamingOff) {
mRoamingOffRegistrants.notifyRegistrants();
}
if (hasLocationChanged) {
phone.notifyLocationChanged();
}
if (! isGprsConsistent(gprsState, ss.getState())) {
if (!mStartedGprsRegCheck && !mReportedGprsNoReg) {
mStartedGprsRegCheck = true;
int check_period = Settings.Secure.getInt(
phone.getContext().getContentResolver(),
Settings.Secure.GPRS_REGISTER_CHECK_PERIOD_MS,
DEFAULT_GPRS_CHECK_PERIOD_MILLIS);
sendMessageDelayed(obtainMessage(EVENT_CHECK_REPORT_GPRS),
check_period);
}
} else {
mReportedGprsNoReg = false;
}
}
/**
* Check if GPRS got registered while voice is registered.
*
* @param gprsState for GPRS registration state, i.e. CGREG in GSM
* @param serviceState for voice registration state, i.e. CREG in GSM
* @return false if device only register to voice but not gprs
*/
private boolean isGprsConsistent(int gprsState, int serviceState) {
return !((serviceState == ServiceState.STATE_IN_SERVICE) &&
(gprsState != ServiceState.STATE_IN_SERVICE));
}
/**
* Returns a TimeZone object based only on parameters from the NITZ string.
*/
private TimeZone getNitzTimeZone(int offset, boolean dst, long when) {
TimeZone guess = findTimeZone(offset, dst, when);
if (guess == null) {
// Couldn't find a proper timezone. Perhaps the DST data is wrong.
guess = findTimeZone(offset, !dst, when);
}
if (DBG) log("getNitzTimeZone returning " + (guess == null ? guess : guess.getID()));
return guess;
}
private TimeZone findTimeZone(int offset, boolean dst, long when) {
int rawOffset = offset;
if (dst) {
rawOffset -= 3600000;
}
String[] zones = TimeZone.getAvailableIDs(rawOffset);
TimeZone guess = null;
Date d = new Date(when);
for (String zone : zones) {
TimeZone tz = TimeZone.getTimeZone(zone);
if (tz.getOffset(when) == offset &&
tz.inDaylightTime(d) == dst) {
guess = tz;
break;
}
}
return guess;
}
private void queueNextSignalStrengthPoll() {
if (dontPollSignalStrength) {
// The radio is telling us about signal strength changes
// we don't have to ask it
return;
}
Message msg;
msg = obtainMessage();
msg.what = EVENT_POLL_SIGNAL_STRENGTH;
long nextTime;
// TODO Don't poll signal strength if screen is off
sendMessageDelayed(msg, POLL_PERIOD_MILLIS);
}
/**
* Send signal-strength-changed notification if changed.
* Called both for solicited and unsolicited signal strength updates.
*/
private void onSignalStrengthResult(AsyncResult ar) {
SignalStrength oldSignalStrength = mSignalStrength;
int rssi = 99;
int lteSignalStrength = -1;
int lteRsrp = -1;
int lteRsrq = -1;
int lteRssnr = SignalStrength.INVALID_SNR;
int lteCqi = -1;
if (ar.exception != null) {
// -1 = unknown
// most likely radio is resetting/disconnected
setSignalStrengthDefaultValues();
} else {
int[] ints = (int[])ar.result;
// bug 658816 seems to be a case where the result is 0-length
if (ints.length != 0) {
rssi = ints[0];
lteSignalStrength = ints[7];
lteRsrp = ints[8];
lteRsrq = ints[9];
lteRssnr = ints[10];
lteCqi = ints[11];
} else {
loge("Bogus signal strength response");
rssi = 99;
}
}
mSignalStrength = new SignalStrength(rssi, -1, -1, -1,
-1, -1, -1, lteSignalStrength, lteRsrp, lteRsrq, lteRssnr, lteCqi, true);
if (!mSignalStrength.equals(oldSignalStrength)) {
try { // This takes care of delayed EVENT_POLL_SIGNAL_STRENGTH (scheduled after
// POLL_PERIOD_MILLIS) during Radio Technology Change)
phone.notifySignalStrength();
} catch (NullPointerException ex) {
log("onSignalStrengthResult() Phone already destroyed: " + ex
+ "SignalStrength not notified");
}
}
}
/**
* Set restricted state based on the OnRestrictedStateChanged notification
* If any voice or packet restricted state changes, trigger a UI
* notification and notify registrants when sim is ready.
*
* @param ar an int value of RIL_RESTRICTED_STATE_*
*/
private void onRestrictedStateChanged(AsyncResult ar) {
RestrictedState newRs = new RestrictedState();
if (DBG) log("onRestrictedStateChanged: E rs "+ mRestrictedState);
if (ar.exception == null) {
int[] ints = (int[])ar.result;
int state = ints[0];
newRs.setCsEmergencyRestricted(
((state & RILConstants.RIL_RESTRICTED_STATE_CS_EMERGENCY) != 0) ||
((state & RILConstants.RIL_RESTRICTED_STATE_CS_ALL) != 0) );
//ignore the normal call and data restricted state before SIM READY
if (phone.getIccCard().getState() == IccCardConstants.State.READY) {
newRs.setCsNormalRestricted(
((state & RILConstants.RIL_RESTRICTED_STATE_CS_NORMAL) != 0) ||
((state & RILConstants.RIL_RESTRICTED_STATE_CS_ALL) != 0) );
newRs.setPsRestricted(
(state & RILConstants.RIL_RESTRICTED_STATE_PS_ALL)!= 0);
}
if (DBG) log("onRestrictedStateChanged: new rs "+ newRs);
if (!mRestrictedState.isPsRestricted() && newRs.isPsRestricted()) {
mPsRestrictEnabledRegistrants.notifyRegistrants();
setNotification(PS_ENABLED);
} else if (mRestrictedState.isPsRestricted() && !newRs.isPsRestricted()) {
mPsRestrictDisabledRegistrants.notifyRegistrants();
setNotification(PS_DISABLED);
}
/**
* There are two kind of cs restriction, normal and emergency. So
* there are 4 x 4 combinations in current and new restricted states
* and we only need to notify when state is changed.
*/
if (mRestrictedState.isCsRestricted()) {
if (!newRs.isCsRestricted()) {
// remove all restriction
setNotification(CS_DISABLED);
} else if (!newRs.isCsNormalRestricted()) {
// remove normal restriction
setNotification(CS_EMERGENCY_ENABLED);
} else if (!newRs.isCsEmergencyRestricted()) {
// remove emergency restriction
setNotification(CS_NORMAL_ENABLED);
}
} else if (mRestrictedState.isCsEmergencyRestricted() &&
!mRestrictedState.isCsNormalRestricted()) {
if (!newRs.isCsRestricted()) {
// remove all restriction
setNotification(CS_DISABLED);
} else if (newRs.isCsRestricted()) {
// enable all restriction
setNotification(CS_ENABLED);
} else if (newRs.isCsNormalRestricted()) {
// remove emergency restriction and enable normal restriction
setNotification(CS_NORMAL_ENABLED);
}
} else if (!mRestrictedState.isCsEmergencyRestricted() &&
mRestrictedState.isCsNormalRestricted()) {
if (!newRs.isCsRestricted()) {
// remove all restriction
setNotification(CS_DISABLED);
} else if (newRs.isCsRestricted()) {
// enable all restriction
setNotification(CS_ENABLED);
} else if (newRs.isCsEmergencyRestricted()) {
// remove normal restriction and enable emergency restriction
setNotification(CS_EMERGENCY_ENABLED);
}
} else {
if (newRs.isCsRestricted()) {
// enable all restriction
setNotification(CS_ENABLED);
} else if (newRs.isCsEmergencyRestricted()) {
// enable emergency restriction
setNotification(CS_EMERGENCY_ENABLED);
} else if (newRs.isCsNormalRestricted()) {
// enable normal restriction
setNotification(CS_NORMAL_ENABLED);
}
}
mRestrictedState = newRs;
}
log("onRestrictedStateChanged: X rs "+ mRestrictedState);
}
/** code is registration state 0-5 from TS 27.007 7.2 */
private int regCodeToServiceState(int code) {
switch (code) {
case 0:
case 2: // 2 is "searching"
case 3: // 3 is "registration denied"
case 4: // 4 is "unknown" no vaild in current baseband
case 10:// same as 0, but indicates that emergency call is possible.
case 12:// same as 2, but indicates that emergency call is possible.
case 13:// same as 3, but indicates that emergency call is possible.
case 14:// same as 4, but indicates that emergency call is possible.
return ServiceState.STATE_OUT_OF_SERVICE;
case 1:
return ServiceState.STATE_IN_SERVICE;
case 5:
// in service, roam
return ServiceState.STATE_IN_SERVICE;
default:
loge("regCodeToServiceState: unexpected service state " + code);
return ServiceState.STATE_OUT_OF_SERVICE;
}
}
/**
* code is registration state 0-5 from TS 27.007 7.2
* returns true if registered roam, false otherwise
*/
private boolean regCodeIsRoaming (int code) {
// 5 is "in service -- roam"
return 5 == code;
}
/**
* Set roaming state when gsmRoaming is true and, if operator mcc is the
* same as sim mcc, ons is different from spn
* @param gsmRoaming TS 27.007 7.2 CREG registered roaming
* @param s ServiceState hold current ons
* @return true for roaming state set
*/
private boolean isRoamingBetweenOperators(boolean gsmRoaming, ServiceState s) {
String spn = SystemProperties.get(TelephonyProperties.PROPERTY_ICC_OPERATOR_ALPHA, "empty");
String onsl = s.getOperatorAlphaLong();
String onss = s.getOperatorAlphaShort();
boolean equalsOnsl = onsl != null && spn.equals(onsl);
boolean equalsOnss = onss != null && spn.equals(onss);
String simNumeric = SystemProperties.get(
TelephonyProperties.PROPERTY_ICC_OPERATOR_NUMERIC, "");
String operatorNumeric = s.getOperatorNumeric();
boolean equalsMcc = true;
try {
equalsMcc = simNumeric.substring(0, 3).
equals(operatorNumeric.substring(0, 3));
} catch (Exception e){
}
return gsmRoaming && !(equalsMcc && (equalsOnsl || equalsOnss));
}
private static int twoDigitsAt(String s, int offset) {
int a, b;
a = Character.digit(s.charAt(offset), 10);
b = Character.digit(s.charAt(offset+1), 10);
if (a < 0 || b < 0) {
throw new RuntimeException("invalid format");
}
return a*10 + b;
}
/**
* @return The current GPRS state. IN_SERVICE is the same as "attached"
* and OUT_OF_SERVICE is the same as detached.
*/
int getCurrentGprsState() {
return gprsState;
}
public int getCurrentDataConnectionState() {
return gprsState;
}
/**
* @return true if phone is camping on a technology (eg UMTS)
* that could support voice and data simultaneously.
*/
public boolean isConcurrentVoiceAndDataAllowed() {
return (mRilRadioTechnology >= ServiceState.RIL_RADIO_TECHNOLOGY_UMTS);
}
/**
* Provides the name of the algorithmic time zone for the specified
* offset. Taken from TimeZone.java.
*/
private static String displayNameFor(int off) {
off = off / 1000 / 60;
char[] buf = new char[9];
buf[0] = 'G';
buf[1] = 'M';
buf[2] = 'T';
if (off < 0) {
buf[3] = '-';
off = -off;
} else {
buf[3] = '+';
}
int hours = off / 60;
int minutes = off % 60;
buf[4] = (char) ('0' + hours / 10);
buf[5] = (char) ('0' + hours % 10);
buf[6] = ':';
buf[7] = (char) ('0' + minutes / 10);
buf[8] = (char) ('0' + minutes % 10);
return new String(buf);
}
/**
* nitzReceiveTime is time_t that the NITZ time was posted
*/
private void setTimeFromNITZString (String nitz, long nitzReceiveTime) {
// "yy/mm/dd,hh:mm:ss(+/-)tz"
// tz is in number of quarter-hours
long start = SystemClock.elapsedRealtime();
if (DBG) {log("NITZ: " + nitz + "," + nitzReceiveTime +
" start=" + start + " delay=" + (start - nitzReceiveTime));
}
try {
/* NITZ time (hour:min:sec) will be in UTC but it supplies the timezone
* offset as well (which we won't worry about until later) */
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
c.clear();
c.set(Calendar.DST_OFFSET, 0);
String[] nitzSubs = nitz.split("[/:,+-]");
int year = 2000 + Integer.parseInt(nitzSubs[0]);
c.set(Calendar.YEAR, year);
// month is 0 based!
int month = Integer.parseInt(nitzSubs[1]) - 1;
c.set(Calendar.MONTH, month);
int date = Integer.parseInt(nitzSubs[2]);
c.set(Calendar.DATE, date);
int hour = Integer.parseInt(nitzSubs[3]);
c.set(Calendar.HOUR, hour);
int minute = Integer.parseInt(nitzSubs[4]);
c.set(Calendar.MINUTE, minute);
int second = Integer.parseInt(nitzSubs[5]);
c.set(Calendar.SECOND, second);
boolean sign = (nitz.indexOf('-') == -1);
int tzOffset = Integer.parseInt(nitzSubs[6]);
int dst = (nitzSubs.length >= 8 ) ? Integer.parseInt(nitzSubs[7])
: 0;
// The zone offset received from NITZ is for current local time,
// so DST correction is already applied. Don't add it again.
//
// tzOffset += dst * 4;
//
// We could unapply it if we wanted the raw offset.
tzOffset = (sign ? 1 : -1) * tzOffset * 15 * 60 * 1000;
TimeZone zone = null;
// As a special extension, the Android emulator appends the name of
// the host computer's timezone to the nitz string. this is zoneinfo
// timezone name of the form Area!Location or Area!Location!SubLocation
// so we need to convert the ! into /
if (nitzSubs.length >= 9) {
String tzname = nitzSubs[8].replace('!','/');
zone = TimeZone.getTimeZone( tzname );
}
String iso = SystemProperties.get(TelephonyProperties.PROPERTY_OPERATOR_ISO_COUNTRY);
if (zone == null) {
if (mGotCountryCode) {
if (iso != null && iso.length() > 0) {
zone = TimeUtils.getTimeZone(tzOffset, dst != 0,
c.getTimeInMillis(),
iso);
} else {
// We don't have a valid iso country code. This is
// most likely because we're on a test network that's
// using a bogus MCC (eg, "001"), so get a TimeZone
// based only on the NITZ parameters.
zone = getNitzTimeZone(tzOffset, (dst != 0), c.getTimeInMillis());
}
}
}
if ((zone == null) || (mZoneOffset != tzOffset) || (mZoneDst != (dst != 0))){
// We got the time before the country or the zone has changed
// so we don't know how to identify the DST rules yet. Save
// the information and hope to fix it up later.
mNeedFixZoneAfterNitz = true;
mZoneOffset = tzOffset;
mZoneDst = dst != 0;
mZoneTime = c.getTimeInMillis();
}
if (zone != null) {
if (getAutoTimeZone()) {
setAndBroadcastNetworkSetTimeZone(zone.getID());
}
saveNitzTimeZone(zone.getID());
}
String ignore = SystemProperties.get("gsm.ignore-nitz");
if (ignore != null && ignore.equals("yes")) {
log("NITZ: Not setting clock because gsm.ignore-nitz is set");
return;
}
try {
mWakeLock.acquire();
if (getAutoTime()) {
long millisSinceNitzReceived
= SystemClock.elapsedRealtime() - nitzReceiveTime;
if (millisSinceNitzReceived < 0) {
// Sanity check: something is wrong
if (DBG) {
log("NITZ: not setting time, clock has rolled "
+ "backwards since NITZ time was received, "
+ nitz);
}
return;
}
if (millisSinceNitzReceived > Integer.MAX_VALUE) {
// If the time is this far off, something is wrong > 24 days!
if (DBG) {
log("NITZ: not setting time, processing has taken "
+ (millisSinceNitzReceived / (1000 * 60 * 60 * 24))
+ " days");
}
return;
}
// Note: with range checks above, cast to int is safe
c.add(Calendar.MILLISECOND, (int)millisSinceNitzReceived);
if (DBG) {
log("NITZ: Setting time of day to " + c.getTime()
+ " NITZ receive delay(ms): " + millisSinceNitzReceived
+ " gained(ms): "
+ (c.getTimeInMillis() - System.currentTimeMillis())
+ " from " + nitz);
}
setAndBroadcastNetworkSetTime(c.getTimeInMillis());
Log.i(LOG_TAG, "NITZ: after Setting time of day");
}
SystemProperties.set("gsm.nitz.time", String.valueOf(c.getTimeInMillis()));
saveNitzTime(c.getTimeInMillis());
if (false) {
long end = SystemClock.elapsedRealtime();
log("NITZ: end=" + end + " dur=" + (end - start));
}
mNitzUpdatedTime = true;
} finally {
mWakeLock.release();
}
} catch (RuntimeException ex) {
loge("NITZ: Parsing NITZ time " + nitz + " ex=" + ex);
}
}
private boolean getAutoTime() {
try {
return Settings.System.getInt(phone.getContext().getContentResolver(),
Settings.System.AUTO_TIME) > 0;
} catch (SettingNotFoundException snfe) {
return true;
}
}
private boolean getAutoTimeZone() {
try {
return Settings.System.getInt(phone.getContext().getContentResolver(),
Settings.System.AUTO_TIME_ZONE) > 0;
} catch (SettingNotFoundException snfe) {
return true;
}
}
private void saveNitzTimeZone(String zoneId) {
mSavedTimeZone = zoneId;
}
private void saveNitzTime(long time) {
mSavedTime = time;
mSavedAtTime = SystemClock.elapsedRealtime();
}
/**
* Set the timezone and send out a sticky broadcast so the system can
* determine if the timezone was set by the carrier.
*
* @param zoneId timezone set by carrier
*/
private void setAndBroadcastNetworkSetTimeZone(String zoneId) {
if (DBG) log("setAndBroadcastNetworkSetTimeZone: setTimeZone=" + zoneId);
AlarmManager alarm =
(AlarmManager) phone.getContext().getSystemService(Context.ALARM_SERVICE);
alarm.setTimeZone(zoneId);
Intent intent = new Intent(TelephonyIntents.ACTION_NETWORK_SET_TIMEZONE);
intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
intent.putExtra("time-zone", zoneId);
phone.getContext().sendStickyBroadcast(intent);
if (DBG) {
log("setAndBroadcastNetworkSetTimeZone: call alarm.setTimeZone and broadcast zoneId=" +
zoneId);
}
}
/**
* Set the time and Send out a sticky broadcast so the system can determine
* if the time was set by the carrier.
*
* @param time time set by network
*/
private void setAndBroadcastNetworkSetTime(long time) {
if (DBG) log("setAndBroadcastNetworkSetTime: time=" + time + "ms");
SystemClock.setCurrentTimeMillis(time);
Intent intent = new Intent(TelephonyIntents.ACTION_NETWORK_SET_TIME);
intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
intent.putExtra("time", time);
phone.getContext().sendStickyBroadcast(intent);
}
private void revertToNitzTime() {
if (Settings.System.getInt(phone.getContext().getContentResolver(),
Settings.System.AUTO_TIME, 0) == 0) {
return;
}
if (DBG) {
log("Reverting to NITZ Time: mSavedTime=" + mSavedTime
+ " mSavedAtTime=" + mSavedAtTime);
}
if (mSavedTime != 0 && mSavedAtTime != 0) {
setAndBroadcastNetworkSetTime(mSavedTime
+ (SystemClock.elapsedRealtime() - mSavedAtTime));
}
}
private void revertToNitzTimeZone() {
if (Settings.System.getInt(phone.getContext().getContentResolver(),
Settings.System.AUTO_TIME_ZONE, 0) == 0) {
return;
}
if (DBG) log("Reverting to NITZ TimeZone: tz='" + mSavedTimeZone);
if (mSavedTimeZone != null) {
setAndBroadcastNetworkSetTimeZone(mSavedTimeZone);
}
}
/**
* Post a notification to NotificationManager for restricted state
*
* @param notifyType is one state of PS/CS_*_ENABLE/DISABLE
*/
private void setNotification(int notifyType) {
if (DBG) log("setNotification: create notification " + notifyType);
Context context = phone.getContext();
mNotification = new Notification();
mNotification.when = System.currentTimeMillis();
mNotification.flags = Notification.FLAG_AUTO_CANCEL;
mNotification.icon = com.android.internal.R.drawable.stat_sys_warning;
Intent intent = new Intent();
mNotification.contentIntent = PendingIntent
.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
CharSequence details = "";
CharSequence title = context.getText(com.android.internal.R.string.RestrictedChangedTitle);
int notificationId = CS_NOTIFICATION;
switch (notifyType) {
case PS_ENABLED:
notificationId = PS_NOTIFICATION;
details = context.getText(com.android.internal.R.string.RestrictedOnData);;
break;
case PS_DISABLED:
notificationId = PS_NOTIFICATION;
break;
case CS_ENABLED:
details = context.getText(com.android.internal.R.string.RestrictedOnAllVoice);;
break;
case CS_NORMAL_ENABLED:
details = context.getText(com.android.internal.R.string.RestrictedOnNormal);;
break;
case CS_EMERGENCY_ENABLED:
details = context.getText(com.android.internal.R.string.RestrictedOnEmergency);;
break;
case CS_DISABLED:
// do nothing and cancel the notification later
break;
}
if (DBG) log("setNotification: put notification " + title + " / " +details);
mNotification.tickerText = title;
mNotification.setLatestEventInfo(context, title, details,
mNotification.contentIntent);
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
if (notifyType == PS_DISABLED || notifyType == CS_DISABLED) {
// cancel previous post notification
notificationManager.cancel(notificationId);
} else {
// update restricted state notification
notificationManager.notify(notificationId, mNotification);
}
}
@Override
protected void log(String s) {
Log.d(LOG_TAG, "[GsmSST] " + s);
}
@Override
protected void loge(String s) {
Log.e(LOG_TAG, "[GsmSST] " + s);
}
private static void sloge(String s) {
Log.e(LOG_TAG, "[GsmSST] " + s);
}
@Override
public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
pw.println("GsmServiceStateTracker extends:");
super.dump(fd, pw, args);
pw.println(" phone=" + phone);
pw.println(" cellLoc=" + cellLoc);
pw.println(" newCellLoc=" + newCellLoc);
pw.println(" mPreferredNetworkType=" + mPreferredNetworkType);
pw.println(" gprsState=" + gprsState);
pw.println(" newGPRSState=" + newGPRSState);
pw.println(" mMaxDataCalls=" + mMaxDataCalls);
pw.println(" mNewMaxDataCalls=" + mNewMaxDataCalls);
pw.println(" mReasonDataDenied=" + mReasonDataDenied);
pw.println(" mNewReasonDataDenied=" + mNewReasonDataDenied);
pw.println(" mGsmRoaming=" + mGsmRoaming);
pw.println(" mDataRoaming=" + mDataRoaming);
pw.println(" mEmergencyOnly=" + mEmergencyOnly);
pw.println(" mNeedFixZoneAfterNitz=" + mNeedFixZoneAfterNitz);
pw.println(" mZoneOffset=" + mZoneOffset);
pw.println(" mZoneDst=" + mZoneDst);
pw.println(" mZoneTime=" + mZoneTime);
pw.println(" mGotCountryCode=" + mGotCountryCode);
pw.println(" mNitzUpdatedTime=" + mNitzUpdatedTime);
pw.println(" mSavedTimeZone=" + mSavedTimeZone);
pw.println(" mSavedTime=" + mSavedTime);
pw.println(" mSavedAtTime=" + mSavedAtTime);
pw.println(" mNeedToRegForSimLoaded=" + mNeedToRegForSimLoaded);
pw.println(" mStartedGprsRegCheck=" + mStartedGprsRegCheck);
pw.println(" mReportedGprsNoReg=" + mReportedGprsNoReg);
pw.println(" mNotification=" + mNotification);
pw.println(" mWakeLock=" + mWakeLock);
pw.println(" curSpn=" + curSpn);
pw.println(" curPlmn=" + curPlmn);
pw.println(" curSpnRule=" + curSpnRule);
}
}
| false | true | private void pollStateDone() {
if (DBG) {
log("Poll ServiceState done: " +
" oldSS=[" + ss + "] newSS=[" + newSS +
"] oldGprs=" + gprsState + " newData=" + newGPRSState +
" oldMaxDataCalls=" + mMaxDataCalls +
" mNewMaxDataCalls=" + mNewMaxDataCalls +
" oldReasonDataDenied=" + mReasonDataDenied +
" mNewReasonDataDenied=" + mNewReasonDataDenied +
" oldType=" + ServiceState.rilRadioTechnologyToString(mRilRadioTechnology) +
" newType=" + ServiceState.rilRadioTechnologyToString(mNewRilRadioTechnology));
}
boolean hasRegistered =
ss.getState() != ServiceState.STATE_IN_SERVICE
&& newSS.getState() == ServiceState.STATE_IN_SERVICE;
boolean hasDeregistered =
ss.getState() == ServiceState.STATE_IN_SERVICE
&& newSS.getState() != ServiceState.STATE_IN_SERVICE;
boolean hasGprsAttached =
gprsState != ServiceState.STATE_IN_SERVICE
&& newGPRSState == ServiceState.STATE_IN_SERVICE;
boolean hasGprsDetached =
gprsState == ServiceState.STATE_IN_SERVICE
&& newGPRSState != ServiceState.STATE_IN_SERVICE;
boolean hasRadioTechnologyChanged = mRilRadioTechnology != mNewRilRadioTechnology;
boolean hasChanged = !newSS.equals(ss);
boolean hasRoamingOn = !ss.getRoaming() && newSS.getRoaming();
boolean hasRoamingOff = ss.getRoaming() && !newSS.getRoaming();
boolean hasLocationChanged = !newCellLoc.equals(cellLoc);
// Add an event log when connection state changes
if (ss.getState() != newSS.getState() || gprsState != newGPRSState) {
EventLog.writeEvent(EventLogTags.GSM_SERVICE_STATE_CHANGE,
ss.getState(), gprsState, newSS.getState(), newGPRSState);
}
ServiceState tss;
tss = ss;
ss = newSS;
newSS = tss;
// clean slate for next time
newSS.setStateOutOfService();
GsmCellLocation tcl = cellLoc;
cellLoc = newCellLoc;
newCellLoc = tcl;
// Add an event log when network type switched
// TODO: we may add filtering to reduce the event logged,
// i.e. check preferred network setting, only switch to 2G, etc
if (hasRadioTechnologyChanged) {
int cid = -1;
GsmCellLocation loc = ((GsmCellLocation)phone.getCellLocation());
if (loc != null) cid = loc.getCid();
EventLog.writeEvent(EventLogTags.GSM_RAT_SWITCHED, cid, mRilRadioTechnology,
mNewRilRadioTechnology);
if (DBG) {
log("RAT switched " + ServiceState.rilRadioTechnologyToString(mRilRadioTechnology) +
" -> " + ServiceState.rilRadioTechnologyToString(mNewRilRadioTechnology) +
" at cell " + cid);
}
}
gprsState = newGPRSState;
mReasonDataDenied = mNewReasonDataDenied;
mMaxDataCalls = mNewMaxDataCalls;
mRilRadioTechnology = mNewRilRadioTechnology;
// this new state has been applied - forget it until we get a new new state
mNewRilRadioTechnology = 0;
newSS.setStateOutOfService(); // clean slate for next time
if (hasRadioTechnologyChanged) {
phone.setSystemProperty(TelephonyProperties.PROPERTY_DATA_NETWORK_TYPE,
ServiceState.rilRadioTechnologyToString(mRilRadioTechnology));
}
if (hasRegistered) {
mNetworkAttachedRegistrants.notifyRegistrants();
if (DBG) {
log("pollStateDone: registering current mNitzUpdatedTime=" +
mNitzUpdatedTime + " changing to false");
}
mNitzUpdatedTime = false;
}
if (hasChanged) {
String operatorNumeric;
updateSpnDisplay();
phone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ALPHA,
ss.getOperatorAlphaLong());
String prevOperatorNumeric =
SystemProperties.get(TelephonyProperties.PROPERTY_OPERATOR_NUMERIC, "");
operatorNumeric = ss.getOperatorNumeric();
phone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_NUMERIC, operatorNumeric);
if (operatorNumeric == null) {
if (DBG) log("operatorNumeric is null");
phone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ISO_COUNTRY, "");
mGotCountryCode = false;
mNitzUpdatedTime = false;
} else {
String iso = "";
String mcc = operatorNumeric.substring(0, 3);
try{
iso = MccTable.countryCodeForMcc(Integer.parseInt(mcc));
} catch ( NumberFormatException ex){
loge("pollStateDone: countryCodeForMcc error" + ex);
} catch ( StringIndexOutOfBoundsException ex) {
loge("pollStateDone: countryCodeForMcc error" + ex);
}
phone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ISO_COUNTRY, iso);
mGotCountryCode = true;
TimeZone zone = null;
if (!mNitzUpdatedTime && !mcc.equals("000") && !TextUtils.isEmpty(iso) &&
getAutoTimeZone()) {
// Test both paths if ignore nitz is true
boolean testOneUniqueOffsetPath = SystemProperties.getBoolean(
TelephonyProperties.PROPERTY_IGNORE_NITZ, false) &&
((SystemClock.uptimeMillis() & 1) == 0);
ArrayList<TimeZone> uniqueZones = TimeUtils.getTimeZonesWithUniqueOffsets(iso);
if ((uniqueZones.size() == 1) || testOneUniqueOffsetPath) {
zone = uniqueZones.get(0);
if (DBG) {
log("pollStateDone: no nitz but one TZ for iso-cc=" + iso +
" with zone.getID=" + zone.getID() +
" testOneUniqueOffsetPath=" + testOneUniqueOffsetPath);
}
setAndBroadcastNetworkSetTimeZone(zone.getID());
} else {
if (DBG) {
log("pollStateDone: there are " + uniqueZones.size() +
" unique offsets for iso-cc='" + iso +
" testOneUniqueOffsetPath=" + testOneUniqueOffsetPath +
"', do nothing");
}
}
}
if (shouldFixTimeZoneNow(phone, operatorNumeric, prevOperatorNumeric,
mNeedFixZoneAfterNitz)) {
// If the offset is (0, false) and the timezone property
// is set, use the timezone property rather than
// GMT.
String zoneName = SystemProperties.get(TIMEZONE_PROPERTY);
if (DBG) {
log("pollStateDone: fix time zone zoneName='" + zoneName +
"' mZoneOffset=" + mZoneOffset + " mZoneDst=" + mZoneDst +
" iso-cc='" + iso +
"' iso-cc-idx=" + Arrays.binarySearch(GMT_COUNTRY_CODES, iso));
}
// "(mZoneOffset == 0) && (mZoneDst == false) &&
// (Arrays.binarySearch(GMT_COUNTRY_CODES, iso) < 0)"
// means that we received a NITZ string telling
// it is in GMT+0 w/ DST time zone
// BUT iso tells is NOT, e.g, a wrong NITZ reporting
// local time w/ 0 offset.
if ((mZoneOffset == 0) && (mZoneDst == false) &&
(zoneName != null) && (zoneName.length() > 0) &&
(Arrays.binarySearch(GMT_COUNTRY_CODES, iso) < 0)) {
zone = TimeZone.getDefault();
if (mNeedFixZoneAfterNitz) {
// For wrong NITZ reporting local time w/ 0 offset,
// need adjust time to reflect default timezone setting
long ctm = System.currentTimeMillis();
long tzOffset = zone.getOffset(ctm);
if (DBG) {
log("pollStateDone: tzOffset=" + tzOffset + " ltod=" +
TimeUtils.logTimeOfDay(ctm));
}
if (getAutoTime()) {
long adj = ctm - tzOffset;
if (DBG) log("pollStateDone: adj ltod=" +
TimeUtils.logTimeOfDay(adj));
setAndBroadcastNetworkSetTime(adj);
} else {
// Adjust the saved NITZ time to account for tzOffset.
mSavedTime = mSavedTime - tzOffset;
}
}
if (DBG) log("pollStateDone: using default TimeZone");
} else if (iso.equals("")){
// Country code not found. This is likely a test network.
// Get a TimeZone based only on the NITZ parameters (best guess).
zone = getNitzTimeZone(mZoneOffset, mZoneDst, mZoneTime);
if (DBG) log("pollStateDone: using NITZ TimeZone");
} else {
zone = TimeUtils.getTimeZone(mZoneOffset, mZoneDst, mZoneTime, iso);
if (DBG) log("pollStateDone: using getTimeZone(off, dst, time, iso)");
}
mNeedFixZoneAfterNitz = false;
if (zone != null) {
log("pollStateDone: zone != null zone.getID=" + zone.getID());
if (getAutoTimeZone()) {
setAndBroadcastNetworkSetTimeZone(zone.getID());
}
saveNitzTimeZone(zone.getID());
} else {
log("pollStateDone: zone == null");
}
}
}
phone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ISROAMING,
ss.getRoaming() ? "true" : "false");
phone.notifyServiceStateChanged(ss);
}
if (hasGprsAttached) {
mAttachedRegistrants.notifyRegistrants();
}
if (hasGprsDetached) {
mDetachedRegistrants.notifyRegistrants();
}
if (hasRadioTechnologyChanged) {
phone.notifyDataConnection(Phone.REASON_NW_TYPE_CHANGED);
}
if (hasRoamingOn) {
mRoamingOnRegistrants.notifyRegistrants();
}
if (hasRoamingOff) {
mRoamingOffRegistrants.notifyRegistrants();
}
if (hasLocationChanged) {
phone.notifyLocationChanged();
}
if (! isGprsConsistent(gprsState, ss.getState())) {
if (!mStartedGprsRegCheck && !mReportedGprsNoReg) {
mStartedGprsRegCheck = true;
int check_period = Settings.Secure.getInt(
phone.getContext().getContentResolver(),
Settings.Secure.GPRS_REGISTER_CHECK_PERIOD_MS,
DEFAULT_GPRS_CHECK_PERIOD_MILLIS);
sendMessageDelayed(obtainMessage(EVENT_CHECK_REPORT_GPRS),
check_period);
}
} else {
mReportedGprsNoReg = false;
}
}
| private void pollStateDone() {
if (DBG) {
log("Poll ServiceState done: " +
" oldSS=[" + ss + "] newSS=[" + newSS +
"] oldGprs=" + gprsState + " newData=" + newGPRSState +
" oldMaxDataCalls=" + mMaxDataCalls +
" mNewMaxDataCalls=" + mNewMaxDataCalls +
" oldReasonDataDenied=" + mReasonDataDenied +
" mNewReasonDataDenied=" + mNewReasonDataDenied +
" oldType=" + ServiceState.rilRadioTechnologyToString(mRilRadioTechnology) +
" newType=" + ServiceState.rilRadioTechnologyToString(mNewRilRadioTechnology));
}
boolean hasRegistered =
ss.getState() != ServiceState.STATE_IN_SERVICE
&& newSS.getState() == ServiceState.STATE_IN_SERVICE;
boolean hasDeregistered =
ss.getState() == ServiceState.STATE_IN_SERVICE
&& newSS.getState() != ServiceState.STATE_IN_SERVICE;
boolean hasGprsAttached =
gprsState != ServiceState.STATE_IN_SERVICE
&& newGPRSState == ServiceState.STATE_IN_SERVICE;
boolean hasGprsDetached =
gprsState == ServiceState.STATE_IN_SERVICE
&& newGPRSState != ServiceState.STATE_IN_SERVICE;
boolean hasRadioTechnologyChanged = mRilRadioTechnology != mNewRilRadioTechnology;
boolean hasChanged = !newSS.equals(ss);
boolean hasRoamingOn = !ss.getRoaming() && newSS.getRoaming();
boolean hasRoamingOff = ss.getRoaming() && !newSS.getRoaming();
boolean hasLocationChanged = !newCellLoc.equals(cellLoc);
// Add an event log when connection state changes
if (ss.getState() != newSS.getState() || gprsState != newGPRSState) {
EventLog.writeEvent(EventLogTags.GSM_SERVICE_STATE_CHANGE,
ss.getState(), gprsState, newSS.getState(), newGPRSState);
}
ServiceState tss;
tss = ss;
ss = newSS;
newSS = tss;
// clean slate for next time
newSS.setStateOutOfService();
GsmCellLocation tcl = cellLoc;
cellLoc = newCellLoc;
newCellLoc = tcl;
// Add an event log when network type switched
// TODO: we may add filtering to reduce the event logged,
// i.e. check preferred network setting, only switch to 2G, etc
if (hasRadioTechnologyChanged) {
int cid = -1;
GsmCellLocation loc = ((GsmCellLocation)phone.getCellLocation());
if (loc != null) cid = loc.getCid();
EventLog.writeEvent(EventLogTags.GSM_RAT_SWITCHED, cid, mRilRadioTechnology,
mNewRilRadioTechnology);
if (DBG) {
log("RAT switched " + ServiceState.rilRadioTechnologyToString(mRilRadioTechnology) +
" -> " + ServiceState.rilRadioTechnologyToString(mNewRilRadioTechnology) +
" at cell " + cid);
}
}
gprsState = newGPRSState;
mReasonDataDenied = mNewReasonDataDenied;
mMaxDataCalls = mNewMaxDataCalls;
mRilRadioTechnology = mNewRilRadioTechnology;
// this new state has been applied - forget it until we get a new new state
mNewRilRadioTechnology = 0;
newSS.setStateOutOfService(); // clean slate for next time
if (hasRadioTechnologyChanged) {
phone.setSystemProperty(TelephonyProperties.PROPERTY_DATA_NETWORK_TYPE,
ServiceState.rilRadioTechnologyToString(mRilRadioTechnology));
}
if (hasRegistered) {
mNetworkAttachedRegistrants.notifyRegistrants();
if (DBG) {
log("pollStateDone: registering current mNitzUpdatedTime=" +
mNitzUpdatedTime + " changing to false");
}
mNitzUpdatedTime = false;
}
if (hasChanged) {
String operatorNumeric;
updateSpnDisplay();
phone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ALPHA,
ss.getOperatorAlphaLong());
String prevOperatorNumeric =
SystemProperties.get(TelephonyProperties.PROPERTY_OPERATOR_NUMERIC, "");
operatorNumeric = ss.getOperatorNumeric();
phone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_NUMERIC, operatorNumeric);
if (operatorNumeric == null) {
if (DBG) log("operatorNumeric is null");
phone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ISO_COUNTRY, "");
mGotCountryCode = false;
mNitzUpdatedTime = false;
} else {
String iso = "";
String mcc = "";
try{
mcc = operatorNumeric.substring(0, 3);
iso = MccTable.countryCodeForMcc(Integer.parseInt(mcc));
} catch ( NumberFormatException ex){
loge("pollStateDone: countryCodeForMcc error" + ex);
} catch ( StringIndexOutOfBoundsException ex) {
loge("pollStateDone: countryCodeForMcc error" + ex);
}
phone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ISO_COUNTRY, iso);
mGotCountryCode = true;
TimeZone zone = null;
if (!mNitzUpdatedTime && !mcc.equals("000") && !TextUtils.isEmpty(iso) &&
getAutoTimeZone()) {
// Test both paths if ignore nitz is true
boolean testOneUniqueOffsetPath = SystemProperties.getBoolean(
TelephonyProperties.PROPERTY_IGNORE_NITZ, false) &&
((SystemClock.uptimeMillis() & 1) == 0);
ArrayList<TimeZone> uniqueZones = TimeUtils.getTimeZonesWithUniqueOffsets(iso);
if ((uniqueZones.size() == 1) || testOneUniqueOffsetPath) {
zone = uniqueZones.get(0);
if (DBG) {
log("pollStateDone: no nitz but one TZ for iso-cc=" + iso +
" with zone.getID=" + zone.getID() +
" testOneUniqueOffsetPath=" + testOneUniqueOffsetPath);
}
setAndBroadcastNetworkSetTimeZone(zone.getID());
} else {
if (DBG) {
log("pollStateDone: there are " + uniqueZones.size() +
" unique offsets for iso-cc='" + iso +
" testOneUniqueOffsetPath=" + testOneUniqueOffsetPath +
"', do nothing");
}
}
}
if (shouldFixTimeZoneNow(phone, operatorNumeric, prevOperatorNumeric,
mNeedFixZoneAfterNitz)) {
// If the offset is (0, false) and the timezone property
// is set, use the timezone property rather than
// GMT.
String zoneName = SystemProperties.get(TIMEZONE_PROPERTY);
if (DBG) {
log("pollStateDone: fix time zone zoneName='" + zoneName +
"' mZoneOffset=" + mZoneOffset + " mZoneDst=" + mZoneDst +
" iso-cc='" + iso +
"' iso-cc-idx=" + Arrays.binarySearch(GMT_COUNTRY_CODES, iso));
}
// "(mZoneOffset == 0) && (mZoneDst == false) &&
// (Arrays.binarySearch(GMT_COUNTRY_CODES, iso) < 0)"
// means that we received a NITZ string telling
// it is in GMT+0 w/ DST time zone
// BUT iso tells is NOT, e.g, a wrong NITZ reporting
// local time w/ 0 offset.
if ((mZoneOffset == 0) && (mZoneDst == false) &&
(zoneName != null) && (zoneName.length() > 0) &&
(Arrays.binarySearch(GMT_COUNTRY_CODES, iso) < 0)) {
zone = TimeZone.getDefault();
if (mNeedFixZoneAfterNitz) {
// For wrong NITZ reporting local time w/ 0 offset,
// need adjust time to reflect default timezone setting
long ctm = System.currentTimeMillis();
long tzOffset = zone.getOffset(ctm);
if (DBG) {
log("pollStateDone: tzOffset=" + tzOffset + " ltod=" +
TimeUtils.logTimeOfDay(ctm));
}
if (getAutoTime()) {
long adj = ctm - tzOffset;
if (DBG) log("pollStateDone: adj ltod=" +
TimeUtils.logTimeOfDay(adj));
setAndBroadcastNetworkSetTime(adj);
} else {
// Adjust the saved NITZ time to account for tzOffset.
mSavedTime = mSavedTime - tzOffset;
}
}
if (DBG) log("pollStateDone: using default TimeZone");
} else if (iso.equals("")){
// Country code not found. This is likely a test network.
// Get a TimeZone based only on the NITZ parameters (best guess).
zone = getNitzTimeZone(mZoneOffset, mZoneDst, mZoneTime);
if (DBG) log("pollStateDone: using NITZ TimeZone");
} else {
zone = TimeUtils.getTimeZone(mZoneOffset, mZoneDst, mZoneTime, iso);
if (DBG) log("pollStateDone: using getTimeZone(off, dst, time, iso)");
}
mNeedFixZoneAfterNitz = false;
if (zone != null) {
log("pollStateDone: zone != null zone.getID=" + zone.getID());
if (getAutoTimeZone()) {
setAndBroadcastNetworkSetTimeZone(zone.getID());
}
saveNitzTimeZone(zone.getID());
} else {
log("pollStateDone: zone == null");
}
}
}
phone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ISROAMING,
ss.getRoaming() ? "true" : "false");
phone.notifyServiceStateChanged(ss);
}
if (hasGprsAttached) {
mAttachedRegistrants.notifyRegistrants();
}
if (hasGprsDetached) {
mDetachedRegistrants.notifyRegistrants();
}
if (hasRadioTechnologyChanged) {
phone.notifyDataConnection(Phone.REASON_NW_TYPE_CHANGED);
}
if (hasRoamingOn) {
mRoamingOnRegistrants.notifyRegistrants();
}
if (hasRoamingOff) {
mRoamingOffRegistrants.notifyRegistrants();
}
if (hasLocationChanged) {
phone.notifyLocationChanged();
}
if (! isGprsConsistent(gprsState, ss.getState())) {
if (!mStartedGprsRegCheck && !mReportedGprsNoReg) {
mStartedGprsRegCheck = true;
int check_period = Settings.Secure.getInt(
phone.getContext().getContentResolver(),
Settings.Secure.GPRS_REGISTER_CHECK_PERIOD_MS,
DEFAULT_GPRS_CHECK_PERIOD_MILLIS);
sendMessageDelayed(obtainMessage(EVENT_CHECK_REPORT_GPRS),
check_period);
}
} else {
mReportedGprsNoReg = false;
}
}
|
diff --git a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/breakpoints/StandardJavaBreakpointEditor.java b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/breakpoints/StandardJavaBreakpointEditor.java
index 2bdffa4e5..4175d9776 100644
--- a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/breakpoints/StandardJavaBreakpointEditor.java
+++ b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/breakpoints/StandardJavaBreakpointEditor.java
@@ -1,238 +1,242 @@
/*******************************************************************************
* Copyright (c) 2009, 2010 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.jdt.internal.debug.ui.breakpoints;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.debug.internal.ui.SWTFactory;
import org.eclipse.jdt.debug.core.IJavaBreakpoint;
import org.eclipse.jdt.internal.debug.ui.JDIDebugUIPlugin;
import org.eclipse.jdt.internal.debug.ui.propertypages.PropertyPageMessages;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Text;
/**
* @since 3.6
*/
public class StandardJavaBreakpointEditor extends AbstractJavaBreakpointEditor {
private IJavaBreakpoint fBreakpoint;
private Button fHitCountButton;
private Text fHitCountText;
private Button fSuspendThread;
private Button fSuspendVM;
/**
* Property id for hit count enabled state.
*/
public static final int PROP_HIT_COUNT_ENABLED = 0x1005;
/**
* Property id for breakpoint hit count.
*/
public static final int PROP_HIT_COUNT = 0x1006;
/**
* Property id for suspend policy.
*/
public static final int PROP_SUSPEND_POLICY = 0x1007;
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.debug.ui.breakpoints.AbstractJavaBreakpointEditor#createControl(org.eclipse.swt.widgets.Composite)
*/
public Control createControl(Composite parent) {
return createStandardControls(parent);
}
protected Control createStandardControls(Composite parent) {
Composite composite = SWTFactory.createComposite(parent, parent.getFont(), 4, 1, 0, 0, 0);
fHitCountButton = SWTFactory.createCheckButton(composite, processMnemonics(PropertyPageMessages.JavaBreakpointPage_4), null, false, 1);
fHitCountButton.setLayoutData(new GridData());
fHitCountButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
- fHitCountText.setEnabled(fHitCountButton.getSelection());
+ boolean enabled = fHitCountButton.getSelection();
+ fHitCountText.setEnabled(enabled);
+ if(enabled) {
+ fHitCountText.setFocus();
+ }
setDirty(PROP_HIT_COUNT_ENABLED);
}
});
fHitCountText = SWTFactory.createSingleText(composite, 1);
GridData gd = (GridData) fHitCountText.getLayoutData();
gd.minimumWidth = 50;
fHitCountText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
setDirty(PROP_HIT_COUNT);
}
});
SWTFactory.createLabel(composite, "", 1); // spacer //$NON-NLS-1$
Composite radios = SWTFactory.createComposite(composite, composite.getFont(), 2, 1, GridData.FILL_HORIZONTAL, 0, 0);
fSuspendThread = SWTFactory.createRadioButton(radios, processMnemonics(PropertyPageMessages.JavaBreakpointPage_7), 1);
fSuspendThread.setLayoutData(new GridData());
fSuspendVM = SWTFactory.createRadioButton(radios, processMnemonics(PropertyPageMessages.JavaBreakpointPage_8), 1);
fSuspendVM.setLayoutData(new GridData());
fSuspendThread.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
setDirty(PROP_SUSPEND_POLICY);
}
});
fSuspendVM.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
setDirty(PROP_SUSPEND_POLICY);
}
});
composite.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
dispose();
}
});
return composite;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.debug.ui.breakpoints.AbstractJavaBreakpointEditor#setInput(java.lang.Object)
*/
public void setInput(Object breakpoint) throws CoreException {
if (breakpoint instanceof IJavaBreakpoint) {
setBreakpoint((IJavaBreakpoint) breakpoint);
} else {
setBreakpoint(null);
}
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.debug.ui.breakpoints.AbstractJavaBreakpointEditor#getInput()
*/
public Object getInput() {
return fBreakpoint;
}
/**
* Sets the breakpoint to edit. The same editor can be used iteratively for different breakpoints.
*
* @param breakpoint the breakpoint to edit or <code>null</code> if none
* @exception CoreException if unable to access breakpoint attributes
*/
protected void setBreakpoint(IJavaBreakpoint breakpoint) throws CoreException {
fBreakpoint = breakpoint;
boolean enabled = false;
boolean hasHitCount = false;
String text = ""; //$NON-NLS-1$
boolean suspendThread = true;
if (breakpoint != null) {
enabled = true;
int hitCount = breakpoint.getHitCount();
if (hitCount > 0) {
text = new Integer(hitCount).toString();
hasHitCount = true;
}
suspendThread= breakpoint.getSuspendPolicy() == IJavaBreakpoint.SUSPEND_THREAD;
}
fHitCountButton.setEnabled(enabled);
fHitCountButton.setSelection(enabled & hasHitCount);
fHitCountText.setEnabled(hasHitCount);
fHitCountText.setText(text);
fSuspendThread.setEnabled(enabled);
fSuspendVM.setEnabled(enabled);
fSuspendThread.setSelection(suspendThread);
fSuspendVM.setSelection(!suspendThread);
setDirty(false);
}
/**
* Returns the current breakpoint being edited or <code>null</code> if none.
*
* @return breakpoint or <code>null</code>
*/
protected IJavaBreakpoint getBreakpoint() {
return fBreakpoint;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.debug.ui.breakpoints.AbstractJavaBreakpointEditor#setFocus()
*/
public void setFocus() {
// do nothing
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.debug.ui.breakpoints.AbstractJavaBreakpointEditor#doSave()
*/
public void doSave() throws CoreException {
if (fBreakpoint != null) {
int suspendPolicy = IJavaBreakpoint.SUSPEND_THREAD;
if(fSuspendVM.getSelection()) {
suspendPolicy = IJavaBreakpoint.SUSPEND_VM;
}
fBreakpoint.setSuspendPolicy(suspendPolicy);
int hitCount = -1;
if (fHitCountButton.getSelection()) {
try {
hitCount = Integer.parseInt(fHitCountText.getText());
}
catch (NumberFormatException e) {
throw new CoreException(new Status(IStatus.ERROR, JDIDebugUIPlugin.getUniqueIdentifier(), IStatus.ERROR, PropertyPageMessages.JavaBreakpointPage_0, e));
}
}
fBreakpoint.setHitCount(hitCount);
}
setDirty(false);
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.debug.ui.breakpoints.AbstractJavaBreakpointEditor#getStatus()
*/
public IStatus getStatus() {
if (fHitCountButton.getSelection()) {
String hitCountText= fHitCountText.getText();
int hitCount= -1;
try {
hitCount = Integer.parseInt(hitCountText);
} catch (NumberFormatException e1) {
return new Status(IStatus.ERROR, JDIDebugUIPlugin.getUniqueIdentifier(), IStatus.ERROR, PropertyPageMessages.JavaBreakpointPage_0, null);
}
if (hitCount < 1) {
return new Status(IStatus.ERROR, JDIDebugUIPlugin.getUniqueIdentifier(), IStatus.ERROR, PropertyPageMessages.JavaBreakpointPage_0, null);
}
}
return Status.OK_STATUS;
}
/**
* Creates and returns a check box button with the given text.
*
* @param parent parent composite
* @param text label
* @param propId property id to fire on modification
* @return check box
*/
protected Button createSusupendPropertyEditor(Composite parent, String text, final int propId) {
Button button = new Button(parent, SWT.CHECK);
button.setFont(parent.getFont());
button.setText(text);
GridData gd = new GridData(SWT.BEGINNING);
button.setLayoutData(gd);
button.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
setDirty(propId);
}
});
return button;
}
}
| true | true | protected Control createStandardControls(Composite parent) {
Composite composite = SWTFactory.createComposite(parent, parent.getFont(), 4, 1, 0, 0, 0);
fHitCountButton = SWTFactory.createCheckButton(composite, processMnemonics(PropertyPageMessages.JavaBreakpointPage_4), null, false, 1);
fHitCountButton.setLayoutData(new GridData());
fHitCountButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
fHitCountText.setEnabled(fHitCountButton.getSelection());
setDirty(PROP_HIT_COUNT_ENABLED);
}
});
fHitCountText = SWTFactory.createSingleText(composite, 1);
GridData gd = (GridData) fHitCountText.getLayoutData();
gd.minimumWidth = 50;
fHitCountText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
setDirty(PROP_HIT_COUNT);
}
});
SWTFactory.createLabel(composite, "", 1); // spacer //$NON-NLS-1$
Composite radios = SWTFactory.createComposite(composite, composite.getFont(), 2, 1, GridData.FILL_HORIZONTAL, 0, 0);
fSuspendThread = SWTFactory.createRadioButton(radios, processMnemonics(PropertyPageMessages.JavaBreakpointPage_7), 1);
fSuspendThread.setLayoutData(new GridData());
fSuspendVM = SWTFactory.createRadioButton(radios, processMnemonics(PropertyPageMessages.JavaBreakpointPage_8), 1);
fSuspendVM.setLayoutData(new GridData());
fSuspendThread.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
setDirty(PROP_SUSPEND_POLICY);
}
});
fSuspendVM.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
setDirty(PROP_SUSPEND_POLICY);
}
});
composite.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
dispose();
}
});
return composite;
}
| protected Control createStandardControls(Composite parent) {
Composite composite = SWTFactory.createComposite(parent, parent.getFont(), 4, 1, 0, 0, 0);
fHitCountButton = SWTFactory.createCheckButton(composite, processMnemonics(PropertyPageMessages.JavaBreakpointPage_4), null, false, 1);
fHitCountButton.setLayoutData(new GridData());
fHitCountButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
boolean enabled = fHitCountButton.getSelection();
fHitCountText.setEnabled(enabled);
if(enabled) {
fHitCountText.setFocus();
}
setDirty(PROP_HIT_COUNT_ENABLED);
}
});
fHitCountText = SWTFactory.createSingleText(composite, 1);
GridData gd = (GridData) fHitCountText.getLayoutData();
gd.minimumWidth = 50;
fHitCountText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
setDirty(PROP_HIT_COUNT);
}
});
SWTFactory.createLabel(composite, "", 1); // spacer //$NON-NLS-1$
Composite radios = SWTFactory.createComposite(composite, composite.getFont(), 2, 1, GridData.FILL_HORIZONTAL, 0, 0);
fSuspendThread = SWTFactory.createRadioButton(radios, processMnemonics(PropertyPageMessages.JavaBreakpointPage_7), 1);
fSuspendThread.setLayoutData(new GridData());
fSuspendVM = SWTFactory.createRadioButton(radios, processMnemonics(PropertyPageMessages.JavaBreakpointPage_8), 1);
fSuspendVM.setLayoutData(new GridData());
fSuspendThread.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
setDirty(PROP_SUSPEND_POLICY);
}
});
fSuspendVM.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
setDirty(PROP_SUSPEND_POLICY);
}
});
composite.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
dispose();
}
});
return composite;
}
|
diff --git a/src/graindcafe/tribu/Tribu.java b/src/graindcafe/tribu/Tribu.java
index b745ee2..1ec9972 100644
--- a/src/graindcafe/tribu/Tribu.java
+++ b/src/graindcafe/tribu/Tribu.java
@@ -1,797 +1,798 @@
package graindcafe.tribu;
import graindcafe.tribu.BlockTracer.BlockTrace;
import graindcafe.tribu.Configuration.Constants;
import graindcafe.tribu.Configuration.TribuConfig;
import graindcafe.tribu.Executors.CmdDspawn;
import graindcafe.tribu.Executors.CmdIspawn;
import graindcafe.tribu.Executors.CmdTribu;
import graindcafe.tribu.Executors.CmdZspawn;
import graindcafe.tribu.Inventory.TribuInventory;
import graindcafe.tribu.Inventory.TribuTempInventory;
import graindcafe.tribu.Level.LevelFileLoader;
import graindcafe.tribu.Level.LevelSelector;
import graindcafe.tribu.Level.TribuLevel;
import graindcafe.tribu.Listeners.TribuBlockListener;
import graindcafe.tribu.Listeners.TribuEntityListener;
import graindcafe.tribu.Listeners.TribuPlayerListener;
import graindcafe.tribu.Listeners.TribuWorldListener;
import graindcafe.tribu.Signs.TollSign;
import graindcafe.tribu.TribuZombie.EntityTribuZombie;
import java.io.File;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.logging.Logger;
import me.graindcafe.gls.DefaultLanguage;
import me.graindcafe.gls.Language;
import net.minecraft.server.EntityTypes;
import net.minecraft.server.EntityZombie;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Villager;
import org.bukkit.entity.Wolf;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
public class Tribu extends JavaPlugin {
public static String getExceptionMessage(Exception e) {
String message = e.getLocalizedMessage() + "\n";
for (StackTraceElement st : e.getStackTrace())
message += "[" + st.getFileName() + ":" + st.getLineNumber() + "] " + st.getClassName() + "->" + st.getMethodName() + "\n";
return message;
}
private int aliveCount;
private TribuBlockListener blockListener;
private BlockTrace blockTrace;
private TribuEntityListener entityListener;
public TribuInventory inventorySave;
private boolean isRunning;
private Language language;
private TribuLevel level;
private LevelFileLoader levelLoader;
private LevelSelector levelSelector;
private Logger log;
private TribuPlayerListener playerListener;
private HashMap<Player, PlayerStats> players;
private HashMap<Player,Location> spawnPoint;
private Random rnd;
private LinkedList<PlayerStats> sortedStats;
private TribuSpawner spawner;
private SpawnTimer spawnTimer;
private HashMap<Player, TribuTempInventory> tempInventories;
private boolean waitingForPlayers = false;
private WaveStarter waveStarter;
private TribuWorldListener worldListener;
private TribuConfig config;
public void addPlayer(Player player) {
if (player != null && !players.containsKey(player)) {
if (config.PlayersStoreInventory) {
saveSetTribuInventory(player);
}
PlayerStats stats = new PlayerStats(player);
players.put(player, stats);
sortedStats.add(stats);
if (isWaitingForPlayers())
{
startRunning();
setWaitingForPlayers(false);
}
else if (getLevel() != null && isRunning)
{
player.teleport(level.getDeathSpawn());
messagePlayer(player,language.get("Message.GameInProgress"));
messagePlayer(player,language.get("Message.PlayerDied"));
deadPeople.put(player,null);
}
}
}
public void saveSetTribuInventory(Player player)
{
inventorySave.addInventory(player);
player.getInventory().clear();
player.getInventory().setArmorContents(null);
}
public void addDefaultPackages() {
if (level != null && this.config.DefaultPackages != null)
for (Package pck : this.config.DefaultPackages) {
level.addPackage(pck);
}
}
public void checkAliveCount() {
// log.info("checking alive count " + aliveCount);
int alive = players.size() - deadPeople.size();
if (alive == 0 && isRunning) { //if (aliveCount == 0 && isRunning) { //if deadPeople isnt used.
deadPeople.clear();
stopRunning();
messagePlayers(language.get("Message.ZombieHavePrevailed"));
messagePlayers(String.format(language.get("Message.YouHaveReachedWave"), String.valueOf(getWaveStarter().getWaveNumber())));
if (getPlayersCount() != 0)
getLevelSelector().startVote(Constants.VoteDelay);
}
}
public int getAliveCount() {
return aliveCount;
}
public BlockTrace getBlockTrace() {
return blockTrace;
}
public TribuLevel getLevel() {
return level;
}
public LevelFileLoader getLevelLoader() {
return levelLoader;
}
public LevelSelector getLevelSelector() {
return levelSelector;
}
public String getLocale(String key) {
/*
* String r = language.get(key); if (r == null) { LogWarning(key +
* " not found"); r = ChatColor.RED +
* "An error occured while getting this message"; } return r;
*/
return language.get(key);
}
public Set<Player> getPlayers() {
return this.players.keySet();
}
public int getPlayersCount() {
return this.players.size();
}
public Player getRandomPlayer() {
return sortedStats.get(rnd.nextInt(sortedStats.size())).getPlayer();
}
public LinkedList<PlayerStats> getSortedStats() {
Collections.sort(this.sortedStats);
/*
* Iterator<PlayerStats> i=this.sortedStats.iterator(); while
* (i.hasNext()) { PlayerStats ps = i.next();
* LogInfo(ps.getPlayer().getDisplayName() +" "+ ps.getPoints()); }
*/
return this.sortedStats;
}
public TribuSpawner getSpawner() {
return spawner;
}
public SpawnTimer getSpawnTimer() {
return spawnTimer;
}
public boolean isInsideLevel(Location loc) {
if (isRunning && level != null)
return config.PluginModeServerExclusive || config.PluginModeWorldExclusive || (loc.distance(level.getInitialSpawn()) < config.LevelClearZone);
else
return false;
}
public PlayerStats getStats(Player player) {
return players.get(player);
}
public WaveStarter getWaveStarter() {
return waveStarter;
}
private void initPluginMode() {
if (config.PluginModeServerExclusive) {
for (Player p : this.getServer().getOnlinePlayers())
this.addPlayer(p);
}
if(config.PluginModeWorldExclusive)
{
for(Player d:Bukkit.getWorld(config.PluginModeWorldExclusiveWorldName).getPlayers())
{
this.addPlayer(d);
}
}
if (config.PluginModeDefaultLevel != "")
setLevel(levelLoader.loadLevel(config.PluginModeDefaultLevel));
if (config.PluginModeAutoStart)
startRunning();
}
public void reloadConf() {
this.reloadConfig();
this.loadCustomConf();
this.initPluginMode();
}
public void loadCustomConf() {
TribuLevel level=this.getLevel();
if (level == null)
return;
File worldFile = null, levelFile = null, worldDir, levelDir;
worldDir = new File(Constants.perWorldFolder);
levelDir = new File(Constants.perLevelFolder);
String levelName = level.getName() + ".yml";
String worldName = level.getInitialSpawn().getWorld().getName() + ".yml";
if (!levelDir.exists())
levelDir.mkdirs();
if (!worldDir.exists())
worldDir.mkdirs();
for (File file : levelDir.listFiles()) {
if (file.getName().equalsIgnoreCase(levelName)) {
levelFile = file;
break;
}
}
for (File file : worldDir.listFiles()) {
if (file.getName().equalsIgnoreCase(worldName)) {
worldFile = file;
break;
}
}
if(levelFile!=null)
if(worldFile != null)
this.config=new TribuConfig(levelFile,new TribuConfig(worldFile));
else
this.config=new TribuConfig(levelFile);
else
this.config=new TribuConfig();
/*
try {
config.set("DefaultPackages", null);
config.load(Constants.configFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InvalidConfigurationException e) {
e.printStackTrace();
}
if (worldFile != null) {
YamlConfiguration tmpConf = YamlConfiguration.loadConfiguration(worldFile);
for (String key : tmpConf.getKeys(true))
if (!config.isConfigurationSection(key))
config.set(key, tmpConf.get(key));
}
if (levelFile != null) {
YamlConfiguration tmpConf = YamlConfiguration.loadConfiguration(levelFile);
for (String key : tmpConf.getKeys(true))
if (!config.isConfigurationSection(key))
config.set(key, tmpConf.get(key));
}
*/
}
private void initLanguage() {
DefaultLanguage.setAuthor("Graindcafe");
DefaultLanguage.setName("English");
DefaultLanguage.setVersion(Constants.LanguageFileVersion);
DefaultLanguage.setLanguagesFolder(getDataFolder().getPath() + File.separatorChar + "languages" + File.separatorChar);
DefaultLanguage.setLocales(new HashMap<String, String>() {
private static final long serialVersionUID = 9166935722459443352L;
{
put("File.DefaultLanguageFile",
"# This is your default language file \n# You should not edit it !\n# Create another language file (custom.yml) \n# and put 'Default: english' if your default language is english\n");
put("File.LanguageFileComplete", "# Your language file is complete\n");
put("File.TranslationsToDo", "# Translations to do in this language file\n");
put("Sign.Buy", "Buy");
put("Sign.ToggleSpawner", "Spawn's switch");
put("Sign.Spawner", "Zombie Spawner");
put("Sign.HighscoreNames", "Top Names");
put("Sign.HighscorePoints", "Top Points");
put("Sign.TollSign", "Pay");
put("Message.Stats", ChatColor.GREEN + "Ranking of best zombies killers : ");
put("Message.UnknownItem", ChatColor.YELLOW + "Sorry, unknown item");
put("Message.ZombieSpawnList", ChatColor.GREEN + "%s");
put("Message.ConfirmDeletion", ChatColor.YELLOW + "Please confirm the deletion of the %s level by redoing the command");
put("Message.ThisOperationIsNotCancellable", ChatColor.RED + "This operation is not cancellable!");
put("Message.LevelUnloaded", ChatColor.GREEN + "Level successfully unloaded");
put("Message.InvalidVote", ChatColor.RED + "Invalid vote");
put("Message.ThankyouForYourVote", ChatColor.GREEN + "Thank you for your vote");
put("Message.YouCannotVoteAtThisTime", ChatColor.RED + "You cannot vote at this time");
put("Message.LevelLoadedSuccessfully", ChatColor.GREEN + "Level loaded successfully");
put("Message.LevelIsAlreadyTheCurrentLevel", ChatColor.RED + "Level %s is already the current level");
put("Message.UnableToSaveLevel", ChatColor.RED + "Unable to save level, try again later");
put("Message.UnableToCreatePackage", ChatColor.RED + "Unable to create package, try again later");
put("Message.UnableToLoadLevel", ChatColor.RED + "Unable to load level");
put("Message.NoLevelLoaded", ChatColor.YELLOW + "No level loaded, type '/tribu load' to load one,");
put("Message.NoLevelLoaded2", ChatColor.YELLOW + "or '/tribu create' to create a new one,");
put("Message.TeleportedToDeathSpawn", ChatColor.GREEN + "Teleported to death spawn");
put("Message.DeathSpawnSet", ChatColor.GREEN + "Death spawn set.");
put("Message.TeleportedToInitialSpawn", ChatColor.GREEN + "Teleported to initial spawn");
put("Message.InitialSpawnSet", ChatColor.GREEN + "Initial spawn set.");
put("Message.UnableToSaveCurrentLevel", ChatColor.RED + "Unable to save current level.");
put("Message.LevelSaveSuccessful", ChatColor.GREEN + "Level save successful");
put("Message.LevelCreated", ChatColor.GREEN + "Level " + ChatColor.LIGHT_PURPLE + "%s" + ChatColor.GREEN + " created");
put("Message.UnableToDeleteLevel", ChatColor.RED + "Unable to delete current level.");
put("Message.PackageCreated", ChatColor.RED + "Package created successfully");
put("Message.LevelDeleted", ChatColor.GREEN + "Level deleted successfully.");
put("Message.Levels", ChatColor.GREEN + "Levels: %s");
put("Message.UnknownLevel", ChatColor.RED + "Unknown level: %s");
put("Message.MaybeNotSaved", ChatColor.YELLOW + "Maybe you have not saved this level or you have not set anything in.");
put("Message.ZombieModeEnabled", ChatColor.GREEN + "Zombie Mode enabled!");
put("Message.ZombieModeDisabled", ChatColor.RED + "Zombie Mode disabled!");
put("Message.SpawnpointAdded", ChatColor.GREEN + "Spawnpoint added");
put("Message.SpawnpointRemoved", ChatColor.GREEN + "Spawnpoint removed");
put("Message.InvalidSpawnName", ChatColor.RED + "Invalid spawn name");
put("Message.TeleportedToZombieSpawn", ChatColor.GREEN + "Teleported to zombie spawn " + ChatColor.LIGHT_PURPLE + "%s");
put("Message.UnableToGiveYouThatItem", ChatColor.RED + "Unable to give you that item...");
put("Message.PurchaseSuccessfulMoney", ChatColor.GREEN + "Purchase successful." + ChatColor.DARK_GRAY + " Money: " + ChatColor.GRAY
+ "%s $");
put("Message.YouDontHaveEnoughMoney", ChatColor.DARK_RED + "You don't have enough money for that!");
put("Message.MoneyPoints", ChatColor.DARK_GRAY + "Money: " + ChatColor.GRAY + "%s $" + ChatColor.DARK_GRAY + " Points: "
+ ChatColor.GRAY + "%s");
put("Message.GameInProgress", ChatColor.YELLOW + "Game in progress, you will spawn next round");
put("Message.ZombieHavePrevailed", ChatColor.DARK_RED + "Zombies have prevailed!");
put("Message.YouHaveReachedWave", ChatColor.RED + "You have reached wave " + ChatColor.YELLOW + "%s");
put("Message.YouJoined", ChatColor.GOLD + "You joined the human strengths against zombies.");
put("Message.YouLeft", ChatColor.GOLD + "You left the fight against zombies.");
put("Message.TribuSignAdded", ChatColor.GREEN + "Tribu sign successfully added.");
put("Message.TribuSignRemoved", ChatColor.GREEN + "Tribu sign successfully removed.");
put("Message.ProtectedBlock", ChatColor.YELLOW + "Sorry, this sign is protected, please ask an operator to remove it.");
put("Message.CannotPlaceASpecialSign", ChatColor.YELLOW + "Sorry, you cannot place a special signs, please ask an operator to do it.");
put("Message.ConfigFileReloaded", ChatColor.GREEN + "Config files have been reloaded.");
put("Message.PckNotFound", ChatColor.YELLOW + "Package %s not found in this level.");
put("Message.PckNeedName", ChatColor.YELLOW + "You have to specify the name of the package.");
put("Message.PckNeedOpen", ChatColor.YELLOW + "You have to open or create a package first.");
put("Message.PckNeedId", ChatColor.YELLOW + "You have to specify the at least the id.");
put("Message.PckNeedIdSubid", ChatColor.YELLOW + "You have to specify the id and subid.");
put("Message.PckCreated", ChatColor.GREEN + "The package %s has been created.");
put("Message.PckOpened", ChatColor.GREEN + "The package %s has been opened.");
put("Message.PckSaved", ChatColor.GREEN + "The package %s has been saved and closed.");
put("Message.PckRemoved", ChatColor.GREEN + "The package has been removed.");
put("Message.PckItemDeleted", ChatColor.GREEN + "The item has been deleted.");
put("Message.PckItemAdded", ChatColor.GREEN + "The item \"%s\" has been successfully added.");
put("Message.PckItemAddFailed", ChatColor.YELLOW + "The item \"%s\" could not be added.");
put("Message.PckList", ChatColor.GREEN + "Packages of this level : %s.");
put("Message.PckNoneOpened", ChatColor.YELLOW + "none opened/specified");
put("Message.LevelNotReady", ChatColor.YELLOW
+ "The level is not ready to run. Make sure you create/load a level and that it contains zombie spawns.");
put("Message.Deny", ChatColor.RED + "A zombie denied your action, sorry.");
put("Message.AlreadyIn", ChatColor.YELLOW + "You are already in.");
put("Broadcast.MapChosen", ChatColor.DARK_BLUE + "Level " + ChatColor.LIGHT_PURPLE + "%s" + ChatColor.DARK_BLUE + " has been chosen");
put("Broadcast.MapVoteStarting", ChatColor.DARK_AQUA + "Level vote starting,");
put("Broadcast.Type", ChatColor.DARK_AQUA + "Type ");
put("Broadcast.SlashVoteForMap", ChatColor.GOLD + "'/tribu vote %s'" + ChatColor.DARK_AQUA + " for map " + ChatColor.BLUE + "%s");
put("Broadcast.VoteClosingInSeconds", ChatColor.DARK_AQUA + "Vote closing in %s seconds");
put("Broadcast.StartingWave", ChatColor.GRAY + "Starting wave " + ChatColor.DARK_RED + "%s" + ChatColor.GRAY + ", "
+ ChatColor.DARK_RED + "%s" + ChatColor.GRAY + " Zombies @ " + ChatColor.DARK_RED + "%s" + ChatColor.GRAY + " health");
put("Broadcast.Wave", ChatColor.DARK_GRAY + "Wave " + ChatColor.DARK_RED + "%s" + ChatColor.DARK_GRAY + " starting in "
+ ChatColor.DARK_RED + "%s" + ChatColor.DARK_GRAY + " seconds.");
put("Broadcast.WaveComplete", ChatColor.GOLD + "Wave Complete");
put("Info.LevelFound", ChatColor.YELLOW + "%s levels found");
put("Info.Enable", ChatColor.WHITE + "Starting " + ChatColor.DARK_RED + "Tribu" + ChatColor.WHITE
+ " by Graindcafe, original author : samp20");
put("Info.Disable", ChatColor.YELLOW + "Stopping Tribu");
put("Info.LevelSaved", ChatColor.GREEN + "Level saved");
put("Info.ChosenLanguage", ChatColor.YELLOW + "Chosen language : %s (default). Provided by : %s.");
put("Info.LevelFolderDoesntExist", ChatColor.RED + "Level folder doesn't exist");
put("Warning.AllSpawnsCurrentlyUnloaded", ChatColor.YELLOW + "All zombies spawns are currently unloaded.");
put("Warning.UnableToSaveLevel", ChatColor.RED + "Unable to save level");
put("Warning.ThisCommandCannotBeUsedFromTheConsole", ChatColor.RED + "This command cannot be used from the console");
put("Warning.IOErrorOnFileDelete", ChatColor.RED + "IO error on file delete");
put("Warning.LanguageFileOutdated", ChatColor.RED + "Your current language file is outdated");
put("Warning.LanguageFileMissing", ChatColor.RED + "The chosen language file is missing");
put("Warning.UnableToAddSign", ChatColor.RED + "Unable to add sign, maybe you've changed your locales, or signs' tags.");
put("Warning.UnknownFocus",
ChatColor.RED + "The string given for the configuration Zombies.Focus is not recognized : %s . It could be 'None','Nearest','Random','DeathSpawn','InitialSpawn'.");
put("Warning.NoSpawns", ChatColor.RED + "You didn't set any zombie spawn.");
put("Severe.TribuCantMkdir",
ChatColor.RED + "Tribu can't make dirs so it cannot create the level directory, you would not be able to save levels ! You can't use Tribu !");
put("Severe.WorldInvalidFileVersion", ChatColor.RED + "World invalid file version");
put("Severe.WorldDoesntExist", ChatColor.RED + "World doesn't exist");
put("Severe.ErrorDuringLevelLoading", ChatColor.RED + "Error during level loading : %s");
put("Severe.ErrorDuringLevelSaving", ChatColor.RED + "Error during level saving : %s");
put("Severe.PlayerHaveNotRetrivedHisItems", ChatColor.RED + "The player %s have not retrieved his items, they will be deleted ! Items list : %s");
put("Severe.Exception", ChatColor.RED + "Exception: %s");
put("Severe.PlayerDidntGetInvBack", ChatColor.RED + "didn't get his inventory back because he was returned null. (Maybe he was not in server?)");
put("Message.PlayerDied",ChatColor.RED + "You are dead.");
put("Message.PlayerRevive",ChatColor.GREEN + "You have been revived.");
+ put("Message.PlayerWrongWorld","You are in the incorrect world. Please join world " + ChatColor.LIGHT_PURPLE + config.PluginModeWorldExclusiveWorldName + ChatColor.RED + " to join the game.");
}
});
language = Language.init(log, config.PluginModeLanguage);
Constants.MessageMoneyPoints = language.get("Message.MoneyPoints");
Constants.MessageZombieSpawnList = language.get("Message.ZombieSpawnList");
}
public boolean isAlive(Player player) {
return players.get(player).isalive();
}
public TribuConfig config()
{
return config;
}
public boolean isPlaying(Player p) {
return players.containsKey(p);
}
public boolean isRunning() {
return isRunning;
}
public void keepTempInv(Player p, ItemStack[] items) {
// log.info("Keep " + items.length + " items for " +
// p.getDisplayName());
tempInventories.put(p, new TribuTempInventory(p, items));
}
public void LogInfo(String message) {
log.info("[Tribu] " + message);
}
public void LogSevere(String message) {
log.severe("[Tribu] " + message);
}
public void LogWarning(String message) {
log.warning("[Tribu] " + message);
}
@Override
public void onDisable() {
for(String player:TribuInventory.inventories.keySet()) //this will only get players if the players inventory has been set. (for world Exclusive)
{
Player theplayer = Bukkit.getPlayer(player);
if(theplayer != null)
{
inventorySave.restoreInventory(theplayer);
} else
{
log.severe(player + language.get("Severe.PlayerDidntGetInvBack"));
}
}
if(this.isRunning)
{
blockTrace.reverse();
}
players.clear();
sortedStats.clear();
stopRunning();
LogInfo(language.get("Info.Disable"));
}
@Override
public void onEnable() {
log = Logger.getLogger("Minecraft");
rnd = new Random();
Constants.rebuildPath(getDataFolder().getPath() + File.separatorChar);
this.config=new TribuConfig();
initLanguage();
try {
@SuppressWarnings("rawtypes")
Class[] args = { Class.class, String.class, Integer.TYPE, Integer.TYPE, Integer.TYPE };
Method a = EntityTypes.class.getDeclaredMethod("a", args);
a.setAccessible(true);
a.invoke(a, EntityTribuZombie.class, "Zombie", 54, '\uafaf', 7969893);
a.invoke(a, EntityZombie.class, "Zombie", 54, '\uafaf', 7969893);
} catch (Exception e) {
e.printStackTrace();
setEnabled(false);
return;
}
isRunning = false;
aliveCount = 0;
level = null;
blockTrace = new BlockTrace();
tempInventories = new HashMap<Player, TribuTempInventory>();
inventorySave = new TribuInventory();
players = new HashMap<Player, PlayerStats>();
spawnPoint=new HashMap<Player,Location>();
sortedStats = new LinkedList<PlayerStats>();
levelLoader = new LevelFileLoader(this);
levelSelector = new LevelSelector(this);
spawner = new TribuSpawner(this);
spawnTimer = new SpawnTimer(this);
waveStarter = new WaveStarter(this);
// Create listeners
playerListener = new TribuPlayerListener(this);
entityListener = new TribuEntityListener(this);
blockListener = new TribuBlockListener(this);
worldListener = new TribuWorldListener(this);
this.initPluginMode();
this.loadCustomConf();
getServer().getPluginManager().registerEvents(playerListener, this);
getServer().getPluginManager().registerEvents(entityListener, this);
getServer().getPluginManager().registerEvents(blockListener, this);
getServer().getPluginManager().registerEvents(worldListener, this);
getCommand("dspawn").setExecutor(new CmdDspawn(this));
getCommand("zspawn").setExecutor(new CmdZspawn(this));
getCommand("ispawn").setExecutor(new CmdIspawn(this));
getCommand("tribu").setExecutor(new CmdTribu(this));
LogInfo(language.get("Info.Enable"));
}
public void resetedSpawnAdd(Player p,Location point)
{
spawnPoint.put(p, point);
}
public void removePlayer(Player player) {
if (player != null && players.containsKey(player)) {
if (isAlive(player)) {
aliveCount--;
}
sortedStats.remove(players.get(player));
inventorySave.restoreInventory(player);
players.remove(player);
if(player.isOnline() && spawnPoint.containsKey(player))
{
player.setBedSpawnLocation(spawnPoint.remove(player));
}
// check alive AFTER player remove
checkAliveCount();
if (!player.isDead())
restoreInventory(player);
}
}
public void restoreInventory(Player p) {
// log.info("Restore items for " + p.getDisplayName());
inventorySave.restoreInventory(p);
}
public void restoreTempInv(Player p) {
// log.info("Restore items for " + p.getDisplayName());
if (tempInventories.containsKey(p))
tempInventories.remove(p).restore();
}
public void revivePlayer(Player player) {
if(spawnPoint.containsKey(player))
{
player.setBedSpawnLocation(spawnPoint.remove(player));
}
players.get(player).revive();
if (config.WaveStartHealPlayers)
player.setHealth(20);
restoreTempInv(player);
aliveCount++;
}
public void revivePlayers(boolean teleportAll) {
aliveCount = 0;
for (Player player : players.keySet()) {
revivePlayer(player);
if (isRunning && level != null && (teleportAll || !isAlive(player))) {
player.teleport(level.getInitialSpawn());
}
}
}
public void setDead(Player player) {
if (players.containsKey(player)) {
if (isAlive(player)) {
aliveCount--;
PlayerStats p = players.get(player);
p.resetMoney();
p.subtractmoney(config.StatsOnPlayerDeathMoney);
p.subtractPoints(config.StatsOnPlayerDeathPoints);
p.msgStats();
messagePlayers(ChatColor.LIGHT_PURPLE + player.getName() + ChatColor.RED + " has died.");
/*
* Set<Entry<Player, PlayerStats>> stats = players.entrySet();
* for (Entry<Player, PlayerStats> stat : stats) {
* stat.getValue().subtractPoints(50);
* stat.getValue().resetMoney(); stat.getValue().msgStats(); }
*/
}
deadPeople.put(player,null);
players.get(player).kill();
if (getLevel() != null && isRunning) {
checkAliveCount();
}
}
}
public void setLevel(TribuLevel level) {
this.level = level;
this.loadCustomConf();
}
public boolean startRunning() {
if (!isRunning && getLevel() != null) {
if (players.isEmpty()) {
setWaitingForPlayers(true);
} else {
// Before (next instruction) it will saves current default
// packages to the level, saving theses packages with the level
this.addDefaultPackages();
// Make sure no data is lost if server decides to die
// during a game and player forgot to /level save
if (!getLevelLoader().saveLevel(getLevel())) {
LogWarning(language.get("Warning.UnableToSaveLevel"));
} else {
LogInfo(language.get("Info.LevelSaved"));
}
if (this.getLevel().getSpawns().isEmpty()) {
LogWarning(language.get("Warning.NoSpawns"));
return false;
}
if (!config.PluginModeAutoStart)
setWaitingForPlayers(false);
isRunning = true;
if (config.PluginModeServerExclusive || config.PluginModeWorldExclusive)
for (LivingEntity e : level.getInitialSpawn().getWorld().getLivingEntities()) {
if (!(e instanceof Player) && !(e instanceof Wolf) && !(e instanceof Villager))
e.damage(Integer.MAX_VALUE);
}
else
for (LivingEntity e : level.getInitialSpawn().getWorld().getLivingEntities()) {
if ((e.getLocation().distance(level.getInitialSpawn())) < config.LevelClearZone
&& !(e instanceof Player) && !(e instanceof Wolf) && !(e instanceof Villager))
e.damage(Integer.MAX_VALUE);
}
getLevel().initSigns();
this.sortedStats.clear();
for (Player save : players.keySet()) //makes sure all inventorys have been saved
{
inventorySave.addInventory(save);
save.getInventory().clear();
save.getInventory().setArmorContents(null);
}
for (PlayerStats stat : players.values()) {
stat.resetPoints();
stat.resetMoney();
this.sortedStats.add(stat);
}
getWaveStarter().resetWave();
revivePlayers(true);
getWaveStarter().scheduleWave(Constants.TicksBySecond * config.WaveStartDelay);
}
}
return true;
}
public void stopRunning() {
if (isRunning) {
isRunning = false;
getSpawnTimer().Stop();
getWaveStarter().cancelWave();
getSpawner().clearZombies();
getLevelSelector().cancelVote();
blockTrace.reverse();
deadPeople.clear();
TollSign.getAllowedPlayer().clear();
for(String player:TribuInventory.inventories.keySet()) //this will only get players if the players inventory has been set. (for world Exclusive or server)
{
Player theplayer = Bukkit.getPlayer(player);
if(theplayer != null)
{
inventorySave.restoreInventory(theplayer);
} else
{
log.severe("[Tribu] " + player + " didn't get his inventory back because player was returned null. (Maybe he was not in server?)");
}
}
for(Player fd:Bukkit.getServer().getWorld(config.PluginModeWorldExclusiveWorldName).getPlayers()) //teleports all players to spawn when game ends
{
fd.teleport(level.getInitialSpawn());
}
if (!config.PluginModeServerExclusive || !config.PluginModeWorldExclusive) {
players.clear();
}
}
}
//to avoid warnings
public boolean isWaitingForPlayers() {
return waitingForPlayers;
}
//to avoid warnings
public void setWaitingForPlayers(boolean waitingForPlayers) {
this.waitingForPlayers = waitingForPlayers;
}
public boolean isCorrectWorld(World World)
{
if(config.PluginModeServerExclusive)
{
return true; //continue (ignore world)
} else
if(config.PluginModeWorldExclusive)
{
String world = World.toString();
String[] ar = world.split("=");
if(!ar[1].replace("}", "").equalsIgnoreCase(config.PluginModeWorldExclusiveWorldName))
{
return false; //your in wrong world
}
return true; //your in correct world
} else
{
LogSevere("We have a big problem in isCorrectWorld()");
return true; //continue (ignore world)
}
}
/*
* public static void messagePlayer(CommandSender sender, String message) {
if(message.isEmpty())
return;
if (sender == null)
Logger.getLogger("Minecraft").info(ChatColor.stripColor(message));
else
sender.sendMessage(message);
}
*/
public void messageTribuPlayers(String msg) //This wil message only the players (confused what this is for haha)
{
if(msg.isEmpty())
return;
for(Player p : players.keySet())
{
p.sendMessage(ChatColor.GRAY + "[Tribu] " + msg);
}
}
public void messagePlayers(String message) //this will message ALL of the players in that world.
{
for(Player players:Bukkit.getWorld(config.PluginModeWorldExclusiveWorldName).getPlayers())
{
players.sendMessage(ChatColor.GRAY + "[Tribu] " + message);
}
}
public static void messagePlayer(CommandSender user, String message) //this will message a set player.
{
((Player) user).sendMessage(ChatColor.GRAY + "[Tribu] " + message);
}
public Map<Player,String> deadPeople = new HashMap<Player,String>();
}
| true | true | public void checkAliveCount() {
// log.info("checking alive count " + aliveCount);
int alive = players.size() - deadPeople.size();
if (alive == 0 && isRunning) { //if (aliveCount == 0 && isRunning) { //if deadPeople isnt used.
deadPeople.clear();
stopRunning();
messagePlayers(language.get("Message.ZombieHavePrevailed"));
messagePlayers(String.format(language.get("Message.YouHaveReachedWave"), String.valueOf(getWaveStarter().getWaveNumber())));
if (getPlayersCount() != 0)
getLevelSelector().startVote(Constants.VoteDelay);
}
}
public int getAliveCount() {
return aliveCount;
}
public BlockTrace getBlockTrace() {
return blockTrace;
}
public TribuLevel getLevel() {
return level;
}
public LevelFileLoader getLevelLoader() {
return levelLoader;
}
public LevelSelector getLevelSelector() {
return levelSelector;
}
public String getLocale(String key) {
/*
* String r = language.get(key); if (r == null) { LogWarning(key +
* " not found"); r = ChatColor.RED +
* "An error occured while getting this message"; } return r;
*/
return language.get(key);
}
public Set<Player> getPlayers() {
return this.players.keySet();
}
public int getPlayersCount() {
return this.players.size();
}
public Player getRandomPlayer() {
return sortedStats.get(rnd.nextInt(sortedStats.size())).getPlayer();
}
public LinkedList<PlayerStats> getSortedStats() {
Collections.sort(this.sortedStats);
/*
* Iterator<PlayerStats> i=this.sortedStats.iterator(); while
* (i.hasNext()) { PlayerStats ps = i.next();
* LogInfo(ps.getPlayer().getDisplayName() +" "+ ps.getPoints()); }
*/
return this.sortedStats;
}
public TribuSpawner getSpawner() {
return spawner;
}
public SpawnTimer getSpawnTimer() {
return spawnTimer;
}
public boolean isInsideLevel(Location loc) {
if (isRunning && level != null)
return config.PluginModeServerExclusive || config.PluginModeWorldExclusive || (loc.distance(level.getInitialSpawn()) < config.LevelClearZone);
else
return false;
}
public PlayerStats getStats(Player player) {
return players.get(player);
}
public WaveStarter getWaveStarter() {
return waveStarter;
}
private void initPluginMode() {
if (config.PluginModeServerExclusive) {
for (Player p : this.getServer().getOnlinePlayers())
this.addPlayer(p);
}
if(config.PluginModeWorldExclusive)
{
for(Player d:Bukkit.getWorld(config.PluginModeWorldExclusiveWorldName).getPlayers())
{
this.addPlayer(d);
}
}
if (config.PluginModeDefaultLevel != "")
setLevel(levelLoader.loadLevel(config.PluginModeDefaultLevel));
if (config.PluginModeAutoStart)
startRunning();
}
public void reloadConf() {
this.reloadConfig();
this.loadCustomConf();
this.initPluginMode();
}
public void loadCustomConf() {
TribuLevel level=this.getLevel();
if (level == null)
return;
File worldFile = null, levelFile = null, worldDir, levelDir;
worldDir = new File(Constants.perWorldFolder);
levelDir = new File(Constants.perLevelFolder);
String levelName = level.getName() + ".yml";
String worldName = level.getInitialSpawn().getWorld().getName() + ".yml";
if (!levelDir.exists())
levelDir.mkdirs();
if (!worldDir.exists())
worldDir.mkdirs();
for (File file : levelDir.listFiles()) {
if (file.getName().equalsIgnoreCase(levelName)) {
levelFile = file;
break;
}
}
for (File file : worldDir.listFiles()) {
if (file.getName().equalsIgnoreCase(worldName)) {
worldFile = file;
break;
}
}
if(levelFile!=null)
if(worldFile != null)
this.config=new TribuConfig(levelFile,new TribuConfig(worldFile));
else
this.config=new TribuConfig(levelFile);
else
this.config=new TribuConfig();
/*
try {
config.set("DefaultPackages", null);
config.load(Constants.configFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InvalidConfigurationException e) {
e.printStackTrace();
}
if (worldFile != null) {
YamlConfiguration tmpConf = YamlConfiguration.loadConfiguration(worldFile);
for (String key : tmpConf.getKeys(true))
if (!config.isConfigurationSection(key))
config.set(key, tmpConf.get(key));
}
if (levelFile != null) {
YamlConfiguration tmpConf = YamlConfiguration.loadConfiguration(levelFile);
for (String key : tmpConf.getKeys(true))
if (!config.isConfigurationSection(key))
config.set(key, tmpConf.get(key));
}
*/
}
private void initLanguage() {
DefaultLanguage.setAuthor("Graindcafe");
DefaultLanguage.setName("English");
DefaultLanguage.setVersion(Constants.LanguageFileVersion);
DefaultLanguage.setLanguagesFolder(getDataFolder().getPath() + File.separatorChar + "languages" + File.separatorChar);
DefaultLanguage.setLocales(new HashMap<String, String>() {
private static final long serialVersionUID = 9166935722459443352L;
{
put("File.DefaultLanguageFile",
"# This is your default language file \n# You should not edit it !\n# Create another language file (custom.yml) \n# and put 'Default: english' if your default language is english\n");
put("File.LanguageFileComplete", "# Your language file is complete\n");
put("File.TranslationsToDo", "# Translations to do in this language file\n");
put("Sign.Buy", "Buy");
put("Sign.ToggleSpawner", "Spawn's switch");
put("Sign.Spawner", "Zombie Spawner");
put("Sign.HighscoreNames", "Top Names");
put("Sign.HighscorePoints", "Top Points");
put("Sign.TollSign", "Pay");
put("Message.Stats", ChatColor.GREEN + "Ranking of best zombies killers : ");
put("Message.UnknownItem", ChatColor.YELLOW + "Sorry, unknown item");
put("Message.ZombieSpawnList", ChatColor.GREEN + "%s");
put("Message.ConfirmDeletion", ChatColor.YELLOW + "Please confirm the deletion of the %s level by redoing the command");
put("Message.ThisOperationIsNotCancellable", ChatColor.RED + "This operation is not cancellable!");
put("Message.LevelUnloaded", ChatColor.GREEN + "Level successfully unloaded");
put("Message.InvalidVote", ChatColor.RED + "Invalid vote");
put("Message.ThankyouForYourVote", ChatColor.GREEN + "Thank you for your vote");
put("Message.YouCannotVoteAtThisTime", ChatColor.RED + "You cannot vote at this time");
put("Message.LevelLoadedSuccessfully", ChatColor.GREEN + "Level loaded successfully");
put("Message.LevelIsAlreadyTheCurrentLevel", ChatColor.RED + "Level %s is already the current level");
put("Message.UnableToSaveLevel", ChatColor.RED + "Unable to save level, try again later");
put("Message.UnableToCreatePackage", ChatColor.RED + "Unable to create package, try again later");
put("Message.UnableToLoadLevel", ChatColor.RED + "Unable to load level");
put("Message.NoLevelLoaded", ChatColor.YELLOW + "No level loaded, type '/tribu load' to load one,");
put("Message.NoLevelLoaded2", ChatColor.YELLOW + "or '/tribu create' to create a new one,");
put("Message.TeleportedToDeathSpawn", ChatColor.GREEN + "Teleported to death spawn");
put("Message.DeathSpawnSet", ChatColor.GREEN + "Death spawn set.");
put("Message.TeleportedToInitialSpawn", ChatColor.GREEN + "Teleported to initial spawn");
put("Message.InitialSpawnSet", ChatColor.GREEN + "Initial spawn set.");
put("Message.UnableToSaveCurrentLevel", ChatColor.RED + "Unable to save current level.");
put("Message.LevelSaveSuccessful", ChatColor.GREEN + "Level save successful");
put("Message.LevelCreated", ChatColor.GREEN + "Level " + ChatColor.LIGHT_PURPLE + "%s" + ChatColor.GREEN + " created");
put("Message.UnableToDeleteLevel", ChatColor.RED + "Unable to delete current level.");
put("Message.PackageCreated", ChatColor.RED + "Package created successfully");
put("Message.LevelDeleted", ChatColor.GREEN + "Level deleted successfully.");
put("Message.Levels", ChatColor.GREEN + "Levels: %s");
put("Message.UnknownLevel", ChatColor.RED + "Unknown level: %s");
put("Message.MaybeNotSaved", ChatColor.YELLOW + "Maybe you have not saved this level or you have not set anything in.");
put("Message.ZombieModeEnabled", ChatColor.GREEN + "Zombie Mode enabled!");
put("Message.ZombieModeDisabled", ChatColor.RED + "Zombie Mode disabled!");
put("Message.SpawnpointAdded", ChatColor.GREEN + "Spawnpoint added");
put("Message.SpawnpointRemoved", ChatColor.GREEN + "Spawnpoint removed");
put("Message.InvalidSpawnName", ChatColor.RED + "Invalid spawn name");
put("Message.TeleportedToZombieSpawn", ChatColor.GREEN + "Teleported to zombie spawn " + ChatColor.LIGHT_PURPLE + "%s");
put("Message.UnableToGiveYouThatItem", ChatColor.RED + "Unable to give you that item...");
put("Message.PurchaseSuccessfulMoney", ChatColor.GREEN + "Purchase successful." + ChatColor.DARK_GRAY + " Money: " + ChatColor.GRAY
+ "%s $");
put("Message.YouDontHaveEnoughMoney", ChatColor.DARK_RED + "You don't have enough money for that!");
put("Message.MoneyPoints", ChatColor.DARK_GRAY + "Money: " + ChatColor.GRAY + "%s $" + ChatColor.DARK_GRAY + " Points: "
+ ChatColor.GRAY + "%s");
put("Message.GameInProgress", ChatColor.YELLOW + "Game in progress, you will spawn next round");
put("Message.ZombieHavePrevailed", ChatColor.DARK_RED + "Zombies have prevailed!");
put("Message.YouHaveReachedWave", ChatColor.RED + "You have reached wave " + ChatColor.YELLOW + "%s");
put("Message.YouJoined", ChatColor.GOLD + "You joined the human strengths against zombies.");
put("Message.YouLeft", ChatColor.GOLD + "You left the fight against zombies.");
put("Message.TribuSignAdded", ChatColor.GREEN + "Tribu sign successfully added.");
put("Message.TribuSignRemoved", ChatColor.GREEN + "Tribu sign successfully removed.");
put("Message.ProtectedBlock", ChatColor.YELLOW + "Sorry, this sign is protected, please ask an operator to remove it.");
put("Message.CannotPlaceASpecialSign", ChatColor.YELLOW + "Sorry, you cannot place a special signs, please ask an operator to do it.");
put("Message.ConfigFileReloaded", ChatColor.GREEN + "Config files have been reloaded.");
put("Message.PckNotFound", ChatColor.YELLOW + "Package %s not found in this level.");
put("Message.PckNeedName", ChatColor.YELLOW + "You have to specify the name of the package.");
put("Message.PckNeedOpen", ChatColor.YELLOW + "You have to open or create a package first.");
put("Message.PckNeedId", ChatColor.YELLOW + "You have to specify the at least the id.");
put("Message.PckNeedIdSubid", ChatColor.YELLOW + "You have to specify the id and subid.");
put("Message.PckCreated", ChatColor.GREEN + "The package %s has been created.");
put("Message.PckOpened", ChatColor.GREEN + "The package %s has been opened.");
put("Message.PckSaved", ChatColor.GREEN + "The package %s has been saved and closed.");
put("Message.PckRemoved", ChatColor.GREEN + "The package has been removed.");
put("Message.PckItemDeleted", ChatColor.GREEN + "The item has been deleted.");
put("Message.PckItemAdded", ChatColor.GREEN + "The item \"%s\" has been successfully added.");
put("Message.PckItemAddFailed", ChatColor.YELLOW + "The item \"%s\" could not be added.");
put("Message.PckList", ChatColor.GREEN + "Packages of this level : %s.");
put("Message.PckNoneOpened", ChatColor.YELLOW + "none opened/specified");
put("Message.LevelNotReady", ChatColor.YELLOW
+ "The level is not ready to run. Make sure you create/load a level and that it contains zombie spawns.");
put("Message.Deny", ChatColor.RED + "A zombie denied your action, sorry.");
put("Message.AlreadyIn", ChatColor.YELLOW + "You are already in.");
put("Broadcast.MapChosen", ChatColor.DARK_BLUE + "Level " + ChatColor.LIGHT_PURPLE + "%s" + ChatColor.DARK_BLUE + " has been chosen");
put("Broadcast.MapVoteStarting", ChatColor.DARK_AQUA + "Level vote starting,");
put("Broadcast.Type", ChatColor.DARK_AQUA + "Type ");
put("Broadcast.SlashVoteForMap", ChatColor.GOLD + "'/tribu vote %s'" + ChatColor.DARK_AQUA + " for map " + ChatColor.BLUE + "%s");
put("Broadcast.VoteClosingInSeconds", ChatColor.DARK_AQUA + "Vote closing in %s seconds");
put("Broadcast.StartingWave", ChatColor.GRAY + "Starting wave " + ChatColor.DARK_RED + "%s" + ChatColor.GRAY + ", "
+ ChatColor.DARK_RED + "%s" + ChatColor.GRAY + " Zombies @ " + ChatColor.DARK_RED + "%s" + ChatColor.GRAY + " health");
put("Broadcast.Wave", ChatColor.DARK_GRAY + "Wave " + ChatColor.DARK_RED + "%s" + ChatColor.DARK_GRAY + " starting in "
+ ChatColor.DARK_RED + "%s" + ChatColor.DARK_GRAY + " seconds.");
put("Broadcast.WaveComplete", ChatColor.GOLD + "Wave Complete");
put("Info.LevelFound", ChatColor.YELLOW + "%s levels found");
put("Info.Enable", ChatColor.WHITE + "Starting " + ChatColor.DARK_RED + "Tribu" + ChatColor.WHITE
+ " by Graindcafe, original author : samp20");
put("Info.Disable", ChatColor.YELLOW + "Stopping Tribu");
put("Info.LevelSaved", ChatColor.GREEN + "Level saved");
put("Info.ChosenLanguage", ChatColor.YELLOW + "Chosen language : %s (default). Provided by : %s.");
put("Info.LevelFolderDoesntExist", ChatColor.RED + "Level folder doesn't exist");
put("Warning.AllSpawnsCurrentlyUnloaded", ChatColor.YELLOW + "All zombies spawns are currently unloaded.");
put("Warning.UnableToSaveLevel", ChatColor.RED + "Unable to save level");
put("Warning.ThisCommandCannotBeUsedFromTheConsole", ChatColor.RED + "This command cannot be used from the console");
put("Warning.IOErrorOnFileDelete", ChatColor.RED + "IO error on file delete");
put("Warning.LanguageFileOutdated", ChatColor.RED + "Your current language file is outdated");
put("Warning.LanguageFileMissing", ChatColor.RED + "The chosen language file is missing");
put("Warning.UnableToAddSign", ChatColor.RED + "Unable to add sign, maybe you've changed your locales, or signs' tags.");
put("Warning.UnknownFocus",
ChatColor.RED + "The string given for the configuration Zombies.Focus is not recognized : %s . It could be 'None','Nearest','Random','DeathSpawn','InitialSpawn'.");
put("Warning.NoSpawns", ChatColor.RED + "You didn't set any zombie spawn.");
put("Severe.TribuCantMkdir",
ChatColor.RED + "Tribu can't make dirs so it cannot create the level directory, you would not be able to save levels ! You can't use Tribu !");
put("Severe.WorldInvalidFileVersion", ChatColor.RED + "World invalid file version");
put("Severe.WorldDoesntExist", ChatColor.RED + "World doesn't exist");
put("Severe.ErrorDuringLevelLoading", ChatColor.RED + "Error during level loading : %s");
put("Severe.ErrorDuringLevelSaving", ChatColor.RED + "Error during level saving : %s");
put("Severe.PlayerHaveNotRetrivedHisItems", ChatColor.RED + "The player %s have not retrieved his items, they will be deleted ! Items list : %s");
put("Severe.Exception", ChatColor.RED + "Exception: %s");
put("Severe.PlayerDidntGetInvBack", ChatColor.RED + "didn't get his inventory back because he was returned null. (Maybe he was not in server?)");
put("Message.PlayerDied",ChatColor.RED + "You are dead.");
put("Message.PlayerRevive",ChatColor.GREEN + "You have been revived.");
}
});
language = Language.init(log, config.PluginModeLanguage);
Constants.MessageMoneyPoints = language.get("Message.MoneyPoints");
Constants.MessageZombieSpawnList = language.get("Message.ZombieSpawnList");
}
public boolean isAlive(Player player) {
return players.get(player).isalive();
}
public TribuConfig config()
{
return config;
}
public boolean isPlaying(Player p) {
return players.containsKey(p);
}
public boolean isRunning() {
return isRunning;
}
public void keepTempInv(Player p, ItemStack[] items) {
// log.info("Keep " + items.length + " items for " +
// p.getDisplayName());
tempInventories.put(p, new TribuTempInventory(p, items));
}
public void LogInfo(String message) {
log.info("[Tribu] " + message);
}
public void LogSevere(String message) {
log.severe("[Tribu] " + message);
}
public void LogWarning(String message) {
log.warning("[Tribu] " + message);
}
@Override
public void onDisable() {
for(String player:TribuInventory.inventories.keySet()) //this will only get players if the players inventory has been set. (for world Exclusive)
{
Player theplayer = Bukkit.getPlayer(player);
if(theplayer != null)
{
inventorySave.restoreInventory(theplayer);
} else
{
log.severe(player + language.get("Severe.PlayerDidntGetInvBack"));
}
}
if(this.isRunning)
{
blockTrace.reverse();
}
players.clear();
sortedStats.clear();
stopRunning();
LogInfo(language.get("Info.Disable"));
}
@Override
public void onEnable() {
log = Logger.getLogger("Minecraft");
rnd = new Random();
Constants.rebuildPath(getDataFolder().getPath() + File.separatorChar);
this.config=new TribuConfig();
initLanguage();
try {
@SuppressWarnings("rawtypes")
Class[] args = { Class.class, String.class, Integer.TYPE, Integer.TYPE, Integer.TYPE };
Method a = EntityTypes.class.getDeclaredMethod("a", args);
a.setAccessible(true);
a.invoke(a, EntityTribuZombie.class, "Zombie", 54, '\uafaf', 7969893);
a.invoke(a, EntityZombie.class, "Zombie", 54, '\uafaf', 7969893);
} catch (Exception e) {
e.printStackTrace();
setEnabled(false);
return;
}
isRunning = false;
aliveCount = 0;
level = null;
blockTrace = new BlockTrace();
tempInventories = new HashMap<Player, TribuTempInventory>();
inventorySave = new TribuInventory();
players = new HashMap<Player, PlayerStats>();
spawnPoint=new HashMap<Player,Location>();
sortedStats = new LinkedList<PlayerStats>();
levelLoader = new LevelFileLoader(this);
levelSelector = new LevelSelector(this);
spawner = new TribuSpawner(this);
spawnTimer = new SpawnTimer(this);
waveStarter = new WaveStarter(this);
// Create listeners
playerListener = new TribuPlayerListener(this);
entityListener = new TribuEntityListener(this);
blockListener = new TribuBlockListener(this);
worldListener = new TribuWorldListener(this);
this.initPluginMode();
this.loadCustomConf();
getServer().getPluginManager().registerEvents(playerListener, this);
getServer().getPluginManager().registerEvents(entityListener, this);
getServer().getPluginManager().registerEvents(blockListener, this);
getServer().getPluginManager().registerEvents(worldListener, this);
getCommand("dspawn").setExecutor(new CmdDspawn(this));
getCommand("zspawn").setExecutor(new CmdZspawn(this));
getCommand("ispawn").setExecutor(new CmdIspawn(this));
getCommand("tribu").setExecutor(new CmdTribu(this));
LogInfo(language.get("Info.Enable"));
}
public void resetedSpawnAdd(Player p,Location point)
{
spawnPoint.put(p, point);
}
public void removePlayer(Player player) {
if (player != null && players.containsKey(player)) {
if (isAlive(player)) {
aliveCount--;
}
sortedStats.remove(players.get(player));
inventorySave.restoreInventory(player);
players.remove(player);
if(player.isOnline() && spawnPoint.containsKey(player))
{
player.setBedSpawnLocation(spawnPoint.remove(player));
}
// check alive AFTER player remove
checkAliveCount();
if (!player.isDead())
restoreInventory(player);
}
}
public void restoreInventory(Player p) {
// log.info("Restore items for " + p.getDisplayName());
inventorySave.restoreInventory(p);
}
public void restoreTempInv(Player p) {
// log.info("Restore items for " + p.getDisplayName());
if (tempInventories.containsKey(p))
tempInventories.remove(p).restore();
}
public void revivePlayer(Player player) {
if(spawnPoint.containsKey(player))
{
player.setBedSpawnLocation(spawnPoint.remove(player));
}
players.get(player).revive();
if (config.WaveStartHealPlayers)
player.setHealth(20);
restoreTempInv(player);
aliveCount++;
}
public void revivePlayers(boolean teleportAll) {
aliveCount = 0;
for (Player player : players.keySet()) {
revivePlayer(player);
if (isRunning && level != null && (teleportAll || !isAlive(player))) {
player.teleport(level.getInitialSpawn());
}
}
}
public void setDead(Player player) {
if (players.containsKey(player)) {
if (isAlive(player)) {
aliveCount--;
PlayerStats p = players.get(player);
p.resetMoney();
p.subtractmoney(config.StatsOnPlayerDeathMoney);
p.subtractPoints(config.StatsOnPlayerDeathPoints);
p.msgStats();
messagePlayers(ChatColor.LIGHT_PURPLE + player.getName() + ChatColor.RED + " has died.");
/*
* Set<Entry<Player, PlayerStats>> stats = players.entrySet();
* for (Entry<Player, PlayerStats> stat : stats) {
* stat.getValue().subtractPoints(50);
* stat.getValue().resetMoney(); stat.getValue().msgStats(); }
*/
}
deadPeople.put(player,null);
players.get(player).kill();
if (getLevel() != null && isRunning) {
checkAliveCount();
}
}
}
public void setLevel(TribuLevel level) {
this.level = level;
this.loadCustomConf();
}
public boolean startRunning() {
if (!isRunning && getLevel() != null) {
if (players.isEmpty()) {
setWaitingForPlayers(true);
} else {
// Before (next instruction) it will saves current default
// packages to the level, saving theses packages with the level
this.addDefaultPackages();
// Make sure no data is lost if server decides to die
// during a game and player forgot to /level save
if (!getLevelLoader().saveLevel(getLevel())) {
LogWarning(language.get("Warning.UnableToSaveLevel"));
} else {
LogInfo(language.get("Info.LevelSaved"));
}
if (this.getLevel().getSpawns().isEmpty()) {
LogWarning(language.get("Warning.NoSpawns"));
return false;
}
if (!config.PluginModeAutoStart)
setWaitingForPlayers(false);
isRunning = true;
if (config.PluginModeServerExclusive || config.PluginModeWorldExclusive)
for (LivingEntity e : level.getInitialSpawn().getWorld().getLivingEntities()) {
if (!(e instanceof Player) && !(e instanceof Wolf) && !(e instanceof Villager))
e.damage(Integer.MAX_VALUE);
}
else
for (LivingEntity e : level.getInitialSpawn().getWorld().getLivingEntities()) {
if ((e.getLocation().distance(level.getInitialSpawn())) < config.LevelClearZone
&& !(e instanceof Player) && !(e instanceof Wolf) && !(e instanceof Villager))
e.damage(Integer.MAX_VALUE);
}
getLevel().initSigns();
this.sortedStats.clear();
for (Player save : players.keySet()) //makes sure all inventorys have been saved
{
inventorySave.addInventory(save);
save.getInventory().clear();
save.getInventory().setArmorContents(null);
}
for (PlayerStats stat : players.values()) {
stat.resetPoints();
stat.resetMoney();
this.sortedStats.add(stat);
}
getWaveStarter().resetWave();
revivePlayers(true);
getWaveStarter().scheduleWave(Constants.TicksBySecond * config.WaveStartDelay);
}
}
return true;
}
public void stopRunning() {
if (isRunning) {
isRunning = false;
getSpawnTimer().Stop();
getWaveStarter().cancelWave();
getSpawner().clearZombies();
getLevelSelector().cancelVote();
blockTrace.reverse();
deadPeople.clear();
TollSign.getAllowedPlayer().clear();
for(String player:TribuInventory.inventories.keySet()) //this will only get players if the players inventory has been set. (for world Exclusive or server)
{
Player theplayer = Bukkit.getPlayer(player);
if(theplayer != null)
{
inventorySave.restoreInventory(theplayer);
} else
{
log.severe("[Tribu] " + player + " didn't get his inventory back because player was returned null. (Maybe he was not in server?)");
}
}
for(Player fd:Bukkit.getServer().getWorld(config.PluginModeWorldExclusiveWorldName).getPlayers()) //teleports all players to spawn when game ends
{
fd.teleport(level.getInitialSpawn());
}
if (!config.PluginModeServerExclusive || !config.PluginModeWorldExclusive) {
players.clear();
}
}
}
//to avoid warnings
public boolean isWaitingForPlayers() {
return waitingForPlayers;
}
//to avoid warnings
public void setWaitingForPlayers(boolean waitingForPlayers) {
this.waitingForPlayers = waitingForPlayers;
}
public boolean isCorrectWorld(World World)
{
if(config.PluginModeServerExclusive)
{
return true; //continue (ignore world)
} else
if(config.PluginModeWorldExclusive)
{
String world = World.toString();
String[] ar = world.split("=");
if(!ar[1].replace("}", "").equalsIgnoreCase(config.PluginModeWorldExclusiveWorldName))
{
return false; //your in wrong world
}
return true; //your in correct world
} else
{
LogSevere("We have a big problem in isCorrectWorld()");
return true; //continue (ignore world)
}
}
/*
* public static void messagePlayer(CommandSender sender, String message) {
if(message.isEmpty())
return;
if (sender == null)
Logger.getLogger("Minecraft").info(ChatColor.stripColor(message));
else
sender.sendMessage(message);
}
| public void checkAliveCount() {
// log.info("checking alive count " + aliveCount);
int alive = players.size() - deadPeople.size();
if (alive == 0 && isRunning) { //if (aliveCount == 0 && isRunning) { //if deadPeople isnt used.
deadPeople.clear();
stopRunning();
messagePlayers(language.get("Message.ZombieHavePrevailed"));
messagePlayers(String.format(language.get("Message.YouHaveReachedWave"), String.valueOf(getWaveStarter().getWaveNumber())));
if (getPlayersCount() != 0)
getLevelSelector().startVote(Constants.VoteDelay);
}
}
public int getAliveCount() {
return aliveCount;
}
public BlockTrace getBlockTrace() {
return blockTrace;
}
public TribuLevel getLevel() {
return level;
}
public LevelFileLoader getLevelLoader() {
return levelLoader;
}
public LevelSelector getLevelSelector() {
return levelSelector;
}
public String getLocale(String key) {
/*
* String r = language.get(key); if (r == null) { LogWarning(key +
* " not found"); r = ChatColor.RED +
* "An error occured while getting this message"; } return r;
*/
return language.get(key);
}
public Set<Player> getPlayers() {
return this.players.keySet();
}
public int getPlayersCount() {
return this.players.size();
}
public Player getRandomPlayer() {
return sortedStats.get(rnd.nextInt(sortedStats.size())).getPlayer();
}
public LinkedList<PlayerStats> getSortedStats() {
Collections.sort(this.sortedStats);
/*
* Iterator<PlayerStats> i=this.sortedStats.iterator(); while
* (i.hasNext()) { PlayerStats ps = i.next();
* LogInfo(ps.getPlayer().getDisplayName() +" "+ ps.getPoints()); }
*/
return this.sortedStats;
}
public TribuSpawner getSpawner() {
return spawner;
}
public SpawnTimer getSpawnTimer() {
return spawnTimer;
}
public boolean isInsideLevel(Location loc) {
if (isRunning && level != null)
return config.PluginModeServerExclusive || config.PluginModeWorldExclusive || (loc.distance(level.getInitialSpawn()) < config.LevelClearZone);
else
return false;
}
public PlayerStats getStats(Player player) {
return players.get(player);
}
public WaveStarter getWaveStarter() {
return waveStarter;
}
private void initPluginMode() {
if (config.PluginModeServerExclusive) {
for (Player p : this.getServer().getOnlinePlayers())
this.addPlayer(p);
}
if(config.PluginModeWorldExclusive)
{
for(Player d:Bukkit.getWorld(config.PluginModeWorldExclusiveWorldName).getPlayers())
{
this.addPlayer(d);
}
}
if (config.PluginModeDefaultLevel != "")
setLevel(levelLoader.loadLevel(config.PluginModeDefaultLevel));
if (config.PluginModeAutoStart)
startRunning();
}
public void reloadConf() {
this.reloadConfig();
this.loadCustomConf();
this.initPluginMode();
}
public void loadCustomConf() {
TribuLevel level=this.getLevel();
if (level == null)
return;
File worldFile = null, levelFile = null, worldDir, levelDir;
worldDir = new File(Constants.perWorldFolder);
levelDir = new File(Constants.perLevelFolder);
String levelName = level.getName() + ".yml";
String worldName = level.getInitialSpawn().getWorld().getName() + ".yml";
if (!levelDir.exists())
levelDir.mkdirs();
if (!worldDir.exists())
worldDir.mkdirs();
for (File file : levelDir.listFiles()) {
if (file.getName().equalsIgnoreCase(levelName)) {
levelFile = file;
break;
}
}
for (File file : worldDir.listFiles()) {
if (file.getName().equalsIgnoreCase(worldName)) {
worldFile = file;
break;
}
}
if(levelFile!=null)
if(worldFile != null)
this.config=new TribuConfig(levelFile,new TribuConfig(worldFile));
else
this.config=new TribuConfig(levelFile);
else
this.config=new TribuConfig();
/*
try {
config.set("DefaultPackages", null);
config.load(Constants.configFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InvalidConfigurationException e) {
e.printStackTrace();
}
if (worldFile != null) {
YamlConfiguration tmpConf = YamlConfiguration.loadConfiguration(worldFile);
for (String key : tmpConf.getKeys(true))
if (!config.isConfigurationSection(key))
config.set(key, tmpConf.get(key));
}
if (levelFile != null) {
YamlConfiguration tmpConf = YamlConfiguration.loadConfiguration(levelFile);
for (String key : tmpConf.getKeys(true))
if (!config.isConfigurationSection(key))
config.set(key, tmpConf.get(key));
}
*/
}
private void initLanguage() {
DefaultLanguage.setAuthor("Graindcafe");
DefaultLanguage.setName("English");
DefaultLanguage.setVersion(Constants.LanguageFileVersion);
DefaultLanguage.setLanguagesFolder(getDataFolder().getPath() + File.separatorChar + "languages" + File.separatorChar);
DefaultLanguage.setLocales(new HashMap<String, String>() {
private static final long serialVersionUID = 9166935722459443352L;
{
put("File.DefaultLanguageFile",
"# This is your default language file \n# You should not edit it !\n# Create another language file (custom.yml) \n# and put 'Default: english' if your default language is english\n");
put("File.LanguageFileComplete", "# Your language file is complete\n");
put("File.TranslationsToDo", "# Translations to do in this language file\n");
put("Sign.Buy", "Buy");
put("Sign.ToggleSpawner", "Spawn's switch");
put("Sign.Spawner", "Zombie Spawner");
put("Sign.HighscoreNames", "Top Names");
put("Sign.HighscorePoints", "Top Points");
put("Sign.TollSign", "Pay");
put("Message.Stats", ChatColor.GREEN + "Ranking of best zombies killers : ");
put("Message.UnknownItem", ChatColor.YELLOW + "Sorry, unknown item");
put("Message.ZombieSpawnList", ChatColor.GREEN + "%s");
put("Message.ConfirmDeletion", ChatColor.YELLOW + "Please confirm the deletion of the %s level by redoing the command");
put("Message.ThisOperationIsNotCancellable", ChatColor.RED + "This operation is not cancellable!");
put("Message.LevelUnloaded", ChatColor.GREEN + "Level successfully unloaded");
put("Message.InvalidVote", ChatColor.RED + "Invalid vote");
put("Message.ThankyouForYourVote", ChatColor.GREEN + "Thank you for your vote");
put("Message.YouCannotVoteAtThisTime", ChatColor.RED + "You cannot vote at this time");
put("Message.LevelLoadedSuccessfully", ChatColor.GREEN + "Level loaded successfully");
put("Message.LevelIsAlreadyTheCurrentLevel", ChatColor.RED + "Level %s is already the current level");
put("Message.UnableToSaveLevel", ChatColor.RED + "Unable to save level, try again later");
put("Message.UnableToCreatePackage", ChatColor.RED + "Unable to create package, try again later");
put("Message.UnableToLoadLevel", ChatColor.RED + "Unable to load level");
put("Message.NoLevelLoaded", ChatColor.YELLOW + "No level loaded, type '/tribu load' to load one,");
put("Message.NoLevelLoaded2", ChatColor.YELLOW + "or '/tribu create' to create a new one,");
put("Message.TeleportedToDeathSpawn", ChatColor.GREEN + "Teleported to death spawn");
put("Message.DeathSpawnSet", ChatColor.GREEN + "Death spawn set.");
put("Message.TeleportedToInitialSpawn", ChatColor.GREEN + "Teleported to initial spawn");
put("Message.InitialSpawnSet", ChatColor.GREEN + "Initial spawn set.");
put("Message.UnableToSaveCurrentLevel", ChatColor.RED + "Unable to save current level.");
put("Message.LevelSaveSuccessful", ChatColor.GREEN + "Level save successful");
put("Message.LevelCreated", ChatColor.GREEN + "Level " + ChatColor.LIGHT_PURPLE + "%s" + ChatColor.GREEN + " created");
put("Message.UnableToDeleteLevel", ChatColor.RED + "Unable to delete current level.");
put("Message.PackageCreated", ChatColor.RED + "Package created successfully");
put("Message.LevelDeleted", ChatColor.GREEN + "Level deleted successfully.");
put("Message.Levels", ChatColor.GREEN + "Levels: %s");
put("Message.UnknownLevel", ChatColor.RED + "Unknown level: %s");
put("Message.MaybeNotSaved", ChatColor.YELLOW + "Maybe you have not saved this level or you have not set anything in.");
put("Message.ZombieModeEnabled", ChatColor.GREEN + "Zombie Mode enabled!");
put("Message.ZombieModeDisabled", ChatColor.RED + "Zombie Mode disabled!");
put("Message.SpawnpointAdded", ChatColor.GREEN + "Spawnpoint added");
put("Message.SpawnpointRemoved", ChatColor.GREEN + "Spawnpoint removed");
put("Message.InvalidSpawnName", ChatColor.RED + "Invalid spawn name");
put("Message.TeleportedToZombieSpawn", ChatColor.GREEN + "Teleported to zombie spawn " + ChatColor.LIGHT_PURPLE + "%s");
put("Message.UnableToGiveYouThatItem", ChatColor.RED + "Unable to give you that item...");
put("Message.PurchaseSuccessfulMoney", ChatColor.GREEN + "Purchase successful." + ChatColor.DARK_GRAY + " Money: " + ChatColor.GRAY
+ "%s $");
put("Message.YouDontHaveEnoughMoney", ChatColor.DARK_RED + "You don't have enough money for that!");
put("Message.MoneyPoints", ChatColor.DARK_GRAY + "Money: " + ChatColor.GRAY + "%s $" + ChatColor.DARK_GRAY + " Points: "
+ ChatColor.GRAY + "%s");
put("Message.GameInProgress", ChatColor.YELLOW + "Game in progress, you will spawn next round");
put("Message.ZombieHavePrevailed", ChatColor.DARK_RED + "Zombies have prevailed!");
put("Message.YouHaveReachedWave", ChatColor.RED + "You have reached wave " + ChatColor.YELLOW + "%s");
put("Message.YouJoined", ChatColor.GOLD + "You joined the human strengths against zombies.");
put("Message.YouLeft", ChatColor.GOLD + "You left the fight against zombies.");
put("Message.TribuSignAdded", ChatColor.GREEN + "Tribu sign successfully added.");
put("Message.TribuSignRemoved", ChatColor.GREEN + "Tribu sign successfully removed.");
put("Message.ProtectedBlock", ChatColor.YELLOW + "Sorry, this sign is protected, please ask an operator to remove it.");
put("Message.CannotPlaceASpecialSign", ChatColor.YELLOW + "Sorry, you cannot place a special signs, please ask an operator to do it.");
put("Message.ConfigFileReloaded", ChatColor.GREEN + "Config files have been reloaded.");
put("Message.PckNotFound", ChatColor.YELLOW + "Package %s not found in this level.");
put("Message.PckNeedName", ChatColor.YELLOW + "You have to specify the name of the package.");
put("Message.PckNeedOpen", ChatColor.YELLOW + "You have to open or create a package first.");
put("Message.PckNeedId", ChatColor.YELLOW + "You have to specify the at least the id.");
put("Message.PckNeedIdSubid", ChatColor.YELLOW + "You have to specify the id and subid.");
put("Message.PckCreated", ChatColor.GREEN + "The package %s has been created.");
put("Message.PckOpened", ChatColor.GREEN + "The package %s has been opened.");
put("Message.PckSaved", ChatColor.GREEN + "The package %s has been saved and closed.");
put("Message.PckRemoved", ChatColor.GREEN + "The package has been removed.");
put("Message.PckItemDeleted", ChatColor.GREEN + "The item has been deleted.");
put("Message.PckItemAdded", ChatColor.GREEN + "The item \"%s\" has been successfully added.");
put("Message.PckItemAddFailed", ChatColor.YELLOW + "The item \"%s\" could not be added.");
put("Message.PckList", ChatColor.GREEN + "Packages of this level : %s.");
put("Message.PckNoneOpened", ChatColor.YELLOW + "none opened/specified");
put("Message.LevelNotReady", ChatColor.YELLOW
+ "The level is not ready to run. Make sure you create/load a level and that it contains zombie spawns.");
put("Message.Deny", ChatColor.RED + "A zombie denied your action, sorry.");
put("Message.AlreadyIn", ChatColor.YELLOW + "You are already in.");
put("Broadcast.MapChosen", ChatColor.DARK_BLUE + "Level " + ChatColor.LIGHT_PURPLE + "%s" + ChatColor.DARK_BLUE + " has been chosen");
put("Broadcast.MapVoteStarting", ChatColor.DARK_AQUA + "Level vote starting,");
put("Broadcast.Type", ChatColor.DARK_AQUA + "Type ");
put("Broadcast.SlashVoteForMap", ChatColor.GOLD + "'/tribu vote %s'" + ChatColor.DARK_AQUA + " for map " + ChatColor.BLUE + "%s");
put("Broadcast.VoteClosingInSeconds", ChatColor.DARK_AQUA + "Vote closing in %s seconds");
put("Broadcast.StartingWave", ChatColor.GRAY + "Starting wave " + ChatColor.DARK_RED + "%s" + ChatColor.GRAY + ", "
+ ChatColor.DARK_RED + "%s" + ChatColor.GRAY + " Zombies @ " + ChatColor.DARK_RED + "%s" + ChatColor.GRAY + " health");
put("Broadcast.Wave", ChatColor.DARK_GRAY + "Wave " + ChatColor.DARK_RED + "%s" + ChatColor.DARK_GRAY + " starting in "
+ ChatColor.DARK_RED + "%s" + ChatColor.DARK_GRAY + " seconds.");
put("Broadcast.WaveComplete", ChatColor.GOLD + "Wave Complete");
put("Info.LevelFound", ChatColor.YELLOW + "%s levels found");
put("Info.Enable", ChatColor.WHITE + "Starting " + ChatColor.DARK_RED + "Tribu" + ChatColor.WHITE
+ " by Graindcafe, original author : samp20");
put("Info.Disable", ChatColor.YELLOW + "Stopping Tribu");
put("Info.LevelSaved", ChatColor.GREEN + "Level saved");
put("Info.ChosenLanguage", ChatColor.YELLOW + "Chosen language : %s (default). Provided by : %s.");
put("Info.LevelFolderDoesntExist", ChatColor.RED + "Level folder doesn't exist");
put("Warning.AllSpawnsCurrentlyUnloaded", ChatColor.YELLOW + "All zombies spawns are currently unloaded.");
put("Warning.UnableToSaveLevel", ChatColor.RED + "Unable to save level");
put("Warning.ThisCommandCannotBeUsedFromTheConsole", ChatColor.RED + "This command cannot be used from the console");
put("Warning.IOErrorOnFileDelete", ChatColor.RED + "IO error on file delete");
put("Warning.LanguageFileOutdated", ChatColor.RED + "Your current language file is outdated");
put("Warning.LanguageFileMissing", ChatColor.RED + "The chosen language file is missing");
put("Warning.UnableToAddSign", ChatColor.RED + "Unable to add sign, maybe you've changed your locales, or signs' tags.");
put("Warning.UnknownFocus",
ChatColor.RED + "The string given for the configuration Zombies.Focus is not recognized : %s . It could be 'None','Nearest','Random','DeathSpawn','InitialSpawn'.");
put("Warning.NoSpawns", ChatColor.RED + "You didn't set any zombie spawn.");
put("Severe.TribuCantMkdir",
ChatColor.RED + "Tribu can't make dirs so it cannot create the level directory, you would not be able to save levels ! You can't use Tribu !");
put("Severe.WorldInvalidFileVersion", ChatColor.RED + "World invalid file version");
put("Severe.WorldDoesntExist", ChatColor.RED + "World doesn't exist");
put("Severe.ErrorDuringLevelLoading", ChatColor.RED + "Error during level loading : %s");
put("Severe.ErrorDuringLevelSaving", ChatColor.RED + "Error during level saving : %s");
put("Severe.PlayerHaveNotRetrivedHisItems", ChatColor.RED + "The player %s have not retrieved his items, they will be deleted ! Items list : %s");
put("Severe.Exception", ChatColor.RED + "Exception: %s");
put("Severe.PlayerDidntGetInvBack", ChatColor.RED + "didn't get his inventory back because he was returned null. (Maybe he was not in server?)");
put("Message.PlayerDied",ChatColor.RED + "You are dead.");
put("Message.PlayerRevive",ChatColor.GREEN + "You have been revived.");
put("Message.PlayerWrongWorld","You are in the incorrect world. Please join world " + ChatColor.LIGHT_PURPLE + config.PluginModeWorldExclusiveWorldName + ChatColor.RED + " to join the game.");
}
});
language = Language.init(log, config.PluginModeLanguage);
Constants.MessageMoneyPoints = language.get("Message.MoneyPoints");
Constants.MessageZombieSpawnList = language.get("Message.ZombieSpawnList");
}
public boolean isAlive(Player player) {
return players.get(player).isalive();
}
public TribuConfig config()
{
return config;
}
public boolean isPlaying(Player p) {
return players.containsKey(p);
}
public boolean isRunning() {
return isRunning;
}
public void keepTempInv(Player p, ItemStack[] items) {
// log.info("Keep " + items.length + " items for " +
// p.getDisplayName());
tempInventories.put(p, new TribuTempInventory(p, items));
}
public void LogInfo(String message) {
log.info("[Tribu] " + message);
}
public void LogSevere(String message) {
log.severe("[Tribu] " + message);
}
public void LogWarning(String message) {
log.warning("[Tribu] " + message);
}
@Override
public void onDisable() {
for(String player:TribuInventory.inventories.keySet()) //this will only get players if the players inventory has been set. (for world Exclusive)
{
Player theplayer = Bukkit.getPlayer(player);
if(theplayer != null)
{
inventorySave.restoreInventory(theplayer);
} else
{
log.severe(player + language.get("Severe.PlayerDidntGetInvBack"));
}
}
if(this.isRunning)
{
blockTrace.reverse();
}
players.clear();
sortedStats.clear();
stopRunning();
LogInfo(language.get("Info.Disable"));
}
@Override
public void onEnable() {
log = Logger.getLogger("Minecraft");
rnd = new Random();
Constants.rebuildPath(getDataFolder().getPath() + File.separatorChar);
this.config=new TribuConfig();
initLanguage();
try {
@SuppressWarnings("rawtypes")
Class[] args = { Class.class, String.class, Integer.TYPE, Integer.TYPE, Integer.TYPE };
Method a = EntityTypes.class.getDeclaredMethod("a", args);
a.setAccessible(true);
a.invoke(a, EntityTribuZombie.class, "Zombie", 54, '\uafaf', 7969893);
a.invoke(a, EntityZombie.class, "Zombie", 54, '\uafaf', 7969893);
} catch (Exception e) {
e.printStackTrace();
setEnabled(false);
return;
}
isRunning = false;
aliveCount = 0;
level = null;
blockTrace = new BlockTrace();
tempInventories = new HashMap<Player, TribuTempInventory>();
inventorySave = new TribuInventory();
players = new HashMap<Player, PlayerStats>();
spawnPoint=new HashMap<Player,Location>();
sortedStats = new LinkedList<PlayerStats>();
levelLoader = new LevelFileLoader(this);
levelSelector = new LevelSelector(this);
spawner = new TribuSpawner(this);
spawnTimer = new SpawnTimer(this);
waveStarter = new WaveStarter(this);
// Create listeners
playerListener = new TribuPlayerListener(this);
entityListener = new TribuEntityListener(this);
blockListener = new TribuBlockListener(this);
worldListener = new TribuWorldListener(this);
this.initPluginMode();
this.loadCustomConf();
getServer().getPluginManager().registerEvents(playerListener, this);
getServer().getPluginManager().registerEvents(entityListener, this);
getServer().getPluginManager().registerEvents(blockListener, this);
getServer().getPluginManager().registerEvents(worldListener, this);
getCommand("dspawn").setExecutor(new CmdDspawn(this));
getCommand("zspawn").setExecutor(new CmdZspawn(this));
getCommand("ispawn").setExecutor(new CmdIspawn(this));
getCommand("tribu").setExecutor(new CmdTribu(this));
LogInfo(language.get("Info.Enable"));
}
public void resetedSpawnAdd(Player p,Location point)
{
spawnPoint.put(p, point);
}
public void removePlayer(Player player) {
if (player != null && players.containsKey(player)) {
if (isAlive(player)) {
aliveCount--;
}
sortedStats.remove(players.get(player));
inventorySave.restoreInventory(player);
players.remove(player);
if(player.isOnline() && spawnPoint.containsKey(player))
{
player.setBedSpawnLocation(spawnPoint.remove(player));
}
// check alive AFTER player remove
checkAliveCount();
if (!player.isDead())
restoreInventory(player);
}
}
public void restoreInventory(Player p) {
// log.info("Restore items for " + p.getDisplayName());
inventorySave.restoreInventory(p);
}
public void restoreTempInv(Player p) {
// log.info("Restore items for " + p.getDisplayName());
if (tempInventories.containsKey(p))
tempInventories.remove(p).restore();
}
public void revivePlayer(Player player) {
if(spawnPoint.containsKey(player))
{
player.setBedSpawnLocation(spawnPoint.remove(player));
}
players.get(player).revive();
if (config.WaveStartHealPlayers)
player.setHealth(20);
restoreTempInv(player);
aliveCount++;
}
public void revivePlayers(boolean teleportAll) {
aliveCount = 0;
for (Player player : players.keySet()) {
revivePlayer(player);
if (isRunning && level != null && (teleportAll || !isAlive(player))) {
player.teleport(level.getInitialSpawn());
}
}
}
public void setDead(Player player) {
if (players.containsKey(player)) {
if (isAlive(player)) {
aliveCount--;
PlayerStats p = players.get(player);
p.resetMoney();
p.subtractmoney(config.StatsOnPlayerDeathMoney);
p.subtractPoints(config.StatsOnPlayerDeathPoints);
p.msgStats();
messagePlayers(ChatColor.LIGHT_PURPLE + player.getName() + ChatColor.RED + " has died.");
/*
* Set<Entry<Player, PlayerStats>> stats = players.entrySet();
* for (Entry<Player, PlayerStats> stat : stats) {
* stat.getValue().subtractPoints(50);
* stat.getValue().resetMoney(); stat.getValue().msgStats(); }
*/
}
deadPeople.put(player,null);
players.get(player).kill();
if (getLevel() != null && isRunning) {
checkAliveCount();
}
}
}
public void setLevel(TribuLevel level) {
this.level = level;
this.loadCustomConf();
}
public boolean startRunning() {
if (!isRunning && getLevel() != null) {
if (players.isEmpty()) {
setWaitingForPlayers(true);
} else {
// Before (next instruction) it will saves current default
// packages to the level, saving theses packages with the level
this.addDefaultPackages();
// Make sure no data is lost if server decides to die
// during a game and player forgot to /level save
if (!getLevelLoader().saveLevel(getLevel())) {
LogWarning(language.get("Warning.UnableToSaveLevel"));
} else {
LogInfo(language.get("Info.LevelSaved"));
}
if (this.getLevel().getSpawns().isEmpty()) {
LogWarning(language.get("Warning.NoSpawns"));
return false;
}
if (!config.PluginModeAutoStart)
setWaitingForPlayers(false);
isRunning = true;
if (config.PluginModeServerExclusive || config.PluginModeWorldExclusive)
for (LivingEntity e : level.getInitialSpawn().getWorld().getLivingEntities()) {
if (!(e instanceof Player) && !(e instanceof Wolf) && !(e instanceof Villager))
e.damage(Integer.MAX_VALUE);
}
else
for (LivingEntity e : level.getInitialSpawn().getWorld().getLivingEntities()) {
if ((e.getLocation().distance(level.getInitialSpawn())) < config.LevelClearZone
&& !(e instanceof Player) && !(e instanceof Wolf) && !(e instanceof Villager))
e.damage(Integer.MAX_VALUE);
}
getLevel().initSigns();
this.sortedStats.clear();
for (Player save : players.keySet()) //makes sure all inventorys have been saved
{
inventorySave.addInventory(save);
save.getInventory().clear();
save.getInventory().setArmorContents(null);
}
for (PlayerStats stat : players.values()) {
stat.resetPoints();
stat.resetMoney();
this.sortedStats.add(stat);
}
getWaveStarter().resetWave();
revivePlayers(true);
getWaveStarter().scheduleWave(Constants.TicksBySecond * config.WaveStartDelay);
}
}
return true;
}
public void stopRunning() {
if (isRunning) {
isRunning = false;
getSpawnTimer().Stop();
getWaveStarter().cancelWave();
getSpawner().clearZombies();
getLevelSelector().cancelVote();
blockTrace.reverse();
deadPeople.clear();
TollSign.getAllowedPlayer().clear();
for(String player:TribuInventory.inventories.keySet()) //this will only get players if the players inventory has been set. (for world Exclusive or server)
{
Player theplayer = Bukkit.getPlayer(player);
if(theplayer != null)
{
inventorySave.restoreInventory(theplayer);
} else
{
log.severe("[Tribu] " + player + " didn't get his inventory back because player was returned null. (Maybe he was not in server?)");
}
}
for(Player fd:Bukkit.getServer().getWorld(config.PluginModeWorldExclusiveWorldName).getPlayers()) //teleports all players to spawn when game ends
{
fd.teleport(level.getInitialSpawn());
}
if (!config.PluginModeServerExclusive || !config.PluginModeWorldExclusive) {
players.clear();
}
}
}
//to avoid warnings
public boolean isWaitingForPlayers() {
return waitingForPlayers;
}
//to avoid warnings
public void setWaitingForPlayers(boolean waitingForPlayers) {
this.waitingForPlayers = waitingForPlayers;
}
public boolean isCorrectWorld(World World)
{
if(config.PluginModeServerExclusive)
{
return true; //continue (ignore world)
} else
if(config.PluginModeWorldExclusive)
{
String world = World.toString();
String[] ar = world.split("=");
if(!ar[1].replace("}", "").equalsIgnoreCase(config.PluginModeWorldExclusiveWorldName))
{
return false; //your in wrong world
}
return true; //your in correct world
} else
{
LogSevere("We have a big problem in isCorrectWorld()");
return true; //continue (ignore world)
}
}
/*
* public static void messagePlayer(CommandSender sender, String message) {
if(message.isEmpty())
return;
if (sender == null)
Logger.getLogger("Minecraft").info(ChatColor.stripColor(message));
else
sender.sendMessage(message);
}
|
diff --git a/src/at/fundev/oobe/TemplatablePackager.java b/src/at/fundev/oobe/TemplatablePackager.java
index 21bfb6d..65e9aec 100644
--- a/src/at/fundev/oobe/TemplatablePackager.java
+++ b/src/at/fundev/oobe/TemplatablePackager.java
@@ -1,237 +1,237 @@
package at.fundev.oobe;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import at.fundev.oobe.model.Metadata;
import at.fundev.oobe.model.PostEntry;
import at.fundev.oobe.utils.EncodingDetector;
public class TemplatablePackager extends Task implements Constants {
private String input;
private String template;
private String outputDir;
private String metaDataFile = META_DATA_JSON_FILE;
private <T> void process() throws FileNotFoundException, IOException {
if(getInput() == null || getTemplate() == null) {
return;
}
Metadata md = Metadata.fromFile(metaDataFile);
File inputFile = new File(getInput());
if(inputFile.isDirectory()) {
File[] inputFiles = inputFile.listFiles(new FileFilter() {
@Override
public boolean accept(File file) {
return file.getName().endsWith(".html");
}
});
for(File htmlFile : inputFiles) {
processInputFile(htmlFile, md);
}
} else {
processInputFile(inputFile, md);
}
}
private void processInputFile(File inputFile, Metadata md) throws IOException {
File templateFile = new File(getTemplate());
if(!inputFile.exists()) {
throw new FileNotFoundException(String.format("The input file %s doesn't exist.", inputFile.getName()));
}
if(!templateFile.exists()) {
throw new FileNotFoundException(String.format("The template file %s doesn't exist.", templateFile.getName()));
}
String charset = EncodingDetector.of(inputFile).getEncoding();
charset = charset != null ? charset : EncodingDetector.DEFAULT_ENCODING; // default to UTF-8 and hope for the best
Document inputDoc = Jsoup.parse(inputFile, charset);
Map<String, String> articleData = new HashMap<String, String>();
Element contentElem = inputDoc.select("body").first();
System.out.println(contentElem.text());
for(Element link : contentElem.select("img")) {
link.attr("src", "img/" + link.attr("src"));
}
Element headerElem = contentElem.select(".maketitle").first();
Element titleElem = headerElem.select(".titleHead").first();
+ Element authorElem = headerElem.select(".author").first();
- Element authorElem = headerElem.select(".author.cmr-12").first();
Element dateElem = headerElem.select(".date").first();
headerElem.remove();
addIfNotNull(titleElem, TITLE_NAME, articleData);
addIfNotNull(authorElem, AUTHOR_NAME, articleData);
addIfNotNull(dateElem, DATE_NAME, articleData);
fillOutTemplate(contentElem, articleData, inputFile, md);
}
private String sanitizeSpecialChars(String input) {
return (input == null) ? null : input.replace("ä", "ä")
.replace("Ä", "Ä")
.replace("ö", "ö")
.replace("Ö", "Ö")
.replace("ü", "ü")
.replace("Ü", "Ü")
.replace("ß", "ß");
}
private void addMetaData(Map<String, String> articleData, Metadata data, String path) throws IOException {
PostEntry entry = new PostEntry();
entry.setName(articleData.get(TITLE_NAME));
entry.setDate(articleData.get(DATE_NAME));
entry.setAuthor(articleData.get(AUTHOR_NAME));
entry.setFilePath(path);
int index = data.getEntries() != null ? data.getEntries().indexOf(entry) : -1;
if(index != -1) {
data.getEntries().set(index, entry);
} else {
data.getEntries().add(entry);
}
data.persist();
}
private void addIfNotNull(Element value, String key, Map<String, String> parsedItems) {
if(value == null) {
return;
}
parsedItems.put(key, value.text());
}
private void fillOutTemplate(Element content, Map<String, String> articleData, File inputFile, Metadata md) throws IOException {
String fileName = inputFile.getName();
File outputFile = new File(getOutputDir(), fileName);
addMetaData(articleData, md, outputFile.getAbsolutePath());
if(content != null) {
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(outputFile), EncodingDetector.DEFAULT_ENCODING));
String contentHtml = getTemplateText();
for(String key : articleData.keySet()) {
contentHtml = contentHtml.replace(key, articleData.get(key));
}
contentHtml = contentHtml.replace(CONTENT_NAME, sanitizeSpecialChars(content.html()));
writer.write(contentHtml);
writer.flush();
writer.close();
System.out.println("Written to output File: " + outputFile);
} else {
throw new IOException("No content element found in template file.");
}
}
private String getTemplateText() throws IOException {
File templateFile = new File(template);
String charset = EncodingDetector.of(templateFile).getEncoding();
charset = (charset == null) ? EncodingDetector.DEFAULT_ENCODING : charset;
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(templateFile), charset));
StringBuffer buf = new StringBuffer();
String cur = null;
while((cur = reader.readLine()) != null) {
buf.append(cur);
}
reader.close();
return buf.toString();
}
public static void main(String[] args) {
if(args.length < 3) {
System.err.println("Usage: TemplatablePackager <input> <template> <outputDir>");
System.exit(1);
}
String input = args[0];
String template = args[1];
String outputDir = args[2];
TemplatablePackager templatePackager = new TemplatablePackager();
templatePackager.setInput(input);
templatePackager.setTemplate(template);
templatePackager.setOutputDir(outputDir);
try {
templatePackager.process();
} catch (IOException e) {
System.err.println(e.getMessage());
System.exit(1);
}
}
@Override
public void execute() throws BuildException {
try {
process();
} catch(IOException e) {
throw new BuildException(e);
}
}
public String getInput() {
return input;
}
public void setInput(String input) {
this.input = input;
}
public String getTemplate() {
return template;
}
public void setTemplate(String template) {
this.template = template;
}
public String getOutputDir() {
return outputDir;
}
public void setOutputDir(String outputDir) {
this.outputDir = outputDir;
}
}
| false | true | private void processInputFile(File inputFile, Metadata md) throws IOException {
File templateFile = new File(getTemplate());
if(!inputFile.exists()) {
throw new FileNotFoundException(String.format("The input file %s doesn't exist.", inputFile.getName()));
}
if(!templateFile.exists()) {
throw new FileNotFoundException(String.format("The template file %s doesn't exist.", templateFile.getName()));
}
String charset = EncodingDetector.of(inputFile).getEncoding();
charset = charset != null ? charset : EncodingDetector.DEFAULT_ENCODING; // default to UTF-8 and hope for the best
Document inputDoc = Jsoup.parse(inputFile, charset);
Map<String, String> articleData = new HashMap<String, String>();
Element contentElem = inputDoc.select("body").first();
System.out.println(contentElem.text());
for(Element link : contentElem.select("img")) {
link.attr("src", "img/" + link.attr("src"));
}
Element headerElem = contentElem.select(".maketitle").first();
Element titleElem = headerElem.select(".titleHead").first();
Element authorElem = headerElem.select(".author.cmr-12").first();
Element dateElem = headerElem.select(".date").first();
headerElem.remove();
addIfNotNull(titleElem, TITLE_NAME, articleData);
addIfNotNull(authorElem, AUTHOR_NAME, articleData);
addIfNotNull(dateElem, DATE_NAME, articleData);
fillOutTemplate(contentElem, articleData, inputFile, md);
}
| private void processInputFile(File inputFile, Metadata md) throws IOException {
File templateFile = new File(getTemplate());
if(!inputFile.exists()) {
throw new FileNotFoundException(String.format("The input file %s doesn't exist.", inputFile.getName()));
}
if(!templateFile.exists()) {
throw new FileNotFoundException(String.format("The template file %s doesn't exist.", templateFile.getName()));
}
String charset = EncodingDetector.of(inputFile).getEncoding();
charset = charset != null ? charset : EncodingDetector.DEFAULT_ENCODING; // default to UTF-8 and hope for the best
Document inputDoc = Jsoup.parse(inputFile, charset);
Map<String, String> articleData = new HashMap<String, String>();
Element contentElem = inputDoc.select("body").first();
System.out.println(contentElem.text());
for(Element link : contentElem.select("img")) {
link.attr("src", "img/" + link.attr("src"));
}
Element headerElem = contentElem.select(".maketitle").first();
Element titleElem = headerElem.select(".titleHead").first();
Element authorElem = headerElem.select(".author").first();
Element dateElem = headerElem.select(".date").first();
headerElem.remove();
addIfNotNull(titleElem, TITLE_NAME, articleData);
addIfNotNull(authorElem, AUTHOR_NAME, articleData);
addIfNotNull(dateElem, DATE_NAME, articleData);
fillOutTemplate(contentElem, articleData, inputFile, md);
}
|
diff --git a/contrib/MFJ.java b/contrib/MFJ.java
index c35e1e3..40395c0 100644
--- a/contrib/MFJ.java
+++ b/contrib/MFJ.java
@@ -1,99 +1,99 @@
import org.uwcs.choob.*;
import org.uwcs.choob.modules.*;
import org.uwcs.choob.support.*;
import org.uwcs.choob.support.events.*;
//Calendar support
import java.util.GregorianCalendar;
/**
* Random command implementations from myself. Enjoy.
*
* @author MFJ
*/
public class MFJ
{
/**
* Implements JB's !dance command, with different outputs
*/
public void commandDance(Message con, Modules mods, IRCInterface irc)
{
int type = (int) (10 * Math.random());
String dance;
switch (type)
{
case 0: dance = " waltzes to Beautiful Ohio!"; break;
case 1: dance = " tangos to Amigo Cavano!"; break;
case 2: dance = " dances the Samba away!"; break;
case 3: dance = " swings gracefully to Billie Holiday."; break;
case 4: dance = " jives to the Summertime blues."; break;
case 5: dance = " does the Cha Cha!"; break;
case 6: dance = " dances the Flamenco all night!"; break;
case 7: dance = " steps into a Vienese Waltz."; break;
case 8: dance = " gets on down to The Monkees."; break;
case 9: dance = " BADGER BADGER BADGER .... MUSHROOM MUSHROOM!";break;
default: dance = " carts them off to the police station."; break;
}
irc.sendContextAction( con, "grabs " + con.getNick() + " and" + dance );
}
/**
* Implements JB's !colour command
*/
public void commandColour(Message con, Modules mods, IRCInterface irc)
{
GregorianCalendar cal = new GregorianCalendar();
int type = cal.get(cal.DAY_OF_MONTH);
String colour;
switch (type)
{
case 1: colour = "Slate Blue"; break;
case 2: colour = "Indian Red"; break;
case 3: colour = "Pale Turquoise"; break;
case 4: colour = "Cornsilk"; break;
case 5: colour = "Spring Green"; break;
case 6: colour = "Burly Wood"; break;
case 7: colour = "Lime Green"; break;
case 8: colour = "Linen"; break;
case 9: colour = "Magenta"; break;
case 10: colour = "Maroon"; break;
case 11: colour = "Aqua Marine"; break;
case 12: colour = "Salmon"; break;
case 13: colour = "Saddle Brown"; break;
case 14: colour = "Midnight Blue"; break;
case 15: colour = "Feldspar"; break;
case 16: colour = "Misty Rose"; break;
case 17: colour = "Moccasin"; break;
case 18: colour = "Navajo White"; break;
case 19: colour = "Navy"; break;
case 20: colour = "Old Lace"; break;
case 21: colour = "Olive"; break;
case 22: colour = "Golden Rod"; break;
case 23: colour = "Orange"; break;
case 24: colour = "White Smoke"; break;
case 25: colour = "Orchid"; break;
case 26: colour = "Tomato"; break;
case 27: colour = "Snow"; break;
case 28: colour = "lemon Chiffon"; break;
case 29: colour = "Pale Violet Red";break;
case 30: colour = "Mint Cream"; break;
case 31: colour = "PeachPuff"; break;
default: colour = "Black"; break;
}
- irc.sendContextAction( con, "Today's colour is " + colour + ".");
+ irc.sendContextMessage( con, "Today's colour is " + colour + ".");
}
/**
* Americans--
*/
public void commandColor(Message con, Modules mods, IRCInterface irc)
{
commandColour(con, mods, irc);
}
}
| true | true | public void commandColour(Message con, Modules mods, IRCInterface irc)
{
GregorianCalendar cal = new GregorianCalendar();
int type = cal.get(cal.DAY_OF_MONTH);
String colour;
switch (type)
{
case 1: colour = "Slate Blue"; break;
case 2: colour = "Indian Red"; break;
case 3: colour = "Pale Turquoise"; break;
case 4: colour = "Cornsilk"; break;
case 5: colour = "Spring Green"; break;
case 6: colour = "Burly Wood"; break;
case 7: colour = "Lime Green"; break;
case 8: colour = "Linen"; break;
case 9: colour = "Magenta"; break;
case 10: colour = "Maroon"; break;
case 11: colour = "Aqua Marine"; break;
case 12: colour = "Salmon"; break;
case 13: colour = "Saddle Brown"; break;
case 14: colour = "Midnight Blue"; break;
case 15: colour = "Feldspar"; break;
case 16: colour = "Misty Rose"; break;
case 17: colour = "Moccasin"; break;
case 18: colour = "Navajo White"; break;
case 19: colour = "Navy"; break;
case 20: colour = "Old Lace"; break;
case 21: colour = "Olive"; break;
case 22: colour = "Golden Rod"; break;
case 23: colour = "Orange"; break;
case 24: colour = "White Smoke"; break;
case 25: colour = "Orchid"; break;
case 26: colour = "Tomato"; break;
case 27: colour = "Snow"; break;
case 28: colour = "lemon Chiffon"; break;
case 29: colour = "Pale Violet Red";break;
case 30: colour = "Mint Cream"; break;
case 31: colour = "PeachPuff"; break;
default: colour = "Black"; break;
}
irc.sendContextAction( con, "Today's colour is " + colour + ".");
}
| public void commandColour(Message con, Modules mods, IRCInterface irc)
{
GregorianCalendar cal = new GregorianCalendar();
int type = cal.get(cal.DAY_OF_MONTH);
String colour;
switch (type)
{
case 1: colour = "Slate Blue"; break;
case 2: colour = "Indian Red"; break;
case 3: colour = "Pale Turquoise"; break;
case 4: colour = "Cornsilk"; break;
case 5: colour = "Spring Green"; break;
case 6: colour = "Burly Wood"; break;
case 7: colour = "Lime Green"; break;
case 8: colour = "Linen"; break;
case 9: colour = "Magenta"; break;
case 10: colour = "Maroon"; break;
case 11: colour = "Aqua Marine"; break;
case 12: colour = "Salmon"; break;
case 13: colour = "Saddle Brown"; break;
case 14: colour = "Midnight Blue"; break;
case 15: colour = "Feldspar"; break;
case 16: colour = "Misty Rose"; break;
case 17: colour = "Moccasin"; break;
case 18: colour = "Navajo White"; break;
case 19: colour = "Navy"; break;
case 20: colour = "Old Lace"; break;
case 21: colour = "Olive"; break;
case 22: colour = "Golden Rod"; break;
case 23: colour = "Orange"; break;
case 24: colour = "White Smoke"; break;
case 25: colour = "Orchid"; break;
case 26: colour = "Tomato"; break;
case 27: colour = "Snow"; break;
case 28: colour = "lemon Chiffon"; break;
case 29: colour = "Pale Violet Red";break;
case 30: colour = "Mint Cream"; break;
case 31: colour = "PeachPuff"; break;
default: colour = "Black"; break;
}
irc.sendContextMessage( con, "Today's colour is " + colour + ".");
}
|
diff --git a/vtm/src/org/oscim/renderer/BufferObject.java b/vtm/src/org/oscim/renderer/BufferObject.java
index 38361433..6c8a6838 100644
--- a/vtm/src/org/oscim/renderer/BufferObject.java
+++ b/vtm/src/org/oscim/renderer/BufferObject.java
@@ -1,214 +1,214 @@
/*
* Copyright 2012 Hannes Janetzek
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General 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 License for more details.
*
* You should have received a copy of the GNU Lesser General License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.oscim.renderer;
import java.nio.Buffer;
import org.oscim.backend.GL20;
import org.oscim.backend.Log;
public final class BufferObject {
private final static String TAG = BufferObject.class.getName();
private static GL20 GL;
private static final int MB = 1024 * 1024;
private static final int LIMIT_BUFFERS = 16 * MB;
// GL identifier
public int id;
// allocated bytes
public int size;
BufferObject next;
int target;
BufferObject(int target, int id) {
this.id = id;
this.target = target;
}
public void loadBufferData(Buffer buf, int newSize) {
boolean clear = false;
if (buf.position() != 0) {
Log.d(TAG, "rewind your buffer: " + buf.position());
}
GL.glBindBuffer(target, id);
// reuse memory allocated for vbo when possible and allocated
// memory is less then four times the new data
if (!clear && (size > newSize) && (size < newSize * 4)) {
GL.glBufferSubData(target, 0, newSize, buf);
} else {
mBufferMemoryUsage += newSize - size;
size = newSize;
GL.glBufferData(target, size, buf, GL20.GL_DYNAMIC_DRAW);
}
}
public void bind() {
GL.glBindBuffer(target, id);
}
// ---------------------------- pool ----------------------------
// bytes currently loaded in VBOs
private static int mBufferMemoryUsage;
public static void checkBufferUsage(boolean force) {
// try to clear some unused vbo when exceding limit
if (mBufferMemoryUsage < LIMIT_BUFFERS)
return;
Log.d(TAG, "buffer object usage: "
+ mBufferMemoryUsage / MB
+ "MB, force: " + force);
mBufferMemoryUsage -= BufferObject.limitUsage(1024 * 1024);
Log.d(TAG, "now: " + mBufferMemoryUsage / MB + "MB");
}
private final static BufferObject pool[] = new BufferObject[2];
private final static int counter[] = new int[2];
public static synchronized BufferObject get(int target, int size) {
int t = (target == GL20.GL_ARRAY_BUFFER) ? 0 : 1;
if (pool[t] == null) {
if (counter[t] != 0)
Log.d(TAG, "BUG: missing BufferObjects: " + counter);
createBuffers(target, 10);
counter[t] += 10;
}
counter[t]--;
if (size != 0) {
// find an item that has bound more than 'size' bytes.
// this has the advantage that either memory can be reused or
// a large unused block will be replaced by a smaller one.
BufferObject prev = null;
for (BufferObject bo = pool[t]; bo != null; bo = bo.next) {
if (bo.size > size) {
if (prev == null)
pool[t] = bo.next;
else
prev.next = bo.next;
bo.next = null;
return bo;
}
prev = bo;
}
}
BufferObject bo = pool[t];
pool[t] = pool[t].next;
bo.next = null;
return bo;
}
public static synchronized void release(BufferObject bo) {
if (bo == null)
return;
// if (counter > 200) {
// Log.d(TAG, "should clear some buffers " + counter);
// }
int t = (bo.target == GL20.GL_ARRAY_BUFFER) ? 0 : 1;
bo.next = pool[t];
pool[t] = bo;
counter[t]++;
}
// Note: only call from GL-Thread
static synchronized int limitUsage(int reduce) {
int vboIds[] = new int[10];
int freed = 0;
for (int t = 0; t < 2; t++) {
int removed = 0;
BufferObject prev = pool[t];
if (prev == null) {
Log.d(TAG, "nothing to free");
- return 0;
+ continue;
}
for (BufferObject bo = pool[t].next; bo != null;) {
if (bo.size > 0) {
freed += bo.size;
bo.size = 0;
vboIds[removed++] = bo.id;
prev.next = bo.next;
bo = bo.next;
if (removed == 10 || reduce < freed)
break;
} else {
prev = bo;
bo = bo.next;
}
}
if (removed > 0) {
GLUtils.glDeleteBuffers(removed, vboIds);
counter[t] -= removed;
}
}
return freed;
}
static void createBuffers(int target, int num) {
int[] mVboIds = GLUtils.glGenBuffers(num);
int t = (target == GL20.GL_ARRAY_BUFFER) ? 0 : 1;
for (int i = 0; i < num; i++) {
BufferObject bo = new BufferObject(target, mVboIds[i]);
bo.next = pool[t];
pool[t] = bo;
}
}
static synchronized void clear() {
mBufferMemoryUsage = 0;
pool[0] = null;
pool[1] = null;
counter[0] = 0;
counter[1] = 0;
}
static synchronized void init(GL20 gl, int num) {
GL = gl;
createBuffers(GL20.GL_ARRAY_BUFFER, num);
counter[0] += num;
}
}
| true | true | static synchronized int limitUsage(int reduce) {
int vboIds[] = new int[10];
int freed = 0;
for (int t = 0; t < 2; t++) {
int removed = 0;
BufferObject prev = pool[t];
if (prev == null) {
Log.d(TAG, "nothing to free");
return 0;
}
for (BufferObject bo = pool[t].next; bo != null;) {
if (bo.size > 0) {
freed += bo.size;
bo.size = 0;
vboIds[removed++] = bo.id;
prev.next = bo.next;
bo = bo.next;
if (removed == 10 || reduce < freed)
break;
} else {
prev = bo;
bo = bo.next;
}
}
if (removed > 0) {
GLUtils.glDeleteBuffers(removed, vboIds);
counter[t] -= removed;
}
}
return freed;
}
| static synchronized int limitUsage(int reduce) {
int vboIds[] = new int[10];
int freed = 0;
for (int t = 0; t < 2; t++) {
int removed = 0;
BufferObject prev = pool[t];
if (prev == null) {
Log.d(TAG, "nothing to free");
continue;
}
for (BufferObject bo = pool[t].next; bo != null;) {
if (bo.size > 0) {
freed += bo.size;
bo.size = 0;
vboIds[removed++] = bo.id;
prev.next = bo.next;
bo = bo.next;
if (removed == 10 || reduce < freed)
break;
} else {
prev = bo;
bo = bo.next;
}
}
if (removed > 0) {
GLUtils.glDeleteBuffers(removed, vboIds);
counter[t] -= removed;
}
}
return freed;
}
|
diff --git a/fingerpaint/src/nl/tue/fingerpaint/client/storage/FileExporter.java b/fingerpaint/src/nl/tue/fingerpaint/client/storage/FileExporter.java
index 2fb0b52..163b011 100644
--- a/fingerpaint/src/nl/tue/fingerpaint/client/storage/FileExporter.java
+++ b/fingerpaint/src/nl/tue/fingerpaint/client/storage/FileExporter.java
@@ -1,57 +1,59 @@
package nl.tue.fingerpaint.client.storage;
import com.google.gwt.canvas.client.Canvas;
import com.google.gwt.dom.client.CanvasElement;
/**
* Utility class that can be used to export files.
*
* @author Group Fingerpaint
*/
public class FileExporter {
/**
* Exports the line chart that is currently shown on screen as an svg
* image. " xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\"" is
* automatically added to the resulting svg, so it should not already
* be present.
*
* @param svg SVG image as a string.
*/
public static void exportSvgImage(String svg) {
// Add tags to indicate that this should be an svg image
- svg = svg.substring(0, 4)
- + " xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\""
- + svg.substring(4, svg.length());
+ if (!svg.contains("xmlns")) {
+ svg = svg.substring(0, 4)
+ + " xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\""
+ + svg.substring(4, svg.length());
+ }
promptSvgDownload(svg);
}
/**
* Exports the canvas to a png image
*
* @param canvas Canvas to export
*/
public static void exportCanvasImage(Canvas canvas) {
promptCanvasDownload(canvas.getCanvasElement());
}
/**
* Saves a string representing an svg file to disk by showing a file download dialog.
* @param svg File to save, in string representation.
*/
private static native void promptSvgDownload(String svg) /*-{
var blob = new $wnd.Blob([svg], {type: "image/svg+xml;charset=utf-8"});
$wnd.saveAs(blob, "graph.svg");
}-*/;
private static native void promptCanvasDownload(CanvasElement element) /*-{
element.toBlob(function(blob) {
$wnd.saveAs(
blob
, "distribution.png"
);
}, "image/png");
}-*/;
}
| true | true | public static void exportSvgImage(String svg) {
// Add tags to indicate that this should be an svg image
svg = svg.substring(0, 4)
+ " xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\""
+ svg.substring(4, svg.length());
promptSvgDownload(svg);
}
| public static void exportSvgImage(String svg) {
// Add tags to indicate that this should be an svg image
if (!svg.contains("xmlns")) {
svg = svg.substring(0, 4)
+ " xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\""
+ svg.substring(4, svg.length());
}
promptSvgDownload(svg);
}
|
diff --git a/ini/trakem2/imaging/Registration.java b/ini/trakem2/imaging/Registration.java
index 0f372dc1..0b5d8550 100644
--- a/ini/trakem2/imaging/Registration.java
+++ b/ini/trakem2/imaging/Registration.java
@@ -1,1974 +1,1974 @@
/**
TrakEM2 plugin for ImageJ(C).
Copyright (C) 2005,2006 Albert Cardona and Rodney Douglas.
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 (http://www.gnu.org/licenses/gpl.txt)
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
You may contact Albert Cardona at acardona at ini.phys.ethz.ch
Institute of Neuroinformatics, University of Zurich / ETH, Switzerland.
**/
package ini.trakem2.imaging;
import static mpi.fruitfly.math.General.*;
import mpi.fruitfly.general.ImageArrayConverter;
import mpi.fruitfly.general.MultiThreading;
//////
import mpi.fruitfly.math.datastructures.FloatArray2D;
import mpi.fruitfly.registration.FloatArray2DSIFT;
import mpi.fruitfly.registration.Feature;
import mpi.fruitfly.registration.PointMatch;
/////
import mpi.fruitfly.registration.ImageFilter;
//////
import mpi.fruitfly.registration.Tile;
import mpi.fruitfly.registration.Model;
import mpi.fruitfly.registration.TModel2D;
import mpi.fruitfly.registration.TRModel2D;
//////
import mpi.fruitfly.analysis.FitLine;
/* // New package, with AffineModel2D
import mpicbg.imagefeatures.Feature;
import mpicbg.imagefeatures.FloatArray2DSIFT;
import mpicbg.imagefeatures.FloatArray2D;
import mpicbg.models.Tile;
import mpicbg.models.Model;
import mpicbg.models.AffineModel2D;
import mpicbg.models.RigidModel2D;
import mpicbg.models.TranslationModel2D;
*/
import ini.trakem2.Project;
import ini.trakem2.display.*;
import ini.trakem2.utils.*;
import ini.trakem2.persistence.Loader;
import ini.trakem2.ControlWindow;
import ini.trakem2.imaging.StitchingTEM;
import ij.ImagePlus;
import ij.process.*;
import ij.gui.GenericDialog;
import ij.gui.Roi;
import java.awt.Point;
import java.awt.geom.Point2D;
import java.awt.Rectangle;
import java.util.*;
import java.awt.geom.AffineTransform;
import java.io.File;
import java.io.Serializable;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Accessor methods to Stephan Preibisch's FFT-based registration,
* and to Stephan Saalfeld's SIFT-based registration.
* <pre>
Preibisch's registration:
- returns angles between 0 and 180, perfectly reciprocal (img1 to img2 equals img2 to img1)
- is non-reciprocal (but almos) for translations (must choose between best)
- will only work reliably if there is at least 50% overlap between any two images to register
SIFT consumes plenty of memory:
- in extracting features:
- ImageArrayConverter.ImageToFloatArray2D:
- makes a new FloatProcessor (so the original pointers can be set to null)
- makes a new FloatArray2D from the FloatProcessor
- FloatArray2DSIFT:
- makes a new FloatArray2DScaleOctaveDoGDetector
- makes a new float[] for the descriptorMask
- FloatArray2DSIFT.init:
- makes a new FloatArray2DScaleOctave
- makes one new ImageFilter.createGaussianKernel1D for each step
- makes one new FloatArray2DScaleOctave for each octave
- ImageFilter.computeGaussianFastMirror: duplicates the FloatArray2D
In all, the above relates to the input image width and height as:
area = width * height
size = area * sizeof(float) * 2
plus a factorial factor for the octaves of aprox 1.5,
plus another 1.5 for all the small arrays created on the meanwhile:
size = area * 8 * 2 * 3 = area * 48 (aprox.)
</pre>
* */
public class Registration {
static public final int GLOBAL_MINIMIZATION = 0;
static public final int LAYER_SIFT = 1;
static public Bureaucrat registerLayers(final Layer layer, final int kind) {
if (layer.getParent().size() <= 1) {
Utils.showMessage("There is only one layer.");
return null;
}
final GenericDialog gd = new GenericDialog("Choose first and last");
gd.addMessage("Choose first and last layers to register:");
Utils.addLayerRangeChoices(layer, gd); /// $#%! where are my lisp macros
switch (kind) {
case LAYER_SIFT:
gd.addCheckbox("Propagate last transform: ", true);
break;
case GLOBAL_MINIMIZATION:
gd.addCheckbox("Tiles are rougly registered: ", false);
gd.addCheckbox("Consider largest graph only, in each layer", false);
gd.addCheckbox("Hide tiles from non-largest graph", false);
gd.addCheckbox("Delete tiles from non-largest graph", false);
break;
}
//TODO//gd.addCheckbox("Transform segmentations", true);
gd.showDialog();
if (gd.wasCanceled()) return null;
final int i_first = gd.getNextChoiceIndex();
final int i_start = layer.getParent().indexOf(layer);
final int i_last = gd.getNextChoiceIndex();
final boolean[] option = new boolean[5]; // by default all slots are false
option[0] = gd.getNextBoolean();
if (kind == GLOBAL_MINIMIZATION) {
option[1] = gd.getNextBoolean(); // largest graph only
option[2] = gd.getNextBoolean(); // hide other tiles
option[3] = gd.getNextBoolean(); // delete other tiles
}
option[4] = true; // show dialog
//TODO//final boolean tr_seg = gd.getNextBoolean();
switch (kind) {
case GLOBAL_MINIMIZATION:
List<Layer> lla = layer.getParent().getLayers().subList(i_first, i_last +1);
Layer[] la = new Layer[lla.size()];
la = lla.toArray(la);
return registerTilesSIFT(la, option);
case LAYER_SIFT:
return registerLayers(layer.getParent(), i_first, i_start, i_last, option[0]);
}
return null;
}
/** Register a subset of consecutive layers of the LayerSet, starting at 'start' (which is unmodified)
* and proceeding both towards first and towards last.
* If @param propagate is true, the last transform is applied to all other subsequent, non-included layers .
* @return The Bureaucrat thread in charge of the task, or null if the parameters are invalid.
*/
static public Bureaucrat registerLayers(final LayerSet layer_set, final int first, final int start, final int last, final boolean propagate) {
// check preconditions
if (null == layer_set || first > start || first > last || start > last || last >= layer_set.size()) {
Utils.log2("Registration.registerLayers: invalid parameters: " + layer_set + ", first: " + first + ", start: " + start + ", last" + last);
return null;
}
// outside the Worker thread, so that the dialog can be controled with Macro.setOptions
// if the calling Thread's name starts with "Run$_"
final Registration.SIFTParameters sp = new Registration.SIFTParameters(layer_set.getProject());
if (!sp.setup()) return null;
final Worker worker = new Worker("Registering stack slices") {
public void run() {
startedWorking();
boolean massive_mode = layer_set.getProject().getLoader().getMassiveMode();
layer_set.getProject().getLoader().setMassiveMode(true); // should be done with startLargeUpdate
try {
// build lists (Layers are consecutive)
final List<Layer> list1 = new ArrayList<Layer>();
list1.addAll(layer_set.getLayers().subList(first, start+1)); // endings are exclusive
Collections.reverse(list1);
final List<Layer> list2 = new ArrayList<Layer>();
list2.addAll(layer_set.getLayers().subList(start, last+1)); // kludge because subList ends up removing stuff from the main Layer list!
// remove empty layers
for (Iterator it = list1.iterator(); it.hasNext(); ) {
Layer la = (Layer)it.next();
if (0 == la.getDisplayables(Patch.class).size()) {
it.remove();
Utils.log2("FORE: Removing from registration list layer with no images " + la.getProject().findLayerThing(la).getTitle() + " -- " + la);
}
}
for (Iterator it = list2.iterator(); it.hasNext(); ) {
Layer la = (Layer)it.next();
if (0 == la.getDisplayables(Patch.class).size()) {
it.remove();
Utils.log2("AFT: Removing from registration list layer with no images " + la.getProject().findLayerThing(la).getTitle() + " -- " + la);
}
}
// there must be some way to make inner anonymous methods or something to avoid duplicating code like this.
// iterate in pairs
final Layer layer_start = (Layer)list2.get(0); // even if there is only one element, list2 will contain the starting layer as the first element. Should be equivalent to layer_set.get(start)
// check assumptions
if (0 == layer_start.count(Patch.class)) {
Utils.log2("Registration of layers: ERROR: the starting layer is empty.");
finishedWorking();
return;
}
// prune empty layers (so they are ignored)
checkLayerList(list1);
checkLayerList(list2);
if (list1.size() <= 1 && list2.size() <= 1) {
finishedWorking();
return;
}
// ensure proper snapshots
layer_set.setMinimumDimensions();
//
final Rectangle box = layer_start.getMinimalBoundingBox(Patch.class);
final ImagePlus imp = layer_start.getProject().getLoader().getFlatImage(layer_start, box, sp.scale, 0xFFFFFFFF, ImagePlus.GRAY8, Patch.class, true);
final Object[] ob1 = processLayerList(list1, imp, box, sp, propagate, this);
final Object[] ob2 = processLayerList(list2, imp, box, sp, propagate, this);
// transfer the last affine transform to the remaining layers
if (propagate) {
if (0 != first || first != start) {
if (null == ob1) {
// can't propagate
Utils.log2("Can't propagate towards the first layer in the layer set.");
} else {
// propagate from first towards zero
AffineTransform at1 = (AffineTransform)ob1[0];
for (Iterator it = layer_set.getLayers().subList(0, first).iterator(); it.hasNext(); ){
// preconcatenate the transform to every Patch in the Layer
((Layer)it.next()).apply(Patch.class, at1);
}
}
}
if (layer_set.size() -1 != last) {
if (null == ob2) {
// can't propagate
Utils.log2("Can't propagate towards the last layer in the layer set");
} else {
AffineTransform at2 = (AffineTransform)ob2[0];
// propagate towards the last slice
for (Iterator it = layer_set.getLayers().subList(last+1, layer_set.size()).iterator(); it.hasNext(); ) {
// preconcatenate the transform to every Patch in the Layer
((Layer)it.next()).apply(Patch.class, at2);
}
}
}
}
// trim and polish:
layer_set.setMinimumDimensions();
// redistribute images to buckets:
HashSet<Layer> all_layers = new HashSet<Layer>();
all_layers.addAll(list1);
all_layers.addAll(list2);
layer_set.getProject().getLoader().recreateBuckets(all_layers);
} catch (Exception e) {
IJError.print(e);
}
layer_set.getProject().getLoader().setMassiveMode(massive_mode);
finishedWorking();
}
};
// watcher thread
final Bureaucrat burro = new Bureaucrat(worker, layer_set.getProject());
burro.goHaveBreakfast();
return burro;
}
static private void checkLayerList(final List list) {
for (Iterator it = list.iterator(); it.hasNext(); ) {
Layer la = (Layer)it.next();
if (0 == la.count(Patch.class)) it.remove();
}
// TODO: check that there aren't any elements linking any two consecutive layers together.
}
static private Object[] processLayerList(final List list, final ImagePlus imp_first, final Rectangle box_first, final Registration.SIFTParameters sp, final boolean propagate, final Worker worker) {
// check preconditions
if (list.size() <= 1 || worker.hasQuitted()) return null;
//
Object[] result = null;
// if i == 1:
result = registerSIFT((Layer)list.get(0), (Layer)list.get(1), new Object[]{imp_first, box_first, null, null}, sp);
// else:
for (int i=2; i<list.size(); i++) {
if (worker.hasQuitted()) return null;
final Layer la1 = (Layer)list.get(i-1);
final Layer la2 = (Layer)list.get(i);
result = registerSIFT(la1, la2, null, sp);
// !@#$% TODO this needs fine-tuning
la1.getProject().getLoader().releaseToFit(Loader.MIN_FREE_BYTES * 20);
}
//Loader.runGCAll();
return result;
}
/** Makes a snapshot with the Patch objects in both layers at the given scale, and rotates/translates all Displayable elements in the second Layer relative to the first.
*
* @return the AffineTransform only for now. I will eventually figure out a way to do safe caching with no loss of precision, carrying along the AffineTransform.
*/
static public Object[] registerSIFT(final Layer layer1, final Layer layer2, Object[] cached, final Registration.SIFTParameters sp) {
try {
// prepare flat images for each layer
Rectangle box1 = null;
ImagePlus imp1 = null;
Vector<Feature> fs1 = null;
AffineTransform at_accum = null;
if (null == cached) {
Utils.log2( "cached is null in Registration.java:277" );
box1 = layer1.getMinimalBoundingBox(Patch.class);
Utils.log2( "layer1.getminimalBoundingBox succeeded with " + box1 );
imp1 = layer1.getProject().getLoader().getFlatImage(layer1, box1, sp.scale, 0xFFFFFFFF, ImagePlus.GRAY8, Patch.class, true);
Utils.log2( "layer1.getProject().getLoader().getFlatImage succeeded with " + imp1 );
} else {
imp1 = (ImagePlus)cached[0];
box1 = (Rectangle)cached[1];
fs1 = (Vector<Feature>)cached[2];
at_accum = (AffineTransform)cached[3];
}
Rectangle box2 = layer2.getMinimalBoundingBox(Patch.class);
ImagePlus imp2 = layer2.getProject().getLoader().getFlatImage(layer2, box2, sp.scale, 0xFFFFFFFF, ImagePlus.GRAY8, Patch.class, true);
FloatProcessor fp1 = Utils.fastConvertToFloat(imp1.getProcessor(), imp1.getType()); // (FloatProcessor)imp1.getProcessor().convertToFloat();
FloatProcessor fp2 = Utils.fastConvertToFloat(imp2.getProcessor(), imp1.getType()); //(FloatProcessor)imp2.getProcessor().convertToFloat();
if (null == cached) { // created locally, flushed locally since there's no caching
Loader.flush(imp1);
imp1 = null;
}
Loader.flush(imp2); // WARNING this may have to be removed if caching is enabled
imp2 = null;
// ready to start
Object[] result = Registration.registerSIFT(fp1, fp2, fs1, sp);
if (null != result) {
// use the returned AffineTransform to adjust all Patch objects in layer2
// The transform is the same for a part as for the whole.
// Since the flat image was done considering the tranforms of each tile,
// the returned transform simply needs to be preconcatenated to the tile's:
AffineTransform at = (AffineTransform)result[2];
// correct for the difference in position of flat image boxes
final AffineTransform atap = new AffineTransform();
// so that 0,0 of each image is the same, which is what SIFT expects
atap.translate(box1.x, box1.y);
atap.concatenate(at);
atap.translate(-box2.x, -box2.y);
// apply accumulated transform
if (null != at_accum) at.preConcatenate(at_accum);
// preconcatenate the transform to every Patch in the Layer
layer2.apply(Patch.class, atap);
Utils.log2("Registered layer " + layer2 + " to " + layer1);
Vector< PointMatch > inliers = ( Vector< PointMatch > )result[ 3 ];
// cleanup
result = null; // contains the fs1 and fs2
// TODO the above is temporary; need to figure out how to properly cache
return new Object[]{ atap, box1, box2, inliers };
} else {
// fall back to phase-correlation
Utils.log2("Registration.registerSIFT for Layers: falling back to phase-correlation");
Utils.log2("\t--- Not yet implemented");
}
// repaint the second Layer, if it is showing in any Display:
// no need // Display.repaint(layer2, null, 0);
// redistribute images to buckets:
layer2.recreateBuckets();
} catch (Exception e) {
IJError.print(e);
}
return null;
}
/** Registers the second image relative to the first. Returns an array of:
* - the set of features for the first image
* - the set of features for the second image
* - the AffineTransform defining the registration of the second image relative to the first.
*
* The given @param fs1 may be null, in which case it will be generated from the first ImagePlus. It is here so that caching is possible.
* @param initial_sigma is adjustable, so that high magnification steps can be skipped for noisy or highly variable datasets, which show most similarity at coarser, lower magnification levels.
*
* Returns null if the model is not significant.
*/
static public Object[] registerSIFT(
FloatProcessor ip1,
FloatProcessor ip2,
Vector < Feature > fs1,
final Registration.SIFTParameters sp )
{
// ensure enough memory space (in bytes: area * 48 * 2)
// times 2, ... !@#$%
long size = 2 * (ip1.getWidth() * ip1.getHeight() * 48L + ip2.getWidth() * ip2.getHeight() * 48L);
Utils.log2("size is: " + size);
while (!sp.project.getLoader().releaseToFit(size) && size > 10000000) { // 10 Mb
size = (size / 3) * 2; // if it fails, at least release as much as possible
Utils.log2("size is: " + size);
// size /= 1.5 was NOT failing at the compiler level! Uh?
}
// prepare both sets of features
if (null == fs1) fs1 = getSIFTFeatures(ip1, sp);
ip1 = null;
//Loader.runGCAll(); // cleanup
final Vector<Feature> fs2 = getSIFTFeatures( ip2, sp );
// free all those temporary arrays
ip2 = null;
//Loader.runGCAll();
// compare in the order that image2 should be moved relative to imag1
final Vector< PointMatch > candidates = FloatArray2DSIFT.createMatches( fs2, fs1, 1.5f, null, Float.MAX_VALUE );
final Vector< PointMatch > inliers = new Vector< PointMatch >();
Model model;
if (1 == sp.dimension) {
// translation and rotation
model = TRModel2D.estimateBestModel(
candidates,
inliers,
sp.min_epsilon,
sp.max_epsilon,
sp.min_inlier_ratio );
} else {
// translation only
model = TModel2D.estimateBestModel(
candidates,
inliers,
sp.min_epsilon,
sp.max_epsilon,
sp.min_inlier_ratio );
}
final AffineTransform at = new AffineTransform();
if (model != null) {
// debug
Utils.log2( "inliers: " + inliers.size() + " corresp: " + candidates.size());
// images may have different sizes
/**
* TODO Different sizes are no problem as long as the top left
* corner is at the fixed position (x0:0.0f, y0:0.0f). If this is not the
* case, translate the image relative to this position. That is,
* translate the pivot point of the rotation and translate the translation
* vector itself.
*/
// rotation origin at the top left corner of the image (0.0f, 0.0f) of the image.
AffineTransform at_current = new AffineTransform( model.getAffine() );
double[] m = new double[ 6 ];
at_current.getMatrix( m );
m[ 4 ] /= sp.scale;
m[ 5 ] /= sp.scale;
at_current.setTransform( m[ 0 ], m[ 1 ], m[ 2 ], m[ 3 ], m[ 4 ], m[ 5 ] );
at.concatenate( at_current );
} else {
Utils.log("No sufficient model found, keeping original transformation for " + ip2);
return null;
}
return new Object[]{fs1, fs2, at, inliers};
}
/** Returns a sorted list of the SIFT features extracted from the given ImagePlus. */
final static public Vector<Feature> getSIFTFeatures(ImageProcessor ip, final Registration.SIFTParameters sp) {
FloatArray2D fa = ImageArrayConverter.ImageToFloatArray2D(Utils.fastConvertToFloat(ip)); //ip.convertToFloat());
ip = null; // enable GC
ImageFilter.enhance( fa, 1.0f ); // done in place
fa = ImageFilter.computeGaussianFastMirror(
fa,
(float)Math.sqrt(sp.initial_sigma * sp.initial_sigma - 0.25));
final FloatArray2DSIFT sift = new FloatArray2DSIFT(sp.fdsize, sp.fdbins);
sift.init(fa, sp.steps, sp.initial_sigma, sp.min_size, sp.max_size);
fa = null; // enableGC
final Vector<Feature> fs = sift.run(sp.max_size);
Collections.sort(fs);
return fs;
}
/** Will cross-correlate slices in a separate Thread; leaves the given slice untouched.
* @param base_slice is the reference slice from which the stack will be registered, i.e. it won't be affected in any way.
*/
static public Bureaucrat registerStackSlices(final Patch base_slice) {
// find linked images in different layers and register them
//
// setup parameters. Put outside the Worker so the dialog is controlable from a Macro.setOptions(...) if the Thread's name that calls this method starts with the string "Run$_"
final Registration.SIFTParameters sp = new Registration.SIFTParameters(base_slice.getProject());
if (!sp.setup()) {
return null;
}
final Worker worker = new Worker("Registering stack slices") {
public void run() {
try {
startedWorking();
correlateSlices(base_slice, new HashSet(), this, sp/*, null*/); // using non-recursive version
// ensure there are no negative numbers in the x,y
base_slice.getLayer().getParent().setMinimumDimensions();
} catch (Exception e) {
IJError.print(e);
}
finishedWorking();
}
};
// watcher thread
final Bureaucrat burro = new Bureaucrat(worker, base_slice.getProject());
burro.goHaveBreakfast();
return burro;
}
/** Recursive into linked images in other layers. */
static private void correlateSlices(final Patch slice, final HashSet hs_done, final Worker worker, final Registration.SIFTParameters sp, final Vector<Feature> fs_slice) {
if (hs_done.contains(slice)) return;
hs_done.add(slice);
// iterate over all Patches directly linked to the given slice
// recursive version: has memory releasing problems.
HashSet hs = slice.getLinked(Patch.class);
Utils.log2("@@@ size: " + hs.size());
for (Iterator it = hs.iterator(); it.hasNext(); ) {
if (worker.hasQuitted()) return;
final Patch p = (Patch)it.next();
if (hs_done.contains(p)) continue;
// skip linked images within the same layer
if (p.getLayer() == slice.getLayer()) continue;
// ensure there are no negative numbers in the x,y
slice.getLayer().getParent().setMinimumDimensions();
// go
final Object[] result = Registration.registerWithSIFTLandmarks(slice, p, sp, fs_slice);
// enable GC:
if (null != result) {
result[0] = null;
result[2] = null;
}
Registration.correlateSlices(p, hs_done, worker, sp, null != result ? (Vector<Feature>)result[1] : null); // I give it the feature set of the moving patch, which in this call will serve as base
}
}
/** Non-recursive version (for the processing; the assembly of the stack chain is recursive). */
static private void correlateSlices(final Patch slice, final HashSet hs_done, final Worker worker, final Registration.SIFTParameters sp) {
// non-recursive version: build the chain first. Assumes there are only two chains max.
final ArrayList al_chain1 = new ArrayList();
final ArrayList al_chain2 = new ArrayList();
for (Iterator it = slice.getLinked(Patch.class).iterator(); it.hasNext(); ) {
if (0 == al_chain1.size()) {
al_chain1.add(slice);
al_chain1.add(it.next());
buildChain(al_chain1);
continue;
}
if (0 == al_chain2.size()) {
al_chain2.add(slice);
al_chain2.add(it.next());
buildChain(al_chain2);
continue;
}
break; // only two max; a Patch of a stack should never have more than two Patch linked to it
}
if (al_chain1.size() >= 2) processChain(al_chain1, sp, worker);
if (al_chain2.size() >= 2) processChain(al_chain2, sp, worker);
}
/** Take the last one of the chain, inspect its linked Patches, add the one that is not yet included, continue building. Recursive. */
static private void buildChain(final ArrayList al_chain) {
final Patch p = (Patch)al_chain.get(al_chain.size()-1);
for (Iterator it = p.getLinked(Patch.class).iterator(); it.hasNext(); ) {
Object ob = it.next();
if (al_chain.contains(ob)) continue;
else {
al_chain.add(ob);
buildChain(al_chain);
break;
}
}
}
static private void processChain(final ArrayList al_chain, final Registration.SIFTParameters sp, final Worker worker) {
Object[] result = null;
for (int i=1; i<al_chain.size(); i++) {
if (worker.hasQuitted()) return;
result = registerWithSIFTLandmarks((Patch)al_chain.get(i-1), (Patch)al_chain.get(i), sp, null == result ? null : (Vector<Feature>)result[1]);
}
}
static public Object[] registerWithSIFTLandmarks(final Patch base, final Patch moving, final Registration.SIFTParameters sp, final Vector<Feature> fs_base) {
return registerWithSIFTLandmarks(base, moving, sp, fs_base, true, true);
}
/** The @param fs_base is the vector of features of the base Patch, and can be null -in which case it will be computed. */
static public Object[] registerWithSIFTLandmarks(final Patch base, final Patch moving, final Registration.SIFTParameters sp, final Vector<Feature> fs_base, boolean apply, boolean fallback_to_phase_correlation) {
if (null != moving.getLayer()) Utils.log2("processing layer " + moving.getLayer().getParent().indexOf(moving.getLayer()));
FloatProcessor fp1 = (FloatProcessor)StitchingTEM.makeStripe(base, sp.scale, true);
FloatProcessor fp2 = (FloatProcessor)StitchingTEM.makeStripe(moving, sp.scale, true);
Object[] result = Registration.registerSIFT(fp1, fp2, fs_base, sp);
// enable garbage collection!
fp1 = null;
fp2 = null;
// no hope. The recursion prevents from lots of memory from ever being released.
// MWAHAHA so I made a non-recursive smart-ass version.
// It is somewhat disturbing that each SIFT match at max_size 1600 was using nearly 400 Mb, and all of them were NOT released because of the recursion.
//Loader.runGCAll();
//base.getProject().getLoader().releaseToFit(Loader.MIN_FREE_BYTES * 20);
AffineTransform atr = null;
if (null != result) {
atr = (AffineTransform)result[2];
} else if (fallback_to_phase_correlation) {
// failed, fall back to phase-correlation
Utils.log2("Automatic landmark detection failed, falling back to phase-correlation.");
atr = Registration.correlate(base, moving, sp.scale);
if (null != atr) {
result = new Object[4];
result[2] = atr;
}
}
if (apply && null != atr) {
AffineTransform at_moving = moving.getAffineTransform();
at_moving.setToIdentity(); // be sure to CLEAR it totally
// set to the given result
at_moving.setTransform(atr);
// pre-apply the base's transform
at_moving.preConcatenate(base.getAffineTransform());
moving.updateBucket();
at_moving = null;
if (ControlWindow.isGUIEnabled()) {
Rectangle box = moving.getBoundingBox();
box.add(moving.getBoundingBox());
Display.repaint(moving.getLayer(), box, 1);
box = null;
}
}
return result;
}
static public class SIFTParameters implements Serializable {
transient public Project project = null; // not in serialized object
// filled with default values
public float scale = 1.0f;
public int steps = 3;
public float initial_sigma = 1.6f;
public int fdsize = 8;
public int fdbins = 8;
/** size restrictions for scale octaves, use octaves < max_size and > min_size only */
public int min_size = 64;
public int max_size = 1024;
/** Maximal initial drift of landmark relative to its matching landmark in the other image, to consider when searching. Also used as increment for epsilon when there was no sufficient model found.*/
public float min_epsilon = 2.0f;
public float max_epsilon = 100.0f;
/** Minimal percent of good landmarks found */
public float min_inlier_ratio = 0.05f;
/** A message to show within the dialog, at the top, for information purposes. */
public String msg = null;
/** Minimal allowed alignment error in px (across sections) */
public float cs_min_epsilon = 1.0f;
/** Maximal allowed alignment error in px (across sections) */
public float cs_max_epsilon = 50.0f;
/** 0 means only translation, 1 means both translation and rotation. */
public int dimension = 1;
/** Whether to show options for cross-layer registration or not in the dialog. */
public boolean cross_layer = false;
public boolean tiles_prealigned = false;
/** Plain constructor for Serialization to work properly. */
public SIFTParameters() {}
public SIFTParameters(Project project) {
this.project = project;
}
public SIFTParameters(Project project, String msg, boolean cross_layer) {
this(project);
this.msg = msg;
this.cross_layer = cross_layer;
}
public void print() {
Utils.log2(new StringBuffer("SIFTParameters:\n")
.append(null != msg ? "\tmsg:" + msg + "\n" : "")
.append("\tscale: ").append(scale).append('\n')
.append("\tsteps per scale octave: ").append(steps).append('\n')
.append("\tinitial gaussian blur: ").append(initial_sigma).append('\n')
.append("\tfeature descriptor size: ").append(fdsize).append('\n')
.append("\tfeature descriptor orientation bins: ").append(fdbins).append('\n')
.append("\tminimum image size: ").append(min_size).append('\n')
.append("\tmaximum image size: ").append(max_size).append('\n')
.append("\tminimal alignment error: ").append(min_epsilon).append('\n')
.append("\tmaximal alignment error: ").append(max_epsilon).append('\n')
.append("\tminimal inlier ratio: ").append(min_inlier_ratio)
.toString());
}
public boolean setup() {
final GenericDialog gd = new GenericDialog("Options");
if (null != msg) gd.addMessage(msg);
gd.addSlider("scale (%):", 1, 100, scale*100);
gd.addNumericField("steps_per_scale_octave :", steps, 0);
gd.addNumericField("initial_gaussian_blur :", initial_sigma, 2);
gd.addNumericField("feature_descriptor_size :", fdsize, 0);
gd.addNumericField("feature_descriptor_orientation_bins :", fdbins, 0);
gd.addNumericField("minimum_image_size :", min_size, 0);
gd.addNumericField("maximum_image_size :", max_size, 0);
gd.addNumericField("minimal_alignment_error :", min_epsilon, 2);
gd.addNumericField("maximal_alignment_error :", max_epsilon, 2);
if (cross_layer) {
gd.addNumericField("cs_min_epsilon :", cs_min_epsilon, 2);
gd.addNumericField("cs_max_epsilon :", cs_max_epsilon, 2);
}
gd.addNumericField("minimal_inlier_ratio :", min_inlier_ratio, 2);
final String[] regtype = new String[]{"translation only", "translation and rotation"};
gd.addChoice("registration_type :", regtype, regtype[dimension]);
gd.addCheckbox("tiles_are_prealigned", tiles_prealigned);
gd.showDialog();
if (gd.wasCanceled()) return false;
this.scale = (float)gd.getNextNumber() / 100;
this.steps = (int)gd.getNextNumber();
this.initial_sigma = (float)gd.getNextNumber();
this.fdsize = (int)gd.getNextNumber();
this.fdbins = (int)gd.getNextNumber();
this.min_size = (int)gd.getNextNumber();
this.max_size = (int)gd.getNextNumber();
this.min_epsilon = (float)gd.getNextNumber();
this.max_epsilon = (float)gd.getNextNumber();
if (cross_layer) {
this.cs_min_epsilon = (float)gd.getNextNumber();
this.cs_max_epsilon = (float)gd.getNextNumber();
}
this.min_inlier_ratio = (float)gd.getNextNumber();
this.dimension = gd.getNextChoiceIndex();
this.tiles_prealigned = gd.getNextBoolean();
// debug:
print();
return true;
}
/** Returns the size in bytes of a Feature object. */
public final long getFeatureObjectSize() {
return FloatArray2DSIFT.getFeatureObjectSize(fdsize, fdbins);
}
/** Compare parameters relevant for creating features and return true if all coincide. */
public final boolean sameFeatures(final Registration.SIFTParameters sp) {
if (max_size == sp.max_size
&& scale == sp.scale
&& min_size == sp.min_size
&& fdbins == sp.fdbins
&& fdsize == sp.fdsize
&& initial_sigma == sp.initial_sigma
&& steps == sp.steps) {
return true;
}
return false;
}
}
/** Returns null on failure. */
static private AffineTransform correlate(final Patch base, final Patch moving, final float scale) {
Utils.log2("Correlating #" + moving.getId() + " to #" + base.getId());
// test rotation first TODO
final double[] pc = StitchingTEM.correlate(base, moving, 1f, scale, StitchingTEM.TOP_BOTTOM, 0, 0, base.getProject().getProperty("min_R", StitchingTEM.DEFAULT_MIN_R));
if (pc[2] != StitchingTEM.SUCCESS) {
// R is too low to be trusted
Utils.log2("Bad R coefficient, skipping " + moving);
return null; // don't move
}
Utils.log2("BASE: x, y " + base.getX() + " , " + base.getY() + "\n\t pc x,y: " + pc[0] + ", " + pc[1]);
Utils.showStatus("--- Done correlating target #" + moving.getId() + " to base #" + base.getId(), false);
AffineTransform at = new AffineTransform();
at.translate(pc[0], pc[1]);
return at;
}
/** Single-threaded: one layer after the other, to avoid memory saturation. The feature finding with SIFT is multithreaded.
* If position_as_hint is true, then each tile will only try to find feature correspondences
* with overlapping tiles.
*
* Assumes all layers belong to the same project, and are CONTINUOUS in Z space.
*
* Will show a dialog for SIFT parameters setup.
*
* Ported from Stephan Saalfeld's SIFT_Align_LayerSet.java plugin
*
*/
static public Bureaucrat registerTilesSIFT(final Layer[] layer, final boolean overlapping_only) {
return registerTilesSIFT(layer, new boolean[]{overlapping_only, false, false, false, false});
}
static public Bureaucrat registerTilesSIFT(final Layer[] layer, final boolean[] options) {
return registerTilesSIFT(layer, options, 512, 0.5f);
}
static public Bureaucrat registerTilesSIFT(final Layer[] layer, final boolean[] options, final int max_size, final float scale) {
if (null == layer || 0 == layer.length) return null;
final boolean overlapping_only = options[0];
final boolean largest_graph_only = options[1];
final boolean hide_other_tiles = options[2];
final boolean delete_other_tiles = options[3];
final boolean show_dialog = options[4];
final Worker worker_ = new Worker("Free tile registration") {
public void run() {
startedWorking();
try {
final Worker worker = this; // J jate java
final LayerSet set = layer[0].getParent();
final String[] dimensions = { "translation", "translation and rotation" };
int dimension_ = 1;
// Parameters for tile-to-tile registration
final SIFTParameters sp = new SIFTParameters(set.getProject(), "Options for tile-to-tile registration", false);
sp.steps = 3;
sp.initial_sigma = 1.6f;
sp.fdsize = 8;
sp.fdbins = 8;
sp.min_size = 64;
sp.max_size = max_size;
sp.min_epsilon = 1.0f;
sp.max_epsilon = 10.0f;
sp.cs_min_epsilon = 1.0f;
sp.cs_max_epsilon = 50.0f;
sp.min_inlier_ratio = 0.05f;
sp.scale = scale;
sp.tiles_prealigned = overlapping_only;
- boolean global_optimization = false;
+ boolean global_optimization = true;
final Registration.SIFTParameters sp_gross_interlayer = new Registration.SIFTParameters(set.getProject(), "Options for coarse layer registration", true);
if (show_dialog) {
// 1 - Simple setup
GenericDialog gds = new GenericDialog("Setup");
gds.addNumericField("maximum_image_size :", sp.max_size, 0);
gds.addNumericField("maximal_alignment_error :", sp.max_epsilon, 2);
gds.addCheckbox("Layers_are_roughly_prealigned", sp.tiles_prealigned);
- gds.addCheckbox("Disable global optimization", global_optimization);
+ gds.addCheckbox("Disable global optimization", !global_optimization);
gds.addCheckbox("Advanced setup", false);
gds.showDialog();
if (gds.wasCanceled()) {
finishedWorking();
return;
}
sp.max_size = (int)gds.getNextNumber();
sp.max_epsilon = (float)gds.getNextNumber();
sp.tiles_prealigned = gds.getNextBoolean();
- global_optimization = gds.getNextBoolean();
+ global_optimization = !gds.getNextBoolean();
boolean advanced_setup = gds.getNextBoolean();
// 2 - Optional advanced setup
if (advanced_setup) {
if (!sp.setup()) {
finishedWorking();
return;
}
// 3 - Inter-layer registration setup
if (!sp_gross_interlayer.setup()) {
finishedWorking();
return;
}
}
}
// start:
final ArrayList< Layer > layers = new ArrayList< Layer >();
for (int k=0; k<layer.length; k++) {
layers.add( layer[k] );
}
//final ArrayList< Vector< Feature > > featureSets1 = new ArrayList< Vector< Feature > >();
//final ArrayList< Vector< Feature > > featureSets2 = new ArrayList< Vector< Feature > >();
//
// fsets1, fsets2 used to be featureSets1, featureSets2
// The elements of these arrays may be null, or may be not.
// When null, the feature set is assumed to have been serialized and thus is retrieved from there.
Vector<Feature>[] fsets1=null, fsets2=null;
final ArrayList< Patch > patches1 = new ArrayList< Patch >();
final ArrayList< Tile > tiles1 = new ArrayList< Tile >();
final ArrayList< Patch > patches2 = new ArrayList< Patch >();
final ArrayList< Tile > tiles2 = new ArrayList< Tile >();
final ArrayList< Tile > all_tiles = new ArrayList< Tile >();
final ArrayList< Patch > all_patches = new ArrayList< Patch >();
final ArrayList< Tile > fixed_tiles = new ArrayList< Tile >();
Layer previous_layer = null;
// the storage folder for serialized features
final Loader loader = set.getProject().getLoader();
String storage_folder_ = loader.getStorageFolder() + "features.ser/";
File sdir = new File(storage_folder_);
if (!sdir.exists()) {
try {
sdir.mkdir();
} catch (Exception e) {
storage_folder_ = null; // can't store
}
}
final String storage_folder = storage_folder_;
for ( Layer layer : layers )
{
if (hasQuitted()) return;
final ArrayList< Tile > layer_fixed_tiles = new ArrayList< Tile >();
Utils.log( "Registering layer " + ( set.indexOf( layer ) + 1 ) + " of " + set.size() );
// ignore empty layers
if ( !layer.contains( Patch.class ) )
{
Utils.log2( "Ignoring empty layer." );
continue;
}
if ( null != previous_layer )
{
//featureSets1.clear();
//featureSets1.addAll( featureSets2 );
fsets1 = fsets2;
patches1.clear();
patches1.addAll( patches2 );
tiles1.clear();
tiles1.addAll( tiles2 );
}
patches2.clear();
//featureSets2.clear();
tiles2.clear();
ArrayList tmp = new ArrayList();
tmp.addAll(layer.getDisplayables( Patch.class ));
patches2.addAll( tmp ); // I hate generics. Incovertible types? Not at all!
// extract SIFT-features in all patches
// (multi threaded version)
// "generic array creation" error ? //fsets2 = new Vector<Feature>[ patches2.size() ];
fsets2 = (Vector<Feature>[])new Vector[ patches2.size() ];
final Tile[] tls = new Tile[ fsets2.length ];
Registration.generateTilesAndFeatures(patches2, tls, fsets2, sp, storage_folder, worker);
if (hasQuitted()) return;
//#################################################################
for ( int k = 0; k < fsets2.length; k++ )
{
//featureSets2.add( fsets2[ k ] );
tiles2.add( tls[ k ] );
}
// identify correspondences and inspect connectivity
Registration.connectTiles(patches2, tiles2, /*featureSets2*/ fsets2, sp, storage_folder, worker);
// identify connected graphs
ArrayList< ArrayList< Tile > > graphs = Tile.identifyConnectedGraphs( tiles2 );
Utils.log2( graphs.size() + " graphs detected." );
if (largest_graph_only) {
final ArrayList<Patch> other_patches = new ArrayList<Patch>();
// remove graphs other than the largest, and remove tiles from tiles2 as well
if (1 != graphs.size()) {
int len = 0;
ArrayList<Tile> largest = null;
for (ArrayList<Tile> graph : graphs) {
if (graph.size() > len) {
len = graph.size();
largest = graph;
}
}
// remove all tiles from tiles2 except those that belong to the largest graph
//tiles2.retainAll(largest); // all other tiles are removed
// Can't ... patches2 would not be in synch, so:
graphs.remove(largest);
for (ArrayList<Tile> graph : graphs) {
for (Tile tile : graph) {
int index = tiles2.indexOf(tile);
other_patches.add(patches2.remove(index));
tiles2.remove(index);
}
}
int n_graphs = graphs.size();
graphs.clear();
graphs.add(largest); // so now graphs contains only one
Utils.log2("Removed " + n_graphs + "\n\t--> focusing on largest graph with " + largest.size() + " tiles.");
}
if (hide_other_tiles || delete_other_tiles) {
if (other_patches.size() > 0) {
for (Patch pa : other_patches) {
if (delete_other_tiles) {
pa.unlink(); // just in case: it could stop all
pa.remove(false);
} else if (hide_other_tiles) pa.setVisible(false);
}
Patch first = other_patches.get(0);
if (delete_other_tiles) Utils.log("Layer " + first.getLayer() + ": Deleted " + other_patches.size() + " images.");
else if (hide_other_tiles) Utils.log("Layer " + first.getLayer() + ": Hided " + other_patches.size() + " images.");
}
}
}
if ( sp.tiles_prealigned && graphs.size() > 1 )
{
/**
* We have to trust the given alignment. Try to add synthetic
* correspondences to disconnected graphs having overlapping
* tiles.
*/
Utils.log2( "Synthetically connecting graphs using the given alignment." );
Registration.connectDisconnectedGraphs( graphs, tiles2, patches2 );
/**
* check the connectivity graphs again. Hopefully there is
* only one graph now. If not, we still have to fix one tile
* per graph, regardless if it is only one or several oth them.
*/
graphs = Tile.identifyConnectedGraphs( tiles2 );
Utils.log2( graphs.size() + " graphs detected after synthetic connection." );
}
// fix one tile per graph, meanwhile update the tiles
layer_fixed_tiles.addAll(Registration.pickFixedTiles(graphs));
// update all tiles, for error and distance correction
for ( Tile tile : tiles2 ) tile.update();
// optimize the pose of all tiles in the current layer
Registration.minimizeAll( tiles2, patches2, layer_fixed_tiles, set, sp.max_epsilon, worker );
// repaint all Displays showing a Layer of the edited LayerSet
Display.update( set );
// store for global minimization
all_tiles.addAll( tiles2 );
all_patches.addAll( patches2 );
if ( null != previous_layer )
{
/**
* 1 - Coarse registration
*
* TODO Think about re-using the correspondences identified
* during coarse registration for the tiles. That introduces
* the following issues:
*
* - coordinate transfer of snapshot-coordinates to
* layer-coordinates in both layers
* - identification of the closest tiles in both layers
* (whose centers are closest to the layer-coordinate of the
* detection)
* - appropriate weight for the correspondence
* - if this is the sole correpondence of a tile, minimization
* as well as model estimation of higher order models than
* translation will fail because of missing information
* -> How to handle this, how to handle this for
* graph-connectivity?
*/
/**
* returns an Object[] with
* [0] AffineTransform that transforms layer towards previous_layer
* [1] bounding box of previous_layer in world coordinates
* [2] bounding box of layer in world coordinates
* [3] true correspondences with p1 in layer and p2 in previous_layer,
* both in the local coordinate frames defined by box1 and box2 and
* scaled with sp_gross_interlayer.scale
*/
Object[] ob = Registration.registerSIFT( previous_layer, layer, null, sp_gross_interlayer );
int original_max_size = sp_gross_interlayer.max_size;
float original_max_epsilon = sp_gross_interlayer.max_epsilon;
while (null == ob || null == ob[0]) {
int next_max_size = sp_gross_interlayer.max_size;
float next_max_epsilon = sp_gross_interlayer.max_epsilon;
// need to recurse up both the max size and the maximal alignment error
if (next_max_epsilon < 300) {
next_max_epsilon += 100;
}
Rectangle rfit1 = previous_layer.getMinimalBoundingBox(Patch.class);
Rectangle rfit2 = layer.getMinimalBoundingBox(Patch.class);
if (next_max_size < rfit1.width || next_max_size < rfit1.height
|| next_max_size < rfit2.width || next_max_size < rfit2.height) {
next_max_size += 1024;
} else {
// fail completely
Utils.log2("FAILED to align layers " + set.indexOf(previous_layer) + " and " + set.indexOf(layer));
// Need to fall back to totally unguided double-layer registration
// TODO
//
break;
}
sp_gross_interlayer.max_size = next_max_size;
sp_gross_interlayer.max_epsilon = next_max_epsilon;
ob = Registration.registerSIFT(previous_layer, layer, null, sp_gross_interlayer);
}
// fix back modified parameters
sp_gross_interlayer.max_size = original_max_size;
sp_gross_interlayer.max_epsilon = original_max_epsilon;
if ( null != ob && null != ob[ 0 ] )
{
// defensive programming ... ;)
AffineTransform at = ( AffineTransform )ob[ 0 ];
Rectangle previous_layer_box = ( Rectangle )ob[ 1 ];
Rectangle layer_box = ( Rectangle )ob[ 2 ];
Vector< PointMatch > inliers = ( Vector< PointMatch > )ob[ 3 ];
/**
* Find the closest tiles in both layers for each of the
* inliers and append a correponding nail to it
*/
for ( PointMatch inlier : inliers )
{
// transfer the coordinates to actual world coordinates
float[] previous_layer_coords = inlier.getP2().getL();
previous_layer_coords[ 0 ] = previous_layer_coords[ 0 ] / sp_gross_interlayer.scale + previous_layer_box.x;
previous_layer_coords[ 1 ] = previous_layer_coords[ 1 ] / sp_gross_interlayer.scale + previous_layer_box.y;
float[] layer_coords = inlier.getP1().getL();
layer_coords[ 0 ] = layer_coords[ 0 ] / sp_gross_interlayer.scale + layer_box.x;
layer_coords[ 1 ] = layer_coords[ 1 ] / sp_gross_interlayer.scale + layer_box.y;
// find the tile whose center is closest to the points in previous_layer
Tile previous_layer_closest_tile = null;
float previous_layer_min_d = Float.MAX_VALUE;
for ( Tile tile : tiles1 )
{
tile.update();
float[] tw = tile.getWC();
float dx = tw[ 0 ] - previous_layer_coords[ 0 ];
dx *= dx;
float dy = tw[ 1 ] - previous_layer_coords[ 1 ];
dy *= dy;
float d = ( float )Math.sqrt( dx + dy );
if ( d < previous_layer_min_d )
{
previous_layer_min_d = d;
previous_layer_closest_tile = tile;
}
}
Utils.log2( "Tile " + tiles1.indexOf( previous_layer_closest_tile ) + " is closest in previous layer:" );
Utils.log2( " distance: " + previous_layer_min_d );
// find the tile whose center is closest to the points in layer
Tile layer_closest_tile = null;
float layer_min_d = Float.MAX_VALUE;
for ( Tile tile : tiles2 )
{
tile.update();
float[] tw = tile.getWC();
float dx = tw[ 0 ] - layer_coords[ 0 ];
dx *= dx;
float dy = tw[ 1 ] - layer_coords[ 1 ];
dy *= dy;
float d = ( float )Math.sqrt( dx + dy );
if ( d < layer_min_d )
{
layer_min_d = d;
layer_closest_tile = tile;
}
}
Utils.log2( "Tile " + tiles2.indexOf( layer_closest_tile ) + " is closest in layer:" );
Utils.log2( " distance: " + layer_min_d );
if ( previous_layer_closest_tile != null && layer_closest_tile != null )
{
// Utils.log2( "world coordinates in previous layer: " + previous_layer_coords[ 0 ] + ", " + previous_layer_coords[ 1 ] );
// Utils.log2( "world coordinates in layer: " + layer_coords[ 0 ] + ", " + layer_coords[ 1 ] );
// transfer the world coordinates to local tile coordinates
previous_layer_closest_tile.getModel().applyInverseInPlace( previous_layer_coords );
layer_closest_tile.getModel().applyInverseInPlace( layer_coords );
// Utils.log2( "local coordinates in previous layer: " + previous_layer_coords[ 0 ] + ", " + previous_layer_coords[ 1 ] );
// Utils.log2( "local coordinates in layer: " + layer_coords[ 0 ] + ", " + layer_coords[ 1 ] );
// create PointMatch for both tiles
mpi.fruitfly.registration.Point previous_layer_point = new mpi.fruitfly.registration.Point( previous_layer_coords );
mpi.fruitfly.registration.Point layer_point = new mpi.fruitfly.registration.Point( layer_coords );
previous_layer_closest_tile.addMatch(
new PointMatch(
previous_layer_point,
layer_point,
inlier.getWeight() / sp_gross_interlayer.scale ) );
layer_closest_tile.addMatch(
new PointMatch(
layer_point,
previous_layer_point,
inlier.getWeight() / sp_gross_interlayer.scale ) );
previous_layer_closest_tile.addConnectedTile( layer_closest_tile );
layer_closest_tile.addConnectedTile( previous_layer_closest_tile );
}
}
TRModel2D model = new TRModel2D();
model.getAffine().setTransform( at );
for ( Tile tile : tiles2 )
( ( TRModel2D )tile.getModel() ).preConcatenate( model );
// repaint all Displays showing a Layer of the edited LayerSet
layer.recreateBuckets();
Display.update( layer );
}
Registration.identifyCrossLayerCorrespondences(
tiles1,
patches1,
fsets1 /*featureSets1*/,
tiles2,
patches2,
fsets2 /*featureSets2*/,
( null != ob && null != ob[ 0 ] ),
sp,
storage_folder,
worker);
// check the connectivity graphs
ArrayList< Tile > both_layer_tiles = new ArrayList< Tile >();
both_layer_tiles.addAll( tiles1 );
both_layer_tiles.addAll( tiles2 );
graphs = Tile.identifyConnectedGraphs( both_layer_tiles );
Utils.log2( graphs.size() + " cross-section graphs detected." );
// if ( graphs.size() > 1 && ( null != ob && null != ob[ 0 ] ) )
// {
// /**
// * We have to trust the given alignment. Try to add synthetic
// * correspondences to disconnected graphs having overlapping
// * tiles.
// */
// ArrayList< Patch > both_layer_patches = new ArrayList< Patch >();
// both_layer_patches.addAll( patches1 );
// both_layer_patches.addAll( patches2 );
// this.connectDisconnectedGraphs( graphs, both_layer_tiles, both_layer_patches );
//
// /**
// * check the connectivity graphs again. Hopefully there is
// * only one graph now. If not, we still have to fix one tile
// * per graph, regardless if it is only one or several of them.
// */
// graphs = Tile.identifyConnectedGraphs( tiles2 );
// Utils.log2( graphs.size() + " cross-section graphs detected after synthetic connection." );
// }
}
previous_layer = layer;
}
// find the global nail
/**
* One tile per connected graph has to be fixed to make the problem
* solvable, otherwise it is ill defined and has an infinite number
* of solutions.
*/
ArrayList< ArrayList< Tile > > graphs = Tile.identifyConnectedGraphs( all_tiles );
Utils.log2( graphs.size() + " global graphs detected." );
fixed_tiles.clear();
// fix one tile per graph, meanwhile update the tiles
fixed_tiles.addAll(Registration.pickFixedTiles(graphs));
// again, for error and distance correction
for ( Tile tile : all_tiles ) tile.update();
// global minimization
try {
if (global_optimization) {
Utils.log("Performing global minimization...");
Registration.minimizeAll( all_tiles, all_patches, fixed_tiles, set, sp.cs_max_epsilon, worker );
Utils.log("Done!");
}
} catch (Throwable t) {
IJError.print(t);
}
// update selection internals in all open Displays
Display.updateSelection( Display.getFront() );
// repaint all Displays showing a Layer of the edited LayerSet
Display.update( set );
} catch (Exception e) {
e.printStackTrace();
} finally {
finishedWorking();
}
}};
Bureaucrat burro = new Bureaucrat(worker_, layer[0].getProject());
burro.goHaveBreakfast();
return burro;
}
/**
* Interconnect disconnected graphs with synthetically added correspondences.
* This implies the tiles to be prealigned.
*
* May fail if the disconnected graphs do not overlap at all.
*
* @param graphs
* @param tiles
* @param patches
*/
static private final void connectDisconnectedGraphs(
final List< ArrayList< Tile > > graphs,
final List< Tile > tiles,
final List< Patch > patches)
{
/**
* We have to trust the given alignment. Try to add synthetic
* correspondences to disconnected graphs having overlapping
* tiles.
*/
Utils.log2( "Synthetically connecting graphs using the given alignment." );
ArrayList< Tile > empty_tiles = new ArrayList< Tile >();
for ( ArrayList< Tile > graph : graphs )
{
if ( graph.size() == 1 )
{
/**
* This is a single unconnected tile.
*/
empty_tiles.add( graph.get( 0 ) );
}
}
for ( ArrayList< Tile > graph : graphs )
{
for ( Tile tile : graph )
{
boolean is_empty = empty_tiles.contains( tile );
Patch patch = patches.get( tiles.indexOf( tile ) );
final Rectangle r = patch.getBoundingBox();
// check this patch against each patch of the other graphs
for ( ArrayList< Tile > other_graph : graphs )
{
if ( other_graph.equals( graph ) ) continue;
for ( Tile other_tile : other_graph )
{
Patch other_patch = patches.get( tiles.indexOf( other_tile ) );
if ( patch.intersects( other_patch ) )
{
/**
* TODO get a proper intersection polygon instead
* of the intersection of bounding boxes.
*
* - Where to add the faked nails then?
*/
final Rectangle rp = other_patch.getBoundingBox().intersection( r );
int xp1 = rp.x;
int yp1 = rp.y;
int xp2 = rp.x + rp.width;
int yp2 = rp.y + rp.height;
Point2D.Double dcp1 = patch.inverseTransformPoint( xp1, yp1 );
Point2D.Double dcp2 = patch.inverseTransformPoint( xp2, yp2 );
Point2D.Double dp1 = other_patch.inverseTransformPoint( xp1, yp1 );
Point2D.Double dp2 = other_patch.inverseTransformPoint( xp2, yp2 );
mpi.fruitfly.registration.Point cp1 = new mpi.fruitfly.registration.Point(
new float[]{ ( float )dcp1.x, ( float )dcp1.y } );
mpi.fruitfly.registration.Point cp2 = new mpi.fruitfly.registration.Point(
new float[]{ ( float )dcp2.x, ( float )dcp2.y } );
mpi.fruitfly.registration.Point p1 = new mpi.fruitfly.registration.Point(
new float[]{ ( float )dp1.x, ( float )dp1.y } );
mpi.fruitfly.registration.Point p2 = new mpi.fruitfly.registration.Point(
new float[]{ ( float )dp2.x, ( float )dp2.y } );
ArrayList< PointMatch > a1 = new ArrayList<PointMatch>();
a1.add( new PointMatch( cp1, p1, 1.0f ) );
a1.add( new PointMatch( cp2, p2, 1.0f ) );
tile.addMatches( a1 );
ArrayList< PointMatch > a2 = new ArrayList<PointMatch>();
if ( is_empty )
{
/**
* very low weight instead of 0.0
*
* TODO nothing could lead to disconntected graphs that were
* connected by one empty tile only...
*/
a2.add( new PointMatch( p1, cp1, 0.1f ) );
a2.add( new PointMatch( p2, cp2, 0.1f ) );
}
else
{
a2.add( new PointMatch( p1, cp1, 1.0f ) );
a2.add( new PointMatch( p2, cp2, 1.0f ) );
}
other_tile.addMatches( a2 );
// and tell them that they are connected now
tile.addConnectedTile( other_tile );
other_tile.addConnectedTile( tile );
}
}
}
}
}
}
static private class TrendObserver
{
public int i; // iteration
public double v; // value
public double d; // first derivative
public double m; // mean
public double var; // variance
public double std; // standard-deviation
public void add( double new_value )
{
if ( i == 0 )
{
i = 1;
v = new_value;
d = 0.0;
m = v;
var = 0.0;
std = 0.0;
}
else
{
d = new_value - v;
v = new_value;
m = ( v + m * ( double )i++ ) / ( double )i;
double tmp = v - m;
var += tmp * tmp / ( double )i;
std = Math.sqrt( var );
}
}
}
/**
* minimize the overall displacement of a set of tiles, propagate the
* estimated models to a corresponding set of patches and redraw
*
* @param tiles
* @param patches
* @param fixed_tiles do not touch these tiles
* @param update_this
*
* TODO revise convergence check
* particularly for unguided minimization, it is hard to identify
* convergence due to presence of local minima
*
* Johannes Schindelin suggested to start from a good guess, which is
* e.g. the propagated unoptimized pose of a tile relative to its
* connected tile that was already identified during RANSAC
* correpondence check. Thank you, Johannes, great hint!
*/
static private final void minimizeAll(
final List< Tile > tiles,
final List< Patch > patches,
final List< Tile > fixed_tiles,
final LayerSet set,
float max_error,
Worker worker)
{
// find all affected layers and disable their buckets
final HashSet<Layer> hsla = new HashSet<Layer>();
for (Patch pa : patches) hsla.add(pa.getLayer());
for (Layer la : hsla) la.setBucketsEnabled(false);
try {
int num_patches = patches.size();
double od = Double.MAX_VALUE;
double dd = Double.MAX_VALUE;
double min_d = Double.MAX_VALUE;
double max_d = Double.MIN_VALUE;
int iteration = 1;
int cc = 0;
double[] dall = new double[100];
int next = 0;
// debug:
//TrendObserver observer = new TrendObserver();
while ( next < 100000 ) // safety check
{
if (worker.hasQuitted()) return;
for ( int i = 0; i < num_patches; ++i )
{
Tile tile = tiles.get( i );
if ( fixed_tiles.contains( tile ) ) continue;
tile.update();
tile.minimizeModel();
tile.update();
patches.get( i ).getAffineTransform().setTransform( tile.getModel().getAffine() );
}
double cd = 0.0;
min_d = Double.MAX_VALUE;
max_d = Double.MIN_VALUE;
for ( Tile t : tiles )
{
t.update();
double d = t.getDistance();
if ( d < min_d ) min_d = d;
if ( d > max_d ) max_d = d;
cd += d;
}
cd /= tiles.size();
dd = Math.abs( od - cd );
od = cd;
if (0 == next % 100) Utils.showStatus( "displacement: " + Utils.cutNumber( od, 3) + " [" + Utils.cutNumber( min_d, 3 ) + "; " + Utils.cutNumber( max_d, 3 ) + "] after " + iteration + " iterations", false);
//observer.add( od );
//Utils.log( observer.i + " " + observer.v + " " + observer.d + " " + observer.m + " " + observer.std );
//cc = d < 0.00025 ? cc + 1 : 0;
cc = dd < 0.001 ? cc + 1 : 0;
if (dall.length == next) {
double[] dall2 = new double[dall.length + 100];
System.arraycopy(dall, 0, dall2, 0, dall.length);
dall = dall2;
}
dall[next++] = dd;
// cut the last 'n'
if (next > 100) { // wait until completing at least 'n' iterations
double[] dn = new double[100];
System.arraycopy(dall, dall.length - 100, dn, 0, 100);
// fit curve
double[] ft = FitLine.fitLine(dn);
// ft[1] StdDev
// ft[2] m (slope)
//if ( Math.abs( ft[ 1 ] ) < 0.001 )
// TODO revise convergence check or start from better guesses
if ( od < max_error && ft[ 2 ] >= 0.0 )
{
Utils.log2( "Exiting at iteration " + next + " with slope " + Utils.cutNumber( ft[ 2 ], 3 ) );
break;
}
}
if (0 == next % 100) Display.update( set );
++iteration;
}
Utils.log2( "Successfully optimized configuration of " + tiles.size() + " tiles:" );
Utils.log2( " average displacement: " + Utils.cutNumber( od, 3 ) + "px" );
Utils.log2( " minimal displacement: " + Utils.cutNumber( min_d, 3 ) + "px" );
Utils.log2( " maximal displacement: " + Utils.cutNumber( max_d, 3 ) + "px" );
} catch (Throwable t) {
IJError.print(t);
}
// re-enable buckets and recreate them.
for (Layer la : hsla) la.setBucketsEnabled(true);
set.getProject().getLoader().recreateBuckets(hsla);
Display.update( set );
}
/**
* Identify point correspondences from two sets of tiles, patches and SIFT-features.
*
* @note List< List< Feature > > should work but doesn't.
* Java "generics" are the crappiest bullshit I have ever seen.
* They should hire a linguist!
*
* @param tiles1
* @param patches1
* @param tiles2
* @param patches2
*/
static private final void identifyCrossLayerCorrespondences(
List< Tile > tiles1,
List< Patch > patches1,
Vector<Feature>[] fsets1, //List< Vector< Feature > > featureSets1,
List< Tile > tiles2,
List< Patch > patches2,
Vector<Feature>[] fsets2, //List< Vector< Feature > > featureSets2,
boolean is_prealigned,
final SIFTParameters sp,
final String storage_folder,
Worker worker)
{
int num_patches2 = patches2.size();
int num_patches1 = patches1.size();
for ( int i = 0; i < num_patches2; ++i )
{
if (worker.hasQuitted()) return;
final Patch current_patch = patches2.get( i );
final Tile current_tile = tiles2.get( i );
final Vector<Feature> fsi = (null == fsets2[i] ? Registration.deserialize(current_patch, sp, storage_folder) : fsets2[i]);
for ( int j = 0; j < num_patches1; ++j )
{
if (worker.hasQuitted()) return;
Patch other_patch = patches1.get( j );
Tile other_tile = tiles1.get( j );
if ( !is_prealigned || current_patch.intersects( other_patch ) )
{
long start_time = System.currentTimeMillis();
System.out.print( "identifying correspondences using brute force ..." );
Vector< PointMatch > candidates = FloatArray2DSIFT.createMatches(
fsi, //featureSets2.get( i ),
(null == fsets1[j] ? Registration.deserialize(other_patch, sp, storage_folder) : fsets1[j]), //featureSets1.get( j ),
1.25f,
null,
Float.MAX_VALUE );
Utils.log2( " took " + ( System.currentTimeMillis() - start_time ) + "ms" );
Utils.log2( "Tiles " + i + " and " + j + " have " + candidates.size() + " potentially corresponding features." );
final Vector< PointMatch > inliers = new Vector< PointMatch >();
TRModel2D mo = TRModel2D.estimateBestModel(
candidates,
inliers,
sp.cs_min_epsilon,
sp.cs_max_epsilon,
sp.min_inlier_ratio);
if ( mo != null )
{
Utils.log2( inliers.size() + " of them are good." );
current_tile.connect( other_tile, inliers );
}
else
{
Utils.log2( "None of them is good." );
}
}
}
}
}
/** Generates a Tile and a Vector of Features for each given patch, and puts them into the given arrays,
* in the same order.
* Multithreaded, runs in as many available CPU cores as possible.
* Will write to fsets only in the event that features cannot be serialized to disk.
*/
static private void generateTilesAndFeatures(final ArrayList<Patch> patches, final Tile[] tls, final Vector[] fsets, final SIFTParameters sp, final String storage_folder, final Worker worker) {
final Thread[] threads = MultiThreading.newThreads();
// roughly, we expect about 1000 features per 512x512 image
final long feature_size = (long)((sp.max_size * sp.max_size) / (512 * 512) * 1000 * FloatArray2DSIFT.getFeatureObjectSize(sp.fdsize, sp.fdbins) * 1.5);
final AtomicInteger ai = new AtomicInteger( 0 ); // from 0 to patches2.length
final int num_pa = patches.size();
final Patch[] pa = new Patch[ num_pa ];
patches.toArray( pa );
final Loader loader = pa[0].getProject().getLoader();
final AtomicInteger count = new AtomicInteger(0);
for (int ithread = 0; ithread < threads.length; ++ithread) {
final int si = ithread;
threads[ ithread ] = new Thread(new Runnable() {
public void run() {
final FloatArray2DSIFT sift = new FloatArray2DSIFT(sp.fdsize, sp.fdbins);
for (int k = ai.getAndIncrement(); k < num_pa; k = ai.getAndIncrement()) {
if (worker.hasQuitted()) return;
//
final Patch patch = pa[k];
// Extract features
Vector<Feature> fs = Registration.deserialize(patch, sp, storage_folder);
if (null == fs) {
final ImageProcessor ip = patch.getImageProcessor();
FloatArray2D fa = ImageArrayConverter.ImageToFloatArray2D(ip.convertToByte(true));
loader.releaseToFit(ip.getWidth() * ip.getHeight() * 96L + feature_size);
ImageFilter.enhance(fa, 1.0f);
fa = ImageFilter.computeGaussianFastMirror(fa, (float)Math.sqrt(sp.initial_sigma * sp.initial_sigma - 0.25));
sift.init(fa, sp.steps, sp.initial_sigma, sp.min_size, sp.max_size);
fs = sift.run(sp.max_size);
Collections.sort(fs);
// store in the array only if serialization fails, such as when impossible to write to disk
if (!Registration.serialize(patch, fs, sp, storage_folder)) {
fsets[k] = fs;
} else fsets[k] = null;
} else {
// don't store
fsets[k] = null;
}
Utils.log2(fs.size() + " features");
// Create Tile, with a specific model:
Model model;
if (0 == sp.dimension) model = new TModel2D(); // translation only
else model = new TRModel2D(); // both translation and rotation
model.getAffine().setTransform(patch.getAffineTransform());
tls[k] = new Tile((float)patch.getWidth(), (float)patch.getHeight(), model);
Utils.showProgress((double)count.incrementAndGet() / num_pa);
Utils.showStatus(new StringBuffer("Extracted features for ").append(count.get()).append('/').append(num_pa).append(" tiles").toString(), false);
}
}
});
}
MultiThreading.startAndJoin(threads);
Utils.showProgress(1);
}
/** Test all to all or all to overlapping only, and make appropriate connections between tiles. */
static private void connectTiles(final ArrayList<Patch> patches, final ArrayList<Tile> tiles, final Vector<Feature>[] fsets, final SIFTParameters sp, final String storage_folder, final Worker worker) {
final int num_patches = patches.size();
final AtomicInteger count = new AtomicInteger(0);
final Lock lock = new Lock();
final AtomicInteger ai = new AtomicInteger(0);
final Thread[] threads = MultiThreading.newThreads();
for (int ithread=0; ithread<threads.length; ithread++) {
threads[ithread] = new Thread() { public void run() {
try {
for ( int i = ai.getAndIncrement(); i < num_patches; i = ai.getAndIncrement() )
{
if (worker.hasQuitted()) return;
final Patch current_patch = patches.get( i );
final Tile current_tile = tiles.get( i );
final Vector<Feature> fsi = (null == fsets[i] ? Registration.deserialize(current_patch, sp, storage_folder) : fsets[i]);
for ( int j = i + 1; j < num_patches; ++j )
{
if (worker.hasQuitted()) return;
final Patch other_patch = patches.get( j );
final Tile other_tile = tiles.get( j );
if ( !sp.tiles_prealigned || current_patch.intersects( other_patch ) )
{
//long start_time = System.currentTimeMillis();
//System.out.print( "Tiles " + i + " and " + j + ": identifying correspondences using brute force ..." );
Vector< PointMatch > correspondences = FloatArray2DSIFT.createMatches(
fsi, // featureSets.get( i ),
(null == fsets[j] ? Registration.deserialize(other_patch, sp, storage_folder) : fsets[j]), //featureSets.get( j ),
1.25f,
null,
Float.MAX_VALUE );
//Utils.log2( " took " + ( System.currentTimeMillis() - start_time ) + "ms" );
Utils.log2( new StringBuffer("Tiles ").append(i).append(" and ").append(j).append(" have ").append(correspondences.size()).append(" potentially corresponding features.").toString() );
final Vector< PointMatch > inliers = new Vector< PointMatch >();
TRModel2D model = TRModel2D.estimateBestModel(
correspondences,
inliers,
sp.min_epsilon,
sp.max_epsilon,
sp.min_inlier_ratio );
if ( model != null ) { // that implies that inliers is not empty
// Global (and excessive) locking, but it's hard to avoid deadlocks
// when in need of synch over two objects at the same time (current_tile and other_tile)
// In addition the connect call is very cheap compared to the model extraction.
synchronized (lock) {
current_tile.connect( other_tile, inliers );
}
}
Utils.showProgress((double)count.incrementAndGet() / num_patches);
Utils.showStatus(new StringBuffer("Connected ").append(count.get()).append('/').append(num_patches).append(" tiles").toString(), false);
}
}
}
} catch (Exception e) {
Utils.log("Failed connecting tiles!");
IJError.print(e);
worker.quit();
}
}};
}
MultiThreading.startAndJoin(threads);
Utils.showProgress(1);
}
/** Will find a fixed tile for each graph, and Will also update each tile.
* Returns the array of fixed tiles, at one per graph.
*/
static private ArrayList<Tile> pickFixedTiles(ArrayList<ArrayList<Tile>> graphs) {
final ArrayList<Tile> fixed_tiles = new ArrayList<Tile>();
// fix one tile per graph, meanwhile update the tiles
for (ArrayList<Tile> graph : graphs) {
Tile fixed = null;
int max_num_matches = 0;
for (Tile tile : graph) {
tile.update();
int num_matches = tile.getNumMatches();
if (max_num_matches < num_matches) {
max_num_matches = num_matches;
fixed = tile;
}
}
fixed_tiles.add(fixed);
}
return fixed_tiles;
}
/** Freely register all-to-all the given set of patches; optionally provide a fixed Patch. Will respect locked tiles. */
static public Bureaucrat registerTilesSIFT(final HashSet<Patch> hs_patches, final Patch fixed, final Registration.SIFTParameters sp_, final boolean overlapping_only) {
if (null == hs_patches || hs_patches.size() < 2) return null;
final LayerSet set = hs_patches.iterator().next().getLayerSet();
final Worker worker_ = new Worker("Free tile registration") {
public void run() {
startedWorking();
try {
//////
final Worker worker = this; // J jate java
SIFTParameters sp = sp_;
if (null == sp) {
sp = new SIFTParameters(set.getProject());
sp.tiles_prealigned = overlapping_only;
if (!sp.setup()) {
finishedWorking();
return;
}
} else {
sp.tiles_prealigned = overlapping_only;
}
// the storage folder for serialized features
String storage_folder = set.getProject().getLoader().getStorageFolder() + "features.ser/";
File sdir = new File(storage_folder);
if (!sdir.exists()) {
try {
sdir.mkdir();
} catch (Exception e) {
storage_folder = null; // can't store
}
}
// java noise: filling datastructures
final ArrayList<Patch> patches = new ArrayList<Patch>();
patches.addAll(hs_patches);
Tile[] tls = new Tile[patches.size()];
Vector[] fsets = new Vector[tls.length];
Registration.generateTilesAndFeatures(patches, tls, fsets, sp, storage_folder, worker);
// java noise: filling datastructures
final ArrayList<Tile> tiles = new ArrayList<Tile>();
//ArrayList<Vector<Feature>> featureSets = new ArrayList<Vector<Feature>>();
for (int k=0; k<tls.length; k++) {
tiles.add(tls[k]);
//featureSets.add(fsets[k]);
}
Registration.connectTiles(patches, tiles, /*featureSets*/ fsets, sp, storage_folder, worker);
//featureSets = null;
ArrayList<ArrayList<Tile>> graphs = Tile.identifyConnectedGraphs(tiles);
Utils.log2(graphs.size() + " graphs detected.");
final ArrayList<Tile> fixed_tiles = new ArrayList<Tile>();
int i = patches.indexOf(fixed);
if (null != fixed && -1 != i && 1 == graphs.size()) {
fixed_tiles.add(tls[i]);
} else {
// find one tile per graph to nail down
fixed_tiles.addAll(Registration.pickFixedTiles(graphs));
}
// in addition, respect locked tiles (add them as fixed if not there already)
int il = 0;
for (Patch patch : patches) {
if (patch.isLocked2() && !fixed_tiles.contains(patch)) fixed_tiles.add(tls[il]);
il++;
}
// again, for error and distance correction
for ( Tile tile : tiles ) tile.update();
// global minimization
Registration.minimizeAll(tiles, patches, fixed_tiles, patches.get(0).getLayerSet(), sp.cs_max_epsilon, worker);
//////
} catch (Exception e) {
e.printStackTrace();
} finally {
finishedWorking();
}
}};
Bureaucrat burro = new Bureaucrat(worker_, set.getProject());
burro.goHaveBreakfast();
return burro;
}
/** A tuple. */
static final class Features implements Serializable {
Registration.SIFTParameters sp;
Vector<Feature> v;
Features(final Registration.SIFTParameters sp, final Vector<Feature> v) {
this.sp = sp;
this.v = v;
}
}
static public boolean serialize(final Patch p, final Vector<Feature> v, final Registration.SIFTParameters sp, final String storage_folder) {
if (null == storage_folder) return false;
final Features fe = new Features(sp, v);
return p.getProject().getLoader().serialize(fe, new StringBuffer(storage_folder).append("features_").append(p.getId()).append(".ser").toString());
}
/** Retrieve the features only if saved with the exact same relevant SIFT parameters. */
static public Vector<Feature> deserialize(final Patch p, final Registration.SIFTParameters sp, final String storage_folder) {
if (null == storage_folder) return null;
final Object ob = p.getProject().getLoader().deserialize(new StringBuffer(storage_folder).append("features_").append(p.getId()).append(".ser").toString());
if (null != ob) {
try {
final Features fe = (Features)ob;
if (sp.sameFeatures(fe.sp) && null != fe.v) {
return fe.v;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
}
| false | true | static public Bureaucrat registerTilesSIFT(final Layer[] layer, final boolean[] options, final int max_size, final float scale) {
if (null == layer || 0 == layer.length) return null;
final boolean overlapping_only = options[0];
final boolean largest_graph_only = options[1];
final boolean hide_other_tiles = options[2];
final boolean delete_other_tiles = options[3];
final boolean show_dialog = options[4];
final Worker worker_ = new Worker("Free tile registration") {
public void run() {
startedWorking();
try {
final Worker worker = this; // J jate java
final LayerSet set = layer[0].getParent();
final String[] dimensions = { "translation", "translation and rotation" };
int dimension_ = 1;
// Parameters for tile-to-tile registration
final SIFTParameters sp = new SIFTParameters(set.getProject(), "Options for tile-to-tile registration", false);
sp.steps = 3;
sp.initial_sigma = 1.6f;
sp.fdsize = 8;
sp.fdbins = 8;
sp.min_size = 64;
sp.max_size = max_size;
sp.min_epsilon = 1.0f;
sp.max_epsilon = 10.0f;
sp.cs_min_epsilon = 1.0f;
sp.cs_max_epsilon = 50.0f;
sp.min_inlier_ratio = 0.05f;
sp.scale = scale;
sp.tiles_prealigned = overlapping_only;
boolean global_optimization = false;
final Registration.SIFTParameters sp_gross_interlayer = new Registration.SIFTParameters(set.getProject(), "Options for coarse layer registration", true);
if (show_dialog) {
// 1 - Simple setup
GenericDialog gds = new GenericDialog("Setup");
gds.addNumericField("maximum_image_size :", sp.max_size, 0);
gds.addNumericField("maximal_alignment_error :", sp.max_epsilon, 2);
gds.addCheckbox("Layers_are_roughly_prealigned", sp.tiles_prealigned);
gds.addCheckbox("Disable global optimization", global_optimization);
gds.addCheckbox("Advanced setup", false);
gds.showDialog();
if (gds.wasCanceled()) {
finishedWorking();
return;
}
sp.max_size = (int)gds.getNextNumber();
sp.max_epsilon = (float)gds.getNextNumber();
sp.tiles_prealigned = gds.getNextBoolean();
global_optimization = gds.getNextBoolean();
boolean advanced_setup = gds.getNextBoolean();
// 2 - Optional advanced setup
if (advanced_setup) {
if (!sp.setup()) {
finishedWorking();
return;
}
// 3 - Inter-layer registration setup
if (!sp_gross_interlayer.setup()) {
finishedWorking();
return;
}
}
}
// start:
final ArrayList< Layer > layers = new ArrayList< Layer >();
for (int k=0; k<layer.length; k++) {
layers.add( layer[k] );
}
//final ArrayList< Vector< Feature > > featureSets1 = new ArrayList< Vector< Feature > >();
//final ArrayList< Vector< Feature > > featureSets2 = new ArrayList< Vector< Feature > >();
//
// fsets1, fsets2 used to be featureSets1, featureSets2
// The elements of these arrays may be null, or may be not.
// When null, the feature set is assumed to have been serialized and thus is retrieved from there.
Vector<Feature>[] fsets1=null, fsets2=null;
final ArrayList< Patch > patches1 = new ArrayList< Patch >();
final ArrayList< Tile > tiles1 = new ArrayList< Tile >();
final ArrayList< Patch > patches2 = new ArrayList< Patch >();
final ArrayList< Tile > tiles2 = new ArrayList< Tile >();
final ArrayList< Tile > all_tiles = new ArrayList< Tile >();
final ArrayList< Patch > all_patches = new ArrayList< Patch >();
final ArrayList< Tile > fixed_tiles = new ArrayList< Tile >();
Layer previous_layer = null;
// the storage folder for serialized features
final Loader loader = set.getProject().getLoader();
String storage_folder_ = loader.getStorageFolder() + "features.ser/";
File sdir = new File(storage_folder_);
if (!sdir.exists()) {
try {
sdir.mkdir();
} catch (Exception e) {
storage_folder_ = null; // can't store
}
}
final String storage_folder = storage_folder_;
for ( Layer layer : layers )
{
if (hasQuitted()) return;
final ArrayList< Tile > layer_fixed_tiles = new ArrayList< Tile >();
Utils.log( "Registering layer " + ( set.indexOf( layer ) + 1 ) + " of " + set.size() );
// ignore empty layers
if ( !layer.contains( Patch.class ) )
{
Utils.log2( "Ignoring empty layer." );
continue;
}
if ( null != previous_layer )
{
//featureSets1.clear();
//featureSets1.addAll( featureSets2 );
fsets1 = fsets2;
patches1.clear();
patches1.addAll( patches2 );
tiles1.clear();
tiles1.addAll( tiles2 );
}
patches2.clear();
//featureSets2.clear();
tiles2.clear();
ArrayList tmp = new ArrayList();
tmp.addAll(layer.getDisplayables( Patch.class ));
patches2.addAll( tmp ); // I hate generics. Incovertible types? Not at all!
// extract SIFT-features in all patches
// (multi threaded version)
// "generic array creation" error ? //fsets2 = new Vector<Feature>[ patches2.size() ];
fsets2 = (Vector<Feature>[])new Vector[ patches2.size() ];
final Tile[] tls = new Tile[ fsets2.length ];
Registration.generateTilesAndFeatures(patches2, tls, fsets2, sp, storage_folder, worker);
if (hasQuitted()) return;
//#################################################################
for ( int k = 0; k < fsets2.length; k++ )
{
//featureSets2.add( fsets2[ k ] );
tiles2.add( tls[ k ] );
}
// identify correspondences and inspect connectivity
Registration.connectTiles(patches2, tiles2, /*featureSets2*/ fsets2, sp, storage_folder, worker);
// identify connected graphs
ArrayList< ArrayList< Tile > > graphs = Tile.identifyConnectedGraphs( tiles2 );
Utils.log2( graphs.size() + " graphs detected." );
if (largest_graph_only) {
final ArrayList<Patch> other_patches = new ArrayList<Patch>();
// remove graphs other than the largest, and remove tiles from tiles2 as well
if (1 != graphs.size()) {
int len = 0;
ArrayList<Tile> largest = null;
for (ArrayList<Tile> graph : graphs) {
if (graph.size() > len) {
len = graph.size();
largest = graph;
}
}
// remove all tiles from tiles2 except those that belong to the largest graph
//tiles2.retainAll(largest); // all other tiles are removed
// Can't ... patches2 would not be in synch, so:
graphs.remove(largest);
for (ArrayList<Tile> graph : graphs) {
for (Tile tile : graph) {
int index = tiles2.indexOf(tile);
other_patches.add(patches2.remove(index));
tiles2.remove(index);
}
}
int n_graphs = graphs.size();
graphs.clear();
graphs.add(largest); // so now graphs contains only one
Utils.log2("Removed " + n_graphs + "\n\t--> focusing on largest graph with " + largest.size() + " tiles.");
}
if (hide_other_tiles || delete_other_tiles) {
if (other_patches.size() > 0) {
for (Patch pa : other_patches) {
if (delete_other_tiles) {
pa.unlink(); // just in case: it could stop all
pa.remove(false);
} else if (hide_other_tiles) pa.setVisible(false);
}
Patch first = other_patches.get(0);
if (delete_other_tiles) Utils.log("Layer " + first.getLayer() + ": Deleted " + other_patches.size() + " images.");
else if (hide_other_tiles) Utils.log("Layer " + first.getLayer() + ": Hided " + other_patches.size() + " images.");
}
}
}
if ( sp.tiles_prealigned && graphs.size() > 1 )
{
/**
* We have to trust the given alignment. Try to add synthetic
* correspondences to disconnected graphs having overlapping
* tiles.
*/
Utils.log2( "Synthetically connecting graphs using the given alignment." );
Registration.connectDisconnectedGraphs( graphs, tiles2, patches2 );
/**
* check the connectivity graphs again. Hopefully there is
* only one graph now. If not, we still have to fix one tile
* per graph, regardless if it is only one or several oth them.
*/
graphs = Tile.identifyConnectedGraphs( tiles2 );
Utils.log2( graphs.size() + " graphs detected after synthetic connection." );
}
// fix one tile per graph, meanwhile update the tiles
layer_fixed_tiles.addAll(Registration.pickFixedTiles(graphs));
// update all tiles, for error and distance correction
for ( Tile tile : tiles2 ) tile.update();
// optimize the pose of all tiles in the current layer
Registration.minimizeAll( tiles2, patches2, layer_fixed_tiles, set, sp.max_epsilon, worker );
// repaint all Displays showing a Layer of the edited LayerSet
Display.update( set );
// store for global minimization
all_tiles.addAll( tiles2 );
all_patches.addAll( patches2 );
if ( null != previous_layer )
{
/**
* 1 - Coarse registration
*
* TODO Think about re-using the correspondences identified
* during coarse registration for the tiles. That introduces
* the following issues:
*
* - coordinate transfer of snapshot-coordinates to
* layer-coordinates in both layers
* - identification of the closest tiles in both layers
* (whose centers are closest to the layer-coordinate of the
* detection)
* - appropriate weight for the correspondence
* - if this is the sole correpondence of a tile, minimization
* as well as model estimation of higher order models than
* translation will fail because of missing information
* -> How to handle this, how to handle this for
* graph-connectivity?
*/
/**
* returns an Object[] with
* [0] AffineTransform that transforms layer towards previous_layer
* [1] bounding box of previous_layer in world coordinates
* [2] bounding box of layer in world coordinates
* [3] true correspondences with p1 in layer and p2 in previous_layer,
* both in the local coordinate frames defined by box1 and box2 and
* scaled with sp_gross_interlayer.scale
*/
Object[] ob = Registration.registerSIFT( previous_layer, layer, null, sp_gross_interlayer );
int original_max_size = sp_gross_interlayer.max_size;
float original_max_epsilon = sp_gross_interlayer.max_epsilon;
while (null == ob || null == ob[0]) {
int next_max_size = sp_gross_interlayer.max_size;
float next_max_epsilon = sp_gross_interlayer.max_epsilon;
// need to recurse up both the max size and the maximal alignment error
if (next_max_epsilon < 300) {
next_max_epsilon += 100;
}
Rectangle rfit1 = previous_layer.getMinimalBoundingBox(Patch.class);
Rectangle rfit2 = layer.getMinimalBoundingBox(Patch.class);
if (next_max_size < rfit1.width || next_max_size < rfit1.height
|| next_max_size < rfit2.width || next_max_size < rfit2.height) {
next_max_size += 1024;
} else {
// fail completely
Utils.log2("FAILED to align layers " + set.indexOf(previous_layer) + " and " + set.indexOf(layer));
// Need to fall back to totally unguided double-layer registration
// TODO
//
break;
}
sp_gross_interlayer.max_size = next_max_size;
sp_gross_interlayer.max_epsilon = next_max_epsilon;
ob = Registration.registerSIFT(previous_layer, layer, null, sp_gross_interlayer);
}
// fix back modified parameters
sp_gross_interlayer.max_size = original_max_size;
sp_gross_interlayer.max_epsilon = original_max_epsilon;
if ( null != ob && null != ob[ 0 ] )
{
// defensive programming ... ;)
AffineTransform at = ( AffineTransform )ob[ 0 ];
Rectangle previous_layer_box = ( Rectangle )ob[ 1 ];
Rectangle layer_box = ( Rectangle )ob[ 2 ];
Vector< PointMatch > inliers = ( Vector< PointMatch > )ob[ 3 ];
/**
* Find the closest tiles in both layers for each of the
* inliers and append a correponding nail to it
*/
for ( PointMatch inlier : inliers )
{
// transfer the coordinates to actual world coordinates
float[] previous_layer_coords = inlier.getP2().getL();
previous_layer_coords[ 0 ] = previous_layer_coords[ 0 ] / sp_gross_interlayer.scale + previous_layer_box.x;
previous_layer_coords[ 1 ] = previous_layer_coords[ 1 ] / sp_gross_interlayer.scale + previous_layer_box.y;
float[] layer_coords = inlier.getP1().getL();
layer_coords[ 0 ] = layer_coords[ 0 ] / sp_gross_interlayer.scale + layer_box.x;
layer_coords[ 1 ] = layer_coords[ 1 ] / sp_gross_interlayer.scale + layer_box.y;
// find the tile whose center is closest to the points in previous_layer
Tile previous_layer_closest_tile = null;
float previous_layer_min_d = Float.MAX_VALUE;
for ( Tile tile : tiles1 )
{
tile.update();
float[] tw = tile.getWC();
float dx = tw[ 0 ] - previous_layer_coords[ 0 ];
dx *= dx;
float dy = tw[ 1 ] - previous_layer_coords[ 1 ];
dy *= dy;
float d = ( float )Math.sqrt( dx + dy );
if ( d < previous_layer_min_d )
{
previous_layer_min_d = d;
previous_layer_closest_tile = tile;
}
}
Utils.log2( "Tile " + tiles1.indexOf( previous_layer_closest_tile ) + " is closest in previous layer:" );
Utils.log2( " distance: " + previous_layer_min_d );
// find the tile whose center is closest to the points in layer
Tile layer_closest_tile = null;
float layer_min_d = Float.MAX_VALUE;
for ( Tile tile : tiles2 )
{
tile.update();
float[] tw = tile.getWC();
float dx = tw[ 0 ] - layer_coords[ 0 ];
dx *= dx;
float dy = tw[ 1 ] - layer_coords[ 1 ];
dy *= dy;
float d = ( float )Math.sqrt( dx + dy );
if ( d < layer_min_d )
{
layer_min_d = d;
layer_closest_tile = tile;
}
}
Utils.log2( "Tile " + tiles2.indexOf( layer_closest_tile ) + " is closest in layer:" );
Utils.log2( " distance: " + layer_min_d );
if ( previous_layer_closest_tile != null && layer_closest_tile != null )
{
// Utils.log2( "world coordinates in previous layer: " + previous_layer_coords[ 0 ] + ", " + previous_layer_coords[ 1 ] );
// Utils.log2( "world coordinates in layer: " + layer_coords[ 0 ] + ", " + layer_coords[ 1 ] );
// transfer the world coordinates to local tile coordinates
previous_layer_closest_tile.getModel().applyInverseInPlace( previous_layer_coords );
layer_closest_tile.getModel().applyInverseInPlace( layer_coords );
// Utils.log2( "local coordinates in previous layer: " + previous_layer_coords[ 0 ] + ", " + previous_layer_coords[ 1 ] );
// Utils.log2( "local coordinates in layer: " + layer_coords[ 0 ] + ", " + layer_coords[ 1 ] );
// create PointMatch for both tiles
mpi.fruitfly.registration.Point previous_layer_point = new mpi.fruitfly.registration.Point( previous_layer_coords );
mpi.fruitfly.registration.Point layer_point = new mpi.fruitfly.registration.Point( layer_coords );
previous_layer_closest_tile.addMatch(
new PointMatch(
previous_layer_point,
layer_point,
inlier.getWeight() / sp_gross_interlayer.scale ) );
layer_closest_tile.addMatch(
new PointMatch(
layer_point,
previous_layer_point,
inlier.getWeight() / sp_gross_interlayer.scale ) );
previous_layer_closest_tile.addConnectedTile( layer_closest_tile );
layer_closest_tile.addConnectedTile( previous_layer_closest_tile );
}
}
TRModel2D model = new TRModel2D();
model.getAffine().setTransform( at );
for ( Tile tile : tiles2 )
( ( TRModel2D )tile.getModel() ).preConcatenate( model );
// repaint all Displays showing a Layer of the edited LayerSet
layer.recreateBuckets();
Display.update( layer );
}
Registration.identifyCrossLayerCorrespondences(
tiles1,
patches1,
fsets1 /*featureSets1*/,
tiles2,
patches2,
fsets2 /*featureSets2*/,
( null != ob && null != ob[ 0 ] ),
sp,
storage_folder,
worker);
// check the connectivity graphs
ArrayList< Tile > both_layer_tiles = new ArrayList< Tile >();
both_layer_tiles.addAll( tiles1 );
both_layer_tiles.addAll( tiles2 );
graphs = Tile.identifyConnectedGraphs( both_layer_tiles );
Utils.log2( graphs.size() + " cross-section graphs detected." );
// if ( graphs.size() > 1 && ( null != ob && null != ob[ 0 ] ) )
// {
// /**
// * We have to trust the given alignment. Try to add synthetic
// * correspondences to disconnected graphs having overlapping
// * tiles.
// */
// ArrayList< Patch > both_layer_patches = new ArrayList< Patch >();
// both_layer_patches.addAll( patches1 );
// both_layer_patches.addAll( patches2 );
// this.connectDisconnectedGraphs( graphs, both_layer_tiles, both_layer_patches );
//
// /**
// * check the connectivity graphs again. Hopefully there is
// * only one graph now. If not, we still have to fix one tile
// * per graph, regardless if it is only one or several of them.
// */
// graphs = Tile.identifyConnectedGraphs( tiles2 );
// Utils.log2( graphs.size() + " cross-section graphs detected after synthetic connection." );
// }
}
previous_layer = layer;
}
// find the global nail
/**
* One tile per connected graph has to be fixed to make the problem
* solvable, otherwise it is ill defined and has an infinite number
* of solutions.
*/
ArrayList< ArrayList< Tile > > graphs = Tile.identifyConnectedGraphs( all_tiles );
Utils.log2( graphs.size() + " global graphs detected." );
fixed_tiles.clear();
// fix one tile per graph, meanwhile update the tiles
fixed_tiles.addAll(Registration.pickFixedTiles(graphs));
// again, for error and distance correction
for ( Tile tile : all_tiles ) tile.update();
// global minimization
try {
if (global_optimization) {
Utils.log("Performing global minimization...");
Registration.minimizeAll( all_tiles, all_patches, fixed_tiles, set, sp.cs_max_epsilon, worker );
Utils.log("Done!");
}
} catch (Throwable t) {
IJError.print(t);
}
// update selection internals in all open Displays
Display.updateSelection( Display.getFront() );
// repaint all Displays showing a Layer of the edited LayerSet
Display.update( set );
} catch (Exception e) {
e.printStackTrace();
} finally {
finishedWorking();
}
}};
Bureaucrat burro = new Bureaucrat(worker_, layer[0].getProject());
burro.goHaveBreakfast();
return burro;
}
| static public Bureaucrat registerTilesSIFT(final Layer[] layer, final boolean[] options, final int max_size, final float scale) {
if (null == layer || 0 == layer.length) return null;
final boolean overlapping_only = options[0];
final boolean largest_graph_only = options[1];
final boolean hide_other_tiles = options[2];
final boolean delete_other_tiles = options[3];
final boolean show_dialog = options[4];
final Worker worker_ = new Worker("Free tile registration") {
public void run() {
startedWorking();
try {
final Worker worker = this; // J jate java
final LayerSet set = layer[0].getParent();
final String[] dimensions = { "translation", "translation and rotation" };
int dimension_ = 1;
// Parameters for tile-to-tile registration
final SIFTParameters sp = new SIFTParameters(set.getProject(), "Options for tile-to-tile registration", false);
sp.steps = 3;
sp.initial_sigma = 1.6f;
sp.fdsize = 8;
sp.fdbins = 8;
sp.min_size = 64;
sp.max_size = max_size;
sp.min_epsilon = 1.0f;
sp.max_epsilon = 10.0f;
sp.cs_min_epsilon = 1.0f;
sp.cs_max_epsilon = 50.0f;
sp.min_inlier_ratio = 0.05f;
sp.scale = scale;
sp.tiles_prealigned = overlapping_only;
boolean global_optimization = true;
final Registration.SIFTParameters sp_gross_interlayer = new Registration.SIFTParameters(set.getProject(), "Options for coarse layer registration", true);
if (show_dialog) {
// 1 - Simple setup
GenericDialog gds = new GenericDialog("Setup");
gds.addNumericField("maximum_image_size :", sp.max_size, 0);
gds.addNumericField("maximal_alignment_error :", sp.max_epsilon, 2);
gds.addCheckbox("Layers_are_roughly_prealigned", sp.tiles_prealigned);
gds.addCheckbox("Disable global optimization", !global_optimization);
gds.addCheckbox("Advanced setup", false);
gds.showDialog();
if (gds.wasCanceled()) {
finishedWorking();
return;
}
sp.max_size = (int)gds.getNextNumber();
sp.max_epsilon = (float)gds.getNextNumber();
sp.tiles_prealigned = gds.getNextBoolean();
global_optimization = !gds.getNextBoolean();
boolean advanced_setup = gds.getNextBoolean();
// 2 - Optional advanced setup
if (advanced_setup) {
if (!sp.setup()) {
finishedWorking();
return;
}
// 3 - Inter-layer registration setup
if (!sp_gross_interlayer.setup()) {
finishedWorking();
return;
}
}
}
// start:
final ArrayList< Layer > layers = new ArrayList< Layer >();
for (int k=0; k<layer.length; k++) {
layers.add( layer[k] );
}
//final ArrayList< Vector< Feature > > featureSets1 = new ArrayList< Vector< Feature > >();
//final ArrayList< Vector< Feature > > featureSets2 = new ArrayList< Vector< Feature > >();
//
// fsets1, fsets2 used to be featureSets1, featureSets2
// The elements of these arrays may be null, or may be not.
// When null, the feature set is assumed to have been serialized and thus is retrieved from there.
Vector<Feature>[] fsets1=null, fsets2=null;
final ArrayList< Patch > patches1 = new ArrayList< Patch >();
final ArrayList< Tile > tiles1 = new ArrayList< Tile >();
final ArrayList< Patch > patches2 = new ArrayList< Patch >();
final ArrayList< Tile > tiles2 = new ArrayList< Tile >();
final ArrayList< Tile > all_tiles = new ArrayList< Tile >();
final ArrayList< Patch > all_patches = new ArrayList< Patch >();
final ArrayList< Tile > fixed_tiles = new ArrayList< Tile >();
Layer previous_layer = null;
// the storage folder for serialized features
final Loader loader = set.getProject().getLoader();
String storage_folder_ = loader.getStorageFolder() + "features.ser/";
File sdir = new File(storage_folder_);
if (!sdir.exists()) {
try {
sdir.mkdir();
} catch (Exception e) {
storage_folder_ = null; // can't store
}
}
final String storage_folder = storage_folder_;
for ( Layer layer : layers )
{
if (hasQuitted()) return;
final ArrayList< Tile > layer_fixed_tiles = new ArrayList< Tile >();
Utils.log( "Registering layer " + ( set.indexOf( layer ) + 1 ) + " of " + set.size() );
// ignore empty layers
if ( !layer.contains( Patch.class ) )
{
Utils.log2( "Ignoring empty layer." );
continue;
}
if ( null != previous_layer )
{
//featureSets1.clear();
//featureSets1.addAll( featureSets2 );
fsets1 = fsets2;
patches1.clear();
patches1.addAll( patches2 );
tiles1.clear();
tiles1.addAll( tiles2 );
}
patches2.clear();
//featureSets2.clear();
tiles2.clear();
ArrayList tmp = new ArrayList();
tmp.addAll(layer.getDisplayables( Patch.class ));
patches2.addAll( tmp ); // I hate generics. Incovertible types? Not at all!
// extract SIFT-features in all patches
// (multi threaded version)
// "generic array creation" error ? //fsets2 = new Vector<Feature>[ patches2.size() ];
fsets2 = (Vector<Feature>[])new Vector[ patches2.size() ];
final Tile[] tls = new Tile[ fsets2.length ];
Registration.generateTilesAndFeatures(patches2, tls, fsets2, sp, storage_folder, worker);
if (hasQuitted()) return;
//#################################################################
for ( int k = 0; k < fsets2.length; k++ )
{
//featureSets2.add( fsets2[ k ] );
tiles2.add( tls[ k ] );
}
// identify correspondences and inspect connectivity
Registration.connectTiles(patches2, tiles2, /*featureSets2*/ fsets2, sp, storage_folder, worker);
// identify connected graphs
ArrayList< ArrayList< Tile > > graphs = Tile.identifyConnectedGraphs( tiles2 );
Utils.log2( graphs.size() + " graphs detected." );
if (largest_graph_only) {
final ArrayList<Patch> other_patches = new ArrayList<Patch>();
// remove graphs other than the largest, and remove tiles from tiles2 as well
if (1 != graphs.size()) {
int len = 0;
ArrayList<Tile> largest = null;
for (ArrayList<Tile> graph : graphs) {
if (graph.size() > len) {
len = graph.size();
largest = graph;
}
}
// remove all tiles from tiles2 except those that belong to the largest graph
//tiles2.retainAll(largest); // all other tiles are removed
// Can't ... patches2 would not be in synch, so:
graphs.remove(largest);
for (ArrayList<Tile> graph : graphs) {
for (Tile tile : graph) {
int index = tiles2.indexOf(tile);
other_patches.add(patches2.remove(index));
tiles2.remove(index);
}
}
int n_graphs = graphs.size();
graphs.clear();
graphs.add(largest); // so now graphs contains only one
Utils.log2("Removed " + n_graphs + "\n\t--> focusing on largest graph with " + largest.size() + " tiles.");
}
if (hide_other_tiles || delete_other_tiles) {
if (other_patches.size() > 0) {
for (Patch pa : other_patches) {
if (delete_other_tiles) {
pa.unlink(); // just in case: it could stop all
pa.remove(false);
} else if (hide_other_tiles) pa.setVisible(false);
}
Patch first = other_patches.get(0);
if (delete_other_tiles) Utils.log("Layer " + first.getLayer() + ": Deleted " + other_patches.size() + " images.");
else if (hide_other_tiles) Utils.log("Layer " + first.getLayer() + ": Hided " + other_patches.size() + " images.");
}
}
}
if ( sp.tiles_prealigned && graphs.size() > 1 )
{
/**
* We have to trust the given alignment. Try to add synthetic
* correspondences to disconnected graphs having overlapping
* tiles.
*/
Utils.log2( "Synthetically connecting graphs using the given alignment." );
Registration.connectDisconnectedGraphs( graphs, tiles2, patches2 );
/**
* check the connectivity graphs again. Hopefully there is
* only one graph now. If not, we still have to fix one tile
* per graph, regardless if it is only one or several oth them.
*/
graphs = Tile.identifyConnectedGraphs( tiles2 );
Utils.log2( graphs.size() + " graphs detected after synthetic connection." );
}
// fix one tile per graph, meanwhile update the tiles
layer_fixed_tiles.addAll(Registration.pickFixedTiles(graphs));
// update all tiles, for error and distance correction
for ( Tile tile : tiles2 ) tile.update();
// optimize the pose of all tiles in the current layer
Registration.minimizeAll( tiles2, patches2, layer_fixed_tiles, set, sp.max_epsilon, worker );
// repaint all Displays showing a Layer of the edited LayerSet
Display.update( set );
// store for global minimization
all_tiles.addAll( tiles2 );
all_patches.addAll( patches2 );
if ( null != previous_layer )
{
/**
* 1 - Coarse registration
*
* TODO Think about re-using the correspondences identified
* during coarse registration for the tiles. That introduces
* the following issues:
*
* - coordinate transfer of snapshot-coordinates to
* layer-coordinates in both layers
* - identification of the closest tiles in both layers
* (whose centers are closest to the layer-coordinate of the
* detection)
* - appropriate weight for the correspondence
* - if this is the sole correpondence of a tile, minimization
* as well as model estimation of higher order models than
* translation will fail because of missing information
* -> How to handle this, how to handle this for
* graph-connectivity?
*/
/**
* returns an Object[] with
* [0] AffineTransform that transforms layer towards previous_layer
* [1] bounding box of previous_layer in world coordinates
* [2] bounding box of layer in world coordinates
* [3] true correspondences with p1 in layer and p2 in previous_layer,
* both in the local coordinate frames defined by box1 and box2 and
* scaled with sp_gross_interlayer.scale
*/
Object[] ob = Registration.registerSIFT( previous_layer, layer, null, sp_gross_interlayer );
int original_max_size = sp_gross_interlayer.max_size;
float original_max_epsilon = sp_gross_interlayer.max_epsilon;
while (null == ob || null == ob[0]) {
int next_max_size = sp_gross_interlayer.max_size;
float next_max_epsilon = sp_gross_interlayer.max_epsilon;
// need to recurse up both the max size and the maximal alignment error
if (next_max_epsilon < 300) {
next_max_epsilon += 100;
}
Rectangle rfit1 = previous_layer.getMinimalBoundingBox(Patch.class);
Rectangle rfit2 = layer.getMinimalBoundingBox(Patch.class);
if (next_max_size < rfit1.width || next_max_size < rfit1.height
|| next_max_size < rfit2.width || next_max_size < rfit2.height) {
next_max_size += 1024;
} else {
// fail completely
Utils.log2("FAILED to align layers " + set.indexOf(previous_layer) + " and " + set.indexOf(layer));
// Need to fall back to totally unguided double-layer registration
// TODO
//
break;
}
sp_gross_interlayer.max_size = next_max_size;
sp_gross_interlayer.max_epsilon = next_max_epsilon;
ob = Registration.registerSIFT(previous_layer, layer, null, sp_gross_interlayer);
}
// fix back modified parameters
sp_gross_interlayer.max_size = original_max_size;
sp_gross_interlayer.max_epsilon = original_max_epsilon;
if ( null != ob && null != ob[ 0 ] )
{
// defensive programming ... ;)
AffineTransform at = ( AffineTransform )ob[ 0 ];
Rectangle previous_layer_box = ( Rectangle )ob[ 1 ];
Rectangle layer_box = ( Rectangle )ob[ 2 ];
Vector< PointMatch > inliers = ( Vector< PointMatch > )ob[ 3 ];
/**
* Find the closest tiles in both layers for each of the
* inliers and append a correponding nail to it
*/
for ( PointMatch inlier : inliers )
{
// transfer the coordinates to actual world coordinates
float[] previous_layer_coords = inlier.getP2().getL();
previous_layer_coords[ 0 ] = previous_layer_coords[ 0 ] / sp_gross_interlayer.scale + previous_layer_box.x;
previous_layer_coords[ 1 ] = previous_layer_coords[ 1 ] / sp_gross_interlayer.scale + previous_layer_box.y;
float[] layer_coords = inlier.getP1().getL();
layer_coords[ 0 ] = layer_coords[ 0 ] / sp_gross_interlayer.scale + layer_box.x;
layer_coords[ 1 ] = layer_coords[ 1 ] / sp_gross_interlayer.scale + layer_box.y;
// find the tile whose center is closest to the points in previous_layer
Tile previous_layer_closest_tile = null;
float previous_layer_min_d = Float.MAX_VALUE;
for ( Tile tile : tiles1 )
{
tile.update();
float[] tw = tile.getWC();
float dx = tw[ 0 ] - previous_layer_coords[ 0 ];
dx *= dx;
float dy = tw[ 1 ] - previous_layer_coords[ 1 ];
dy *= dy;
float d = ( float )Math.sqrt( dx + dy );
if ( d < previous_layer_min_d )
{
previous_layer_min_d = d;
previous_layer_closest_tile = tile;
}
}
Utils.log2( "Tile " + tiles1.indexOf( previous_layer_closest_tile ) + " is closest in previous layer:" );
Utils.log2( " distance: " + previous_layer_min_d );
// find the tile whose center is closest to the points in layer
Tile layer_closest_tile = null;
float layer_min_d = Float.MAX_VALUE;
for ( Tile tile : tiles2 )
{
tile.update();
float[] tw = tile.getWC();
float dx = tw[ 0 ] - layer_coords[ 0 ];
dx *= dx;
float dy = tw[ 1 ] - layer_coords[ 1 ];
dy *= dy;
float d = ( float )Math.sqrt( dx + dy );
if ( d < layer_min_d )
{
layer_min_d = d;
layer_closest_tile = tile;
}
}
Utils.log2( "Tile " + tiles2.indexOf( layer_closest_tile ) + " is closest in layer:" );
Utils.log2( " distance: " + layer_min_d );
if ( previous_layer_closest_tile != null && layer_closest_tile != null )
{
// Utils.log2( "world coordinates in previous layer: " + previous_layer_coords[ 0 ] + ", " + previous_layer_coords[ 1 ] );
// Utils.log2( "world coordinates in layer: " + layer_coords[ 0 ] + ", " + layer_coords[ 1 ] );
// transfer the world coordinates to local tile coordinates
previous_layer_closest_tile.getModel().applyInverseInPlace( previous_layer_coords );
layer_closest_tile.getModel().applyInverseInPlace( layer_coords );
// Utils.log2( "local coordinates in previous layer: " + previous_layer_coords[ 0 ] + ", " + previous_layer_coords[ 1 ] );
// Utils.log2( "local coordinates in layer: " + layer_coords[ 0 ] + ", " + layer_coords[ 1 ] );
// create PointMatch for both tiles
mpi.fruitfly.registration.Point previous_layer_point = new mpi.fruitfly.registration.Point( previous_layer_coords );
mpi.fruitfly.registration.Point layer_point = new mpi.fruitfly.registration.Point( layer_coords );
previous_layer_closest_tile.addMatch(
new PointMatch(
previous_layer_point,
layer_point,
inlier.getWeight() / sp_gross_interlayer.scale ) );
layer_closest_tile.addMatch(
new PointMatch(
layer_point,
previous_layer_point,
inlier.getWeight() / sp_gross_interlayer.scale ) );
previous_layer_closest_tile.addConnectedTile( layer_closest_tile );
layer_closest_tile.addConnectedTile( previous_layer_closest_tile );
}
}
TRModel2D model = new TRModel2D();
model.getAffine().setTransform( at );
for ( Tile tile : tiles2 )
( ( TRModel2D )tile.getModel() ).preConcatenate( model );
// repaint all Displays showing a Layer of the edited LayerSet
layer.recreateBuckets();
Display.update( layer );
}
Registration.identifyCrossLayerCorrespondences(
tiles1,
patches1,
fsets1 /*featureSets1*/,
tiles2,
patches2,
fsets2 /*featureSets2*/,
( null != ob && null != ob[ 0 ] ),
sp,
storage_folder,
worker);
// check the connectivity graphs
ArrayList< Tile > both_layer_tiles = new ArrayList< Tile >();
both_layer_tiles.addAll( tiles1 );
both_layer_tiles.addAll( tiles2 );
graphs = Tile.identifyConnectedGraphs( both_layer_tiles );
Utils.log2( graphs.size() + " cross-section graphs detected." );
// if ( graphs.size() > 1 && ( null != ob && null != ob[ 0 ] ) )
// {
// /**
// * We have to trust the given alignment. Try to add synthetic
// * correspondences to disconnected graphs having overlapping
// * tiles.
// */
// ArrayList< Patch > both_layer_patches = new ArrayList< Patch >();
// both_layer_patches.addAll( patches1 );
// both_layer_patches.addAll( patches2 );
// this.connectDisconnectedGraphs( graphs, both_layer_tiles, both_layer_patches );
//
// /**
// * check the connectivity graphs again. Hopefully there is
// * only one graph now. If not, we still have to fix one tile
// * per graph, regardless if it is only one or several of them.
// */
// graphs = Tile.identifyConnectedGraphs( tiles2 );
// Utils.log2( graphs.size() + " cross-section graphs detected after synthetic connection." );
// }
}
previous_layer = layer;
}
// find the global nail
/**
* One tile per connected graph has to be fixed to make the problem
* solvable, otherwise it is ill defined and has an infinite number
* of solutions.
*/
ArrayList< ArrayList< Tile > > graphs = Tile.identifyConnectedGraphs( all_tiles );
Utils.log2( graphs.size() + " global graphs detected." );
fixed_tiles.clear();
// fix one tile per graph, meanwhile update the tiles
fixed_tiles.addAll(Registration.pickFixedTiles(graphs));
// again, for error and distance correction
for ( Tile tile : all_tiles ) tile.update();
// global minimization
try {
if (global_optimization) {
Utils.log("Performing global minimization...");
Registration.minimizeAll( all_tiles, all_patches, fixed_tiles, set, sp.cs_max_epsilon, worker );
Utils.log("Done!");
}
} catch (Throwable t) {
IJError.print(t);
}
// update selection internals in all open Displays
Display.updateSelection( Display.getFront() );
// repaint all Displays showing a Layer of the edited LayerSet
Display.update( set );
} catch (Exception e) {
e.printStackTrace();
} finally {
finishedWorking();
}
}};
Bureaucrat burro = new Bureaucrat(worker_, layer[0].getProject());
burro.goHaveBreakfast();
return burro;
}
|
diff --git a/src/com/android/email/mail/transport/SmtpSender.java b/src/com/android/email/mail/transport/SmtpSender.java
index 71a86306..a9b13a66 100644
--- a/src/com/android/email/mail/transport/SmtpSender.java
+++ b/src/com/android/email/mail/transport/SmtpSender.java
@@ -1,334 +1,334 @@
/*
* 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.email.mail.transport;
import android.content.Context;
import android.util.Base64;
import android.util.Log;
import com.android.email.Email;
import com.android.email.mail.Sender;
import com.android.email.mail.Transport;
import com.android.emailcommon.Logging;
import com.android.emailcommon.internet.Rfc822Output;
import com.android.emailcommon.mail.Address;
import com.android.emailcommon.mail.AuthenticationFailedException;
import com.android.emailcommon.mail.CertificateValidationException;
import com.android.emailcommon.mail.MessagingException;
import com.android.emailcommon.provider.Account;
import com.android.emailcommon.provider.EmailContent.Message;
import com.android.emailcommon.provider.HostAuth;
import java.io.IOException;
import java.net.Inet6Address;
import java.net.InetAddress;
import javax.net.ssl.SSLException;
/**
* This class handles all of the protocol-level aspects of sending messages via SMTP.
* TODO Remove dependence upon URI; there's no reason why we need it here
*/
public class SmtpSender extends Sender {
private final Context mContext;
private Transport mTransport;
private String mUsername;
private String mPassword;
/**
* Static named constructor.
*/
public static Sender newInstance(Account account, Context context) throws MessagingException {
return new SmtpSender(context, account);
}
/**
* Creates a new sender for the given account.
*/
private SmtpSender(Context context, Account account) throws MessagingException {
mContext = context;
HostAuth sendAuth = account.getOrCreateHostAuthSend(context);
if (sendAuth == null || !"smtp".equalsIgnoreCase(sendAuth.mProtocol)) {
throw new MessagingException("Unsupported protocol");
}
// defaults, which can be changed by security modifiers
int connectionSecurity = Transport.CONNECTION_SECURITY_NONE;
int defaultPort = 587;
// check for security flags and apply changes
if ((sendAuth.mFlags & HostAuth.FLAG_SSL) != 0) {
connectionSecurity = Transport.CONNECTION_SECURITY_SSL;
defaultPort = 465;
} else if ((sendAuth.mFlags & HostAuth.FLAG_TLS) != 0) {
connectionSecurity = Transport.CONNECTION_SECURITY_TLS;
}
boolean trustCertificates = ((sendAuth.mFlags & HostAuth.FLAG_TRUST_ALL) != 0);
int port = defaultPort;
if (sendAuth.mPort != HostAuth.PORT_UNKNOWN) {
port = sendAuth.mPort;
}
mTransport = new MailTransport("IMAP");
mTransport.setHost(sendAuth.mAddress);
mTransport.setPort(port);
mTransport.setSecurity(connectionSecurity, trustCertificates);
String[] userInfoParts = sendAuth.getLogin();
if (userInfoParts != null) {
mUsername = userInfoParts[0];
mPassword = userInfoParts[1];
}
}
/**
* For testing only. Injects a different transport. The transport should already be set
* up and ready to use. Do not use for real code.
* @param testTransport The Transport to inject and use for all future communication.
*/
/* package */ void setTransport(Transport testTransport) {
mTransport = testTransport;
}
@Override
public void open() throws MessagingException {
try {
mTransport.open();
// Eat the banner
executeSimpleCommand(null);
String localHost = "localhost";
// Try to get local address in the proper format.
InetAddress localAddress = mTransport.getLocalAddress();
if (localAddress != null) {
// Address Literal formatted in accordance to RFC2821 Sec. 4.1.3
StringBuilder sb = new StringBuilder();
sb.append('[');
if (localAddress instanceof Inet6Address) {
sb.append("IPv6:");
}
sb.append(localAddress.getHostAddress());
sb.append(']');
localHost = sb.toString();
}
String result = executeSimpleCommand("EHLO " + localHost);
/*
* TODO may need to add code to fall back to HELO I switched it from
* using HELO on non STARTTLS connections because of AOL's mail
* server. It won't let you use AUTH without EHLO.
* We should really be paying more attention to the capabilities
* and only attempting auth if it's available, and warning the user
* if not.
*/
if (mTransport.canTryTlsSecurity()) {
- if (result.contains("-STARTTLS")) {
+ if (result.contains("STARTTLS")) {
executeSimpleCommand("STARTTLS");
mTransport.reopenTls();
/*
* Now resend the EHLO. Required by RFC2487 Sec. 5.2, and more specifically,
* Exim.
*/
result = executeSimpleCommand("EHLO " + localHost);
} else {
if (Email.DEBUG) {
Log.d(Logging.LOG_TAG, "TLS not supported but required");
}
throw new MessagingException(MessagingException.TLS_REQUIRED);
}
}
/*
* result contains the results of the EHLO in concatenated form
*/
boolean authLoginSupported = result.matches(".*AUTH.*LOGIN.*$");
boolean authPlainSupported = result.matches(".*AUTH.*PLAIN.*$");
if (mUsername != null && mUsername.length() > 0 && mPassword != null
&& mPassword.length() > 0) {
if (authPlainSupported) {
saslAuthPlain(mUsername, mPassword);
}
else if (authLoginSupported) {
saslAuthLogin(mUsername, mPassword);
}
else {
if (Email.DEBUG) {
Log.d(Logging.LOG_TAG, "No valid authentication mechanism found.");
}
throw new MessagingException(MessagingException.AUTH_REQUIRED);
}
}
} catch (SSLException e) {
if (Email.DEBUG) {
Log.d(Logging.LOG_TAG, e.toString());
}
throw new CertificateValidationException(e.getMessage(), e);
} catch (IOException ioe) {
if (Email.DEBUG) {
Log.d(Logging.LOG_TAG, ioe.toString());
}
throw new MessagingException(MessagingException.IOERROR, ioe.toString());
}
}
@Override
public void sendMessage(long messageId) throws MessagingException {
close();
open();
Message message = Message.restoreMessageWithId(mContext, messageId);
if (message == null) {
throw new MessagingException("Trying to send non-existent message id="
+ Long.toString(messageId));
}
Address from = Address.unpackFirst(message.mFrom);
Address[] to = Address.unpack(message.mTo);
Address[] cc = Address.unpack(message.mCc);
Address[] bcc = Address.unpack(message.mBcc);
try {
executeSimpleCommand("MAIL FROM: " + "<" + from.getAddress() + ">");
for (Address address : to) {
executeSimpleCommand("RCPT TO: " + "<" + address.getAddress() + ">");
}
for (Address address : cc) {
executeSimpleCommand("RCPT TO: " + "<" + address.getAddress() + ">");
}
for (Address address : bcc) {
executeSimpleCommand("RCPT TO: " + "<" + address.getAddress() + ">");
}
executeSimpleCommand("DATA");
// TODO byte stuffing
Rfc822Output.writeTo(mContext, messageId,
new EOLConvertingOutputStream(mTransport.getOutputStream()),
false /* do not use smart reply */,
false /* do not send BCC */);
executeSimpleCommand("\r\n.");
} catch (IOException ioe) {
throw new MessagingException("Unable to send message", ioe);
}
}
/**
* Close the protocol (and the transport below it).
*
* MUST NOT return any exceptions.
*/
@Override
public void close() {
mTransport.close();
}
/**
* Send a single command and wait for a single response. Handles responses that continue
* onto multiple lines. Throws MessagingException if response code is 4xx or 5xx. All traffic
* is logged (if debug logging is enabled) so do not use this function for user ID or password.
*
* @param command The command string to send to the server.
* @return Returns the response string from the server.
*/
private String executeSimpleCommand(String command) throws IOException, MessagingException {
return executeSensitiveCommand(command, null);
}
/**
* Send a single command and wait for a single response. Handles responses that continue
* onto multiple lines. Throws MessagingException if response code is 4xx or 5xx.
*
* @param command The command string to send to the server.
* @param sensitiveReplacement If the command includes sensitive data (e.g. authentication)
* please pass a replacement string here (for logging).
* @return Returns the response string from the server.
*/
private String executeSensitiveCommand(String command, String sensitiveReplacement)
throws IOException, MessagingException {
if (command != null) {
mTransport.writeLine(command, sensitiveReplacement);
}
String line = mTransport.readLine();
String result = line;
while (line.length() >= 4 && line.charAt(3) == '-') {
line = mTransport.readLine();
result += line.substring(3);
}
if (result.length() > 0) {
char c = result.charAt(0);
if ((c == '4') || (c == '5')) {
throw new MessagingException(result);
}
}
return result;
}
// C: AUTH LOGIN
// S: 334 VXNlcm5hbWU6
// C: d2VsZG9u
// S: 334 UGFzc3dvcmQ6
// C: dzNsZDBu
// S: 235 2.0.0 OK Authenticated
//
// Lines 2-5 of the conversation contain base64-encoded information. The same conversation, with base64 strings decoded, reads:
//
//
// C: AUTH LOGIN
// S: 334 Username:
// C: weldon
// S: 334 Password:
// C: w3ld0n
// S: 235 2.0.0 OK Authenticated
private void saslAuthLogin(String username, String password) throws MessagingException,
AuthenticationFailedException, IOException {
try {
executeSimpleCommand("AUTH LOGIN");
executeSensitiveCommand(
Base64.encodeToString(username.getBytes(), Base64.NO_WRAP),
"/username redacted/");
executeSensitiveCommand(
Base64.encodeToString(password.getBytes(), Base64.NO_WRAP),
"/password redacted/");
}
catch (MessagingException me) {
if (me.getMessage().length() > 1 && me.getMessage().charAt(1) == '3') {
throw new AuthenticationFailedException(me.getMessage());
}
throw me;
}
}
private void saslAuthPlain(String username, String password) throws MessagingException,
AuthenticationFailedException, IOException {
byte[] data = ("\000" + username + "\000" + password).getBytes();
data = Base64.encode(data, Base64.NO_WRAP);
try {
executeSensitiveCommand("AUTH PLAIN " + new String(data), "AUTH PLAIN /redacted/");
}
catch (MessagingException me) {
if (me.getMessage().length() > 1 && me.getMessage().charAt(1) == '3') {
throw new AuthenticationFailedException(me.getMessage());
}
throw me;
}
}
}
| true | true | public void open() throws MessagingException {
try {
mTransport.open();
// Eat the banner
executeSimpleCommand(null);
String localHost = "localhost";
// Try to get local address in the proper format.
InetAddress localAddress = mTransport.getLocalAddress();
if (localAddress != null) {
// Address Literal formatted in accordance to RFC2821 Sec. 4.1.3
StringBuilder sb = new StringBuilder();
sb.append('[');
if (localAddress instanceof Inet6Address) {
sb.append("IPv6:");
}
sb.append(localAddress.getHostAddress());
sb.append(']');
localHost = sb.toString();
}
String result = executeSimpleCommand("EHLO " + localHost);
/*
* TODO may need to add code to fall back to HELO I switched it from
* using HELO on non STARTTLS connections because of AOL's mail
* server. It won't let you use AUTH without EHLO.
* We should really be paying more attention to the capabilities
* and only attempting auth if it's available, and warning the user
* if not.
*/
if (mTransport.canTryTlsSecurity()) {
if (result.contains("-STARTTLS")) {
executeSimpleCommand("STARTTLS");
mTransport.reopenTls();
/*
* Now resend the EHLO. Required by RFC2487 Sec. 5.2, and more specifically,
* Exim.
*/
result = executeSimpleCommand("EHLO " + localHost);
} else {
if (Email.DEBUG) {
Log.d(Logging.LOG_TAG, "TLS not supported but required");
}
throw new MessagingException(MessagingException.TLS_REQUIRED);
}
}
/*
* result contains the results of the EHLO in concatenated form
*/
boolean authLoginSupported = result.matches(".*AUTH.*LOGIN.*$");
boolean authPlainSupported = result.matches(".*AUTH.*PLAIN.*$");
if (mUsername != null && mUsername.length() > 0 && mPassword != null
&& mPassword.length() > 0) {
if (authPlainSupported) {
saslAuthPlain(mUsername, mPassword);
}
else if (authLoginSupported) {
saslAuthLogin(mUsername, mPassword);
}
else {
if (Email.DEBUG) {
Log.d(Logging.LOG_TAG, "No valid authentication mechanism found.");
}
throw new MessagingException(MessagingException.AUTH_REQUIRED);
}
}
} catch (SSLException e) {
if (Email.DEBUG) {
Log.d(Logging.LOG_TAG, e.toString());
}
throw new CertificateValidationException(e.getMessage(), e);
} catch (IOException ioe) {
if (Email.DEBUG) {
Log.d(Logging.LOG_TAG, ioe.toString());
}
throw new MessagingException(MessagingException.IOERROR, ioe.toString());
}
}
| public void open() throws MessagingException {
try {
mTransport.open();
// Eat the banner
executeSimpleCommand(null);
String localHost = "localhost";
// Try to get local address in the proper format.
InetAddress localAddress = mTransport.getLocalAddress();
if (localAddress != null) {
// Address Literal formatted in accordance to RFC2821 Sec. 4.1.3
StringBuilder sb = new StringBuilder();
sb.append('[');
if (localAddress instanceof Inet6Address) {
sb.append("IPv6:");
}
sb.append(localAddress.getHostAddress());
sb.append(']');
localHost = sb.toString();
}
String result = executeSimpleCommand("EHLO " + localHost);
/*
* TODO may need to add code to fall back to HELO I switched it from
* using HELO on non STARTTLS connections because of AOL's mail
* server. It won't let you use AUTH without EHLO.
* We should really be paying more attention to the capabilities
* and only attempting auth if it's available, and warning the user
* if not.
*/
if (mTransport.canTryTlsSecurity()) {
if (result.contains("STARTTLS")) {
executeSimpleCommand("STARTTLS");
mTransport.reopenTls();
/*
* Now resend the EHLO. Required by RFC2487 Sec. 5.2, and more specifically,
* Exim.
*/
result = executeSimpleCommand("EHLO " + localHost);
} else {
if (Email.DEBUG) {
Log.d(Logging.LOG_TAG, "TLS not supported but required");
}
throw new MessagingException(MessagingException.TLS_REQUIRED);
}
}
/*
* result contains the results of the EHLO in concatenated form
*/
boolean authLoginSupported = result.matches(".*AUTH.*LOGIN.*$");
boolean authPlainSupported = result.matches(".*AUTH.*PLAIN.*$");
if (mUsername != null && mUsername.length() > 0 && mPassword != null
&& mPassword.length() > 0) {
if (authPlainSupported) {
saslAuthPlain(mUsername, mPassword);
}
else if (authLoginSupported) {
saslAuthLogin(mUsername, mPassword);
}
else {
if (Email.DEBUG) {
Log.d(Logging.LOG_TAG, "No valid authentication mechanism found.");
}
throw new MessagingException(MessagingException.AUTH_REQUIRED);
}
}
} catch (SSLException e) {
if (Email.DEBUG) {
Log.d(Logging.LOG_TAG, e.toString());
}
throw new CertificateValidationException(e.getMessage(), e);
} catch (IOException ioe) {
if (Email.DEBUG) {
Log.d(Logging.LOG_TAG, ioe.toString());
}
throw new MessagingException(MessagingException.IOERROR, ioe.toString());
}
}
|
diff --git a/Statics/src/edu/gatech/statics/modes/fbd/FBDChecker.java b/Statics/src/edu/gatech/statics/modes/fbd/FBDChecker.java
index 346ec9bf..c6f34865 100644
--- a/Statics/src/edu/gatech/statics/modes/fbd/FBDChecker.java
+++ b/Statics/src/edu/gatech/statics/modes/fbd/FBDChecker.java
@@ -1,943 +1,943 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.gatech.statics.modes.fbd;
import edu.gatech.statics.application.StaticsApplication;
import edu.gatech.statics.exercise.Diagram;
import edu.gatech.statics.exercise.Exercise;
import edu.gatech.statics.math.AnchoredVector;
import edu.gatech.statics.math.Unit;
import edu.gatech.statics.math.Vector;
import edu.gatech.statics.math.Vector3bd;
import edu.gatech.statics.objects.Body;
import edu.gatech.statics.objects.Connector;
import edu.gatech.statics.objects.Load;
import edu.gatech.statics.objects.Measurement;
import edu.gatech.statics.objects.Point;
import edu.gatech.statics.objects.SimulationObject;
import edu.gatech.statics.objects.bodies.Cable;
import edu.gatech.statics.objects.bodies.TwoForceMember;
import edu.gatech.statics.objects.connectors.Connector2ForceMember2d;
import edu.gatech.statics.objects.connectors.Fix2d;
import edu.gatech.statics.objects.connectors.Pin2d;
import edu.gatech.statics.util.Pair;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
/**
*
* @author Calvin Ashmore
*/
public class FBDChecker {
private FreeBodyDiagram diagram;
//private Joint nextJoint;
//private boolean done = false;
private boolean verbose = true;
protected FreeBodyDiagram getDiagram() {
return diagram;
}
public FBDChecker(FreeBodyDiagram diagram) {
this.diagram = diagram;
}
/**
* Get all of the symbolic measurements in the schematic, for making sure their names
* do are not being used for AnchoredVectors.
* @return
*/
private List<Measurement> getSymbolicMeasurements() {
List<Measurement> m = new ArrayList<Measurement>();
for (SimulationObject obj : FreeBodyDiagram.getSchematic().allObjects()) {
if (obj instanceof Measurement && ((Measurement) obj).isSymbol()) {
m.add((Measurement) obj);
}
}
return m;
}
/**
* The verbose flag lets the checker know whether to report information on failure.
* Verbose output will report both information to the logger and to the advice box.
* @param enable
*/
public void setVerbose(boolean enable) {
verbose = enable;
}
/**
* Get all the points in the schematic, to check against for force names.
* @return
*/
private List<Point> getAllPoints() {
List<Point> m = new ArrayList<Point>();
for (SimulationObject obj : FreeBodyDiagram.getSchematic().allObjects()) {
if (obj instanceof Point) {
m.add((Point) obj);
}
}
return m;
}
/**
* Get the given AnchoredVectors that are present in the diagram.
* The givens are AnchoredVectors present in the schematic, and should be added to the diagram
* by the user in the FBD. Givens are first looked up in the symbol manager to
* see if a stored symbol has been used.
* @return
*/
private List<AnchoredVector> getGivenLoads() {
List<AnchoredVector> givenLoads = new ArrayList<AnchoredVector>();
// look through everything in the schematic, we want to pick out the loads
// on the correct bodies.
for (Body body : FreeBodyDiagram.getSchematic().allBodies()) {
if (diagram.getBodySubset().getBodies().contains(body)) {
for (SimulationObject obj : body.getAttachedObjects()) {
if (obj instanceof Load) {
Load given = (Load) obj;
// attempt to find an equivalent that might have been stored in the symbol manager.
AnchoredVector symbolEquivalent = Exercise.getExercise().getSymbolManager().getLoad(given.getAnchoredVector());
if (symbolEquivalent != null) {
givenLoads.add(symbolEquivalent);
} else {
givenLoads.add(given.getAnchoredVector());
}
}
}
}
}
return givenLoads;
}
private void logInfo(String info) {
if (verbose) {
Logger.getLogger("Statics").info(info);
}
}
private void setAdviceKey(String key, Object... parameters) {
if (verbose) {
StaticsApplication.getApp().setAdviceKey(key, parameters);
}
}
public boolean checkDiagram() {
//done = false;
// step 1: assemble a list of all the forces the user has added.
List<AnchoredVector> addedLoads = new ArrayList<AnchoredVector>(diagram.getCurrentState().getAddedLoads());
logInfo("check: user added AnchoredVectors: " + addedLoads);
if (addedLoads.size() <= 0) {
logInfo("check: diagram does not contain any AnchoredVectors");
logInfo("check: FAILED");
setAdviceKey("fbd_feedback_check_fail_add");
return false;
}
// step 2: for vectors that we can click on and add, ie, given added forces,
// make sure that the user has added all of them.
for (AnchoredVector given : getGivenLoads()) {
boolean ok = performGivenCheck(addedLoads, given);
if (!ok) {
return false;
}
}
// step 3: Make sure weights exist, and remove them from our addedForces.
for (Body body : diagram.getBodySubset().getBodies()) {
if (body.getWeight().getDiagramValue().floatValue() == 0) {
continue;
}
AnchoredVector weight = new AnchoredVector(
body.getCenterOfMassPoint(),
new Vector(Unit.force, Vector3bd.UNIT_Y.negate(),
new BigDecimal(body.getWeight().doubleValue())));
boolean ok = performWeightCheck(addedLoads, weight, body);
if (!ok) {
return false;
}
}
// Step 4: go through all the border connectors connecting this FBD to the external world,
// and check each AnchoredVector implied by the connector.
for (int i = 0; i < diagram.allObjects().size(); i++) {
SimulationObject obj = diagram.allObjects().get(i);
if (!(obj instanceof Connector)) {
continue;
}
Connector connector = (Connector) obj;
// find the body in this diagram to which the connector is attached.
Body body = null;
if (diagram.allBodies().contains(connector.getBody1())) {
body = connector.getBody1();
}
if (diagram.allBodies().contains(connector.getBody2())) {
body = connector.getBody2();
}
// ^ is java's XOR operator
// we want the joint IF it connects a body in the body list
// to a body that is not in the body list. This means xor.
if (!(diagram.getBodySubset().getBodies().contains(connector.getBody1()) ^
diagram.getBodySubset().getBodies().contains(connector.getBody2()))) {
continue;
}
// build a list of the AnchoredVectors at this point
List<AnchoredVector> userAnchoredVectorsAtConnector = new ArrayList<AnchoredVector>();
for (AnchoredVector AnchoredVector : addedLoads) {
if (AnchoredVector.getAnchor().equals(connector.getAnchor())) {
userAnchoredVectorsAtConnector.add(AnchoredVector);
}
}
logInfo("check: testing connector: " + connector);
// special case, userAnchoredVectorsAtConnector is empty:
if (userAnchoredVectorsAtConnector.isEmpty()) {
logInfo("check: have any forces been added");
logInfo("check: FAILED");
setAdviceKey("fbd_feedback_check_fail_joint_reaction", connector.connectorName(), connector.getAnchor().getLabelText());
return false;
}
// //this is trying to make sure two force members have the same values at either end
// if (body instanceof TwoForceMember) {
// List<AnchoredVector> userAnchoredVectorsAtOtherConnector = new ArrayList<AnchoredVector>();
// Connector con;
// if (((TwoForceMember) body).getConnector1() == connector) {
// con = ((TwoForceMember) body).getConnector2();
// } else {
// con = ((TwoForceMember) body).getConnector1();
// }
// for (AnchoredVector AnchoredVector : addedAnchoredVectors) {
// if (AnchoredVector.getAnchor().equals(con.getAnchor())) {
// userAnchoredVectorsAtOtherConnector.add(AnchoredVector);
// }
// }
// if (!userAnchoredVectorsAtConnector.get(0).getLabelText().equalsIgnoreCase(userAnchoredVectorsAtOtherConnector.get(0).getLabelText())) {
// logInfo("check: the user has given a 2ForceMember's AnchoredVectors different values");
// logInfo("check: FAILED");
// setAdviceKey("fbd_feedback_check_fail_2force_not_same");
// return false;
// }
// }
ConnectorCheckResult connectorResult = checkConnector(userAnchoredVectorsAtConnector, connector, body);
switch (connectorResult) {
case passed:
// okay, the check passed without complaint.
// The AnchoredVectors may still not be correct, but that will be tested afterwards.
// for now, continue normally.
break;
case inappropriateDirection:
// check for special case of 2FM:
logInfo("check: User added AnchoredVectors at " + connector.getAnchor().getName() + ": " + userAnchoredVectorsAtConnector);
logInfo("check: Was expecting: " + getReactionAnchoredVectors(connector, connector.getReactions(body)));
if (connector instanceof Connector2ForceMember2d) {
Connector2ForceMember2d connector2fm = (Connector2ForceMember2d) connector;
if (connector2fm.getMember() instanceof Cable) {
// special message for cables:
logInfo("check: user created a cable in compression at point " + connector.getAnchor().getName());
logInfo("check: FAILED");
setAdviceKey("fbd_feedback_check_fail_joint_cable",
connector.getAnchor().getName(),
connector2fm.getMember());
return false;
}
} else {
// one of the directions is the wrong way, and it's not a cable this time
// it is probably a roller or something.
logInfo("check: AnchoredVectors have wrong direction at point " + connector.getAnchor().getName());
logInfo("check: FAILED");
setAdviceKey("fbd_feedback_check_fail_some_reverse", connector.getAnchor().getName());
return false;
}
case somethingExtra:
// this particular check could be fine
// in some problems there are multiple connectors at one point (notably in frame problems)
// and this means that extra AnchoredVectors are okay. We check to see if multiple connectors are present,
// and if so, continue gracefully, as inapporpriate extra things will be checked at the end
// otherwise the check will continue to the next step, "missingSomething" where other conditions
// will be tested.
if (diagram.getConnectorsAtPoint(connector.getAnchor()).size() > 1) {
// continue on.
break;
}
case missingSomething:
// okay, if we are here then either something is missing, or something is extra.
// check against pins or rollers and see what happens.
logInfo("check: User added AnchoredVectors at " + connector.getAnchor().getName() + ": " + userAnchoredVectorsAtConnector);
logInfo("check: Was expecting: " + getReactionAnchoredVectors(connector, connector.getReactions(body)));
// check if this is mistaken for a pin
if (!connector.connectorName().equals("pin")) {
Pin2d testPin = new Pin2d(connector.getAnchor());
if (checkConnector(userAnchoredVectorsAtConnector, testPin, null) == ConnectorCheckResult.passed) {
logInfo("check: user wrongly created a pin at point " + connector.getAnchor().getLabelText());
logInfo("check: FAILED");
setAdviceKey("fbd_feedback_check_fail_joint_wrong_type", connector.getAnchor().getLabelText(), "pin", connector.connectorName());
return false;
}
}
// check if this is mistaken for a fix
if (!connector.connectorName().equals("fix")) {
Fix2d testFix = new Fix2d(connector.getAnchor());
if (checkConnector(userAnchoredVectorsAtConnector, testFix, null) == ConnectorCheckResult.passed) {
logInfo("check: user wrongly created a fix at point " + connector.getAnchor().getLabelText());
logInfo("check: FAILED");
setAdviceKey("fbd_feedback_check_fail_joint_wrong_type", connector.getAnchor().getLabelText(), "fix", connector.connectorName());
return false;
}
}
// otherwise, the user did something strange.
logInfo("check: user simply added reactions to a joint that don't make sense to point " + connector.getAnchor().getLabelText());
logInfo("check: FAILED");
setAdviceKey("fbd_feedback_check_fail_joint_wrong", connector.connectorName(), connector.getAnchor().getLabelText());
return false;
}
// okay, now the connector test has passed.
// We know now that the AnchoredVectors present in the diagram satisfy the reactions for the connector.
// All reactions AnchoredVectors are necessarily symbolic, and thus will either be new symbols, or
// they will be present in the symbol manager.
List<AnchoredVector> expectedReactions = getReactionAnchoredVectors(connector, connector.getReactions(body));
for (AnchoredVector reaction : expectedReactions) {
// get a AnchoredVector and result corresponding to this check.
AnchoredVector loadFromSymbolManager = Exercise.getExercise().getSymbolManager().getLoad(reaction);
if (loadFromSymbolManager != null) {
// make sure the directions are pointing the correct way:
if (reaction.getVectorValue().equals(loadFromSymbolManager.getVectorValue().negate())) {
loadFromSymbolManager = new AnchoredVector(loadFromSymbolManager);
- loadFromSymbolManager.getVectorValue().negateLocal();
+ loadFromSymbolManager.getVectorValue().negate();
}
// of the user AnchoredVectors, only check those which point in maybe the right direction
List<AnchoredVector> userAnchoredVectorsAtConnectorInDirection = new ArrayList<AnchoredVector>();
for (AnchoredVector AnchoredVector : userAnchoredVectorsAtConnector) {
if (AnchoredVector.getVectorValue().equals(reaction.getVectorValue()) ||
AnchoredVector.getVectorValue().equals(reaction.getVectorValue().negate())) {
userAnchoredVectorsAtConnectorInDirection.add(AnchoredVector);
}
}
Pair<AnchoredVector, AnchoredVectorCheckResult> result = checkAllCandidatesAgainstTarget(
userAnchoredVectorsAtConnectorInDirection, loadFromSymbolManager);
AnchoredVector candidate = result.getLeft();
// this AnchoredVector has been solved for already. Now we can check against it.
if (result.getRight() == AnchoredVectorCheckResult.passed) {
// check is OK, we can remove the AnchoredVector from our addedAnchoredVectors.
addedLoads.remove(candidate);
} else {
complainAboutAnchoredVectorCheck(result.getRight(), candidate);
return false;
}
} else {
// this AnchoredVector is new, so it requires a name check.
// let's find a AnchoredVector that seems to match the expected reaction.
AnchoredVector candidate = null;
for (AnchoredVector possibleCandidate : userAnchoredVectorsAtConnector) {
// we know that these all are at the right anchor, so only test direction.
// direction may also be negated, since these are new symbols.
if (possibleCandidate.getVectorValue().equals(reaction.getVectorValue()) ||
possibleCandidate.getVectorValue().equals(reaction.getVectorValue().negate())) {
candidate = possibleCandidate;
}
}
// candidate should not be null at this point since the main test passed.
NameCheckResult nameResult;
if (connector instanceof Connector2ForceMember2d) {
nameResult = checkAnchoredVectorName2FM(candidate, (Connector2ForceMember2d) connector);
} else {
nameResult = checkLoadName(candidate);
}
if (nameResult == NameCheckResult.passed) {
// we're okay!!
addedLoads.remove(candidate);
} else {
complainAboutName(nameResult, candidate);
return false;
}
}
}
}
// Step 5: Make sure we've used all the user added forces.
if (!addedLoads.isEmpty()) {
logInfo("check: user added more forces than necessary: " + addedLoads);
logInfo("check: FAILED");
setAdviceKey("fbd_feedback_check_fail_additional", addedLoads.get(0).getAnchor().getName());
return false;
}
// Step 6: Verify labels
// verify that all unknowns are symbols
// these are reaction forces and moments
// knowns should not be symbols: externals, weights
// symbols must also not be repeated, unless this is valid somehow? (not yet)
// Yay, we've passed the test!
logInfo("check: PASSED!");
return true;
}
/**
* Checks against a given AnchoredVector.
* The check removes the candidate from addedAnchoredVectors if the check passes.
* @param addedAnchoredVectors
* @param given
* @return
*/
protected boolean performGivenCheck(List<AnchoredVector> addedAnchoredVectors, AnchoredVector given) {
List<AnchoredVector> candidates = getCandidates(addedAnchoredVectors, given, given.isSymbol() && !given.isKnown());
// try all candidates
// realistically there should only be one, but this check tries to be secure.
Pair<AnchoredVector, AnchoredVectorCheckResult> result = checkAllCandidatesAgainstTarget(candidates, given);
// we have no candidates, so terminate.
if (result.getRight() == null) {
//user has forgotten to add a given AnchoredVector
logInfo("check: diagram does not contain given AnchoredVector " + given);
logInfo("check: FAILED");
setAdviceKey("fbd_feedback_check_fail_given", given.getAnchor().getLabelText());
return false;
}
AnchoredVector candidate = result.getLeft();
// report failures
switch (result.getRight()) {
case passed:
// Our test has passed, we can continue.
addedAnchoredVectors.remove(candidate);
break;
case shouldNotBeNumeric:
//A given value that should be symbolic has been added as numeric
logInfo("check: external value should be a symbol at point" + given.getAnchor().getName());
logInfo("check: FAILED");
setAdviceKey("fbd_feedback_check_fail_given_symbol", candidate.getQuantity().toString(), candidate.getAnchor().getLabelText());
return false;
case shouldNotBeSymbol:
//A given value that should be numeric has been added as symbolic
logInfo("check: external value should be a numeric at point" + given.getAnchor().getLabelText());
logInfo("check: FAILED");
setAdviceKey("fbd_feedback_check_fail_given_number", candidate.getQuantity().toString(), candidate.getAnchor().getLabelText());
return false;
case wrongSymbol:
// user has given a symbol that does not match the symbol of the given AnchoredVector.
// this is generally okay, but we want there to be consistency if the user has already put a name down.
if (Exercise.getExercise().getSymbolManager().getLoad(candidate) == null) {
// we're okay
addedAnchoredVectors.remove(candidate);
break;
}
default:
complainAboutAnchoredVectorCheck(result.getRight(), candidate);
return false;
}
// user candidate is a symbolic value
if (candidate.isSymbol() && Exercise.getExercise().getSymbolManager().getLoad(candidate) == null) {
NameCheckResult nameResult = checkLoadName(candidate);
if (nameResult != NameCheckResult.passed) {
complainAboutName(nameResult, candidate);
return false;
}
}
return true;
}
/**
* Checks against a weight. This method is very similar to the Given check,
* but uses different log and feedback messages. A good way to do the check might be to abstract them out,
* but the difference is kind of immaterial at this point.
* The check removes the candidate from addedAnchoredVectors if the check passes.
* @param addedAnchoredVectors
* @param given
* @return
*/
protected boolean performWeightCheck(List<AnchoredVector> addedAnchoredVectors, AnchoredVector weight, Body body) {
List<AnchoredVector> candidates = getCandidates(addedAnchoredVectors, weight, weight.isSymbol() && !weight.isKnown());
// try all candidates
// realistically there should only be one, but this check tries to be secure.
Pair<AnchoredVector, AnchoredVectorCheckResult> result = checkAllCandidatesAgainstTarget(candidates, weight);
// we have no candidates, so terminate.
if (result.getRight() == null) {
// weight does not exist in system.
logInfo("check: diagram does not contain weight for " + body);
logInfo("check: weight is: " + weight);
logInfo("check: FAILED");
setAdviceKey("fbd_feedback_check_fail_weight", body.getName());
return false;
}
AnchoredVector candidate = result.getLeft();
// report failures
switch (result.getRight()) {
case passed:
// Our test has passed, we can continue.
addedAnchoredVectors.remove(candidate);
break;
case shouldNotBeNumeric:
//A given value that should be symbolic has been added as numeric
logInfo("check: weight should be a symbol at point" + weight.getAnchor().getName());
logInfo("check: FAILED");
setAdviceKey("fbd_feedback_check_fail_weight_symbol", body.getName());
return false;
case shouldNotBeSymbol:
//A given value that should be numeric has been added as symbolic
logInfo("check: weight should be numeric at point" + weight.getAnchor().getName());
logInfo("check: FAILED");
setAdviceKey("fbd_feedback_check_fail_weight_number", body.getName());
return false;
case wrongNumericValue:
// wrong numeric value
logInfo("check: diagram contains incorrect weight " + weight);
logInfo("check: FAILED");
setAdviceKey("fbd_feedback_check_fail_weight_value", body.getName());
return false;
default:
complainAboutAnchoredVectorCheck(result.getRight(), candidate);
return false;
}
// user candidate is a symbolic value
if (candidate.isSymbol() && Exercise.getExercise().getSymbolManager().getLoad(candidate) == null) {
NameCheckResult nameResult = checkLoadName(candidate);
if (nameResult != NameCheckResult.passed) {
complainAboutName(nameResult, candidate);
return false;
}
}
return true;
}
private void complainAboutAnchoredVectorCheck(AnchoredVectorCheckResult result, AnchoredVector candidate) {
switch (result) {
case shouldNotBeNumeric:
logInfo("check: force should not be numeric: " + candidate);
logInfo("check: FAILED");
setAdviceKey("fbd_feedback_check_fail_numeric", candidate.getUnit().toString(), candidate.getQuantity().toString(), candidate.getAnchor().getName());
return;
case shouldNotBeSymbol:
logInfo("check: force should not be symbol: " + candidate);
logInfo("check: FAILED");
setAdviceKey("fbd_feedback_check_fail_symbol", candidate.getUnit().toString(), candidate.getAnchor().getLabelText(), candidate.getAnchor().getName());
return;
case wrongNumericValue:
logInfo("check: numeric values do not match: " + candidate);
logInfo("check: FAILED");
setAdviceKey("fbd_feedback_check_fail_not_same_number", candidate.getUnit().toString(), candidate.getQuantity().toString(), candidate.getAnchor().getName());
return;
case wrongDirection:
logInfo("check: AnchoredVector is pointing the wrong direction: " + candidate);
logInfo("check: FAILED");
setAdviceKey("fbd_feedback_check_fail_reverse", candidate.getUnit().toString(), candidate.getQuantity().toString(), candidate.getAnchor().getName());
return;
case wrongSymbol:
//the student has created a AnchoredVector with a name that doesn't match its opposing force
logInfo("check: AnchoredVector should equal its opposite: " + candidate);
logInfo("check: FAILED");
setAdviceKey("fbd_feedback_check_fail_not_same_symbol", candidate.getUnit().toString(), candidate.getQuantity().toString(), candidate.getAnchor().getName());
return;
}
}
private void complainAboutName(NameCheckResult result, AnchoredVector candidate) {
switch (result) {
case duplicateInThisDiagram:
case matchesSymbolElsewhere:
logInfo("check: forces and moments should not have the same name as any other force or moment: " + candidate);
logInfo("check: FAILED");
setAdviceKey("fbd_feedback_check_fail_duplicate", candidate.getUnit().toString(), candidate.getAnchor().getLabelText());
return;
case matchesMeasurementSymbol:
logInfo("check: force or moment should not share the same name with an unknown measurement ");
logInfo("check: FAILED");
setAdviceKey("fbd_feedback_check_fail_duplicate_measurement", candidate.getUnit().toString(), candidate.getAnchor().getLabelText());
return;
case matchesPointName:
logInfo("check: anchors and added force/moments should not share names");
logInfo("check: FAILED");
setAdviceKey("fbd_feedback_check_fail_duplicate_anchor", candidate.getUnit().toString(), candidate.getAnchor().getLabelText());
return;
case shouldMatch2FM:
//the student has created a 2FM with non matching forces
logInfo("check: forces on a 2FM need to have the same name: " + candidate);
logInfo("check: FAILED");
setAdviceKey("fbd_feedback_check_fail_2force_not_same");
return;
}
}
protected enum NameCheckResult {
passed, // passed, no conficts
matchesSymbolElsewhere, // same as a symbolic AnchoredVector from another diagram
matchesPointName, // same as the name for a point
matchesMeasurementSymbol, // same as a symbol used in an unknown measurement
duplicateInThisDiagram, // two AnchoredVectors incorrectly have the same name in this diagram
shouldMatch2FM // the opposing forces of a 2FM should match
}
/**
* This check makes sure this AnchoredVector has a suitable name. The given candidate
* must be a symbolic AnchoredVector.
* This check is intended for AnchoredVectors which have *not yet* been added to the symbol manager.
* This check will go through and make sure the name does not coincide with that of a point or
* a different AnchoredVector in this diagram or in other diagrams. A special case must be
* made with Two Force Members, and for these it is necessary to use checkAnchoredVectorName2FM().
* @param candidate
* @return
*/
protected NameCheckResult checkLoadName(AnchoredVector candidate) {
String name = candidate.getSymbolName();
for (SimulationObject obj : Diagram.getSchematic().allObjects()) {
// look through simulation objects to find name conflicts
// first look at measurements
if (obj instanceof Measurement) {
Measurement measure = (Measurement) obj;
if (measure.isSymbol() && measure.getSymbolName().equalsIgnoreCase(name)) {
return NameCheckResult.matchesMeasurementSymbol;
}
}
// then points
if (obj instanceof Point) {
if (name.equalsIgnoreCase(obj.getName())) {
return NameCheckResult.matchesPointName;
}
}
}
// look through other symbols stored in the symbol manager
if (Exercise.getExercise().getSymbolManager().getSymbols().contains(name)) {
//the name exists elsewhere in the fbd
return NameCheckResult.matchesSymbolElsewhere;
}
// now look through other AnchoredVectors in this diagram.
for (AnchoredVector load : diagram.getCurrentState().getAddedLoads()) {
if (load.equals(candidate)) {
continue;
}
if (candidate.getSymbolName().equalsIgnoreCase(load.getSymbolName())) {
return NameCheckResult.duplicateInThisDiagram;
}
}
return NameCheckResult.passed;
}
/**
* This is an extension of the checkAnchoredVectorName() method, which applies specifically
* to AnchoredVectors which are reactions to Two Force Members. This method assumes that the candidate provided is
* actually the reaction force to the 2fm.
* @param candidate
* @param connector
* @return
*/
protected NameCheckResult checkAnchoredVectorName2FM(AnchoredVector candidate, Connector2ForceMember2d connector) {
NameCheckResult result = checkLoadName(candidate);
//if we passed, which we usually want, this means that the AnchoredVectors' labels
//do not match, which is bad
if (result == NameCheckResult.passed) {
for (SimulationObject obj : connector.getMember().getAttachedObjects()) {
if (!(obj instanceof Load)) {
continue;
}
if (connector.getMember().containsPoints(candidate.getAnchor(), ((Load) obj).getAnchor())) {
return NameCheckResult.shouldMatch2FM;
}
}
}
// if the result of the standard check is anything but "there is a duplicate in this diagram"
// then we can return that result. We are only interested in the case where there
// might be a second AnchoredVector with the same name, which implies a duplicate.
if (result != NameCheckResult.duplicateInThisDiagram) {
return result;
}
TwoForceMember member = connector.getMember();
if (!diagram.allBodies().contains(member)) {
return result;
}
Connector2ForceMember2d otherConnector;
if (member.getConnector1() == connector) {
otherConnector = member.getConnector2();
} else if (member.getConnector2() == connector) {
otherConnector = member.getConnector1();
} else {
// shouldn't get here, but fail gracefully
return result;
}
// get the other AnchoredVector that satisfies the reactions of the otherConnector
List<AnchoredVector> AnchoredVectorsAtOtherReaction = getLoadsAtPoint(otherConnector.getAnchor());
List<AnchoredVector> otherConnectorReactions = getReactionAnchoredVectors(connector, otherConnector.getReactions());
AnchoredVector otherReactionTarget = otherConnectorReactions.get(0);
AnchoredVector otherReaction = null;
// iterate through the list and look for the one that should do it.
// we want to find something that could be a reaction on the other end of the 2fm,
// and we want it to match the name of our current AnchoredVector.
for (AnchoredVector otherAnchoredVector : AnchoredVectorsAtOtherReaction) {
if (otherAnchoredVector.getVectorValue().equals(otherReactionTarget.getVectorValue()) ||
otherAnchoredVector.getVectorValue().equals(otherReactionTarget.getVectorValue().negate())) {
if (candidate.getSymbolName().equalsIgnoreCase(otherAnchoredVector.getSymbolName())) {
otherReaction = otherAnchoredVector;
}
}
}
// okay, we found it. That means that this AnchoredVector should have an appropriate name.
// in the case that there is some case that is invalid and escapes the above, it should
// be caught by other parts of the check (for instance, if the user was especially
// difficult and put two reactions at one end of a 2fm or something like that)
if (otherReaction != null) {
return NameCheckResult.passed;
}
return result;
}
/**
* A convenience method to get all of the loads at a given point. This goes through
* all of the loads in the current diagram and checks against them.
* @param point
* @return
*/
protected List<AnchoredVector> getLoadsAtPoint(Point point) {
List<AnchoredVector> loads = new ArrayList<AnchoredVector>();
//for (SimulationObject obj : allObjects) {
for (AnchoredVector load : diagram.getCurrentState().getAddedLoads()) {
if (load.getAnchor().equals(point)) {
loads.add(load);
}
}
return loads;
}
/**
* Attempts to find a AnchoredVector from a pool of possibilities which might match the target.
* The search will search for AnchoredVectors that are the same type, are at the same point, and
* point in the same direction as the target, or the opposite direction, if the
* testOpposites flag is checked.
* @param searchPool
* @param target
* @param testOpposites
* @return
*/
protected List<AnchoredVector> getCandidates(List<AnchoredVector> searchPool, AnchoredVector target, boolean testOpposites) {
List<AnchoredVector> candidates = new ArrayList<AnchoredVector>();
for (AnchoredVector AnchoredVector : searchPool) {
// make sure types are the same
if (AnchoredVector.getClass() != target.getClass()) {
continue;
}
// make sure the anchor is the same
if (!AnchoredVector.getAnchor().equals(target.getAnchor())) {
continue;
}
// add if direction is the same, or is opposite and the testOpposites flag is set
if (AnchoredVector.getVectorValue().equals(target.getVectorValue()) ||
(testOpposites && AnchoredVector.getVectorValue().negate().equals(target.getVectorValue()))) {
candidates.add(AnchoredVector);
}
}
return candidates;
}
/**
* This is a result that is returned when a AnchoredVector is checked against some stored version.
* This works when checking against a given, a weight, or a stored symbolic AnchoredVector.
*/
protected enum AnchoredVectorCheckResult {
passed, //check passes
wrongDirection, // occurs when solved value is in wrong direction
wrongSymbol, // symbol is stored, this should change its symbol
wrongNumericValue, // number is stored, user put in wrong value
shouldNotBeSymbol, // store is numeric
shouldNotBeNumeric // store is symbolic
}
/**
* Like checkAnchoredVectorAgainstTarget() this method aims to check whether a AnchoredVector matches the
* target. However, this method checks against a collection of candidates, rather than just one.
* @param candidates
* @param target
* @return
*/
protected Pair<AnchoredVector, AnchoredVectorCheckResult> checkAllCandidatesAgainstTarget(List<AnchoredVector> candidates, AnchoredVector target) {
AnchoredVectorCheckResult result = null;
AnchoredVector lastCandidate = null;
for (AnchoredVector candidate : candidates) {
lastCandidate = candidate;
result = checkAnchoredVectorAgainstTarget(candidate, target);
if (result == AnchoredVectorCheckResult.passed) {
return new Pair<AnchoredVector, AnchoredVectorCheckResult>(candidate, result);
}
}
return new Pair<AnchoredVector, AnchoredVectorCheckResult>(lastCandidate, result);
}
/**
* Returns a result indicating whether the candidate sufficiently matches the target provided.
* Target can be a stored symbolic AnchoredVector, a given, or a weight. The target could be known, symbolic, numeric,
* or what-have-you. The goal of this check is to abstract out some of the detailed checks making sure
* that candidates are named or valud appropriately and pointing the right direction given
* other information that might be known about other diagrams.
* @param candidate
* @param target
* @return
*/
protected AnchoredVectorCheckResult checkAnchoredVectorAgainstTarget(AnchoredVector candidate, AnchoredVector target) {
if (target.isKnown()) {
// target is a known AnchoredVector
// the numeric value must be correct, and the direction must be correct.
if (!candidate.isKnown()) {
// candidate is not known, so complain.
return AnchoredVectorCheckResult.shouldNotBeSymbol;
}
if (!candidate.getDiagramValue().equals(target.getDiagramValue())) {
// the numeric values are off.
return AnchoredVectorCheckResult.wrongNumericValue;
}
if (!candidate.getVectorValue().equals(target.getVectorValue())) {
// pointing the wrong way
return AnchoredVectorCheckResult.wrongDirection;
}
// this is sufficient for the AnchoredVector to be correct
return AnchoredVectorCheckResult.passed;
} else {
// target is unknown, it must be symbolic
// the symbol must be correct
if (candidate.isKnown()) {
// candidate is not symbolic, so complain
return AnchoredVectorCheckResult.shouldNotBeNumeric;
}
if (!candidate.getSymbolName().equalsIgnoreCase(target.getSymbolName())) {
// candidate has the wrong symbol name
return AnchoredVectorCheckResult.wrongSymbol;
}
// we should be okay now.
return AnchoredVectorCheckResult.passed;
}
}
/**
* This is a result of a check of a connector. This returns *no* information about
* whether the AnchoredVectors are appropriately valued or named, it merely returns information regarding whether
* the AnchoredVectors provided could work for the connector.
*/
protected enum ConnectorCheckResult {
passed, // ok
missingSomething, // some reaction is missing from the candidates
somethingExtra, // the candidates have an extra force that is not necessary
inappropriateDirection, // one or more of the candidates is the wrong direction for the connector
// (ie, in a 2 force member, or in a roller)
}
/**
* Checks to see whether candidateAnchoredVectors, the list of AnchoredVectors provided, is a suitable match for
* the reactions of the given connector. This does not check if the AnchoredVectors are named or have
* the correct names or symbols. This check assumes that all candidateAnchoredVectors are on the connector's anchor.
* The method will return ConnectorCheckResult.somethingExtra if everything is okay except for there being more
* AnchoredVectors than expected. Sometimes, this is okay, for instance if there are more than one connector at a point.
* The check method itself is responsible for identifying these situations and handling them appropriately.
* @param cadidateAnchoredVectors
* @param connector
* @param localBody
* @return
*/
protected ConnectorCheckResult checkConnector(List<AnchoredVector> candidateAnchoredVectors, Connector connector, Body localBody) {
List<Vector> reactions;
if (localBody == null) {
reactions = connector.getReactions();
} else {
reactions = connector.getReactions(localBody);
}
List<AnchoredVector> reactionAnchoredVectors = getReactionAnchoredVectors(connector, reactions);
boolean negatable = connector.isForceDirectionNegatable();
for (AnchoredVector reaction : reactionAnchoredVectors) {
// check each reaction AnchoredVector to make sure it is present and proper
List<AnchoredVector> candidates = getCandidates(candidateAnchoredVectors, reaction, negatable);
if (candidates.isEmpty()) {
// okay, this one is missing, which is bad.
if (!negatable && !getCandidates(candidateAnchoredVectors, reaction, true).isEmpty()) {
// candidates allowing negation is not empty, meaning that user is adding
// a AnchoredVector in the wrong direction
return ConnectorCheckResult.inappropriateDirection;
}
return ConnectorCheckResult.missingSomething;
}
}
// okay, all reactions are accounted for.
// if our list of candidateAnchoredVectors is larger, then there may be a problem
if (candidateAnchoredVectors.size() > reactionAnchoredVectors.size()) {
return ConnectorCheckResult.somethingExtra;
}
// otherwise, we're okay.
return ConnectorCheckResult.passed;
}
/**
* Returns the reactions present from a connector as AnchoredVectors instead of Vectors.
* This returns a fresh new list, so it does no harm to remove AnchoredVectors from it.
* @param joint
* @param reactions
* @return
*/
private List<AnchoredVector> getReactionAnchoredVectors(Connector connector, List<Vector> reactions) {
List<AnchoredVector> loads = new ArrayList<AnchoredVector>();
for (Vector vector : reactions) {
loads.add(new AnchoredVector(connector.getAnchor(), vector));
/*if (vector.getUnit() == Unit.force) {
AnchoredVectors.add(new Force(joint.getAnchor(), vector));
} else if (vector.getUnit() == Unit.moment) {
AnchoredVectors.add(new Moment(joint.getAnchor(), vector));
}*/
}
return loads;
}
}
| true | true | public boolean checkDiagram() {
//done = false;
// step 1: assemble a list of all the forces the user has added.
List<AnchoredVector> addedLoads = new ArrayList<AnchoredVector>(diagram.getCurrentState().getAddedLoads());
logInfo("check: user added AnchoredVectors: " + addedLoads);
if (addedLoads.size() <= 0) {
logInfo("check: diagram does not contain any AnchoredVectors");
logInfo("check: FAILED");
setAdviceKey("fbd_feedback_check_fail_add");
return false;
}
// step 2: for vectors that we can click on and add, ie, given added forces,
// make sure that the user has added all of them.
for (AnchoredVector given : getGivenLoads()) {
boolean ok = performGivenCheck(addedLoads, given);
if (!ok) {
return false;
}
}
// step 3: Make sure weights exist, and remove them from our addedForces.
for (Body body : diagram.getBodySubset().getBodies()) {
if (body.getWeight().getDiagramValue().floatValue() == 0) {
continue;
}
AnchoredVector weight = new AnchoredVector(
body.getCenterOfMassPoint(),
new Vector(Unit.force, Vector3bd.UNIT_Y.negate(),
new BigDecimal(body.getWeight().doubleValue())));
boolean ok = performWeightCheck(addedLoads, weight, body);
if (!ok) {
return false;
}
}
// Step 4: go through all the border connectors connecting this FBD to the external world,
// and check each AnchoredVector implied by the connector.
for (int i = 0; i < diagram.allObjects().size(); i++) {
SimulationObject obj = diagram.allObjects().get(i);
if (!(obj instanceof Connector)) {
continue;
}
Connector connector = (Connector) obj;
// find the body in this diagram to which the connector is attached.
Body body = null;
if (diagram.allBodies().contains(connector.getBody1())) {
body = connector.getBody1();
}
if (diagram.allBodies().contains(connector.getBody2())) {
body = connector.getBody2();
}
// ^ is java's XOR operator
// we want the joint IF it connects a body in the body list
// to a body that is not in the body list. This means xor.
if (!(diagram.getBodySubset().getBodies().contains(connector.getBody1()) ^
diagram.getBodySubset().getBodies().contains(connector.getBody2()))) {
continue;
}
// build a list of the AnchoredVectors at this point
List<AnchoredVector> userAnchoredVectorsAtConnector = new ArrayList<AnchoredVector>();
for (AnchoredVector AnchoredVector : addedLoads) {
if (AnchoredVector.getAnchor().equals(connector.getAnchor())) {
userAnchoredVectorsAtConnector.add(AnchoredVector);
}
}
logInfo("check: testing connector: " + connector);
// special case, userAnchoredVectorsAtConnector is empty:
if (userAnchoredVectorsAtConnector.isEmpty()) {
logInfo("check: have any forces been added");
logInfo("check: FAILED");
setAdviceKey("fbd_feedback_check_fail_joint_reaction", connector.connectorName(), connector.getAnchor().getLabelText());
return false;
}
// //this is trying to make sure two force members have the same values at either end
// if (body instanceof TwoForceMember) {
// List<AnchoredVector> userAnchoredVectorsAtOtherConnector = new ArrayList<AnchoredVector>();
// Connector con;
// if (((TwoForceMember) body).getConnector1() == connector) {
// con = ((TwoForceMember) body).getConnector2();
// } else {
// con = ((TwoForceMember) body).getConnector1();
// }
// for (AnchoredVector AnchoredVector : addedAnchoredVectors) {
// if (AnchoredVector.getAnchor().equals(con.getAnchor())) {
// userAnchoredVectorsAtOtherConnector.add(AnchoredVector);
// }
// }
// if (!userAnchoredVectorsAtConnector.get(0).getLabelText().equalsIgnoreCase(userAnchoredVectorsAtOtherConnector.get(0).getLabelText())) {
// logInfo("check: the user has given a 2ForceMember's AnchoredVectors different values");
// logInfo("check: FAILED");
// setAdviceKey("fbd_feedback_check_fail_2force_not_same");
// return false;
// }
// }
ConnectorCheckResult connectorResult = checkConnector(userAnchoredVectorsAtConnector, connector, body);
switch (connectorResult) {
case passed:
// okay, the check passed without complaint.
// The AnchoredVectors may still not be correct, but that will be tested afterwards.
// for now, continue normally.
break;
case inappropriateDirection:
// check for special case of 2FM:
logInfo("check: User added AnchoredVectors at " + connector.getAnchor().getName() + ": " + userAnchoredVectorsAtConnector);
logInfo("check: Was expecting: " + getReactionAnchoredVectors(connector, connector.getReactions(body)));
if (connector instanceof Connector2ForceMember2d) {
Connector2ForceMember2d connector2fm = (Connector2ForceMember2d) connector;
if (connector2fm.getMember() instanceof Cable) {
// special message for cables:
logInfo("check: user created a cable in compression at point " + connector.getAnchor().getName());
logInfo("check: FAILED");
setAdviceKey("fbd_feedback_check_fail_joint_cable",
connector.getAnchor().getName(),
connector2fm.getMember());
return false;
}
} else {
// one of the directions is the wrong way, and it's not a cable this time
// it is probably a roller or something.
logInfo("check: AnchoredVectors have wrong direction at point " + connector.getAnchor().getName());
logInfo("check: FAILED");
setAdviceKey("fbd_feedback_check_fail_some_reverse", connector.getAnchor().getName());
return false;
}
case somethingExtra:
// this particular check could be fine
// in some problems there are multiple connectors at one point (notably in frame problems)
// and this means that extra AnchoredVectors are okay. We check to see if multiple connectors are present,
// and if so, continue gracefully, as inapporpriate extra things will be checked at the end
// otherwise the check will continue to the next step, "missingSomething" where other conditions
// will be tested.
if (diagram.getConnectorsAtPoint(connector.getAnchor()).size() > 1) {
// continue on.
break;
}
case missingSomething:
// okay, if we are here then either something is missing, or something is extra.
// check against pins or rollers and see what happens.
logInfo("check: User added AnchoredVectors at " + connector.getAnchor().getName() + ": " + userAnchoredVectorsAtConnector);
logInfo("check: Was expecting: " + getReactionAnchoredVectors(connector, connector.getReactions(body)));
// check if this is mistaken for a pin
if (!connector.connectorName().equals("pin")) {
Pin2d testPin = new Pin2d(connector.getAnchor());
if (checkConnector(userAnchoredVectorsAtConnector, testPin, null) == ConnectorCheckResult.passed) {
logInfo("check: user wrongly created a pin at point " + connector.getAnchor().getLabelText());
logInfo("check: FAILED");
setAdviceKey("fbd_feedback_check_fail_joint_wrong_type", connector.getAnchor().getLabelText(), "pin", connector.connectorName());
return false;
}
}
// check if this is mistaken for a fix
if (!connector.connectorName().equals("fix")) {
Fix2d testFix = new Fix2d(connector.getAnchor());
if (checkConnector(userAnchoredVectorsAtConnector, testFix, null) == ConnectorCheckResult.passed) {
logInfo("check: user wrongly created a fix at point " + connector.getAnchor().getLabelText());
logInfo("check: FAILED");
setAdviceKey("fbd_feedback_check_fail_joint_wrong_type", connector.getAnchor().getLabelText(), "fix", connector.connectorName());
return false;
}
}
// otherwise, the user did something strange.
logInfo("check: user simply added reactions to a joint that don't make sense to point " + connector.getAnchor().getLabelText());
logInfo("check: FAILED");
setAdviceKey("fbd_feedback_check_fail_joint_wrong", connector.connectorName(), connector.getAnchor().getLabelText());
return false;
}
// okay, now the connector test has passed.
// We know now that the AnchoredVectors present in the diagram satisfy the reactions for the connector.
// All reactions AnchoredVectors are necessarily symbolic, and thus will either be new symbols, or
// they will be present in the symbol manager.
List<AnchoredVector> expectedReactions = getReactionAnchoredVectors(connector, connector.getReactions(body));
for (AnchoredVector reaction : expectedReactions) {
// get a AnchoredVector and result corresponding to this check.
AnchoredVector loadFromSymbolManager = Exercise.getExercise().getSymbolManager().getLoad(reaction);
if (loadFromSymbolManager != null) {
// make sure the directions are pointing the correct way:
if (reaction.getVectorValue().equals(loadFromSymbolManager.getVectorValue().negate())) {
loadFromSymbolManager = new AnchoredVector(loadFromSymbolManager);
loadFromSymbolManager.getVectorValue().negateLocal();
}
// of the user AnchoredVectors, only check those which point in maybe the right direction
List<AnchoredVector> userAnchoredVectorsAtConnectorInDirection = new ArrayList<AnchoredVector>();
for (AnchoredVector AnchoredVector : userAnchoredVectorsAtConnector) {
if (AnchoredVector.getVectorValue().equals(reaction.getVectorValue()) ||
AnchoredVector.getVectorValue().equals(reaction.getVectorValue().negate())) {
userAnchoredVectorsAtConnectorInDirection.add(AnchoredVector);
}
}
Pair<AnchoredVector, AnchoredVectorCheckResult> result = checkAllCandidatesAgainstTarget(
userAnchoredVectorsAtConnectorInDirection, loadFromSymbolManager);
AnchoredVector candidate = result.getLeft();
// this AnchoredVector has been solved for already. Now we can check against it.
if (result.getRight() == AnchoredVectorCheckResult.passed) {
// check is OK, we can remove the AnchoredVector from our addedAnchoredVectors.
addedLoads.remove(candidate);
} else {
complainAboutAnchoredVectorCheck(result.getRight(), candidate);
return false;
}
} else {
// this AnchoredVector is new, so it requires a name check.
// let's find a AnchoredVector that seems to match the expected reaction.
AnchoredVector candidate = null;
for (AnchoredVector possibleCandidate : userAnchoredVectorsAtConnector) {
// we know that these all are at the right anchor, so only test direction.
// direction may also be negated, since these are new symbols.
if (possibleCandidate.getVectorValue().equals(reaction.getVectorValue()) ||
possibleCandidate.getVectorValue().equals(reaction.getVectorValue().negate())) {
candidate = possibleCandidate;
}
}
// candidate should not be null at this point since the main test passed.
NameCheckResult nameResult;
if (connector instanceof Connector2ForceMember2d) {
nameResult = checkAnchoredVectorName2FM(candidate, (Connector2ForceMember2d) connector);
} else {
nameResult = checkLoadName(candidate);
}
if (nameResult == NameCheckResult.passed) {
// we're okay!!
addedLoads.remove(candidate);
} else {
complainAboutName(nameResult, candidate);
return false;
}
}
}
}
// Step 5: Make sure we've used all the user added forces.
if (!addedLoads.isEmpty()) {
logInfo("check: user added more forces than necessary: " + addedLoads);
logInfo("check: FAILED");
setAdviceKey("fbd_feedback_check_fail_additional", addedLoads.get(0).getAnchor().getName());
return false;
}
// Step 6: Verify labels
// verify that all unknowns are symbols
// these are reaction forces and moments
// knowns should not be symbols: externals, weights
// symbols must also not be repeated, unless this is valid somehow? (not yet)
// Yay, we've passed the test!
logInfo("check: PASSED!");
return true;
}
| public boolean checkDiagram() {
//done = false;
// step 1: assemble a list of all the forces the user has added.
List<AnchoredVector> addedLoads = new ArrayList<AnchoredVector>(diagram.getCurrentState().getAddedLoads());
logInfo("check: user added AnchoredVectors: " + addedLoads);
if (addedLoads.size() <= 0) {
logInfo("check: diagram does not contain any AnchoredVectors");
logInfo("check: FAILED");
setAdviceKey("fbd_feedback_check_fail_add");
return false;
}
// step 2: for vectors that we can click on and add, ie, given added forces,
// make sure that the user has added all of them.
for (AnchoredVector given : getGivenLoads()) {
boolean ok = performGivenCheck(addedLoads, given);
if (!ok) {
return false;
}
}
// step 3: Make sure weights exist, and remove them from our addedForces.
for (Body body : diagram.getBodySubset().getBodies()) {
if (body.getWeight().getDiagramValue().floatValue() == 0) {
continue;
}
AnchoredVector weight = new AnchoredVector(
body.getCenterOfMassPoint(),
new Vector(Unit.force, Vector3bd.UNIT_Y.negate(),
new BigDecimal(body.getWeight().doubleValue())));
boolean ok = performWeightCheck(addedLoads, weight, body);
if (!ok) {
return false;
}
}
// Step 4: go through all the border connectors connecting this FBD to the external world,
// and check each AnchoredVector implied by the connector.
for (int i = 0; i < diagram.allObjects().size(); i++) {
SimulationObject obj = diagram.allObjects().get(i);
if (!(obj instanceof Connector)) {
continue;
}
Connector connector = (Connector) obj;
// find the body in this diagram to which the connector is attached.
Body body = null;
if (diagram.allBodies().contains(connector.getBody1())) {
body = connector.getBody1();
}
if (diagram.allBodies().contains(connector.getBody2())) {
body = connector.getBody2();
}
// ^ is java's XOR operator
// we want the joint IF it connects a body in the body list
// to a body that is not in the body list. This means xor.
if (!(diagram.getBodySubset().getBodies().contains(connector.getBody1()) ^
diagram.getBodySubset().getBodies().contains(connector.getBody2()))) {
continue;
}
// build a list of the AnchoredVectors at this point
List<AnchoredVector> userAnchoredVectorsAtConnector = new ArrayList<AnchoredVector>();
for (AnchoredVector AnchoredVector : addedLoads) {
if (AnchoredVector.getAnchor().equals(connector.getAnchor())) {
userAnchoredVectorsAtConnector.add(AnchoredVector);
}
}
logInfo("check: testing connector: " + connector);
// special case, userAnchoredVectorsAtConnector is empty:
if (userAnchoredVectorsAtConnector.isEmpty()) {
logInfo("check: have any forces been added");
logInfo("check: FAILED");
setAdviceKey("fbd_feedback_check_fail_joint_reaction", connector.connectorName(), connector.getAnchor().getLabelText());
return false;
}
// //this is trying to make sure two force members have the same values at either end
// if (body instanceof TwoForceMember) {
// List<AnchoredVector> userAnchoredVectorsAtOtherConnector = new ArrayList<AnchoredVector>();
// Connector con;
// if (((TwoForceMember) body).getConnector1() == connector) {
// con = ((TwoForceMember) body).getConnector2();
// } else {
// con = ((TwoForceMember) body).getConnector1();
// }
// for (AnchoredVector AnchoredVector : addedAnchoredVectors) {
// if (AnchoredVector.getAnchor().equals(con.getAnchor())) {
// userAnchoredVectorsAtOtherConnector.add(AnchoredVector);
// }
// }
// if (!userAnchoredVectorsAtConnector.get(0).getLabelText().equalsIgnoreCase(userAnchoredVectorsAtOtherConnector.get(0).getLabelText())) {
// logInfo("check: the user has given a 2ForceMember's AnchoredVectors different values");
// logInfo("check: FAILED");
// setAdviceKey("fbd_feedback_check_fail_2force_not_same");
// return false;
// }
// }
ConnectorCheckResult connectorResult = checkConnector(userAnchoredVectorsAtConnector, connector, body);
switch (connectorResult) {
case passed:
// okay, the check passed without complaint.
// The AnchoredVectors may still not be correct, but that will be tested afterwards.
// for now, continue normally.
break;
case inappropriateDirection:
// check for special case of 2FM:
logInfo("check: User added AnchoredVectors at " + connector.getAnchor().getName() + ": " + userAnchoredVectorsAtConnector);
logInfo("check: Was expecting: " + getReactionAnchoredVectors(connector, connector.getReactions(body)));
if (connector instanceof Connector2ForceMember2d) {
Connector2ForceMember2d connector2fm = (Connector2ForceMember2d) connector;
if (connector2fm.getMember() instanceof Cable) {
// special message for cables:
logInfo("check: user created a cable in compression at point " + connector.getAnchor().getName());
logInfo("check: FAILED");
setAdviceKey("fbd_feedback_check_fail_joint_cable",
connector.getAnchor().getName(),
connector2fm.getMember());
return false;
}
} else {
// one of the directions is the wrong way, and it's not a cable this time
// it is probably a roller or something.
logInfo("check: AnchoredVectors have wrong direction at point " + connector.getAnchor().getName());
logInfo("check: FAILED");
setAdviceKey("fbd_feedback_check_fail_some_reverse", connector.getAnchor().getName());
return false;
}
case somethingExtra:
// this particular check could be fine
// in some problems there are multiple connectors at one point (notably in frame problems)
// and this means that extra AnchoredVectors are okay. We check to see if multiple connectors are present,
// and if so, continue gracefully, as inapporpriate extra things will be checked at the end
// otherwise the check will continue to the next step, "missingSomething" where other conditions
// will be tested.
if (diagram.getConnectorsAtPoint(connector.getAnchor()).size() > 1) {
// continue on.
break;
}
case missingSomething:
// okay, if we are here then either something is missing, or something is extra.
// check against pins or rollers and see what happens.
logInfo("check: User added AnchoredVectors at " + connector.getAnchor().getName() + ": " + userAnchoredVectorsAtConnector);
logInfo("check: Was expecting: " + getReactionAnchoredVectors(connector, connector.getReactions(body)));
// check if this is mistaken for a pin
if (!connector.connectorName().equals("pin")) {
Pin2d testPin = new Pin2d(connector.getAnchor());
if (checkConnector(userAnchoredVectorsAtConnector, testPin, null) == ConnectorCheckResult.passed) {
logInfo("check: user wrongly created a pin at point " + connector.getAnchor().getLabelText());
logInfo("check: FAILED");
setAdviceKey("fbd_feedback_check_fail_joint_wrong_type", connector.getAnchor().getLabelText(), "pin", connector.connectorName());
return false;
}
}
// check if this is mistaken for a fix
if (!connector.connectorName().equals("fix")) {
Fix2d testFix = new Fix2d(connector.getAnchor());
if (checkConnector(userAnchoredVectorsAtConnector, testFix, null) == ConnectorCheckResult.passed) {
logInfo("check: user wrongly created a fix at point " + connector.getAnchor().getLabelText());
logInfo("check: FAILED");
setAdviceKey("fbd_feedback_check_fail_joint_wrong_type", connector.getAnchor().getLabelText(), "fix", connector.connectorName());
return false;
}
}
// otherwise, the user did something strange.
logInfo("check: user simply added reactions to a joint that don't make sense to point " + connector.getAnchor().getLabelText());
logInfo("check: FAILED");
setAdviceKey("fbd_feedback_check_fail_joint_wrong", connector.connectorName(), connector.getAnchor().getLabelText());
return false;
}
// okay, now the connector test has passed.
// We know now that the AnchoredVectors present in the diagram satisfy the reactions for the connector.
// All reactions AnchoredVectors are necessarily symbolic, and thus will either be new symbols, or
// they will be present in the symbol manager.
List<AnchoredVector> expectedReactions = getReactionAnchoredVectors(connector, connector.getReactions(body));
for (AnchoredVector reaction : expectedReactions) {
// get a AnchoredVector and result corresponding to this check.
AnchoredVector loadFromSymbolManager = Exercise.getExercise().getSymbolManager().getLoad(reaction);
if (loadFromSymbolManager != null) {
// make sure the directions are pointing the correct way:
if (reaction.getVectorValue().equals(loadFromSymbolManager.getVectorValue().negate())) {
loadFromSymbolManager = new AnchoredVector(loadFromSymbolManager);
loadFromSymbolManager.getVectorValue().negate();
}
// of the user AnchoredVectors, only check those which point in maybe the right direction
List<AnchoredVector> userAnchoredVectorsAtConnectorInDirection = new ArrayList<AnchoredVector>();
for (AnchoredVector AnchoredVector : userAnchoredVectorsAtConnector) {
if (AnchoredVector.getVectorValue().equals(reaction.getVectorValue()) ||
AnchoredVector.getVectorValue().equals(reaction.getVectorValue().negate())) {
userAnchoredVectorsAtConnectorInDirection.add(AnchoredVector);
}
}
Pair<AnchoredVector, AnchoredVectorCheckResult> result = checkAllCandidatesAgainstTarget(
userAnchoredVectorsAtConnectorInDirection, loadFromSymbolManager);
AnchoredVector candidate = result.getLeft();
// this AnchoredVector has been solved for already. Now we can check against it.
if (result.getRight() == AnchoredVectorCheckResult.passed) {
// check is OK, we can remove the AnchoredVector from our addedAnchoredVectors.
addedLoads.remove(candidate);
} else {
complainAboutAnchoredVectorCheck(result.getRight(), candidate);
return false;
}
} else {
// this AnchoredVector is new, so it requires a name check.
// let's find a AnchoredVector that seems to match the expected reaction.
AnchoredVector candidate = null;
for (AnchoredVector possibleCandidate : userAnchoredVectorsAtConnector) {
// we know that these all are at the right anchor, so only test direction.
// direction may also be negated, since these are new symbols.
if (possibleCandidate.getVectorValue().equals(reaction.getVectorValue()) ||
possibleCandidate.getVectorValue().equals(reaction.getVectorValue().negate())) {
candidate = possibleCandidate;
}
}
// candidate should not be null at this point since the main test passed.
NameCheckResult nameResult;
if (connector instanceof Connector2ForceMember2d) {
nameResult = checkAnchoredVectorName2FM(candidate, (Connector2ForceMember2d) connector);
} else {
nameResult = checkLoadName(candidate);
}
if (nameResult == NameCheckResult.passed) {
// we're okay!!
addedLoads.remove(candidate);
} else {
complainAboutName(nameResult, candidate);
return false;
}
}
}
}
// Step 5: Make sure we've used all the user added forces.
if (!addedLoads.isEmpty()) {
logInfo("check: user added more forces than necessary: " + addedLoads);
logInfo("check: FAILED");
setAdviceKey("fbd_feedback_check_fail_additional", addedLoads.get(0).getAnchor().getName());
return false;
}
// Step 6: Verify labels
// verify that all unknowns are symbols
// these are reaction forces and moments
// knowns should not be symbols: externals, weights
// symbols must also not be repeated, unless this is valid somehow? (not yet)
// Yay, we've passed the test!
logInfo("check: PASSED!");
return true;
}
|
diff --git a/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/EmailDigester.java b/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/EmailDigester.java
index c08ce6c0..78bf7b3b 100644
--- a/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/EmailDigester.java
+++ b/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/EmailDigester.java
@@ -1,84 +1,85 @@
package pt.ist.expenditureTrackingSystem.domain;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import myorg.applicationTier.Authenticate;
import myorg.util.Counter;
import org.apache.commons.lang.StringUtils;
import pt.ist.emailNotifier.domain.Email;
import pt.ist.expenditureTrackingSystem.domain.acquisitions.AcquisitionProcessStateType;
import pt.ist.expenditureTrackingSystem.domain.acquisitions.RefundProcessStateType;
import pt.ist.expenditureTrackingSystem.domain.organization.Person;
import pt.ist.fenixWebFramework.services.Service;
import pt.utl.ist.fenix.tools.util.i18n.Language;
public class EmailDigester extends EmailDigester_Base {
public EmailDigester() {
super();
}
private String getBody(Map<AcquisitionProcessStateType, Counter<AcquisitionProcessStateType>> acquisitionMap,
Map<RefundProcessStateType, Counter<RefundProcessStateType>> refundMap) {
StringBuilder builder = new StringBuilder("Caro utilizador, possui processos pendentes na central de compras.\n\n");
if (!acquisitionMap.isEmpty()) {
builder.append("Regime simplificado\n");
for (Counter<AcquisitionProcessStateType> counter : acquisitionMap.values()) {
builder.append("\t");
builder.append(counter.getCountableObject().getLocalizedName());
builder.append("\t");
builder.append(counter.getValue());
builder.append("\n");
}
}
if (!refundMap.isEmpty()) {
builder.append("Processos de reembolso\n");
for (Counter<RefundProcessStateType> counter : refundMap.values()) {
builder.append("\t");
builder.append(counter.getCountableObject().getLocalizedName());
builder.append("\t");
builder.append(counter.getValue());
builder.append("\n");
}
}
builder.append("\n\n---\n");
- builder.append("Esta mensagem foi enviada por meio do sistema Central de Compras. Pode desactivar esta notificação na aplicação.");
+ builder.append("Esta mensagem foi enviada por meio do sistema Central de Compras.\n");
+ builder.append("Pode desactivar o envio destes e-mails fazendo login em http://compras.ist.utl.pt/, aceder à página de resumo seleccionando \"Aquisições\" e desactivando a opção \"Notificação por e-mail\"");
return builder.toString();
}
@Override
@Service
public void executeTask() {
List<String> toAddress = new ArrayList<String>();
Language.setLocale(Language.getDefaultLocale());
for (Person person : ExpenditureTrackingSystem.getInstance().getPeople()) {
if (person.getOptions().getReceiveNotificationsByEmail()) {
Authenticate.authenticate(person.getUsername(), StringUtils.EMPTY);
Map<AcquisitionProcessStateType, Counter<AcquisitionProcessStateType>> generateAcquisitionMap = person
.generateAcquisitionMap();
Map<RefundProcessStateType, Counter<RefundProcessStateType>> generateRefundMap = person.generateRefundMap();
if (!generateAcquisitionMap.isEmpty() || !generateRefundMap.isEmpty()) {
toAddress.clear();
final String email = person.getEmail();
if (email != null) {
toAddress.add(email);
new Email("Central de Compras", "[email protected]", new String[] {}, toAddress, Collections.EMPTY_LIST,
Collections.EMPTY_LIST, "Processos Pendentes", getBody(generateAcquisitionMap, generateRefundMap));
}
}
}
}
}
@Override
public String getLocalizedName() {
return getClass().getName();
}
}
| true | true | private String getBody(Map<AcquisitionProcessStateType, Counter<AcquisitionProcessStateType>> acquisitionMap,
Map<RefundProcessStateType, Counter<RefundProcessStateType>> refundMap) {
StringBuilder builder = new StringBuilder("Caro utilizador, possui processos pendentes na central de compras.\n\n");
if (!acquisitionMap.isEmpty()) {
builder.append("Regime simplificado\n");
for (Counter<AcquisitionProcessStateType> counter : acquisitionMap.values()) {
builder.append("\t");
builder.append(counter.getCountableObject().getLocalizedName());
builder.append("\t");
builder.append(counter.getValue());
builder.append("\n");
}
}
if (!refundMap.isEmpty()) {
builder.append("Processos de reembolso\n");
for (Counter<RefundProcessStateType> counter : refundMap.values()) {
builder.append("\t");
builder.append(counter.getCountableObject().getLocalizedName());
builder.append("\t");
builder.append(counter.getValue());
builder.append("\n");
}
}
builder.append("\n\n---\n");
builder.append("Esta mensagem foi enviada por meio do sistema Central de Compras. Pode desactivar esta notificação na aplicação.");
return builder.toString();
}
| private String getBody(Map<AcquisitionProcessStateType, Counter<AcquisitionProcessStateType>> acquisitionMap,
Map<RefundProcessStateType, Counter<RefundProcessStateType>> refundMap) {
StringBuilder builder = new StringBuilder("Caro utilizador, possui processos pendentes na central de compras.\n\n");
if (!acquisitionMap.isEmpty()) {
builder.append("Regime simplificado\n");
for (Counter<AcquisitionProcessStateType> counter : acquisitionMap.values()) {
builder.append("\t");
builder.append(counter.getCountableObject().getLocalizedName());
builder.append("\t");
builder.append(counter.getValue());
builder.append("\n");
}
}
if (!refundMap.isEmpty()) {
builder.append("Processos de reembolso\n");
for (Counter<RefundProcessStateType> counter : refundMap.values()) {
builder.append("\t");
builder.append(counter.getCountableObject().getLocalizedName());
builder.append("\t");
builder.append(counter.getValue());
builder.append("\n");
}
}
builder.append("\n\n---\n");
builder.append("Esta mensagem foi enviada por meio do sistema Central de Compras.\n");
builder.append("Pode desactivar o envio destes e-mails fazendo login em http://compras.ist.utl.pt/, aceder à página de resumo seleccionando \"Aquisições\" e desactivando a opção \"Notificação por e-mail\"");
return builder.toString();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.